Skip to main content

ethrex_storage/
store.rs

1#[cfg(feature = "rocksdb")]
2use crate::backend::rocksdb::RocksDBBackend;
3use crate::{
4    STORE_METADATA_FILENAME, STORE_SCHEMA_VERSION,
5    api::{
6        StorageBackend, StorageReadView, StorageWriteBatch,
7        tables::{
8            ACCOUNT_CODE_METADATA, ACCOUNT_CODES, ACCOUNT_FLATKEYVALUE, ACCOUNT_TRIE_NODES,
9            BAD_BLOCKS, BLOCK_ACCESS_LISTS, BLOCK_NUMBERS, BODIES, CANONICAL_BLOCK_HASHES,
10            CHAIN_DATA, EXECUTION_WITNESSES, FULLSYNC_HEADERS, HEADERS, INVALID_CHAINS,
11            MISC_VALUES, PENDING_BLOCKS, RECEIPTS_V2, SNAP_STATE, STATE_HISTORY,
12            STORAGE_FLATKEYVALUE, STORAGE_TRIE_NODES, TRANSACTION_LOCATIONS,
13        },
14    },
15    apply_prefix,
16    backend::in_memory::InMemoryBackend,
17    block_data_buffer::BlockDataBuffer,
18    error::StoreError,
19    journal::{FlatDiff, JournalEntry},
20    layering::{Overlay, OverlayCf, TrieLayerCache, TrieWrapper},
21    rlp::{BlockBodyRLP, BlockHeaderRLP, BlockRLP},
22    trie::{BackendTrieDB, BackendTrieDBLocked, classify_trie_key},
23    utils::{ChainDataIndex, SnapStateIndex},
24};
25
26use ethrex_common::{
27    Address, H256, U256,
28    seeded_hash::{SeededHashSet, SeededState},
29    types::{
30        AccountInfo, AccountState, AccountUpdate, Block, BlockBody, BlockHash, BlockHeader,
31        BlockNumber, ChainConfig, Code, CodeMetadata, ForkId, Genesis, GenesisAccount, Index,
32        Receipt, Transaction,
33        block_access_list::BlockAccessList,
34        block_execution_witness::{ExecutionWitness, RpcExecutionWitness},
35    },
36    utils::keccak,
37};
38use ethrex_crypto::{NativeCrypto, keccak::keccak_hash};
39use ethrex_rlp::{
40    decode::{RLPDecode, decode_bytes, decode_rlp_item},
41    encode::RLPEncode,
42    error::RLPDecodeError,
43};
44use ethrex_trie::{EMPTY_TRIE_HASH, Nibbles, Trie, TrieLogger, TrieNode, TrieWitness};
45use ethrex_trie::{Node, NodeRLP};
46use indexmap::IndexMap;
47use lru::LruCache;
48use rayon::prelude::*;
49use serde::{Deserialize, Serialize};
50use std::{
51    collections::{BTreeMap, HashMap, HashSet, hash_map::Entry},
52    fmt::Debug,
53    hash::BuildHasher,
54    io::Write,
55    num::NonZeroUsize,
56    path::{Path, PathBuf},
57    sync::{
58        Arc, Condvar, Mutex, RwLock,
59        atomic::{AtomicUsize, Ordering},
60        mpsc::{SyncSender, TryRecvError, sync_channel},
61    },
62    thread::JoinHandle,
63};
64use tracing::{debug, error, info, warn};
65
66/// Maximum number of execution witnesses to keep in the database
67pub const MAX_WITNESSES: u64 = 128;
68
69// We use one constant for in-memory and another for on-disk backends.
70// This is due to tests requiring state older than 128 blocks.
71// TODO: unify these
72pub const DB_COMMIT_THRESHOLD: usize = 128;
73const IN_MEMORY_COMMIT_THRESHOLD: usize = 10000;
74
75/// Depth-only commit threshold for batch execution (full sync / block import). Each batch
76/// layer holds ~1024 blocks of trie diffs (~1 GB), so we flush after a few layers to bound
77/// memory. The canonical `head - DB_COMMIT_THRESHOLD` safe-commit root never lands on a batch
78/// layer boundary, so batch mode commits by depth instead; this is sound because full sync and
79/// import only ever extend a single canonical chain (no competing forks to mis-commit).
80pub const BATCH_COMMIT_THRESHOLD: usize = 4;
81
82/// Sorted, sharded `multi_get` tuning, shared by the account, storage, and
83/// trie-node batch read paths. A single `multi_get` runs at queue depth 1
84/// (async_io is off), so cold batches are split into contiguous sorted shards
85/// read on separate blocking threads. `KEYS_PER_SHARD` targets shard size,
86/// `MAX_SHARDS` caps concurrency; scattered keys make 64 the sweet spot (128
87/// over-fragments; coldbench).
88const KEYS_PER_SHARD: usize = 256;
89const MAX_SHARDS: usize = 64;
90
91/// Shard count for a sorted, sharded `multi_get` over `n` keys.
92fn shard_count(n: usize) -> usize {
93    n.div_ceil(KEYS_PER_SHARD).clamp(1, MAX_SHARDS)
94}
95
96/// Ceiling on the RocksDB shared block cache: 12 GiB.
97///
98/// This cache holds both data blocks AND the index/bloom-filter blocks for every
99/// open SST file (because we enable `cache_index_and_filter_blocks`), so its size
100/// is the effective upper bound on RocksDB's resident memory footprint. 12 GiB
101/// keeps the filter/index working set resident plus hot EVM state; a sweep on a
102/// synced mainnet node (32 GiB cap) found 8-16 GiB all keep up with head-following,
103/// with larger giving no gain (the OS page cache backstops the uncompressed state
104/// CFs) and ~8 GiB the floor where the filter set starts to thrash.
105pub const MAX_ROCKSDB_BLOCK_CACHE_SIZE_BYTES: usize = 12 * 1024 * 1024 * 1024;
106
107/// Floor on the RocksDB shared block cache: 512 MiB. Below this the per-SST
108/// index and filter blocks no longer stay resident and every trie read pays an
109/// extra disk seek, which is worse than the memory it saves. Applied even when
110/// it exceeds [`ROCKSDB_BLOCK_CACHE_MEMORY_PERCENT`] of a very small host, and
111/// even when it exceeds the detected limit outright: a node given less than this
112/// much memory cannot follow the chain anyway, so the floor is the more useful
113/// failure mode than a cache too small to hold the filters.
114pub const MIN_ROCKSDB_BLOCK_CACHE_SIZE_BYTES: usize = 512 * 1024 * 1024;
115
116/// Share of the host's (or cgroup's) memory the block cache may claim by default.
117///
118/// The rest has to cover the in-memory trie-layer backlog, block execution, the
119/// mempool, peer buffers and allocator slack, so the cache cannot have most of the
120/// machine. At 40% a 32 GiB host lands on the 12 GiB ceiling and a 16 GiB host gets
121/// ~6.4 GiB — under the ~8 GiB thrash floor, but that is the memory-constrained
122/// tradeoff the ceiling's docs describe, and it leaves the node room not to be
123/// OOM-killed.
124pub const ROCKSDB_BLOCK_CACHE_MEMORY_PERCENT: usize = 40;
125
126/// Default RocksDB shared block cache size, derived from the memory this process
127/// is actually allowed to use.
128///
129/// A fixed default cannot serve both a 64 GiB validator and a 16 GiB CI runner: the
130/// ceiling alone is 71% of a 16 GiB host, which leaves no headroom for the rest of
131/// the node. Sizes to [`ROCKSDB_BLOCK_CACHE_MEMORY_PERCENT`] of the detected limit —
132/// the smaller of physical memory and the cgroup limit, so a container is sized
133/// against its own allowance rather than the machine it lands on — clamped to
134/// [`MIN_ROCKSDB_BLOCK_CACHE_SIZE_BYTES`] ..=
135/// [`MAX_ROCKSDB_BLOCK_CACHE_SIZE_BYTES`]. Falls back to the ceiling when the limit
136/// cannot be detected, preserving the previous behavior.
137pub fn default_rocksdb_block_cache_size() -> usize {
138    let physical = physical_memory_bytes();
139    let cgroup = cgroup_memory_limit_bytes();
140    let limit = [physical, cgroup].into_iter().flatten().min();
141    let size = rocksdb_block_cache_size_for(limit);
142    // The cache size used to be a knowable constant; now it depends on the
143    // environment, on a code path that exists because a mis-sized cache was
144    // only ever discovered via an OOM kill. Leave the whole derivation in the
145    // log: which detector won, what it read, and what that resolved to.
146    let source = match (physical, cgroup) {
147        (None, None) => "undetected, falling back to the ceiling",
148        (Some(_), None) => "physical memory",
149        (None, Some(_)) => "cgroup limit",
150        (Some(p), Some(c)) => {
151            if c <= p {
152                "cgroup limit"
153            } else {
154                "physical memory"
155            }
156        }
157    };
158    info!(
159        detected_limit_bytes = ?limit,
160        source,
161        cache_bytes = size,
162        "sized RocksDB block cache"
163    );
164    size
165}
166
167/// Pure part of [`default_rocksdb_block_cache_size`]: the clamp, with the detected
168/// memory limit supplied by the caller. `None` means detection failed.
169pub fn rocksdb_block_cache_size_for(memory_limit: Option<usize>) -> usize {
170    let Some(limit) = memory_limit else {
171        return MAX_ROCKSDB_BLOCK_CACHE_SIZE_BYTES;
172    };
173    (limit.saturating_mul(ROCKSDB_BLOCK_CACHE_MEMORY_PERCENT) / 100).clamp(
174        MIN_ROCKSDB_BLOCK_CACHE_SIZE_BYTES,
175        MAX_ROCKSDB_BLOCK_CACHE_SIZE_BYTES,
176    )
177}
178
179/// `MemTotal` from `/proc/meminfo`, in bytes.
180fn physical_memory_bytes() -> Option<usize> {
181    let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?;
182    let kib: usize = meminfo
183        .lines()
184        .find_map(|line| line.strip_prefix("MemTotal:"))?
185        .split_whitespace()
186        .next()?
187        .parse()
188        .ok()?;
189    kib.checked_mul(1024)
190}
191
192/// The cgroup memory limit that applies to this process, in bytes: `memory.max`
193/// under cgroup v2, falling back to `memory.limit_in_bytes` under v1. Both report
194/// "no limit" out of band — v2 with the literal `max`, v1 with a sentinel near
195/// `u64::MAX` — which yields `None` here (v1's sentinel simply exceeds any real
196/// `MemTotal`, so the `min` above discards it).
197///
198/// The limit may sit on any cgroup between the one the process belongs to and the
199/// mount root — a systemd slice, a Kubernetes pod's parent, an outer container — and
200/// the mount root itself is usually unlimited, so reading the root alone would miss
201/// it. The process's own cgroup comes from `/proc/self/cgroup` and every level up to
202/// the root is read, with the smallest limit winning.
203fn cgroup_memory_limit_bytes() -> Option<usize> {
204    let cgroups = std::fs::read_to_string("/proc/self/cgroup").ok()?;
205    let v2 = cgroups
206        .lines()
207        .find_map(|line| line.strip_prefix("0::"))
208        .and_then(|relative| {
209            cgroup_limit_up_to_root(Path::new("/sys/fs/cgroup"), relative, "memory.max")
210        });
211    v2.or_else(|| {
212        let relative = cgroups.lines().find_map(|line| {
213            // `hierarchy-ID:controller-list:cgroup-path`
214            let mut fields = line.splitn(3, ':');
215            let controllers = fields.nth(1)?;
216            let path = fields.next()?;
217            controllers
218                .split(',')
219                .any(|controller| controller == "memory")
220                .then_some(path)
221        })?;
222        cgroup_limit_up_to_root(
223            Path::new("/sys/fs/cgroup/memory"),
224            relative,
225            "memory.limit_in_bytes",
226        )
227    })
228}
229
230/// Smallest value of `file` across `<mount>/<relative>` and each of its ancestors up
231/// to `mount`, skipping levels whose file is absent or reports no limit.
232fn cgroup_limit_up_to_root(mount: &Path, relative: &str, file: &str) -> Option<usize> {
233    let mut dir = mount.join(relative.trim_start_matches('/'));
234    let mut limit: Option<usize> = None;
235    loop {
236        if let Some(value) = std::fs::read_to_string(dir.join(file))
237            .ok()
238            .and_then(|contents| contents.trim().parse::<usize>().ok())
239        {
240            limit = Some(limit.map_or(value, |current| current.min(value)));
241        }
242        if dir == mount || !dir.pop() {
243            return limit;
244        }
245    }
246}
247
248/// Tunable configuration for [`Store::new_with_config`] and related constructors.
249///
250/// Use [`StoreConfig::default()`] for production-tuned defaults; callers that
251/// don't need to override anything should keep calling [`Store::new`] directly.
252#[derive(Debug, Clone, Copy)]
253pub struct StoreConfig {
254    /// Size in bytes of the RocksDB shared block cache. With
255    /// `cache_index_and_filter_blocks` enabled (the ethrex default), this is
256    /// the effective ceiling on RocksDB's resident memory. Ignored for
257    /// in-memory backends.
258    pub rocksdb_block_cache_size: usize,
259    /// Byte budget of the bytecode cache. `None` keeps [`CODE_CACHE_MAX_SIZE`].
260    pub code_cache_size: Option<u64>,
261    /// Bound on the persist worker's channel: number of staged (acked) live
262    /// messages whose flush may still be in flight. Once full, the next send
263    /// blocks — that is the backpressure that throttles `newPayload`.
264    /// Clamped to `max(1)` at construction (0 would make a rendezvous channel).
265    pub persist_channel_capacity: usize,
266}
267
268impl StoreConfig {
269    /// Every tuned default except the block cache, which the caller supplies.
270    /// An explicit cache size must come through here rather than overwriting a
271    /// [`StoreConfig::default()`], which would run (and log) the memory
272    /// detection only to discard its result.
273    pub fn with_rocksdb_block_cache_size(rocksdb_block_cache_size: usize) -> Self {
274        Self {
275            rocksdb_block_cache_size,
276            code_cache_size: None,
277            persist_channel_capacity: DEFAULT_PERSIST_CHANNEL_CAPACITY,
278        }
279    }
280}
281
282impl Default for StoreConfig {
283    fn default() -> Self {
284        Self::with_rocksdb_block_cache_size(default_rocksdb_block_cache_size())
285    }
286}
287
288/// Control messages for the FlatKeyValue generator
289#[derive(Debug, PartialEq)]
290enum FKVGeneratorControlMessage {
291    Stop,
292    Continue,
293}
294
295/// Byte budget for the in-memory bytecode cache.
296///
297/// Bytecode is a small fraction of the working set next to trie nodes and flat
298/// key-values (which the RocksDB block cache serves), but a cold code read costs a
299/// blob-file fetch plus decompression, so caching contracts pays for itself.
300///
301/// 2 GiB holds ~29k max-size contracts: a 64 KiB contract (EIP-7954) is accounted
302/// at ~72 KiB, its padded bytecode plus the 8 KiB jumpdest bitmap. Entries never
303/// expire and every read that misses inserts (block execution, snap `GetByteCodes`
304/// serving, `eth_getCode`, `eth_call`), so a long-running node fills the budget.
305/// Each entry is also charged [`CODE_CACHE_ENTRY_OVERHEAD`] for its map slot and
306/// buffer headers, so small contracts cannot hold the cache far over its budget.
307const CODE_CACHE_MAX_SIZE: u64 = 2 * 1024 * 1024 * 1024;
308
309/// Entry bound for [`Store::code_metadata_cache`], derived from a 16 MiB ceiling at the
310/// ~64 B an `LruCache` entry costs (32 B key + 8 B value + list/table overhead). The
311/// ~262k lengths it keeps cover every code the 2 GiB code cache can hold while cached
312/// contracts average at least 8 KiB (~10.5 KiB on mainnet). A cache of smaller ones,
313/// such as EIP-7702 delegations, holds more codes than that, and `EXTCODESIZE` on
314/// those falls through to `ACCOUNT_CODE_METADATA`. The bound caps what an
315/// `EXTCODESIZE` sweep over unique contracts can pin.
316const CODE_METADATA_CACHE_MAX_ENTRIES: usize = (16 * 1024 * 1024) / 64;
317
318/// Key used to persist the `flushed_upto` block number in `MISC_VALUES`.
319const FLUSHED_UPTO_KEY: &[u8] = b"bodies_flushed_upto";
320
321/// Single key under which the bounded list of bad blocks is stored in `BAD_BLOCKS`.
322const BAD_BLOCKS_KEY: &[u8] = b"bad_blocks";
323
324/// Maximum number of bad blocks retained for `debug_getBadBlocks`.
325const MAX_BAD_BLOCKS: usize = 16;
326
327/// Heap bytes a [`CodeCache`] entry costs beyond [`Code::size`]: its slot in the map's
328/// entry vector and index, and the headers of the two shared buffers. Measured at 126 to
329/// 133 bytes requested per entry, before the allocator rounds them up to its size classes.
330/// Without it, a cache full of small contracts held nearly twice its budget (1.87x at 32
331/// bytes).
332const CODE_CACHE_ENTRY_OVERHEAD: u64 = 160;
333
334/// Bytecode cache that evicts a uniformly random entry when over budget.
335///
336/// Not LRU on purpose: blocks can walk the same set of contracts over and over, and
337/// once that set outgrows the budget an LRU evicts every entry just before its next
338/// use, so the hit rate collapses to zero. A random victim has no such pathology: with
339/// a set 1.25x the budget about 62% of the reads still hit, and the hit rate shrinks
340/// gradually as the set grows instead of falling off a cliff.
341///
342/// Seeded: entries outlive the block that loaded them, and a deployer can grind its code
343/// hash into a chosen bucket (see `ethrex_common::seeded_hash`).
344struct CodeCache {
345    entries: IndexMap<H256, Code, SeededState>,
346    cache_size: u64,
347    max_size: u64,
348    /// xorshift64* state; seeded per process so the victims cannot be predicted.
349    rng: u64,
350}
351
352// Not derived: `Store` derives `Debug`, and a derived impl here would format every cached
353// bytecode (up to the whole budget) and the RNG state.
354impl std::fmt::Debug for CodeCache {
355    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
356        f.debug_struct("CodeCache")
357            .field("len", &self.entries.len())
358            .field("cache_size", &self.cache_size)
359            .field("max_size", &self.max_size)
360            .finish_non_exhaustive()
361    }
362}
363
364impl Default for CodeCache {
365    fn default() -> Self {
366        Self {
367            entries: IndexMap::default(),
368            cache_size: 0,
369            max_size: CODE_CACHE_MAX_SIZE,
370            // xorshift must not start at zero.
371            rng: std::collections::hash_map::RandomState::new().hash_one(0u64) | 1,
372        }
373    }
374}
375
376impl CodeCache {
377    /// What one cached `code` costs against `max_size`.
378    fn entry_size(code: &Code) -> u64 {
379        (code.size() as u64).saturating_add(CODE_CACHE_ENTRY_OVERHEAD)
380    }
381
382    fn get(&self, code_hash: &H256) -> Result<Option<Code>, StoreError> {
383        Ok(self.entries.get(code_hash).cloned())
384    }
385
386    fn contains(&self, code_hash: &H256) -> bool {
387        self.entries.contains_key(code_hash)
388    }
389
390    fn insert(&mut self, code: &Code) -> Result<(), StoreError> {
391        // A hash already cached must not be added to `cache_size` again, or the counter
392        // drifts up permanently and evicts entries that fit.
393        if self.entries.contains_key(&code.hash) {
394            return Ok(());
395        }
396        // An entry larger than the whole budget would hold the cache over it, so it is
397        // not cached; the caller already has its copy.
398        let size = Self::entry_size(code);
399        if size > self.max_size {
400            return Ok(());
401        }
402
403        // Evicting before the insert keeps the new entry out of the draw, so it stays
404        // cached for the caller about to read it and every victim is equally likely.
405        while self.cache_size + size > self.max_size && !self.entries.is_empty() {
406            let victim = (self.next_random() % self.entries.len() as u64) as usize;
407            if let Some((_, evicted)) = self.entries.swap_remove_index(victim) {
408                self.cache_size -= Self::entry_size(&evicted);
409            }
410        }
411        self.cache_size += size;
412        self.entries.insert(code.hash, code.clone());
413
414        let cache_len = self.entries.len();
415        let current_size = self.cache_size;
416        debug!(
417            "[ACCOUNT CODE CACHE] cache elements (): {cache_len}, total size: {current_size} bytes"
418        );
419        Ok(())
420    }
421
422    fn next_random(&mut self) -> u64 {
423        self.rng ^= self.rng >> 12;
424        self.rng ^= self.rng << 25;
425        self.rng ^= self.rng >> 27;
426        self.rng.wrapping_mul(0x2545_F491_4F6C_DD1D)
427    }
428}
429
430/// Main storage interface for the ethrex client.
431///
432/// `Store` is `Clone` and thread-safe; all clones share the same backend and
433/// caches via `Arc`. Reads consult an in-memory block-data buffer before disk
434/// so not-yet-flushed blocks are always visible.
435#[derive(Debug, Clone)]
436pub struct Store {
437    /// Path to the database directory.
438    db_path: PathBuf,
439    /// Storage backend (InMemory or RocksDB).
440    backend: Arc<dyn StorageBackend>,
441    /// Chain configuration (fork schedule, chain ID, etc.).
442    chain_config: ChainConfig,
443    /// Cache for trie nodes from recent blocks.
444    trie_cache: Arc<RwLock<Arc<TrieLayerCache>>>,
445    /// Channel for controlling the FlatKeyValue generator background task.
446    flatkeyvalue_control_tx: std::sync::mpsc::SyncSender<FKVGeneratorControlMessage>,
447    /// In-memory overlay of block data not yet flushed to disk.
448    block_data_buffer: Arc<RwLock<Arc<BlockDataBuffer>>>,
449    /// Channel to the single persist worker (`apply_updates` → `PersistMessage::Block`,
450    /// `wait_for_persistence_idle` → `PersistMessage::Ping`). The worker is the
451    /// sole mutator of `block_data_buffer` in production.
452    persist_tx: std::sync::mpsc::SyncSender<PersistMessage>,
453    /// Roots whose trie diff-layer is being built but not yet installed in
454    /// `trie_cache`. Trie opens block on these so a just-added block's state is
455    /// never read as stale before its layer lands.
456    pending_trie_roots: Arc<PendingTrieRoots>,
457    /// Cached latest canonical block header. May be slightly stale, which is
458    /// acceptable for RPC "latest" queries and sync operations.
459    latest_block_header: LatestBlockHeaderCache,
460    /// Last computed FlatKeyValue for incremental updates.
461    last_computed_flatkeyvalue: Arc<RwLock<Vec<u8>>>,
462
463    /// Cache for account bytecodes, keyed by the bytecode hash.
464    /// Note that we don't remove entries on account code changes, since
465    /// those changes already affect the code hash stored in the account, and only
466    /// may result in this cache having useless data.
467    account_code_cache: Arc<Mutex<CodeCache>>,
468
469    /// Cache for code metadata (code length), keyed by the bytecode hash.
470    ///
471    /// Bounded: `EXTCODESIZE` reads this on the execution path, so an unbounded map
472    /// would grow by one entry per distinct contract ever asked for a length and never
473    /// give the memory back. See [`CODE_METADATA_CACHE_MAX_ENTRIES`]. Seeded, like
474    /// [`CodeCache`].
475    code_metadata_cache: Arc<Mutex<LruCache<H256, CodeMetadata, SeededState>>>,
476
477    /// Serializes concurrent `forkchoice_update` callers so that the cache
478    /// update and the DB write transaction remain mutually ordered.
479    fcu_lock: Arc<tokio::sync::Mutex<()>>,
480
481    /// Canonical safe-commit state root, computed after each forkchoice update.
482    ///
483    /// Shared with the [`TrieLayerCache`] so that the Store can update the cell without
484    /// replacing the cache Arc. `H256::zero()` means "no safe commit point yet".
485    /// Cloning `Store` shares this cell across all clones, which is required and correct.
486    safe_commit_root: Arc<RwLock<H256>>,
487
488    /// While set, `forkchoice_update_inner` skips STATE_HISTORY pruning (the
489    /// finalized-number update still lands). Set by `Blockchain::enter_reorg` for
490    /// the duration of a deep-reorg apply pass: `Overlay::from_journal` reads
491    /// journal entries one by one with no snapshot isolation, and syncer-driven
492    /// forkchoice updates are not gated by the reorg mutex, so a concurrent
493    /// finality advance could otherwise prune entries out from under overlay
494    /// construction (spurious `MissingEntry`) or between a case-1 attempt and its
495    /// retry. Pruning catches up on the first finality advance after the pass
496    /// ends (the pruned range starts at the lowest entry still present).
497    journal_pruning_paused: Arc<std::sync::atomic::AtomicBool>,
498
499    /// Signalled when an input of the node's sync status may have changed: the
500    /// canonical head, the sync target, the executed head or the synced flag.
501    sync_status_changed: Arc<tokio::sync::watch::Sender<()>>,
502
503    background_threads: Arc<ThreadList>,
504}
505
506#[derive(Debug, Default)]
507struct ThreadList {
508    list: Vec<JoinHandle<()>>,
509}
510
511impl Drop for ThreadList {
512    fn drop(&mut self) {
513        for handle in self.list.drain(..) {
514            let _ = handle.join();
515        }
516    }
517}
518
519/// Storage trie nodes grouped by account address hash.
520///
521/// Each entry contains the hashed account address and the trie nodes
522/// for that account's storage trie.
523pub type StorageTrieNodes = Vec<(H256, Vec<(Nibbles, Vec<u8>)>)>;
524type StorageTries = HashMap<Address, (TrieWitness, Trie)>;
525
526/// Storage backend type selection.
527///
528/// Used when creating a new [`Store`] to specify which backend to use.
529#[derive(Debug, Clone, Copy, PartialEq, Eq)]
530pub enum EngineType {
531    /// In-memory storage, non-persistent. Suitable for testing.
532    InMemory,
533    /// RocksDB storage, persistent. Suitable for production.
534    #[cfg(feature = "rocksdb")]
535    RocksDB,
536}
537
538/// Batch of updates to apply to the store atomically.
539///
540/// Used during block execution to collect all state changes before
541/// committing them to the database in a single transaction.
542pub struct UpdateBatch {
543    /// New nodes to add to the state trie.
544    pub account_updates: Vec<TrieNode>,
545    /// Storage trie updates per account (keyed by hashed address).
546    pub storage_updates: Vec<(H256, Vec<TrieNode>)>,
547    /// Blocks to store.
548    pub blocks: Vec<Block>,
549    /// Receipts to store, grouped by block hash.
550    pub receipts: Vec<(H256, Vec<Receipt>)>,
551    /// Contract code updates (code hash -> bytecode).
552    pub code_updates: Vec<(H256, Code)>,
553    /// Commit gate for this batch's trie layers (independent of `wait_for_flush`).
554    ///
555    /// - `None`: live path (`newPayload`). The persist worker commits by the canonical
556    ///   `head - DB_COMMIT_THRESHOLD` safe-commit root.
557    /// - `Some(depth)`: single-canonical-chain execution (batch import, full sync, startup
558    ///   state regeneration). The persist worker commits every layer deeper than `depth`
559    ///   (see [`Trie::get_commitable_by_depth`]), which bounds resident trie layers to ~`depth`.
560    pub commit_depth: Option<usize>,
561    /// When the persist worker acks (independent of `commit_depth`).
562    ///
563    /// - `false`: ack after staging, so the caller's next-block execution overlaps this
564    ///   block's disk flush. Used by the live path and the per-block re-execution paths
565    ///   (regen / full-sync fallback / import tail) — their memory is already bounded by
566    ///   `commit_depth`'s depth gate and the persist channel capacity, so waiting per block
567    ///   would only serialize CPU and I/O for no benefit.
568    /// - `true`: ack after flush, bounding in-flight work to ~1 message. Used by the bespoke
569    ///   batch path, where a single message carries ~1024 blocks (~1 GB of trie diff) and two
570    ///   in flight would be a real memory cost.
571    pub wait_for_flush: bool,
572}
573
574/// A block's historical chain data to backfill below the snap-sync pivot: the
575/// (already-canonical) header, its body, and its receipts.
576///
577/// `index_transactions` controls whether the transaction-lookup index is written
578/// for this block; the backfill task drives it from the `--history.transactions`
579/// horizon so old blocks can be excluded from the index while still storing their
580/// bodies and receipts.
581pub struct BackfilledBlock {
582    pub header: BlockHeader,
583    pub body: BlockBody,
584    pub receipts: Vec<Receipt>,
585    pub index_transactions: bool,
586}
587
588/// Storage trie updates grouped by account address hash.
589pub type StorageUpdates = Vec<(H256, Vec<(Nibbles, Vec<u8>)>)>;
590
591/// Collection of account state changes from block execution.
592///
593/// Contains all the data needed to update the state trie after
594/// executing a block: account updates, storage updates, and code deployments.
595pub struct AccountUpdatesList {
596    /// Root hash of the state trie after applying these updates.
597    pub state_trie_hash: H256,
598    /// State trie node updates (path -> RLP-encoded node).
599    pub state_updates: Vec<(Nibbles, Vec<u8>)>,
600    /// Storage trie updates per account.
601    pub storage_updates: StorageUpdates,
602    /// New contract bytecode deployments.
603    pub code_updates: Vec<(H256, Code)>,
604}
605
606/// Encodes a tx-location entry as the operand passed to `merge_cf`.
607///
608/// The operand uses the **same encoding as the stored value** — a
609/// `Vec<(BlockNumber, BlockHash, Index)>` with a single element. This is
610/// required for an *associative* merge operator: RocksDB folds operands
611/// together with PartialMerge (during compaction, without a base value), and
612/// the result becomes an operand for a later merge. If the operand format
613/// differed from the merge output (e.g. operand = bare tuple, output = Vec),
614/// the re-fed result would fail to decode and entries would be silently
615/// dropped. Keeping both as `Vec` makes the merge truly associative.
616pub(crate) fn encode_tx_location_operand(
617    block_number: BlockNumber,
618    block_hash: BlockHash,
619    index: Index,
620) -> Vec<u8> {
621    vec![(block_number, block_hash, index)].encode_to_vec()
622}
623
624/// Merge function for the `TRANSACTION_LOCATIONS` column family.
625///
626/// The CF stores `Vec<(BlockNumber, BlockHash, Index)>` keyed by tx hash.
627/// Both stored values and operands use this same `Vec` encoding — this
628/// associativity requirement is mandatory: RocksDB folds operands together
629/// during compaction without a base value (PartialMerge), then feeds that
630/// result back into a later merge. A differing format would silently drop
631/// entries. See `encode_tx_location_operand`.
632///
633/// Within the fold, a later entry with the same `block_hash` replaces an
634/// earlier one (reorg dedupe). On decode failure the merge returns `None`
635/// so RocksDB surfaces a corruption error rather than silently dropping
636/// locations.
637///
638/// Merge instead of read-modify-write avoids the ~5–20 ms/block per-tx point
639/// lookup on the write path; consolidation is deferred to compaction or the
640/// next read.
641pub fn tx_locations_merge(
642    existing: Option<&[u8]>,
643    operands: impl IntoIterator<Item = impl AsRef<[u8]>>,
644) -> Option<Vec<u8>> {
645    // Fold one RLP-encoded `Vec` chunk into `list`, deduping by block_hash
646    // (later entry wins). Returns false on decode failure so the caller can
647    // abort the whole merge.
648    fn fold_chunk(
649        list: &mut Vec<(BlockNumber, BlockHash, Index)>,
650        bytes: &[u8],
651        what: &str,
652    ) -> bool {
653        match <Vec<(BlockNumber, BlockHash, Index)>>::decode(bytes) {
654            Ok(entries) => {
655                for (bn, bh, idx) in entries {
656                    list.retain(|(_, existing_bh, _)| *existing_bh != bh);
657                    list.push((bn, bh, idx));
658                }
659                true
660            }
661            Err(e) => {
662                error!(
663                    "tx_locations_merge: failed to decode {what} ({} bytes): {e}; \
664                     aborting merge to avoid silent data loss",
665                    bytes.len()
666                );
667                false
668            }
669        }
670    }
671
672    let mut list: Vec<(BlockNumber, BlockHash, Index)> = Vec::new();
673
674    // Order matters: RocksDB delivers operands oldest-first.
675    if let Some(bytes) = existing
676        && !fold_chunk(&mut list, bytes, "existing value")
677    {
678        return None;
679    }
680    for op in operands {
681        if !fold_chunk(&mut list, op.as_ref(), "operand") {
682            return None;
683        }
684    }
685    Some(list.encode_to_vec())
686}
687
688impl Store {
689    /// Block until the persist worker has fully processed all previously-sent
690    /// `Block` messages (staged, trie-layer built, flushed, evicted).
691    ///
692    /// Uses an ack-based `Ping` rather than a bare send because the channel is
693    /// buffered — a bare send proves nothing about prior message completion. The
694    /// worker is FIFO, so it handles the `Ping` only after every earlier `Block`
695    /// is done.
696    ///
697    /// Concurrent-producer caveat: if another thread sends a `Block` after the
698    /// `Ping` is enqueued, that block may not be flushed by the time this returns.
699    pub async fn wait_for_persistence_idle(&self) -> Result<(), StoreError> {
700        let tx = self.persist_tx.clone();
701        tokio::task::spawn_blocking(move || {
702            let (ack_tx, ack_rx) = sync_channel::<Result<(), StoreError>>(1);
703            tx.send(PersistMessage::Ping(ack_tx))
704                .map_err(|e| StoreError::Custom(format!("wait_for_persistence_idle send: {e}")))?;
705            ack_rx
706                .recv()
707                .map_err(|e| StoreError::Custom(format!("wait_for_persistence_idle ack: {e}")))?
708        })
709        .await
710        .map_err(|e| StoreError::Custom(format!("wait_for_persistence_idle join: {e}")))?
711    }
712
713    /// Flushes all in-memory state to disk for a clean shutdown.
714    ///
715    /// Sends a `Shutdown` handshake to the persist worker, which (being FIFO)
716    /// first drains every queued `Block`, then force-flushes the block-data
717    /// buffer to disk. Once the worker acks, this syncs the backend (memtables +
718    /// WAL) so the next process start needs no WAL recovery.
719    ///
720    /// The in-memory trie diff-layers are intentionally *not* force-committed.
721    /// The on-disk trie is a single-version, path-based store, so folding the
722    /// non-finalized tail into it would leave a post-restart reorg unable to
723    /// reconstruct the overwritten ancestor state (the node would wedge). The
724    /// recent (< `DB_COMMIT_THRESHOLD`) layers are dropped and re-executed on the
725    /// next start from the deep, reorg-safe on-disk base — exactly as after any
726    /// restart today.
727    ///
728    /// After this returns the persist worker has exited; the store must not be
729    /// used for further writes. Idempotent only in the sense that a second call
730    /// errors on the closed channel — call it exactly once, on shutdown.
731    pub async fn shutdown(&self) -> Result<(), StoreError> {
732        let tx = self.persist_tx.clone();
733        let backend = self.backend.clone();
734        tokio::task::spawn_blocking(move || {
735            let (ack_tx, ack_rx) = sync_channel::<Result<(), StoreError>>(1);
736            tx.send(PersistMessage::Shutdown { ack: ack_tx })
737                .map_err(|e| StoreError::Custom(format!("shutdown send: {e}")))?;
738            ack_rx
739                .recv()
740                .map_err(|e| StoreError::Custom(format!("shutdown ack: {e}")))??;
741            // Worker has flushed block data to the WAL/memtables; make it durable
742            // and recovery-free.
743            backend.flush()
744        })
745        .await
746        .map_err(|e| StoreError::Custom(format!("shutdown join: {e}")))?
747    }
748
749    /// Add a block in a single transaction.
750    /// This will store -> BlockHeader, BlockBody, BlockTransactions, BlockNumber.
751    pub async fn add_block(&self, block: Block) -> Result<(), StoreError> {
752        self.add_blocks(vec![block]).await
753    }
754
755    /// Add a batch of blocks in a single transaction.
756    /// This will store -> BlockHeader, BlockBody, BlockTransactions, BlockNumber.
757    pub async fn add_blocks(&self, blocks: Vec<Block>) -> Result<(), StoreError> {
758        let db = self.backend.clone();
759        tokio::task::spawn_blocking(move || {
760            let mut tx = db.begin_write()?;
761
762            for block in blocks {
763                write_block_data(
764                    tx.as_mut(),
765                    block.header.number,
766                    block.hash(),
767                    &block.header,
768                    &block.body,
769                )?;
770            }
771
772            tx.commit()
773        })
774        .await
775        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
776    }
777
778    /// Add block header
779    pub async fn add_block_header(
780        &self,
781        block_hash: BlockHash,
782        block_header: BlockHeader,
783    ) -> Result<(), StoreError> {
784        let hash_key = block_hash.encode_to_vec();
785        let header_value = BlockHeaderRLP::from(block_header).into_vec();
786        self.write_async(HEADERS, hash_key, header_value).await
787    }
788
789    /// Add a batch of block headers
790    pub async fn add_block_headers(
791        &self,
792        block_headers: Vec<BlockHeader>,
793    ) -> Result<(), StoreError> {
794        let mut txn = self.backend.begin_write()?;
795
796        for header in block_headers {
797            let block_hash = header.hash();
798            let block_number = header.number;
799            let hash_key = block_hash.encode_to_vec();
800            let header_value = BlockHeaderRLP::from(header).into_vec();
801
802            txn.put(HEADERS, &hash_key, &header_value)?;
803
804            let number_key = block_number.to_le_bytes().to_vec();
805            txn.put(BLOCK_NUMBERS, &hash_key, &number_key)?;
806        }
807        txn.commit()?;
808        Ok(())
809    }
810
811    /// Obtain canonical block header
812    pub fn get_block_header(
813        &self,
814        block_number: BlockNumber,
815    ) -> Result<Option<BlockHeader>, StoreError> {
816        let latest = self.latest_block_header.get();
817        if block_number == latest.number {
818            return Ok(Some((*latest).clone()));
819        }
820        // Resolve the canonical hash, then read through the buffer-aware by-hash
821        // path so a canonical-but-still-buffered block is visible (mirrors
822        // `get_block_body`). `load_block_header` is disk-only and would return
823        // `None` for a block whose header has not been flushed yet.
824        let Some(block_hash) = self.get_canonical_block_hash_sync(block_number)? else {
825            return Ok(None);
826        };
827        self.get_block_header_by_hash(block_hash)
828    }
829
830    /// Add block body
831    pub async fn add_block_body(
832        &self,
833        block_hash: BlockHash,
834        block_body: BlockBody,
835    ) -> Result<(), StoreError> {
836        let hash_key = block_hash.encode_to_vec();
837        let body_value = BlockBodyRLP::from(block_body).into_vec();
838        self.write_async(BODIES, hash_key, body_value).await
839    }
840
841    /// Backfill historical chain data for a contiguous range of already-canonical
842    /// blocks (bodies, receipts, and optionally the transaction-lookup index),
843    /// then lower `earliest_block_number` to `new_earliest` — all in one write
844    /// transaction.
845    ///
846    /// This is the storage half of `--history.chain` backfill. It does NOT touch
847    /// state, the trie layer cache, or fork choice: the headers and canonical
848    /// mapping already exist from snap-sync header backfill, so only the
849    /// body / receipt / tx-index tables are filled. Writing the data and advancing
850    /// the frontier atomically preserves the invariant that every block in
851    /// `[earliest_block_number, head]` has a stored body — a crash mid-batch
852    /// leaves both the data and the frontier unchanged, so resume never skips a
853    /// hole.
854    ///
855    /// `new_earliest` must be the lowest block number covered by `blocks` (the
856    /// bottom of the contiguous filled range); the caller fills downward without
857    /// gaps.
858    pub async fn add_backfilled_blocks(
859        &self,
860        blocks: Vec<BackfilledBlock>,
861        new_earliest: BlockNumber,
862    ) -> Result<(), StoreError> {
863        // The frontier block is already stored, and indexed if it is a snap pivot.
864        // `earliest` and the floor are read outside the write transaction: backfill is
865        // their only writer once the node is synced, and it writes one batch at a time.
866        let earliest = self
867            .read_chain_data_block_number(ChainDataIndex::EarliestBlockNumber)
868            .await?
869            .unwrap_or(BlockNumber::MAX);
870        let unindexed_top = blocks
871            .iter()
872            .filter(|block| {
873                !block.index_transactions
874                    && !block.body.transactions.is_empty()
875                    && block.header.number < earliest
876            })
877            .map(|block| block.header.number)
878            .max();
879        let mut tx_index_floor = None;
880        if let Some(top) = unindexed_top {
881            let floor = top.saturating_add(1);
882            let current = self.get_tx_index_floor().await?;
883            tx_index_floor = Some(current.map_or(floor, |current| current.max(floor)));
884        }
885        let backend = self.backend.clone();
886        tokio::task::spawn_blocking(move || {
887            let mut txn = backend.begin_write()?;
888            for block in &blocks {
889                let hash = block.header.hash();
890                let hash_key = hash.encode_to_vec();
891                txn.put(
892                    BODIES,
893                    &hash_key,
894                    &BlockBodyRLP::from(block.body.clone()).into_vec(),
895                )?;
896                for (index, receipt) in block.receipts.iter().enumerate() {
897                    txn.put(
898                        RECEIPTS_V2,
899                        &receipt_key(&hash, index as u64),
900                        &receipt.encode_storage(),
901                    )?;
902                }
903                if block.index_transactions {
904                    for (index, transaction) in block.body.transactions.iter().enumerate() {
905                        txn.merge(
906                            TRANSACTION_LOCATIONS,
907                            transaction.hash(&NativeCrypto).as_bytes(),
908                            &encode_tx_location_operand(block.header.number, hash, index as u64),
909                        )?;
910                    }
911                }
912            }
913            txn.put(
914                CHAIN_DATA,
915                &chain_data_key(ChainDataIndex::EarliestBlockNumber),
916                &new_earliest.to_le_bytes(),
917            )?;
918            if let Some(floor) = tx_index_floor {
919                txn.put(
920                    CHAIN_DATA,
921                    &chain_data_key(ChainDataIndex::TxIndexFloor),
922                    &floor.to_le_bytes(),
923                )?;
924            }
925            txn.commit()
926        })
927        .await
928        .map_err(|e| StoreError::Custom(format!("Backfill write task panicked: {e}")))?
929    }
930
931    /// RocksDB observability snapshot (per-column-family sizes/keys/files, block
932    /// cache, compaction). `None` for the in-memory backend. Read by the metrics
933    /// collector; cheap (RocksDB property reads).
934    pub fn rocksdb_stats(&self) -> Option<crate::api::RocksDbStats> {
935        self.backend.db_stats()
936    }
937
938    /// Obtain canonical block body
939    pub async fn get_block_body(
940        &self,
941        block_number: BlockNumber,
942    ) -> Result<Option<BlockBody>, StoreError> {
943        let Some(block_hash) = self.get_canonical_block_hash_sync(block_number)? else {
944            return Ok(None);
945        };
946
947        self.get_block_body_by_hash(block_hash).await
948    }
949
950    /// Remove canonical block
951    pub async fn remove_block(&self, block_number: BlockNumber) -> Result<(), StoreError> {
952        let Some(hash) = self.get_canonical_block_hash_sync(block_number)? else {
953            return Ok(());
954        };
955
956        let backend = self.backend.clone();
957        tokio::task::spawn_blocking(move || {
958            let hash_key = hash.encode_to_vec();
959
960            let mut txn = backend.begin_write()?;
961            txn.delete(
962                CANONICAL_BLOCK_HASHES,
963                block_number.to_le_bytes().as_slice(),
964            )?;
965            txn.delete(BODIES, &hash_key)?;
966            txn.delete(HEADERS, &hash_key)?;
967            txn.delete(BLOCK_NUMBERS, &hash_key)?;
968            txn.commit()
969        })
970        .await
971        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
972    }
973
974    /// Obtain canonical block bodies in from..=to
975    pub async fn get_block_bodies(
976        &self,
977        from: BlockNumber,
978        to: BlockNumber,
979    ) -> Result<Vec<Option<BlockBody>>, StoreError> {
980        // TODO: Implement read bulk
981        let buffer = self.buffer()?;
982        let backend = self.backend.clone();
983        tokio::task::spawn_blocking(move || {
984            let numbers: Vec<BlockNumber> = (from..=to).collect();
985            let mut block_bodies = Vec::new();
986
987            let txn = backend.begin_read()?;
988            for number in numbers {
989                let Some(hash) = txn
990                    .get(CANONICAL_BLOCK_HASHES, number.to_le_bytes().as_slice())?
991                    .map(|bytes| H256::decode(bytes.as_slice()))
992                    .transpose()?
993                else {
994                    block_bodies.push(None);
995                    continue;
996                };
997                // Consult the in-memory buffer first so a not-yet-flushed body
998                // is not reported as missing (mirrors get_block_bodies_by_hash).
999                if let Some(body) = buffer.get_body(&hash) {
1000                    block_bodies.push(Some(body));
1001                    continue;
1002                }
1003                let hash_key = hash.encode_to_vec();
1004                let block_body_opt = txn
1005                    .get(BODIES, &hash_key)?
1006                    .map(|bytes| BlockBodyRLP::from_bytes(bytes).to())
1007                    .transpose()
1008                    .map_err(StoreError::from)?;
1009
1010                block_bodies.push(block_body_opt);
1011            }
1012
1013            Ok(block_bodies)
1014        })
1015        .await
1016        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
1017    }
1018
1019    /// Obtain block bodies from a list of hashes
1020    pub async fn get_block_bodies_by_hash(
1021        &self,
1022        hashes: Vec<BlockHash>,
1023    ) -> Result<Vec<BlockBody>, StoreError> {
1024        let buffer = self.buffer()?;
1025        let backend = self.backend.clone();
1026        // TODO: Implement read bulk
1027        tokio::task::spawn_blocking(move || {
1028            let txn = backend.begin_read()?;
1029            let mut block_bodies = Vec::new();
1030            for hash in hashes {
1031                // Consult the in-memory buffer first, like the single-hash reader,
1032                // so a not-yet-flushed body is not reported as missing.
1033                if let Some(body) = buffer.get_body(&hash) {
1034                    block_bodies.push(body);
1035                    continue;
1036                }
1037                let hash_key = hash.encode_to_vec();
1038
1039                let Some(block_body) = txn
1040                    .get(BODIES, &hash_key)?
1041                    .map(|bytes| BlockBodyRLP::from_bytes(bytes).to())
1042                    .transpose()
1043                    .map_err(StoreError::from)?
1044                else {
1045                    return Err(StoreError::Custom(format!(
1046                        "Block body not found for hash: {hash}"
1047                    )));
1048                };
1049                block_bodies.push(block_body);
1050            }
1051            Ok(block_bodies)
1052        })
1053        .await
1054        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
1055    }
1056
1057    /// Obtain any block body using the hash
1058    pub async fn get_block_body_by_hash(
1059        &self,
1060        block_hash: BlockHash,
1061    ) -> Result<Option<BlockBody>, StoreError> {
1062        if let Some(b) = self.buffer()?.get_body(&block_hash) {
1063            return Ok(Some(b));
1064        }
1065        self.read_async(BODIES, block_hash.encode_to_vec())
1066            .await?
1067            .map(|bytes| BlockBodyRLP::from_bytes(bytes).to())
1068            .transpose()
1069            .map_err(StoreError::from)
1070    }
1071
1072    pub fn get_block_header_by_hash(
1073        &self,
1074        block_hash: BlockHash,
1075    ) -> Result<Option<BlockHeader>, StoreError> {
1076        let latest = self.latest_block_header.get();
1077        if block_hash == latest.hash() {
1078            return Ok(Some((*latest).clone()));
1079        }
1080        if let Some(h) = self.buffer()?.get_header(&block_hash) {
1081            return Ok(Some(h));
1082        }
1083        self.load_block_header_by_hash(block_hash)
1084    }
1085
1086    pub fn add_pending_block(&self, block: Block) -> Result<(), StoreError> {
1087        let block_hash = block.hash();
1088        let block_value = BlockRLP::from(block).into_vec();
1089        self.write(PENDING_BLOCKS, block_hash.as_bytes().to_vec(), block_value)
1090    }
1091
1092    pub async fn get_pending_block(
1093        &self,
1094        block_hash: BlockHash,
1095    ) -> Result<Option<Block>, StoreError> {
1096        self.read_async(PENDING_BLOCKS, block_hash.as_bytes().to_vec())
1097            .await?
1098            .map(|bytes| BlockRLP::from_bytes(bytes).to())
1099            .transpose()
1100            .map_err(StoreError::from)
1101    }
1102
1103    /// Add block number for a given hash
1104    pub async fn add_block_number(
1105        &self,
1106        block_hash: BlockHash,
1107        block_number: BlockNumber,
1108    ) -> Result<(), StoreError> {
1109        let number_value = block_number.to_le_bytes().to_vec();
1110        self.write_async(BLOCK_NUMBERS, block_hash.encode_to_vec(), number_value)
1111            .await
1112    }
1113
1114    /// Obtain block number for a given hash
1115    pub async fn get_block_number(
1116        &self,
1117        block_hash: BlockHash,
1118    ) -> Result<Option<BlockNumber>, StoreError> {
1119        if let Some(n) = self.buffer()?.get_number(&block_hash) {
1120            return Ok(Some(n));
1121        }
1122        self.read_async(BLOCK_NUMBERS, block_hash.encode_to_vec())
1123            .await?
1124            .map(decode_block_number)
1125            .transpose()
1126    }
1127
1128    /// Whether the transaction index holds `transaction_hash` for the block `block_hash`.
1129    ///
1130    /// Unlike [`Self::get_transaction_location`] this does not ask whether the block is
1131    /// canonical, so the answer does not change while a forkchoice update is written.
1132    pub async fn is_transaction_indexed_in(
1133        &self,
1134        transaction_hash: H256,
1135        block_hash: BlockHash,
1136    ) -> Result<bool, StoreError> {
1137        let buffered = self.buffer()?.get_tx_locations(&transaction_hash);
1138        if buffered.iter().any(|(_, hash, _)| *hash == block_hash) {
1139            return Ok(true);
1140        }
1141        // The buffer is read first: a flush commits to disk before it evicts, so an
1142        // entry that has left the buffer since is on disk by now.
1143        let db = self.backend.clone();
1144        tokio::task::spawn_blocking(move || {
1145            let tx = db.begin_read()?;
1146            let Some(bytes) = tx.get(TRANSACTION_LOCATIONS, transaction_hash.as_bytes())? else {
1147                return Ok(false);
1148            };
1149            let locations = <Vec<(BlockNumber, BlockHash, Index)>>::decode(&bytes)?;
1150            Ok(locations.iter().any(|(_, hash, _)| *hash == block_hash))
1151        })
1152        .await
1153        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
1154    }
1155
1156    /// Store transaction location (block number and index of the transaction within the block)
1157    pub async fn add_transaction_location(
1158        &self,
1159        transaction_hash: H256,
1160        block_number: BlockNumber,
1161        block_hash: BlockHash,
1162        index: Index,
1163    ) -> Result<(), StoreError> {
1164        self.add_transaction_locations(vec![(transaction_hash, block_number, block_hash, index)])
1165            .await
1166    }
1167
1168    /// Store transaction locations in batch (one db transaction for all)
1169    pub async fn add_transaction_locations(
1170        &self,
1171        locations: Vec<(H256, BlockNumber, BlockHash, Index)>,
1172    ) -> Result<(), StoreError> {
1173        let db = self.backend.clone();
1174        tokio::task::spawn_blocking(move || {
1175            let mut tx = db.begin_write()?;
1176            for (tx_hash, block_number, block_hash, index) in locations {
1177                tx.merge(
1178                    TRANSACTION_LOCATIONS,
1179                    tx_hash.as_bytes(),
1180                    &encode_tx_location_operand(block_number, block_hash, index),
1181                )?;
1182            }
1183            tx.commit()
1184        })
1185        .await
1186        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
1187    }
1188
1189    /// Obtain transaction location (block hash and index)
1190    pub async fn get_transaction_location(
1191        &self,
1192        transaction_hash: H256,
1193    ) -> Result<Option<(BlockNumber, BlockHash, Index)>, StoreError> {
1194        let buffered = self.buffer()?.get_tx_locations(&transaction_hash);
1195        let db = self.backend.clone();
1196        tokio::task::spawn_blocking(move || {
1197            let tx = db.begin_read()?;
1198            let mut locations = buffered;
1199            if let Some(bytes) = tx.get(TRANSACTION_LOCATIONS, transaction_hash.as_bytes())? {
1200                locations.extend(<Vec<(BlockNumber, BlockHash, Index)>>::decode(&bytes)?);
1201            }
1202            for (block_number, block_hash, index) in locations {
1203                let canonical_hash = tx
1204                    .get(
1205                        CANONICAL_BLOCK_HASHES,
1206                        block_number.to_le_bytes().as_slice(),
1207                    )?
1208                    .map(|bytes| H256::decode(bytes.as_slice()))
1209                    .transpose()?;
1210                if canonical_hash == Some(block_hash) {
1211                    return Ok(Some((block_number, block_hash, index)));
1212                }
1213            }
1214            Ok(None)
1215        })
1216        .await
1217        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
1218    }
1219
1220    /// Add receipt
1221    pub async fn add_receipt(
1222        &self,
1223        block_hash: BlockHash,
1224        index: Index,
1225        receipt: Receipt,
1226    ) -> Result<(), StoreError> {
1227        let key = receipt_key(&block_hash, index);
1228        // Storage codec (NOT wire/consensus): preserves frame-receipt
1229        // `succeeded` + aggregated logs; identical to encode_to_vec for
1230        // non-frame receipts.
1231        let value = receipt.encode_storage();
1232        self.write_async(RECEIPTS_V2, key, value).await
1233    }
1234
1235    /// Add receipts
1236    pub async fn add_receipts(
1237        &self,
1238        block_hash: BlockHash,
1239        receipts: Vec<Receipt>,
1240    ) -> Result<(), StoreError> {
1241        let batch_items: Vec<_> = receipts
1242            .into_iter()
1243            .enumerate()
1244            .map(|(index, receipt)| {
1245                let key = receipt_key(&block_hash, index as u64);
1246                let value = receipt.encode_storage();
1247                (key, value)
1248            })
1249            .collect();
1250        self.write_batch_async(RECEIPTS_V2, batch_items).await
1251    }
1252
1253    /// Obtain receipt for a canonical block represented by the block number.
1254    pub async fn get_receipt(
1255        &self,
1256        block_number: BlockNumber,
1257        index: Index,
1258    ) -> Result<Option<Receipt>, StoreError> {
1259        // FIXME (#4353)
1260        let Some(block_hash) = self.get_canonical_block_hash(block_number).await? else {
1261            return Ok(None);
1262        };
1263        self.get_receipt_by_block_hash(block_hash, index).await
1264    }
1265
1266    /// Obtain receipt by block hash and index
1267    async fn get_receipt_by_block_hash(
1268        &self,
1269        block_hash: BlockHash,
1270        index: Index,
1271    ) -> Result<Option<Receipt>, StoreError> {
1272        if let Some(r) = self.buffer()?.get_receipt(&block_hash, index) {
1273            return Ok(Some(r));
1274        }
1275        let key = receipt_key(&block_hash, index);
1276        self.read_async(RECEIPTS_V2, key)
1277            .await?
1278            .map(|bytes| Receipt::decode_storage(bytes.as_slice()))
1279            .transpose()
1280            .map_err(StoreError::from)
1281    }
1282
1283    /// Capacity of the bytecode cache, in [`Code::size`] bytes, which is how much
1284    /// bytecode this node is configured to keep resident and so bounds what a block warm
1285    /// reads speculatively.
1286    ///
1287    /// A poisoned cache reports zero, which stops warming rather than warming into a
1288    /// cache no reader can reach.
1289    pub fn code_cache_budget_bytes(&self) -> u64 {
1290        self.account_code_cache
1291            .lock()
1292            .map(|cache| cache.max_size)
1293            .unwrap_or(0)
1294    }
1295
1296    /// Get account code by its hash.
1297    ///
1298    /// Checks the in-memory block-data buffer first, then the bytecode cache
1299    /// (`account_code_cache`), and finally the database.  Code that has been
1300    /// inserted via `engine_newPayload` but not yet flushed to disk is therefore
1301    /// visible to callers without an explicit flush.
1302    pub fn get_account_code(&self, code_hash: H256) -> Result<Option<Code>, StoreError> {
1303        if let Some(code) = self.buffer()?.get_code(&code_hash) {
1304            return Ok(Some(code));
1305        }
1306        // check cache first
1307        if let Some(code) = self
1308            .account_code_cache
1309            .lock()
1310            .map_err(|_| StoreError::LockError)?
1311            .get(&code_hash)?
1312        {
1313            return Ok(Some(code));
1314        }
1315
1316        let Some(bytes) = self
1317            .backend
1318            .begin_read()?
1319            .get(ACCOUNT_CODES, code_hash.as_bytes())?
1320        else {
1321            return Ok(None);
1322        };
1323        let (bytecode_slice, jumpdests) = decode_bytes(&bytes)?;
1324        let (jumpdests, was_legacy) = decode_jumpdests(bytecode_slice, jumpdests)?;
1325        let code = Code::from_parts_unchecked(code_hash, bytecode_slice, jumpdests);
1326
1327        // Self-heal a legacy (pre-bitmap) row so the jumpdest recompute above is
1328        // paid at most once. Fire-and-forget, and only when a Tokio runtime is
1329        // reachable: this read runs on rayon execution-path workers, where
1330        // `spawn` would panic. Skipping just leaves the next read to recompute
1331        // again; there is no correctness dependency (matches the code-metadata
1332        // backfill in `get_code_metadata`).
1333        if was_legacy && let Ok(handle) = tokio::runtime::Handle::try_current() {
1334            let buf = encode_code(&code);
1335            let hash_key = code_hash.0.to_vec();
1336            let backend = self.backend.clone();
1337            handle.spawn(async move {
1338                if let Err(e) = async {
1339                    let mut tx = backend.begin_write()?;
1340                    tx.put(ACCOUNT_CODES, &hash_key, &buf)?;
1341                    tx.commit()
1342                }
1343                .await
1344                {
1345                    tracing::warn!("Failed to rewrite legacy jumpdests during backfill: {e}");
1346                }
1347            });
1348        }
1349
1350        // insert into cache and evict if needed
1351        self.account_code_cache
1352            .lock()
1353            .map_err(|_| StoreError::LockError)?
1354            .insert(&code)?;
1355
1356        Ok(Some(code))
1357    }
1358
1359    /// Batched [`Self::get_account_code`].
1360    ///
1361    /// Resolves the buffer and the bytecode cache first, then reads whatever is left by whichever
1362    /// of two strategies gets more of those reads in flight for a batch this size: a
1363    /// parallel fan-out of point gets, or sorted keys split into contiguous shards read
1364    /// concurrently. See the comment on the read below for how the choice is made. The
1365    /// cache is locked once for the whole batch rather than twice per code.
1366    ///
1367    /// Results are returned in the order of `code_hashes`. Duplicate hashes are read
1368    /// once. `None` means the hash is absent from the database.
1369    ///
1370    /// Every requested code is held at once until the result is dropped, and nothing here
1371    /// bounds that by the code cache budget: a caller reading many contracts it does not
1372    /// control must chunk `code_hashes` and charge each chunk against its own budget.
1373    pub fn get_account_codes_batch(
1374        &self,
1375        code_hashes: &[H256],
1376    ) -> Result<Vec<Option<Code>>, StoreError> {
1377        let mut out: Vec<Option<Code>> = vec![None; code_hashes.len()];
1378        // Positions to fill per distinct hash, so a repeated hash costs one read.
1379        let mut pending: HashMap<H256, Vec<usize>> = HashMap::new();
1380
1381        {
1382            let buffer = self.buffer()?;
1383            let cache = self
1384                .account_code_cache
1385                .lock()
1386                .map_err(|_| StoreError::LockError)?;
1387            for (i, hash) in code_hashes.iter().enumerate() {
1388                if let Some(code) = buffer.get_code(hash) {
1389                    out[i] = Some(code);
1390                } else if let Some(code) = cache.get(hash)? {
1391                    out[i] = Some(code);
1392                } else {
1393                    pending.entry(*hash).or_default().push(i);
1394                }
1395            }
1396        }
1397
1398        if pending.is_empty() {
1399            return Ok(out);
1400        }
1401
1402        let mut missing: Vec<H256> = pending.keys().copied().collect();
1403        missing.sort_unstable();
1404
1405        // Cold blob reads here are latency-bound, so what matters is how many are in
1406        // flight. Two ways to get there, and which one wins depends on the batch size:
1407        //
1408        // * A parallel fan-out of point gets reaches queue depth ~= core count. Cheap
1409        //   for any batch: rayon's pool is already warm.
1410        // * Contiguous shards of the SORTED keys, one blocking thread each, reach queue
1411        //   depth ~= shard count and share RocksDB blocks within a shard. This is the
1412        //   only way past core count (async_io is OFF in this build, so a single
1413        //   `multi_get` runs the whole batch at queue depth 1), but it pays a thread
1414        //   spawn per shard.
1415        //
1416        // So shard only once sharding can actually beat the fan-out, i.e. once the batch
1417        // is wide enough to form more shards than there are cores. Below that the
1418        // fan-out is both deeper and cheaper, and a single serial `multi_get` would be
1419        // far worse than either.
1420        //
1421        // The shard cap has to sit above the core count, or on a host with at least that
1422        // many cores the fan-out would always win and this path would be unreachable.
1423        // Twice the cores guarantees that, with a floor so a small host keeps the depth
1424        // it can already reach: these threads block on I/O rather than compute, so more
1425        // of them than cores is the point.
1426        const KEYS_PER_SHARD: usize = 256;
1427        const MIN_SHARD_CAP: usize = 64;
1428        let parallelism = std::thread::available_parallelism().map_or(8, |p| p.get());
1429        let max_shards = parallelism.saturating_mul(2).max(MIN_SHARD_CAP);
1430        let shards = missing.len().div_ceil(KEYS_PER_SHARD).min(max_shards);
1431        let read_view = self.backend.begin_read()?;
1432        // Both paths decode in whatever thread did the read, so rebuilding the jumpdest
1433        // bitmap for a legacy entry stays off the caller's thread and stays parallel.
1434        let decode = |hash: &H256, value: Option<Vec<u8>>| -> Result<Option<Code>, StoreError> {
1435            let Some(bytes) = value else { return Ok(None) };
1436            let (bytecode_slice, jumpdests) = decode_bytes(&bytes)?;
1437            // This is the bulk prefetch warm path; a legacy row is recomputed here
1438            // and self-healed later when `get_account_code` reads it on the hot path.
1439            let (jumpdests, _was_legacy) = decode_jumpdests(bytecode_slice, jumpdests)?;
1440            Ok(Some(Code::from_parts_unchecked(
1441                *hash,
1442                bytecode_slice,
1443                jumpdests,
1444            )))
1445        };
1446        let decoded: Vec<Result<Option<Code>, StoreError>> = if shards > parallelism {
1447            let chunk = missing.len().div_ceil(shards);
1448            let rv = read_view.as_ref();
1449            let read_shard = |hashes: &[H256]| -> Vec<Result<Option<Code>, StoreError>> {
1450                let keys: Vec<&[u8]> = hashes.iter().map(|h| h.as_bytes()).collect();
1451                rv.multi_get(ACCOUNT_CODES, &keys)
1452                    .into_iter()
1453                    .zip(hashes.iter())
1454                    .map(|(value, hash)| decode(hash, value?))
1455                    .collect()
1456            };
1457            std::thread::scope(|scope| {
1458                let handles: Vec<_> = missing
1459                    .chunks(chunk)
1460                    .map(|ck| (ck, scope.spawn(move || read_shard(ck))))
1461                    .collect();
1462                handles
1463                    .into_iter()
1464                    .flat_map(|(shard, handle)| {
1465                        // A panicked shard becomes an `Err` per key it covered, keeping
1466                        // the results aligned with `missing` and leaving the caller's
1467                        // best-effort handling to decide. Re-panicking here would
1468                        // escalate a warm into taking down whatever runs it.
1469                        handle.join().unwrap_or_else(|_| {
1470                            shard
1471                                .iter()
1472                                .map(|_| {
1473                                    Err(StoreError::Custom(
1474                                        "account code shard panicked".to_string(),
1475                                    ))
1476                                })
1477                                .collect()
1478                        })
1479                    })
1480                    .collect()
1481            })
1482        } else {
1483            // One key per read, so `get` rather than a single-key `multi_get`: the
1484            // batched call sets up its own result buffers, which is pure overhead here.
1485            let rv = read_view.as_ref();
1486            missing
1487                .par_iter()
1488                .map(|hash| decode(hash, rv.get(ACCOUNT_CODES, hash.as_bytes())?))
1489                .collect()
1490        };
1491
1492        let mut fetched: Vec<Code> = Vec::new();
1493        for (hash, code) in missing.iter().zip(decoded.into_iter()) {
1494            let Some(code) = code? else { continue };
1495            for &i in pending.get(hash).into_iter().flatten() {
1496                out[i] = Some(code.clone());
1497            }
1498            fetched.push(code);
1499        }
1500
1501        if !fetched.is_empty() {
1502            let mut cache = self
1503                .account_code_cache
1504                .lock()
1505                .map_err(|_| StoreError::LockError)?;
1506            for code in &fetched {
1507                cache.insert(code)?;
1508            }
1509        }
1510
1511        Ok(out)
1512    }
1513
1514    /// Check if account code exists by its hash, without constructing the full `Code` struct.
1515    /// More efficient than `get_account_code` for existence checks since it skips
1516    /// RLP decoding and `Code` struct construction (no jumpdest-bitmap decoding).
1517    /// Note: The underlying `get()` still reads the value from RocksDB (including blob files).
1518    pub fn code_exists(&self, code_hash: H256) -> Result<bool, StoreError> {
1519        // Code introduced by a not-yet-flushed block lives only in the buffer; check
1520        // it first so a contract created in the current block is visible (matches
1521        // get_account_code / get_code_metadata).
1522        if self.buffer()?.get_code(&code_hash).is_some() {
1523            return Ok(true);
1524        }
1525        // Check cache first
1526        if self
1527            .account_code_cache
1528            .lock()
1529            .map_err(|_| StoreError::LockError)?
1530            .contains(&code_hash)
1531        {
1532            return Ok(true);
1533        }
1534        // Check DB without reading the full value
1535        Ok(self
1536            .backend
1537            .begin_read()?
1538            .get(ACCOUNT_CODES, code_hash.as_bytes())?
1539            .is_some())
1540    }
1541
1542    /// Get code metadata (length) by its hash.
1543    ///
1544    /// Checks cache first, falls back to database. If metadata is missing,
1545    /// falls back to loading full code and extracts length (auto-migration).
1546    pub fn get_code_metadata(&self, code_hash: H256) -> Result<Option<CodeMetadata>, StoreError> {
1547        use ethrex_common::constants::EMPTY_KECCAK_HASH;
1548
1549        // Empty code special case
1550        if code_hash == *EMPTY_KECCAK_HASH {
1551            return Ok(Some(CodeMetadata { length: 0 }));
1552        }
1553
1554        // Check cache first
1555        if let Some(metadata) = self
1556            .code_metadata_cache
1557            .lock()
1558            .map_err(|_| StoreError::LockError)?
1559            .get(&code_hash)
1560            .copied()
1561        {
1562            return Ok(Some(metadata));
1563        }
1564
1565        // Try reading from metadata table
1566        let metadata = if let Some(bytes) = self
1567            .backend
1568            .begin_read()?
1569            .get(ACCOUNT_CODE_METADATA, code_hash.as_bytes())?
1570        {
1571            let length =
1572                u64::from_be_bytes(bytes.try_into().map_err(|_| {
1573                    StoreError::Custom("Invalid metadata length encoding".to_string())
1574                })?);
1575            CodeMetadata { length }
1576        } else {
1577            // Fallback: load full code and extract length (auto-migration)
1578            let Some(code) = self.get_account_code(code_hash)? else {
1579                return Ok(None);
1580            };
1581            let metadata = CodeMetadata {
1582                length: code.len() as u64,
1583            };
1584
1585            // Backfill the row for future reads, fire and forget.
1586            //
1587            // Only when a Tokio runtime is reachable: this read is on the execution
1588            // path (`EXTCODESIZE`), which runs on rayon workers, and
1589            // `tokio::task::spawn` panics outside a runtime. Skipping the backfill
1590            // costs one code read the next time that hash is asked for; panicking
1591            // would take the node down.
1592            if let Ok(handle) = tokio::runtime::Handle::try_current() {
1593                let metadata_buf = metadata.length.to_be_bytes().to_vec();
1594                let hash_key = code_hash.0.to_vec();
1595                let backend = self.backend.clone();
1596                handle.spawn(async move {
1597                    if let Err(e) = async {
1598                        let mut tx = backend.begin_write()?;
1599                        tx.put(ACCOUNT_CODE_METADATA, &hash_key, &metadata_buf)?;
1600                        tx.commit()
1601                    }
1602                    .await
1603                    {
1604                        tracing::warn!("Failed to write code metadata during backfill: {}", e);
1605                    }
1606                });
1607            }
1608
1609            metadata
1610        };
1611
1612        // Update cache
1613        self.code_metadata_cache
1614            .lock()
1615            .map_err(|_| StoreError::LockError)?
1616            .put(code_hash, metadata);
1617
1618        Ok(Some(metadata))
1619    }
1620
1621    /// Add account code
1622    pub async fn add_account_code(&self, code: Code) -> Result<(), StoreError> {
1623        let hash_key = code.hash.0.to_vec();
1624        let buf = encode_code(&code);
1625        let metadata_buf = (code.len() as u64).to_be_bytes();
1626
1627        // Write both code and metadata atomically
1628        let backend = self.backend.clone();
1629        tokio::task::spawn_blocking(move || {
1630            let mut tx = backend.begin_write()?;
1631            tx.put(ACCOUNT_CODES, &hash_key, &buf)?;
1632            tx.put(ACCOUNT_CODE_METADATA, &hash_key, &metadata_buf)?;
1633            tx.commit()
1634        })
1635        .await
1636        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
1637    }
1638
1639    /// Clears all checkpoint data created during the last snap sync
1640    pub async fn clear_snap_state(&self) -> Result<(), StoreError> {
1641        let db = self.backend.clone();
1642        tokio::task::spawn_blocking(move || db.clear_table(SNAP_STATE))
1643            .await
1644            .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
1645    }
1646
1647    pub async fn get_transaction_by_hash(
1648        &self,
1649        transaction_hash: H256,
1650    ) -> Result<Option<Transaction>, StoreError> {
1651        let (_block_number, block_hash, index) =
1652            match self.get_transaction_location(transaction_hash).await? {
1653                Some(location) => location,
1654                None => return Ok(None),
1655            };
1656        self.get_transaction_by_location(block_hash, index).await
1657    }
1658
1659    pub async fn get_transaction_by_location(
1660        &self,
1661        block_hash: H256,
1662        index: u64,
1663    ) -> Result<Option<Transaction>, StoreError> {
1664        let index: usize = index.try_into()?;
1665        if let Some(transaction) = self.buffer()?.get_transaction(&block_hash, index) {
1666            return Ok(transaction);
1667        }
1668        let Some(body) = self.read_async(BODIES, block_hash.encode_to_vec()).await? else {
1669            return Ok(None);
1670        };
1671        Ok(decode_body_transaction(&body, index)?)
1672    }
1673
1674    pub async fn get_block_by_hash(
1675        &self,
1676        block_hash: BlockHash,
1677    ) -> Result<Option<Block>, StoreError> {
1678        let header = match self.get_block_header_by_hash(block_hash)? {
1679            Some(header) => header,
1680            None => return Ok(None),
1681        };
1682        let body = match self.get_block_body_by_hash(block_hash).await? {
1683            Some(body) => body,
1684            None => return Ok(None),
1685        };
1686        Ok(Some(Block::new(header, body)))
1687    }
1688
1689    pub async fn get_block_by_number(
1690        &self,
1691        block_number: BlockNumber,
1692    ) -> Result<Option<Block>, StoreError> {
1693        let Some(block_hash) = self.get_canonical_block_hash(block_number).await? else {
1694            return Ok(None);
1695        };
1696        self.get_block_by_hash(block_hash).await
1697    }
1698
1699    // Get the canonical block hash for a given block number.
1700    pub async fn get_canonical_block_hash(
1701        &self,
1702        block_number: BlockNumber,
1703    ) -> Result<Option<BlockHash>, StoreError> {
1704        let last = self.latest_block_header.get();
1705        if last.number == block_number {
1706            return Ok(Some(last.hash()));
1707        }
1708        let backend = self.backend.clone();
1709        tokio::task::spawn_blocking(move || {
1710            backend
1711                .begin_read()?
1712                .get(
1713                    CANONICAL_BLOCK_HASHES,
1714                    block_number.to_le_bytes().as_slice(),
1715                )?
1716                .map(|bytes| H256::decode(bytes.as_slice()))
1717                .transpose()
1718                .map_err(StoreError::from)
1719        })
1720        .await
1721        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
1722    }
1723
1724    /// Stores the chain configuration values, should only be called once after reading the genesis file
1725    /// Ignores previously stored values if present
1726    pub async fn set_chain_config(&mut self, chain_config: &ChainConfig) -> Result<(), StoreError> {
1727        self.chain_config = *chain_config;
1728        let key = chain_data_key(ChainDataIndex::ChainConfig);
1729        let value = serde_json::to_string(chain_config)
1730            .map_err(|_| StoreError::Custom("Failed to serialize chain config".to_string()))?
1731            .into_bytes();
1732        self.write_async(CHAIN_DATA, key, value).await
1733    }
1734
1735    /// Update earliest block number
1736    pub async fn update_earliest_block_number(
1737        &self,
1738        block_number: BlockNumber,
1739    ) -> Result<(), StoreError> {
1740        let key = chain_data_key(ChainDataIndex::EarliestBlockNumber);
1741        let value = block_number.to_le_bytes().to_vec();
1742        self.write_async(CHAIN_DATA, key, value).await
1743    }
1744
1745    /// Reads a block number stored under the given chain-data index.
1746    async fn read_chain_data_block_number(
1747        &self,
1748        index: ChainDataIndex,
1749    ) -> Result<Option<BlockNumber>, StoreError> {
1750        self.read_async(CHAIN_DATA, chain_data_key(index))
1751            .await?
1752            .map(decode_block_number)
1753            .transpose()
1754    }
1755
1756    /// Obtain earliest block number
1757    pub async fn get_earliest_block_number(&self) -> Result<BlockNumber, StoreError> {
1758        self.read_chain_data_block_number(ChainDataIndex::EarliestBlockNumber)
1759            .await?
1760            .ok_or(StoreError::MissingEarliestBlockNumber)
1761    }
1762
1763    /// Lowest block from which every stored block is in the transaction index, if backfill skipped any.
1764    pub async fn get_tx_index_floor(&self) -> Result<Option<BlockNumber>, StoreError> {
1765        self.read_chain_data_block_number(ChainDataIndex::TxIndexFloor)
1766            .await
1767    }
1768
1769    /// Whether the history bounds (`earliest_block_number` and the transaction index
1770    /// floor) were tracked since the database was created, or have been reconciled
1771    /// since. A database created before they were tracked holds stale ones until then.
1772    /// The marker is not cleared if a release from before it backfills the database
1773    /// afterwards.
1774    pub async fn history_bounds_reconciled(&self) -> Result<bool, StoreError> {
1775        Ok(self
1776            .read_chain_data_block_number(ChainDataIndex::HistoryBoundsReconciled)
1777            .await?
1778            .is_some())
1779    }
1780
1781    /// Marks the history bounds as reconciled, recording the transaction index floor
1782    /// if the reconciliation found one.
1783    pub async fn mark_history_bounds_reconciled(
1784        &self,
1785        tx_index_floor: Option<BlockNumber>,
1786    ) -> Result<(), StoreError> {
1787        let backend = self.backend.clone();
1788        tokio::task::spawn_blocking(move || {
1789            let mut txn = backend.begin_write()?;
1790            if let Some(floor) = tx_index_floor {
1791                txn.put(
1792                    CHAIN_DATA,
1793                    &chain_data_key(ChainDataIndex::TxIndexFloor),
1794                    &floor.to_le_bytes(),
1795                )?;
1796            }
1797            txn.put(
1798                CHAIN_DATA,
1799                &chain_data_key(ChainDataIndex::HistoryBoundsReconciled),
1800                &1u64.to_le_bytes(),
1801            )?;
1802            txn.commit()
1803        })
1804        .await
1805        .map_err(|e| StoreError::Custom(format!("History bounds write task panicked: {e}")))?
1806    }
1807
1808    /// Obtain finalized block number
1809    pub async fn get_finalized_block_number(&self) -> Result<Option<BlockNumber>, StoreError> {
1810        self.read_chain_data_block_number(ChainDataIndex::FinalizedBlockNumber)
1811            .await
1812    }
1813
1814    /// Obtain safe block number
1815    pub async fn get_safe_block_number(&self) -> Result<Option<BlockNumber>, StoreError> {
1816        self.read_chain_data_block_number(ChainDataIndex::SafeBlockNumber)
1817            .await
1818    }
1819
1820    /// Obtain latest block number
1821    pub fn get_latest_block_number(&self) -> Result<BlockNumber, StoreError> {
1822        Ok(self.latest_block_header.get().number)
1823    }
1824
1825    /// Wakes the receivers of [`Self::sync_status_changes`].
1826    pub fn notify_sync_status_changed(&self) {
1827        self.sync_status_changed.send_replace(());
1828    }
1829
1830    /// Resolves `changed()` after each [`Self::notify_sync_status_changed`];
1831    /// signals sent before it is awaited collapse into one.
1832    pub fn sync_status_changes(&self) -> tokio::sync::watch::Receiver<()> {
1833        self.sync_status_changed.subscribe()
1834    }
1835
1836    /// Update pending block number
1837    pub async fn update_pending_block_number(
1838        &self,
1839        block_number: BlockNumber,
1840    ) -> Result<(), StoreError> {
1841        let key = chain_data_key(ChainDataIndex::PendingBlockNumber);
1842        let value = block_number.to_le_bytes().to_vec();
1843        self.write_async(CHAIN_DATA, key, value).await
1844    }
1845
1846    /// Obtain pending block number
1847    pub async fn get_pending_block_number(&self) -> Result<Option<BlockNumber>, StoreError> {
1848        self.read_chain_data_block_number(ChainDataIndex::PendingBlockNumber)
1849            .await
1850    }
1851
1852    /// DB mutation step of `forkchoice_update`.
1853    ///
1854    /// Callers MUST hold `fcu_lock` (only `forkchoice_update` should invoke this).
1855    /// The read of `LatestBlockNumber` below happens outside the write
1856    /// transaction and would be a TOCTOU window without that serialization.
1857    /// Applies a fork-choice update atomically: writes canonical hashes, latest/safe/
1858    /// finalized numbers, and prunes the state-history journal up to the new finalized.
1859    ///
1860    /// **Concurrency:** This function must be called with exclusive access. In
1861    /// production it is gated by `fcu_lock` from [`forkchoice_update`]. The
1862    /// pre-finalized read used to decide journal pruning happens outside the write
1863    /// transaction; without serialization, two concurrent callers could race on
1864    /// `prev_finalized` and double-prune. Tests that call this directly must not
1865    /// run concurrently with another FCU.
1866    async fn forkchoice_update_inner(
1867        &self,
1868        new_canonical_blocks: Vec<(BlockNumber, BlockHash)>,
1869        head_number: BlockNumber,
1870        head_hash: BlockHash,
1871        safe: Option<BlockNumber>,
1872        finalized: Option<BlockNumber>,
1873    ) -> Result<(), StoreError> {
1874        let latest = self.load_latest_block_number().await?.unwrap_or(0);
1875        let db = self.backend.clone();
1876        let journal_pruning_paused = self.journal_pruning_paused.clone();
1877        tokio::task::spawn_blocking(move || {
1878            let mut txn = db.begin_write()?;
1879
1880            for (block_number, block_hash) in new_canonical_blocks {
1881                let head_key = block_number.to_le_bytes();
1882                let head_value = block_hash.encode_to_vec();
1883                txn.put(CANONICAL_BLOCK_HASHES, &head_key, &head_value)?;
1884            }
1885
1886            // Delete canonical entries above the new head by enumerating each key.
1887            // `delete_range` is not safe here: keys are `u64::to_le_bytes()`, and
1888            // RocksDB's lexicographic comparator does not match LE numeric order
1889            // (e.g. block 256 = [0x00, 0x01, ..] sorts before block 11 = [0x0B, ..]),
1890            // so a range-delete would silently miss blocks whose LE first byte is
1891            // smaller than `head+1`'s first byte.
1892            for number in (head_number + 1)..=(latest) {
1893                txn.delete(CANONICAL_BLOCK_HASHES, number.to_le_bytes().as_slice())?;
1894            }
1895
1896            // Make head canonical
1897            let head_key = head_number.to_le_bytes();
1898            let head_value = head_hash.encode_to_vec();
1899            txn.put(CANONICAL_BLOCK_HASHES, &head_key, &head_value)?;
1900
1901            // Update chain data
1902            let latest_key = chain_data_key(ChainDataIndex::LatestBlockNumber);
1903            txn.put(CHAIN_DATA, &latest_key, &head_number.to_le_bytes())?;
1904
1905            if let Some(safe) = safe {
1906                let safe_key = chain_data_key(ChainDataIndex::SafeBlockNumber);
1907                txn.put(CHAIN_DATA, &safe_key, &safe.to_le_bytes())?;
1908            }
1909
1910            if let Some(finalized) = finalized {
1911                let finalized_key = chain_data_key(ChainDataIndex::FinalizedBlockNumber);
1912
1913                // Read the previous finalized number from the same backend before we
1914                // overwrite it. The journal can only be pruned when finality actually
1915                // advances; a no-op or backwards FCU must not touch STATE_HISTORY.
1916                // Pre-merge or fresh chains have no entry; treat as 0.
1917                //
1918                // A length mismatch is treated as a hard error rather than a silent
1919                // fallback to 0: if a future schema change stores this field with a
1920                // different width, the silent default would make `finalized > 0` true
1921                // for every FCU and prune the entire journal. Bail out instead.
1922                let read = db.begin_read()?;
1923                let prev_finalized = match read.get(CHAIN_DATA, &finalized_key)? {
1924                    Some(bytes) => {
1925                        let arr: [u8; 8] = bytes.as_slice().try_into().map_err(|_| {
1926                            StoreError::Custom(format!(
1927                                "FinalizedBlockNumber has unexpected length {} (want 8)",
1928                                bytes.len()
1929                            ))
1930                        })?;
1931                        BlockNumber::from_le_bytes(arr)
1932                    }
1933                    None => 0,
1934                };
1935
1936                txn.put(CHAIN_DATA, &finalized_key, &finalized.to_le_bytes())?;
1937
1938                // Prune every STATE_HISTORY entry at or below the new finalized number
1939                // in the same atomic txn. STATE_HISTORY uses big-endian keys, so
1940                // lexicographic byte order matches numeric order, and `delete_range`
1941                // is half-open `[start, end)`.
1942                //
1943                // The range covers only entries that exist: it starts at the lowest
1944                // entry present and ends at the highest one at or below finality, and
1945                // is skipped when the lowest entry is above finality. Entries are
1946                // written ~DB_COMMIT_THRESHOLD blocks behind head, in increasing block
1947                // order, while finality can be ahead of them (an L2 finalizes head on
1948                // every block), so a range ending at `finalized` would cover block
1949                // numbers whose entries land later. A range delete only hides keys
1950                // written before it, so those entries would survive and the next
1951                // prune would overlap this one. Ending at the highest existing entry
1952                // keeps every range disjoint from the previous ones, and none is
1953                // written when there is nothing to prune. That matters because
1954                // RocksDB keeps unflushed range deletes in the memtable and fragments
1955                // them against each other on reads and flushes: N ranges that all
1956                // start at 0 overlap pairwise, so the fragmented form grows as N², and
1957                // a memtable holding a few thousand of them takes seconds and GBs to
1958                // flush or replay from the WAL. Disjoint ranges fragment in linear
1959                // time and memory.
1960                //
1961                // Skipped while a deep-reorg apply pass is in flight
1962                // (`journal_pruning_paused`): `Overlay::from_journal` reads entries
1963                // with no snapshot isolation, so pruning mid-construction fails it
1964                // with a spurious `MissingEntry`. The finalized-number update above
1965                // still lands; pruning catches up on the next advance after the
1966                // pass ends, because the range starts at whatever entry is lowest.
1967                if finalized > prev_finalized
1968                    && !journal_pruning_paused.load(std::sync::atomic::Ordering::Acquire)
1969                    && let Some(lowest) = read.first_key(STATE_HISTORY)?
1970                {
1971                    let lowest = state_history_key_number(&lowest)?;
1972                    if lowest <= finalized {
1973                        // `first_key` returned an entry, so `last_key` returns one too.
1974                        let highest = match read.last_key(STATE_HISTORY)? {
1975                            Some(key) => state_history_key_number(&key)?,
1976                            None => finalized,
1977                        };
1978                        let end = finalized.min(highest).saturating_add(1);
1979                        txn.delete_range(STATE_HISTORY, &lowest.to_be_bytes(), &end.to_be_bytes())?;
1980                    }
1981                }
1982            }
1983
1984            txn.commit()
1985        })
1986        .await
1987        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
1988    }
1989
1990    pub async fn get_receipts_for_block(
1991        &self,
1992        block_hash: &BlockHash,
1993    ) -> Result<Vec<Receipt>, StoreError> {
1994        self.get_receipts_for_block_from_index(block_hash, 0, None)
1995            .await
1996    }
1997
1998    /// Retrieves receipts for a block starting from the given index,
1999    /// optionally limited to `max_count` receipts.
2000    ///
2001    /// Uses cursor-based prefix iteration over the 32-byte block hash prefix
2002    /// for efficient batch retrieval. Used by:
2003    /// - eth/70 partial receipt requests (EIP-7975) via p2p
2004    /// - `eth_getTransactionReceipt` RPC with a count limit to avoid
2005    ///   fetching the entire block's receipts
2006    pub async fn get_receipts_for_block_from_index(
2007        &self,
2008        block_hash: &BlockHash,
2009        start_index: u64,
2010        max_count: Option<usize>,
2011    ) -> Result<Vec<Receipt>, StoreError> {
2012        if let Some(all) = self.buffer()?.get_receipts(block_hash) {
2013            let start = start_index as usize;
2014            let slice = all.into_iter().skip(start);
2015            return Ok(match max_count {
2016                Some(max) => slice.take(max).collect(),
2017                None => slice.collect(),
2018            });
2019        }
2020        let backend = self.backend.clone();
2021        let block_hash = *block_hash;
2022
2023        tokio::task::spawn_blocking(move || {
2024            let txn = backend.begin_read()?;
2025            let prefix = block_hash.as_bytes().to_vec();
2026            // Seek directly to block_hash || start_index to avoid O(start_index) scan.
2027            // Keys are big-endian u64, so lexicographic order matches numeric order.
2028            let mut seek_key = prefix.clone();
2029            seek_key.extend_from_slice(&start_index.to_be_bytes());
2030            let iter = txn.prefix_iterator(RECEIPTS_V2, &seek_key)?;
2031            let mut receipts = Vec::new();
2032            for result in iter {
2033                let (k, v) = result?;
2034                if !k.starts_with(&prefix) {
2035                    break;
2036                }
2037                if k.len() != 40 {
2038                    continue;
2039                }
2040                receipts.push(Receipt::decode_storage(v.as_ref())?);
2041                if let Some(max) = max_count
2042                    && receipts.len() >= max
2043                {
2044                    break;
2045                }
2046            }
2047            Ok(receipts)
2048        })
2049        .await
2050        .map_err(|e| StoreError::Custom(format!("Task panicked: {e}")))?
2051    }
2052
2053    // Snap State methods
2054
2055    /// Sets the hash of the last header downloaded during a snap sync
2056    pub async fn set_header_download_checkpoint(
2057        &self,
2058        block_hash: BlockHash,
2059    ) -> Result<(), StoreError> {
2060        let key = snap_state_key(SnapStateIndex::HeaderDownloadCheckpoint);
2061        let value = block_hash.encode_to_vec();
2062        self.write_async(SNAP_STATE, key, value).await
2063    }
2064
2065    /// Gets the hash of the last header downloaded during a snap sync
2066    pub async fn get_header_download_checkpoint(&self) -> Result<Option<BlockHash>, StoreError> {
2067        let key = snap_state_key(SnapStateIndex::HeaderDownloadCheckpoint);
2068        self.backend
2069            .begin_read()?
2070            .get(SNAP_STATE, &key)?
2071            .map(|bytes| H256::decode(bytes.as_slice()))
2072            .transpose()
2073            .map_err(StoreError::from)
2074    }
2075
2076    /// The `forkchoice_update` and `new_payload` methods require the `latest_valid_hash`
2077    /// when processing an invalid payload. To provide this, we must track invalid chains.
2078    ///
2079    /// We only store the last known valid head upon encountering a bad block,
2080    /// rather than tracking every subsequent invalid block.
2081    pub async fn set_latest_valid_ancestor(
2082        &self,
2083        bad_block: BlockHash,
2084        latest_valid: BlockHash,
2085    ) -> Result<(), StoreError> {
2086        let value = latest_valid.encode_to_vec();
2087        self.write_async(INVALID_CHAINS, bad_block.as_bytes().to_vec(), value)
2088            .await
2089    }
2090
2091    /// Returns the latest valid ancestor hash for a given invalid block hash.
2092    /// Used to provide `latest_valid_hash` in the Engine API when processing invalid payloads.
2093    pub async fn get_latest_valid_ancestor(
2094        &self,
2095        block: BlockHash,
2096    ) -> Result<Option<BlockHash>, StoreError> {
2097        self.read_async(INVALID_CHAINS, block.as_bytes().to_vec())
2098            .await?
2099            .map(|bytes| H256::decode(bytes.as_slice()))
2100            .transpose()
2101            .map_err(StoreError::from)
2102    }
2103
2104    /// Records a block that failed validation so it can be served by
2105    /// `debug_getBadBlocks`. The list is bounded to [`MAX_BAD_BLOCKS`] entries,
2106    /// kept sorted by descending block number, with the oldest dropped once the
2107    /// bound is exceeded. Duplicate `(number, hash)` entries are ignored.
2108    pub async fn add_bad_block(&self, block: Block) -> Result<(), StoreError> {
2109        let mut bad_blocks = self.get_bad_blocks().await?;
2110        let block_number = block.header.number;
2111        let block_hash = block.hash();
2112        if bad_blocks
2113            .iter()
2114            .any(|b| b.header.number == block_number && b.hash() == block_hash)
2115        {
2116            return Ok(());
2117        }
2118        bad_blocks.push(block);
2119        bad_blocks.sort_by(|a, b| b.header.number.cmp(&a.header.number));
2120        bad_blocks.truncate(MAX_BAD_BLOCKS);
2121        self.write_async(
2122            BAD_BLOCKS,
2123            BAD_BLOCKS_KEY.to_vec(),
2124            bad_blocks.encode_to_vec(),
2125        )
2126        .await
2127    }
2128
2129    /// Returns the recent bad blocks seen by the client, sorted by descending
2130    /// block number. Used by `debug_getBadBlocks`.
2131    pub async fn get_bad_blocks(&self) -> Result<Vec<Block>, StoreError> {
2132        match self.read_async(BAD_BLOCKS, BAD_BLOCKS_KEY.to_vec()).await? {
2133            Some(bytes) => Vec::<Block>::decode(&bytes).map_err(StoreError::from),
2134            None => Ok(Vec::new()),
2135        }
2136    }
2137
2138    /// Obtain block number for a given hash
2139    pub fn get_block_number_sync(
2140        &self,
2141        block_hash: BlockHash,
2142    ) -> Result<Option<BlockNumber>, StoreError> {
2143        if let Some(n) = self.buffer()?.get_number(&block_hash) {
2144            return Ok(Some(n));
2145        }
2146        let txn = self.backend.begin_read()?;
2147        txn.get(BLOCK_NUMBERS, &block_hash.encode_to_vec())?
2148            .map(decode_block_number)
2149            .transpose()
2150    }
2151
2152    /// Get the canonical block hash for a given block number.
2153    pub fn get_canonical_block_hash_sync(
2154        &self,
2155        block_number: BlockNumber,
2156    ) -> Result<Option<BlockHash>, StoreError> {
2157        let last = self.latest_block_header.get();
2158        if last.number == block_number {
2159            return Ok(Some(last.hash()));
2160        }
2161        let txn = self.backend.begin_read()?;
2162        txn.get(
2163            CANONICAL_BLOCK_HASHES,
2164            block_number.to_le_bytes().as_slice(),
2165        )?
2166        .map(|bytes| H256::decode(bytes.as_slice()))
2167        .transpose()
2168        .map_err(StoreError::from)
2169    }
2170
2171    /// CAUTION: This method writes directly to the underlying database, bypassing any caching layer.
2172    /// For updating the state after block execution, use [`Self::store_block_updates`].
2173    pub async fn write_storage_trie_nodes_batch(
2174        &self,
2175        storage_trie_nodes: StorageUpdates,
2176    ) -> Result<(), StoreError> {
2177        let mut txn = self.backend.begin_write()?;
2178        tokio::task::spawn_blocking(move || {
2179            for (address_hash, nodes) in storage_trie_nodes {
2180                for (node_path, node_data) in nodes {
2181                    let key = apply_prefix(Some(address_hash), node_path);
2182                    if node_data.is_empty() {
2183                        txn.delete(STORAGE_TRIE_NODES, key.as_ref())?;
2184                    } else {
2185                        txn.put(STORAGE_TRIE_NODES, key.as_ref(), &node_data)?;
2186                    }
2187                }
2188            }
2189            txn.commit()
2190        })
2191        .await
2192        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
2193    }
2194
2195    /// CAUTION: This method writes directly to the underlying database, bypassing any caching layer.
2196    /// For updating the state after block execution, use [`Self::store_block_updates`].
2197    pub async fn write_account_code_batch(
2198        &self,
2199        account_codes: Vec<(H256, Code)>,
2200    ) -> Result<(), StoreError> {
2201        let mut code_batch_items = Vec::new();
2202        let mut metadata_batch_items = Vec::new();
2203
2204        for (code_hash, code) in account_codes {
2205            let buf = encode_code(&code);
2206            let metadata_buf = (code.len() as u64).to_be_bytes().to_vec();
2207            code_batch_items.push((code_hash.as_bytes().to_vec(), buf));
2208            metadata_batch_items.push((code_hash.as_bytes().to_vec(), metadata_buf));
2209        }
2210
2211        // Write both batches
2212        self.write_batch_async(ACCOUNT_CODES, code_batch_items)
2213            .await?;
2214        self.write_batch_async(ACCOUNT_CODE_METADATA, metadata_batch_items)
2215            .await
2216    }
2217
2218    /// Returns a snapshot of the current block-data buffer.
2219    fn buffer(&self) -> Result<Arc<BlockDataBuffer>, StoreError> {
2220        Ok(self
2221            .block_data_buffer
2222            .read()
2223            .map_err(|_| StoreError::LockError)?
2224            .clone())
2225    }
2226
2227    // Helper methods for async operations with spawn_blocking
2228    // These methods ensure RocksDB I/O doesn't block the tokio runtime
2229
2230    /// Helper method for async writes
2231    /// Spawns blocking task to avoid blocking tokio runtime
2232    pub fn write(
2233        &self,
2234        table: &'static str,
2235        key: Vec<u8>,
2236        value: Vec<u8>,
2237    ) -> Result<(), StoreError> {
2238        let backend = self.backend.clone();
2239        let mut txn = backend.begin_write()?;
2240        txn.put(table, &key, &value)?;
2241        txn.commit()
2242    }
2243
2244    /// Helper method for async writes
2245    /// Spawns blocking task to avoid blocking tokio runtime
2246    async fn write_async(
2247        &self,
2248        table: &'static str,
2249        key: Vec<u8>,
2250        value: Vec<u8>,
2251    ) -> Result<(), StoreError> {
2252        let backend = self.backend.clone();
2253
2254        tokio::task::spawn_blocking(move || {
2255            let mut txn = backend.begin_write()?;
2256            txn.put(table, &key, &value)?;
2257            txn.commit()
2258        })
2259        .await
2260        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
2261    }
2262
2263    /// Helper method for async reads
2264    /// Spawns blocking task to avoid blocking tokio runtime
2265    pub async fn read_async(
2266        &self,
2267        table: &'static str,
2268        key: Vec<u8>,
2269    ) -> Result<Option<Vec<u8>>, StoreError> {
2270        let backend = self.backend.clone();
2271
2272        tokio::task::spawn_blocking(move || {
2273            let txn = backend.begin_read()?;
2274            txn.get(table, &key)
2275        })
2276        .await
2277        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
2278    }
2279
2280    /// Helper method for sync reads
2281    /// Spawns blocking task to avoid blocking tokio runtime
2282    pub fn read(&self, table: &'static str, key: Vec<u8>) -> Result<Option<Vec<u8>>, StoreError> {
2283        let backend = self.backend.clone();
2284        let txn = backend.begin_read()?;
2285        txn.get(table, &key)
2286    }
2287
2288    /// Helper method for batch writes
2289    /// Spawns blocking task to avoid blocking tokio runtime
2290    /// This is the most important optimization for healing performance
2291    pub async fn write_batch_async(
2292        &self,
2293        table: &'static str,
2294        batch_ops: Vec<(Vec<u8>, Vec<u8>)>,
2295    ) -> Result<(), StoreError> {
2296        let backend = self.backend.clone();
2297
2298        tokio::task::spawn_blocking(move || {
2299            let mut txn = backend.begin_write()?;
2300            txn.put_batch(table, batch_ops)?;
2301            txn.commit()
2302        })
2303        .await
2304        .map_err(|e| StoreError::Custom(format!("Task panicked: {}", e)))?
2305    }
2306
2307    /// Helper method for batch writes
2308    pub fn write_batch(
2309        &self,
2310        table: &'static str,
2311        batch_ops: Vec<(Vec<u8>, Vec<u8>)>,
2312    ) -> Result<(), StoreError> {
2313        let backend = self.backend.clone();
2314        let mut txn = backend.begin_write()?;
2315        txn.put_batch(table, batch_ops)?;
2316        txn.commit()
2317    }
2318
2319    pub async fn add_fullsync_batch(&self, headers: Vec<BlockHeader>) -> Result<(), StoreError> {
2320        self.write_batch_async(
2321            FULLSYNC_HEADERS,
2322            headers
2323                .into_iter()
2324                .map(|header| (header.number.to_le_bytes().to_vec(), header.encode_to_vec()))
2325                .collect(),
2326        )
2327        .await
2328    }
2329
2330    pub async fn read_fullsync_batch(
2331        &self,
2332        start: BlockNumber,
2333        limit: u64,
2334    ) -> Result<Vec<Option<BlockHeader>>, StoreError> {
2335        let mut res = vec![];
2336        let read_tx = self.backend.begin_read()?;
2337        // TODO: use read_bulk here
2338        for key in start..start + limit {
2339            let header_opt = read_tx
2340                .get(FULLSYNC_HEADERS, &key.to_le_bytes())?
2341                .map(|header| BlockHeader::decode(&header))
2342                .transpose()?;
2343            res.push(header_opt);
2344        }
2345        Ok(res)
2346    }
2347
2348    pub async fn clear_fullsync_headers(&self) -> Result<(), StoreError> {
2349        self.backend.clear_table(FULLSYNC_HEADERS)
2350    }
2351
2352    /// Delete a key from a table
2353    pub fn delete(&self, table: &'static str, key: Vec<u8>) -> Result<(), StoreError> {
2354        let mut txn = self.backend.begin_write()?;
2355        txn.delete(table, &key)?;
2356        txn.commit()
2357    }
2358
2359    pub fn store_block_updates(&self, update_batch: UpdateBatch) -> Result<(), StoreError> {
2360        self.apply_updates(update_batch)
2361    }
2362
2363    /// Compute `(parent_state_root, last_state_root, last_block_number,
2364    /// last_block_hash)` for a batch's trie update: the state root of the first
2365    /// block's parent, the last block's own state root, and the last block's
2366    /// number and hash (the identity the journal records for the committed
2367    /// layer). Used by `apply_updates` for both the live and full-sync paths
2368    /// (which share the single persist worker).
2369    fn batch_state_roots(
2370        &self,
2371        update_batch: &UpdateBatch,
2372    ) -> Result<(H256, H256, BlockNumber, H256), StoreError> {
2373        let parent_state_root = self
2374            .get_block_header_by_hash(
2375                update_batch
2376                    .blocks
2377                    .first()
2378                    .ok_or(StoreError::UpdateBatchNoBlocks)?
2379                    .header
2380                    .parent_hash,
2381            )?
2382            .map(|header| header.state_root)
2383            .unwrap_or_default();
2384        let last_block = update_batch
2385            .blocks
2386            .last()
2387            .ok_or(StoreError::UpdateBatchNoBlocks)?;
2388        let last_state_root = last_block.header.state_root;
2389        let last_block_number = last_block.header.number;
2390        let last_block_hash = last_block.hash();
2391        Ok((
2392            parent_state_root,
2393            last_state_root,
2394            last_block_number,
2395            last_block_hash,
2396        ))
2397    }
2398
2399    /// Single path for all updates: hand the whole unit (block data + one aggregate trie
2400    /// diff) to the SINGLE persist worker and wait for its ack. `commit_depth` selects the
2401    /// commit gate; `wait_for_flush` selects when the worker acks (see [`UpdateBatch`]).
2402    fn apply_updates(&self, update_batch: UpdateBatch) -> Result<(), StoreError> {
2403        let (parent_state_root, last_state_root, last_block_number, last_block_hash) =
2404            self.batch_state_roots(&update_batch)?;
2405
2406        let UpdateBatch {
2407            account_updates,
2408            storage_updates,
2409            blocks,
2410            receipts,
2411            code_updates,
2412            commit_depth,
2413            wait_for_flush,
2414        } = update_batch;
2415
2416        // Register before handing off to the worker and before this returns, so
2417        // any reader opening this root blocks in `gated_snapshot` until the
2418        // layer is installed rather than snapshotting a stale cache.
2419        self.pending_trie_roots.register(last_state_root)?;
2420
2421        // Pair blocks with receipts. Single-block fast path avoids a HashMap
2422        // allocation; full-sync batch joins by hash.
2423        let blocks_with_receipts: Vec<(Block, Vec<Receipt>)> = if blocks.len() == 1 {
2424            let block = blocks.into_iter().next().expect("len == 1");
2425            let hash = block.hash();
2426            let r = receipts
2427                .into_iter()
2428                .find(|(h, _)| *h == hash)
2429                .map(|(_, r)| r)
2430                .unwrap_or_default();
2431            vec![(block, r)]
2432        } else {
2433            let mut receipts_by_hash: std::collections::HashMap<BlockHash, Vec<Receipt>> =
2434                receipts.into_iter().collect();
2435            blocks
2436                .into_iter()
2437                .map(|b| {
2438                    let r = receipts_by_hash.remove(&b.hash()).unwrap_or_default();
2439                    (b, r)
2440                })
2441                .collect()
2442        };
2443
2444        // Send to the persist worker and wait for its ack.
2445        // wait_for_flush=false: worker acks after staging; the ack carries the PRIOR flush
2446        //   result so a disk error surfaces on the next call.
2447        // wait_for_flush=true: worker acks after flush, bounding in-flight work to ~1.
2448        let (ack_tx, ack_rx) = sync_channel(1);
2449        self.persist_tx
2450            .send(PersistMessage::Block(Box::new(BlockPersist {
2451                blocks: blocks_with_receipts,
2452                codes: code_updates,
2453                parent_state_root,
2454                child_state_root: last_state_root,
2455                account_updates,
2456                storage_updates,
2457                commit_depth,
2458                wait_for_flush,
2459                block_number: last_block_number,
2460                block_hash: last_block_hash,
2461                ack: ack_tx,
2462            })))
2463            .map_err(|e| StoreError::Custom(format!("failed to send block persist: {e}")))?;
2464        ack_rx
2465            .recv()
2466            .map_err(|e| StoreError::Custom(format!("block persist ack failed: {e}")))??;
2467
2468        Ok(())
2469    }
2470
2471    /// Opens (or creates) a store at `path` with the default [`StoreConfig`].
2472    ///
2473    /// Production callers that need to override storage tunables (e.g. the RocksDB
2474    /// block cache size from a CLI option) should use [`Store::new_with_config`].
2475    pub fn new(path: impl AsRef<Path>, engine_type: EngineType) -> Result<Self, StoreError> {
2476        Self::new_with_config(path, engine_type, StoreConfig::default())
2477    }
2478
2479    /// Opens (or creates) a store at `path`, applying the supplied [`StoreConfig`].
2480    pub fn new_with_config(
2481        path: impl AsRef<Path>,
2482        engine_type: EngineType,
2483        config: StoreConfig,
2484    ) -> Result<Self, StoreError> {
2485        let code_cache_size = config.code_cache_size.unwrap_or(CODE_CACHE_MAX_SIZE);
2486        let store = Self::open_with_config(path, engine_type, config)?;
2487        if let Ok(mut cache) = store.account_code_cache.lock() {
2488            cache.max_size = code_cache_size;
2489        }
2490        info!(cache_bytes = code_cache_size, "sized bytecode cache");
2491        Ok(store)
2492    }
2493
2494    fn open_with_config(
2495        path: impl AsRef<Path>,
2496        engine_type: EngineType,
2497        // `config` only feeds the RocksDB backend; without that feature it is unused.
2498        #[cfg_attr(not(feature = "rocksdb"), allow(unused_variables))] config: StoreConfig,
2499    ) -> Result<Self, StoreError> {
2500        let db_path = path.as_ref().to_path_buf();
2501
2502        if engine_type != EngineType::InMemory {
2503            let version = read_store_schema_version(&db_path)?;
2504
2505            match version {
2506                None if db_path.exists() && dir_contains_legacy_db(&db_path)? => {
2507                    // Pre-metadata DB — cannot migrate safely
2508                    return Err(StoreError::NotFoundDBVersion);
2509                }
2510                None => {
2511                    // No metadata and no recognizable database files. The directory
2512                    // may still hold unrelated files (e.g. a JWT secret placed in the
2513                    // datadir by tooling such as EthDocker, see issue #5680), so treat
2514                    // this as a fresh datadir and write the initial metadata instead
2515                    // of erroring out.
2516                    init_metadata_file(&db_path)?;
2517                }
2518                // Neither arm below runs a migration, so neither is a
2519                // `MigrationFailed`: that variant tells the operator the data may be
2520                // half-converted, which is false here — the database is untouched.
2521                Some(v) if v < 1 => {
2522                    // No ethrex ever wrote a v0 marker; the file is corrupt or hand-edited.
2523                    return Err(StoreError::IncompatibleDBVersion {
2524                        found: v,
2525                        expected: STORE_SCHEMA_VERSION,
2526                    });
2527                }
2528                Some(v) if v > STORE_SCHEMA_VERSION => {
2529                    // Written by a newer ethrex. Downgrading is unsupported, but the
2530                    // database is intact: a binary that speaks v{v} opens it as is.
2531                    return Err(StoreError::IncompatibleDBVersion {
2532                        found: v,
2533                        expected: STORE_SCHEMA_VERSION,
2534                    });
2535                }
2536                #[cfg(feature = "rocksdb")]
2537                Some(v) if v < STORE_SCHEMA_VERSION => {
2538                    // Open backend, run migrations, then drop obsolete CFs.
2539                    // Cleanup must happen AFTER migrations so legacy CFs (e.g.
2540                    // `receipts`) are still readable during the migration.
2541                    let rocksdb = Arc::new(RocksDBBackend::open(
2542                        &path,
2543                        config.rocksdb_block_cache_size,
2544                    )?);
2545                    crate::migrations::run_pending_migrations(rocksdb.as_ref(), &db_path, v)?;
2546                    rocksdb.drop_obsolete_cfs(&path);
2547                    let backend: Arc<dyn crate::api::StorageBackend> = rocksdb;
2548                    return Self::from_backend(
2549                        backend,
2550                        db_path,
2551                        DB_COMMIT_THRESHOLD,
2552                        config.persist_channel_capacity,
2553                    );
2554                }
2555                Some(_) => {
2556                    // version == STORE_SCHEMA_VERSION, proceed normally.
2557                    // Without the `rocksdb` feature this also covers v < target,
2558                    // but that path is unreachable since InMemory is the only
2559                    // engine type and the outer guard excludes it.
2560                }
2561            }
2562        }
2563
2564        match engine_type {
2565            #[cfg(feature = "rocksdb")]
2566            EngineType::RocksDB => {
2567                let rocksdb = RocksDBBackend::open(&path, config.rocksdb_block_cache_size)?;
2568                rocksdb.drop_obsolete_cfs(&path);
2569                let backend: Arc<dyn StorageBackend> = Arc::new(rocksdb);
2570                Self::from_backend(
2571                    backend,
2572                    db_path,
2573                    DB_COMMIT_THRESHOLD,
2574                    config.persist_channel_capacity,
2575                )
2576            }
2577            EngineType::InMemory => {
2578                let backend = Arc::new(InMemoryBackend::open()?);
2579                Self::from_backend(
2580                    backend,
2581                    db_path,
2582                    IN_MEMORY_COMMIT_THRESHOLD,
2583                    config.persist_channel_capacity,
2584                )
2585            }
2586        }
2587    }
2588
2589    fn from_backend(
2590        backend: Arc<dyn StorageBackend>,
2591        db_path: PathBuf,
2592        commit_threshold: usize,
2593        persist_channel_capacity: usize,
2594    ) -> Result<Self, StoreError> {
2595        debug!("Initializing Store with {commit_threshold} in-memory diff-layers");
2596        let (fkv_tx, fkv_rx) = std::sync::mpsc::sync_channel(0);
2597        let persist_cap = persist_channel_capacity.max(1); // clamp: 0 would be a rendezvous channel
2598        let (persist_tx, persist_rx) = std::sync::mpsc::sync_channel(persist_cap);
2599
2600        let (last_written, initial_flushed_upto) = {
2601            let tx = backend.begin_read()?;
2602            let last_written = tx
2603                .get(MISC_VALUES, "last_written".as_bytes())?
2604                .unwrap_or_else(|| vec![0u8; 64]);
2605            let last_written = if last_written == [0xff] {
2606                vec![0xff; 64]
2607            } else {
2608                last_written
2609            };
2610            let initial_flushed_upto = match tx.get(MISC_VALUES, FLUSHED_UPTO_KEY)? {
2611                Some(bytes) => decode_flushed_upto(&bytes)?,
2612                None => 0,
2613            };
2614            (last_written, initial_flushed_upto)
2615        };
2616        let mut initial_buffer = BlockDataBuffer::new();
2617        initial_buffer.set_flushed_upto(initial_flushed_upto);
2618
2619        let mut background_threads = Vec::new();
2620        let safe_commit_root = Arc::new(RwLock::new(H256::zero()));
2621        let mut store = Self {
2622            db_path,
2623            backend,
2624            chain_config: Default::default(),
2625            latest_block_header: Default::default(),
2626            trie_cache: Arc::new(RwLock::new(Arc::new(TrieLayerCache::new_with_safe_commit(
2627                commit_threshold,
2628                safe_commit_root.clone(),
2629            )))),
2630            flatkeyvalue_control_tx: fkv_tx,
2631            block_data_buffer: Arc::new(RwLock::new(Arc::new(initial_buffer))),
2632            persist_tx,
2633            pending_trie_roots: Arc::new(PendingTrieRoots::default()),
2634            last_computed_flatkeyvalue: Arc::new(RwLock::new(last_written)),
2635            account_code_cache: Arc::new(Mutex::new(CodeCache::default())),
2636            code_metadata_cache: Arc::new(Mutex::new(LruCache::with_hasher(
2637                NonZeroUsize::new(CODE_METADATA_CACHE_MAX_ENTRIES).unwrap_or(NonZeroUsize::MIN),
2638                SeededState::default(),
2639            ))),
2640            fcu_lock: Arc::new(tokio::sync::Mutex::new(())),
2641            safe_commit_root,
2642            journal_pruning_paused: Arc::new(std::sync::atomic::AtomicBool::new(false)),
2643            sync_status_changed: Arc::new(tokio::sync::watch::Sender::new(())),
2644            background_threads: Default::default(),
2645        };
2646        let backend_clone = store.backend.clone();
2647        let last_computed_fkv = store.last_computed_flatkeyvalue.clone();
2648        background_threads.push(std::thread::spawn(move || {
2649            let rx = fkv_rx;
2650            // Wait for the first Continue to start generation
2651            loop {
2652                match rx.recv() {
2653                    Ok(FKVGeneratorControlMessage::Continue) => break,
2654                    Ok(FKVGeneratorControlMessage::Stop) => {}
2655                    Err(std::sync::mpsc::RecvError) => {
2656                        debug!("Closing FlatKeyValue generator.");
2657                        return;
2658                    }
2659                }
2660            }
2661
2662            let _ = flatkeyvalue_generator(&backend_clone, &last_computed_fkv, &rx)
2663                .inspect_err(|err| error!("Error while generating FlatKeyValue: {err}"));
2664        }));
2665        // The single persist worker: sole swapper of `block_data_buffer`, sole
2666        // builder of trie diff-layers. One DB transaction per `Block` message.
2667        let persist_backend = store.backend.clone();
2668        let persist_buffer = store.block_data_buffer.clone();
2669        let persist_trie_cache = store.trie_cache.clone();
2670        let persist_pending_roots = store.pending_trie_roots.clone();
2671        let persist_fkv_ctl = store.flatkeyvalue_control_tx.clone();
2672        background_threads.push(std::thread::spawn(move || {
2673            let rx = persist_rx;
2674            // Carries the prior flush result: the live path acks after staging,
2675            // so a disk failure surfaces on the next message's ack.
2676            let mut last_flush_result: Result<(), StoreError> = Ok(());
2677            loop {
2678                match rx.recv() {
2679                    Ok(PersistMessage::Block(bp)) => {
2680                        let bp = *bp;
2681                        // Stage block data (sole swapper of the buffer; codes
2682                        // are batch-level and attributed to the first block).
2683                        let staged = mutate_block_buffer(&persist_buffer, move |b| {
2684                            let mut codes = Some(bp.codes);
2685                            for (block, receipts) in bp.blocks {
2686                                b.insert(block, receipts, codes.take().unwrap_or_default());
2687                            }
2688                        });
2689                        if let Err(e) = staged {
2690                            // Stage failure is terminal for this message.
2691                            // Clear the pending root so gated readers are not
2692                            // blocked forever (apply_trie_phase1, which normally
2693                            // does this, is skipped when we continue here).
2694                            persist_pending_roots.clear(bp.child_state_root);
2695                            let _ = bp.ack.send(Err(e));
2696                            continue;
2697                        }
2698                        // ACK-AFTER-STAGING: ack now, carrying the prior flush result.
2699                        // NOTE: this acks block validity BEFORE apply_trie_phase1
2700                        // installs the trie layer below. A phase-1 failure (only
2701                        // reachable via lock poisoning, which is already fatal) is
2702                        // therefore deferred to the next block's ack via
2703                        // last_flush_result rather than attributed to this block;
2704                        // the pending root is still cleared unconditionally, so
2705                        // gated readers error rather than hang.
2706                        if !bp.wait_for_flush {
2707                            let _ = bp
2708                                .ack
2709                                .send(std::mem::replace(&mut last_flush_result, Ok(())));
2710                        }
2711                        // Build + install the trie layer; clear the read gate.
2712                        if let Err(err) = apply_trie_phase1(
2713                            &persist_trie_cache,
2714                            &persist_pending_roots,
2715                            bp.parent_state_root,
2716                            bp.child_state_root,
2717                            bp.block_number,
2718                            bp.block_hash,
2719                            bp.account_updates,
2720                            bp.storage_updates,
2721                        ) {
2722                            error!("persist worker trie phase-1 failed: {err}");
2723                            if bp.wait_for_flush {
2724                                let _ = bp.ack.send(Err(err));
2725                            } else {
2726                                last_flush_result = Err(err);
2727                            }
2728                            continue;
2729                        }
2730                        // Flush block data + commit bottom trie layer when due.
2731                        let flushed = flush_block_data(persist_backend.as_ref(), &persist_buffer)
2732                            .inspect_err(|err| error!("flush_block_data failed: {err}"))
2733                            .and_then(|_| {
2734                                commit_trie_if_due(
2735                                    persist_backend.as_ref(),
2736                                    &persist_trie_cache,
2737                                    &persist_fkv_ctl,
2738                                    bp.parent_state_root,
2739                                    bp.commit_depth,
2740                                    bp.wait_for_flush,
2741                                )
2742                            });
2743                        // ACK-AFTER-FLUSH: ack now (bounds in-flight work to ~1), folding in
2744                        // any prior deferred error. ACK-AFTER-STAGING: stash for the next ack.
2745                        if bp.wait_for_flush {
2746                            let prior = std::mem::replace(&mut last_flush_result, Ok(()));
2747                            let _ = bp.ack.send(prior.and(flushed));
2748                        } else {
2749                            last_flush_result = flushed;
2750                        }
2751                    }
2752                    Ok(PersistMessage::Commit(root)) => match persist_trie_cache.read() {
2753                        Ok(guard) => {
2754                            let trie = guard.clone();
2755                            drop(guard);
2756                            // Forkchoice-driven flush is the live (non-batch) path, so
2757                            // journaling is enabled: pass `is_batch = false`.
2758                            let _ = commit_to_disk(
2759                                persist_backend.as_ref(),
2760                                &persist_fkv_ctl,
2761                                &persist_trie_cache,
2762                                &trie,
2763                                root,
2764                                false,
2765                            )
2766                            .inspect_err(|err| error!("commit_to_disk failed: {err}"));
2767                        }
2768                        Err(_) => error!("trie cache lock poisoned during commit"),
2769                    },
2770                    Ok(PersistMessage::Ping(ack)) => {
2771                        // Idle handshake: reached only after all earlier Block
2772                        // messages are fully processed. Carry the pending flush
2773                        // result so a live-path failure is not silently dropped.
2774                        let _ = ack.send(std::mem::replace(&mut last_flush_result, Ok(())));
2775                    }
2776                    Ok(PersistMessage::Shutdown { ack }) => {
2777                        // Graceful shutdown: drain (already guaranteed by FIFO) and
2778                        // force-flush the not-yet-flushed block-data tail. The trie
2779                        // diff-layers stay in memory and are dropped on exit: the
2780                        // on-disk trie is a single-version path store, so committing
2781                        // the non-finalized tail would make a post-restart reorg
2782                        // unrecoverable. Those layers re-execute on the next start.
2783                        let result = flush_block_data(persist_backend.as_ref(), &persist_buffer);
2784                        let prior = std::mem::replace(&mut last_flush_result, Ok(()));
2785                        let _ = ack.send(prior.and(result));
2786                        // No more work will follow a shutdown request.
2787                        return;
2788                    }
2789                    Err(_) => return,
2790                }
2791            }
2792        }));
2793        store.background_threads = Arc::new(ThreadList {
2794            list: background_threads,
2795        });
2796        Ok(store)
2797    }
2798
2799    /// Opens (or creates) a store at `store_path` and seeds it from the
2800    /// given genesis file, using the default [`StoreConfig`].
2801    pub async fn new_from_genesis(
2802        store_path: &Path,
2803        engine_type: EngineType,
2804        genesis_path: &str,
2805    ) -> Result<Self, StoreError> {
2806        Self::new_from_genesis_with_config(
2807            store_path,
2808            engine_type,
2809            genesis_path,
2810            StoreConfig::default(),
2811        )
2812        .await
2813    }
2814
2815    /// Opens (or creates) a store at `store_path` from genesis, applying the
2816    /// supplied [`StoreConfig`].
2817    pub async fn new_from_genesis_with_config(
2818        store_path: &Path,
2819        engine_type: EngineType,
2820        genesis_path: &str,
2821        config: StoreConfig,
2822    ) -> Result<Self, StoreError> {
2823        let file = std::fs::File::open(genesis_path)
2824            .map_err(|error| StoreError::Custom(format!("Failed to open genesis file: {error}")))?;
2825        let reader = std::io::BufReader::new(file);
2826        let genesis: Genesis = serde_json::from_reader(reader)
2827            .map_err(|e| StoreError::Custom(format!("Failed to deserialize genesis file: {e}")))?;
2828        let mut store = Self::new_with_config(store_path, engine_type, config)?;
2829        store.add_initial_state(genesis).await?;
2830        Ok(store)
2831    }
2832
2833    pub async fn get_account_info(
2834        &self,
2835        block_number: BlockNumber,
2836        address: Address,
2837    ) -> Result<Option<AccountInfo>, StoreError> {
2838        match self.get_canonical_block_hash(block_number).await? {
2839            Some(block_hash) => self.get_account_info_by_hash(block_hash, address),
2840            None => Ok(None),
2841        }
2842    }
2843
2844    pub fn get_account_info_by_hash(
2845        &self,
2846        block_hash: BlockHash,
2847        address: Address,
2848    ) -> Result<Option<AccountInfo>, StoreError> {
2849        let Some(state_trie) = self.state_trie(block_hash)? else {
2850            return Ok(None);
2851        };
2852        let hashed_address = hash_address_fixed(&address);
2853
2854        let Some(encoded_state) = state_trie.get(hashed_address.as_bytes())? else {
2855            return Ok(None);
2856        };
2857
2858        let account_state = AccountState::decode(&encoded_state)?;
2859        Ok(Some(AccountInfo {
2860            code_hash: account_state.code_hash,
2861            balance: account_state.balance,
2862            nonce: account_state.nonce,
2863        }))
2864    }
2865
2866    pub fn get_account_state_by_acc_hash(
2867        &self,
2868        block_hash: BlockHash,
2869        account_hash: H256,
2870    ) -> Result<Option<AccountState>, StoreError> {
2871        let Some(state_trie) = self.state_trie(block_hash)? else {
2872            return Ok(None);
2873        };
2874        let Some(encoded_state) = state_trie.get(account_hash.as_bytes())? else {
2875            return Ok(None);
2876        };
2877        let account_state = AccountState::decode(&encoded_state)?;
2878        Ok(Some(account_state))
2879    }
2880
2881    pub async fn get_fork_id(&self) -> Result<ForkId, StoreError> {
2882        let chain_config = self.get_chain_config();
2883        let genesis_header = self
2884            .load_block_header(0)?
2885            .ok_or(StoreError::MissingEarliestBlockNumber)?;
2886        let block_header = self.latest_block_header.get();
2887
2888        Ok(ForkId::new(
2889            chain_config,
2890            genesis_header,
2891            block_header.timestamp,
2892            block_header.number,
2893        ))
2894    }
2895
2896    pub async fn get_code_by_account_address(
2897        &self,
2898        block_number: BlockNumber,
2899        address: Address,
2900    ) -> Result<Option<Code>, StoreError> {
2901        let Some(block_hash) = self.get_canonical_block_hash(block_number).await? else {
2902            return Ok(None);
2903        };
2904        let Some(state_trie) = self.state_trie(block_hash)? else {
2905            return Ok(None);
2906        };
2907        let hashed_address = hash_address_fixed(&address);
2908        let Some(encoded_state) = state_trie.get(hashed_address.as_bytes())? else {
2909            return Ok(None);
2910        };
2911        let account_state = AccountState::decode(&encoded_state)?;
2912        self.get_account_code(account_state.code_hash)
2913    }
2914
2915    pub async fn get_nonce_by_account_address(
2916        &self,
2917        block_number: BlockNumber,
2918        address: Address,
2919    ) -> Result<Option<u64>, StoreError> {
2920        let Some(block_hash) = self.get_canonical_block_hash(block_number).await? else {
2921            return Ok(None);
2922        };
2923        let Some(state_trie) = self.state_trie(block_hash)? else {
2924            return Ok(None);
2925        };
2926        let hashed_address = hash_address_fixed(&address);
2927        let Some(encoded_state) = state_trie.get(hashed_address.as_bytes())? else {
2928            return Ok(None);
2929        };
2930        let account_state = AccountState::decode(&encoded_state)?;
2931        Ok(Some(account_state.nonce))
2932    }
2933
2934    /// Applies account updates based on the block's latest storage state
2935    /// and returns the new state root after the updates have been applied.
2936    pub fn apply_account_updates_batch(
2937        &self,
2938        block_hash: BlockHash,
2939        account_updates: &[AccountUpdate],
2940    ) -> Result<Option<AccountUpdatesList>, StoreError> {
2941        let Some(mut state_trie) = self.state_trie(block_hash)? else {
2942            return Ok(None);
2943        };
2944
2945        Ok(Some(self.apply_account_updates_from_trie_batch(
2946            &mut state_trie,
2947            account_updates,
2948        )?))
2949    }
2950
2951    pub fn apply_account_updates_from_trie_batch<'a>(
2952        &self,
2953        state_trie: &mut Trie,
2954        account_updates: impl IntoIterator<Item = &'a AccountUpdate>,
2955    ) -> Result<AccountUpdatesList, StoreError> {
2956        let mut ret_storage_updates = Vec::new();
2957        let mut code_updates = Vec::new();
2958        let state_root = state_trie.hash_no_commit(&NativeCrypto);
2959        for update in account_updates {
2960            let hashed_address = hash_address_fixed(&update.address);
2961            if update.removed {
2962                // Remove account from trie
2963                state_trie.remove(hashed_address.as_bytes())?;
2964                continue;
2965            }
2966            // Add or update AccountState in the trie
2967            // Fetch current state or create a new state to be inserted
2968            let mut account_state = match state_trie.get(hashed_address.as_bytes())? {
2969                Some(encoded_state) => AccountState::decode(&encoded_state)?,
2970                None => AccountState::default(),
2971            };
2972            if update.removed_storage {
2973                account_state.storage_root = EMPTY_TRIE_HASH;
2974            }
2975            if let Some(info) = &update.info {
2976                account_state.nonce = info.nonce;
2977                account_state.balance = info.balance;
2978                account_state.code_hash = info.code_hash;
2979                // Store updated code in DB
2980                if let Some(code) = &update.code {
2981                    code_updates.push((info.code_hash, code.clone()));
2982                }
2983            }
2984            // Store the added storage in the account's storage trie and compute its new root
2985            if !update.added_storage.is_empty() {
2986                let mut storage_trie =
2987                    self.open_storage_trie(hashed_address, state_root, account_state.storage_root)?;
2988                for (storage_key, storage_value) in &update.added_storage {
2989                    let hashed_key = hash_key(storage_key);
2990                    if storage_value.is_zero() {
2991                        storage_trie.remove(&hashed_key)?;
2992                    } else {
2993                        storage_trie.insert(hashed_key, storage_value.encode_to_vec())?;
2994                    }
2995                }
2996                let (storage_hash, storage_updates) =
2997                    storage_trie.collect_changes_since_last_hash(&NativeCrypto);
2998                account_state.storage_root = storage_hash;
2999                ret_storage_updates.push((hashed_address, storage_updates));
3000            }
3001            state_trie.insert(
3002                hashed_address.as_bytes().to_vec(),
3003                account_state.encode_to_vec(),
3004            )?;
3005        }
3006        let (state_trie_hash, state_updates) =
3007            state_trie.collect_changes_since_last_hash(&NativeCrypto);
3008
3009        Ok(AccountUpdatesList {
3010            state_trie_hash,
3011            state_updates,
3012            storage_updates: ret_storage_updates,
3013            code_updates,
3014        })
3015    }
3016
3017    /// Performs the same actions as apply_account_updates_from_trie
3018    ///  but also returns the used storage tries with witness recorded
3019    pub fn apply_account_updates_from_trie_with_witness(
3020        &self,
3021        mut state_trie: Trie,
3022        account_updates: &[AccountUpdate],
3023        mut storage_tries: StorageTries,
3024    ) -> Result<(StorageTries, AccountUpdatesList), StoreError> {
3025        let mut ret_storage_updates = Vec::new();
3026
3027        let mut code_updates = Vec::new();
3028
3029        let state_root = state_trie.hash_no_commit(&NativeCrypto);
3030
3031        // Apply in address order. The guest replays these same updates on the nodes recorded
3032        // here, and the nodes a removal reads depend on what was inserted before it: a branch
3033        // left with one child loads that child. Both lists are built from seeded maps, so
3034        // only a sort keeps the two sides touching the same nodes.
3035        let mut ordered: Vec<&AccountUpdate> = account_updates.iter().collect();
3036        ordered.sort_unstable_by_key(|update| update.address);
3037
3038        for update in ordered {
3039            let hashed_address = hash_address(&update.address);
3040
3041            if update.removed {
3042                // Remove account from trie
3043                state_trie.remove(&hashed_address)?;
3044
3045                continue;
3046            }
3047
3048            // Add or update AccountState in the trie
3049            // Fetch current state or create a new state to be inserted
3050            let mut account_state = match state_trie.get(&hashed_address)? {
3051                Some(encoded_state) => AccountState::decode(&encoded_state)?,
3052                None => AccountState::default(),
3053            };
3054
3055            if update.removed_storage {
3056                account_state.storage_root = EMPTY_TRIE_HASH;
3057            }
3058
3059            if let Some(info) = &update.info {
3060                account_state.nonce = info.nonce;
3061
3062                account_state.balance = info.balance;
3063
3064                account_state.code_hash = info.code_hash;
3065
3066                // Store updated code in DB
3067                if let Some(code) = &update.code {
3068                    code_updates.push((info.code_hash, code.clone()));
3069                }
3070            }
3071
3072            // Store the added storage in the account's storage trie and compute its new root
3073            if !update.added_storage.is_empty() {
3074                let (_witness, storage_trie) = match storage_tries.entry(update.address) {
3075                    Entry::Occupied(value) => value.into_mut(),
3076                    Entry::Vacant(vacant) => {
3077                        let trie = self.open_storage_trie(
3078                            H256::from_slice(&hashed_address),
3079                            state_root,
3080                            account_state.storage_root,
3081                        )?;
3082                        vacant.insert(TrieLogger::open_trie(trie))
3083                    }
3084                };
3085
3086                for (storage_key, storage_value) in &update.added_storage {
3087                    let hashed_key = hash_key(storage_key);
3088
3089                    if storage_value.is_zero() {
3090                        storage_trie.remove(&hashed_key)?;
3091                    } else {
3092                        storage_trie.insert(hashed_key, storage_value.encode_to_vec())?;
3093                    }
3094                }
3095
3096                let (storage_hash, storage_updates) =
3097                    storage_trie.collect_changes_since_last_hash(&NativeCrypto);
3098
3099                account_state.storage_root = storage_hash;
3100
3101                ret_storage_updates.push((H256::from_slice(&hashed_address), storage_updates));
3102            }
3103
3104            state_trie.insert(hashed_address, account_state.encode_to_vec())?;
3105        }
3106
3107        let (state_trie_hash, state_updates) =
3108            state_trie.collect_changes_since_last_hash(&NativeCrypto);
3109
3110        let account_updates_list = AccountUpdatesList {
3111            state_trie_hash,
3112            state_updates,
3113            storage_updates: ret_storage_updates,
3114            code_updates,
3115        };
3116
3117        Ok((storage_tries, account_updates_list))
3118    }
3119
3120    /// Adds all genesis accounts and returns the genesis block's state_root
3121    pub async fn setup_genesis_state_trie(
3122        &self,
3123        genesis_accounts: BTreeMap<Address, GenesisAccount>,
3124    ) -> Result<H256, StoreError> {
3125        let mut storage_trie_nodes = vec![];
3126        let mut genesis_state_trie = self.open_direct_state_trie(EMPTY_TRIE_HASH)?;
3127        for (address, account) in genesis_accounts {
3128            let hashed_address = hash_address(&address);
3129            let h256_hashed_address = H256::from_slice(&hashed_address);
3130
3131            // Store account code (as this won't be stored in the trie)
3132            let code = Code::from_bytecode(account.code, &NativeCrypto);
3133            let code_hash = code.hash;
3134            self.add_account_code(code).await?;
3135
3136            // Store the account's storage in a clean storage trie and compute its root
3137            let mut storage_trie =
3138                self.open_direct_storage_trie(h256_hashed_address, EMPTY_TRIE_HASH)?;
3139            for (storage_key, storage_value) in account.storage {
3140                if !storage_value.is_zero() {
3141                    let hashed_key = hash_key(&H256(storage_key.to_big_endian()));
3142                    storage_trie.insert(hashed_key, storage_value.encode_to_vec())?;
3143                }
3144            }
3145
3146            let (storage_root, storage_nodes) =
3147                storage_trie.collect_changes_since_last_hash(&NativeCrypto);
3148
3149            storage_trie_nodes.extend(
3150                storage_nodes
3151                    .into_iter()
3152                    .map(|(path, n)| (apply_prefix(Some(h256_hashed_address), path).into_vec(), n)),
3153            );
3154
3155            // Add account to trie
3156            let account_state = AccountState {
3157                nonce: account.nonce,
3158                balance: account.balance,
3159                storage_root,
3160                code_hash,
3161            };
3162            genesis_state_trie.insert(hashed_address, account_state.encode_to_vec())?;
3163        }
3164
3165        let (state_root, account_trie_nodes) =
3166            genesis_state_trie.collect_changes_since_last_hash(&NativeCrypto);
3167        let account_trie_nodes = account_trie_nodes
3168            .into_iter()
3169            .map(|(path, n)| (apply_prefix(None, path).into_vec(), n))
3170            .collect::<Vec<_>>();
3171
3172        let mut tx = self.backend.begin_write()?;
3173        tx.put_batch(ACCOUNT_TRIE_NODES, account_trie_nodes)?;
3174        tx.put_batch(STORAGE_TRIE_NODES, storage_trie_nodes)?;
3175        tx.commit()?;
3176
3177        Ok(state_root)
3178    }
3179
3180    // Key format: block_number (8 bytes, big-endian) + block_hash (32 bytes)
3181    fn make_witness_key(block_number: u64, block_hash: &BlockHash) -> Vec<u8> {
3182        let mut composite_key = Vec::with_capacity(8 + 32);
3183        composite_key.extend_from_slice(&block_number.to_be_bytes());
3184        composite_key.extend_from_slice(block_hash.as_bytes());
3185        composite_key
3186    }
3187
3188    /// Stores a pre-serialized execution witness for a block.
3189    ///
3190    /// The witness is converted to RPC format (RpcExecutionWitness) before storage
3191    /// to avoid expensive `encode_subtrie` traversal on every read. This pre-computes
3192    /// the serialization at write time instead of read time.
3193    pub fn store_witness(
3194        &self,
3195        block_hash: BlockHash,
3196        block_number: u64,
3197        witness: ExecutionWitness,
3198    ) -> Result<(), StoreError> {
3199        // Convert to RPC format once at storage time
3200        let rpc_witness = RpcExecutionWitness::try_from(witness)?;
3201        let key = Self::make_witness_key(block_number, &block_hash);
3202        let value = serde_json::to_vec(&rpc_witness)?;
3203        self.write(EXECUTION_WITNESSES, key, value)?;
3204        // Clean up old witnesses (keep only last 128)
3205        self.cleanup_old_witnesses(block_number)
3206    }
3207
3208    fn cleanup_old_witnesses(&self, latest_block_number: u64) -> Result<(), StoreError> {
3209        // If we have less than 128 blocks, no cleanup needed
3210        if latest_block_number <= MAX_WITNESSES {
3211            return Ok(());
3212        }
3213
3214        let threshold = latest_block_number - MAX_WITNESSES;
3215
3216        if let Some(oldest_block_number) = self.get_oldest_witness_number()? {
3217            let prefix = oldest_block_number.to_be_bytes();
3218            let mut to_delete = Vec::new();
3219
3220            {
3221                let read_txn = self.backend.begin_read()?;
3222                let iter = read_txn.prefix_iterator(EXECUTION_WITNESSES, &prefix)?;
3223
3224                // We may have multiple witnesses for the same block number (forks)
3225                for item in iter {
3226                    let (key, _value) = item?;
3227                    let mut block_number_bytes = [0u8; 8];
3228                    block_number_bytes.copy_from_slice(&key[0..8]);
3229                    let block_number = u64::from_be_bytes(block_number_bytes);
3230                    if block_number > threshold {
3231                        break;
3232                    }
3233                    to_delete.push(key.to_vec());
3234                }
3235            }
3236
3237            for key in to_delete {
3238                self.delete(EXECUTION_WITNESSES, key)?;
3239            }
3240        };
3241
3242        self.update_oldest_witness_number(threshold + 1)?;
3243
3244        Ok(())
3245    }
3246
3247    fn update_oldest_witness_number(&self, oldest_block_number: u64) -> Result<(), StoreError> {
3248        self.write(
3249            MISC_VALUES,
3250            b"oldest_witness_block_number".to_vec(),
3251            oldest_block_number.to_le_bytes().to_vec(),
3252        )?;
3253        Ok(())
3254    }
3255
3256    fn get_oldest_witness_number(&self) -> Result<Option<u64>, StoreError> {
3257        let Some(value) = self.read(MISC_VALUES, b"oldest_witness_block_number".to_vec())? else {
3258            return Ok(None);
3259        };
3260
3261        let array: [u8; 8] = value.as_slice().try_into().map_err(|_| {
3262            StoreError::Custom("Invalid oldest witness block number bytes".to_string())
3263        })?;
3264        Ok(Some(u64::from_le_bytes(array)))
3265    }
3266
3267    /// Returns the raw JSON bytes of a cached witness for a block.
3268    ///
3269    /// This is the most efficient method for the RPC handler since it avoids
3270    /// deserialization and re-serialization. The bytes can be parsed directly
3271    /// as a JSON Value for the RPC response.
3272    pub fn get_witness_json_bytes(
3273        &self,
3274        block_number: u64,
3275        block_hash: BlockHash,
3276    ) -> Result<Option<Vec<u8>>, StoreError> {
3277        let key = Self::make_witness_key(block_number, &block_hash);
3278        self.read(EXECUTION_WITNESSES, key)
3279    }
3280
3281    /// Returns the deserialized RpcExecutionWitness for a block.
3282    ///
3283    /// Prefer `get_witness_json_bytes` when you need to return the witness
3284    /// as JSON (e.g., for RPC responses) to avoid re-serialization.
3285    pub fn get_witness_by_number_and_hash(
3286        &self,
3287        block_number: u64,
3288        block_hash: BlockHash,
3289    ) -> Result<Option<RpcExecutionWitness>, StoreError> {
3290        let key = Self::make_witness_key(block_number, &block_hash);
3291        match self.read(EXECUTION_WITNESSES, key)? {
3292            Some(value) => {
3293                let witness: RpcExecutionWitness = serde_json::from_slice(&value)?;
3294                Ok(Some(witness))
3295            }
3296            None => Ok(None),
3297        }
3298    }
3299
3300    /// Stores a block access list for a given block hash.
3301    pub fn store_block_access_list(
3302        &self,
3303        block_hash: BlockHash,
3304        bal: &BlockAccessList,
3305    ) -> Result<(), StoreError> {
3306        let mut value = vec![];
3307        bal.encode(&mut value);
3308        self.store_block_access_list_encoded(block_hash, value)
3309    }
3310
3311    /// Store a block access list the caller has already RLP-encoded, so a caller
3312    /// that also needs the encoded size does not encode it twice.
3313    pub fn store_block_access_list_encoded(
3314        &self,
3315        block_hash: BlockHash,
3316        encoded: Vec<u8>,
3317    ) -> Result<(), StoreError> {
3318        self.write(BLOCK_ACCESS_LISTS, block_hash.as_bytes().to_vec(), encoded)
3319    }
3320
3321    /// Returns the block access list for a given block hash, if stored.
3322    pub fn get_block_access_list(
3323        &self,
3324        block_hash: BlockHash,
3325    ) -> Result<Option<BlockAccessList>, StoreError> {
3326        let key = block_hash.as_bytes().to_vec();
3327        match self.read(BLOCK_ACCESS_LISTS, key)? {
3328            Some(value) => {
3329                let bal = BlockAccessList::decode(&value)
3330                    .map_err(|e| StoreError::Custom(format!("Failed to decode BAL: {e}")))?;
3331                Ok(Some(bal))
3332            }
3333            None => Ok(None),
3334        }
3335    }
3336
3337    /// Fetches block access lists for a slice of block hashes, preserving order.
3338    ///
3339    /// Returns `None` at any position where the BAL is unavailable (unknown block,
3340    /// pre-Amsterdam block, or pruned data). Never errors for individual missing entries.
3341    pub fn iter_block_access_lists_by_hashes(
3342        &self,
3343        hashes: &[BlockHash],
3344    ) -> Result<Vec<Option<BlockAccessList>>, StoreError> {
3345        let mut out = Vec::with_capacity(hashes.len());
3346        for hash in hashes {
3347            out.push(self.get_block_access_list(*hash)?);
3348        }
3349        Ok(out)
3350    }
3351
3352    pub async fn add_initial_state(&mut self, genesis: Genesis) -> Result<(), StoreError> {
3353        self.add_initial_state_inner(genesis, false).await
3354    }
3355
3356    /// Like [`Store::add_initial_state`], but trusts a pre-existing datadir's
3357    /// state instead of validating it against the provided genesis. If a genesis
3358    /// header is already stored, it is kept as-is rather than recomputing the
3359    /// genesis state root from `genesis.alloc` and rejecting on mismatch. The
3360    /// chain config from the genesis file is still applied either way.
3361    ///
3362    /// Intended for booting a datadir produced out-of-band (e.g. by a state
3363    /// generator that writes the state trie directly and emits a genesis file
3364    /// with an empty `alloc`), where the operator vouches for the stored state
3365    /// root. Has no effect on a fresh datadir: the genesis is built normally.
3366    pub async fn add_initial_state_skip_validation(
3367        &mut self,
3368        genesis: Genesis,
3369    ) -> Result<(), StoreError> {
3370        self.add_initial_state_inner(genesis, true).await
3371    }
3372
3373    async fn add_initial_state_inner(
3374        &mut self,
3375        genesis: Genesis,
3376        skip_genesis_validation: bool,
3377    ) -> Result<(), StoreError> {
3378        debug!("Storing initial state from genesis");
3379
3380        // Obtain genesis block
3381        let genesis_block = genesis.get_block();
3382        let genesis_block_number = genesis_block.header.number;
3383
3384        let genesis_hash = genesis_block.hash();
3385
3386        let stored_genesis_header = self.load_block_header(genesis_block_number)?;
3387
3388        // Always set the chain config from the genesis file. The in-memory
3389        // `chain_config` starts at `Default::default()` on every boot and is
3390        // not reloaded from the datadir, so skipping this would leave the store
3391        // with the wrong chainId and an empty fork schedule. Skip-validation
3392        // only waives the genesis state-root/header check; the `config` section
3393        // of the genesis file is still authoritative and must be applied.
3394        self.set_chain_config(&genesis.config).await?;
3395
3396        // The cache can't be empty. Clamp the head to the durable block: after a
3397        // crash, `LatestBlockNumber` can be ahead of `flushed_upto` (FCU writes the
3398        // head synchronously while block bodies are buffered), so loading the raw
3399        // latest header would brick boot when its body was never flushed.
3400        if let Some(latest) = self.load_latest_block_number().await? {
3401            self.anchor_to_durable_head(latest).await?;
3402        }
3403
3404        match stored_genesis_header {
3405            Some(header) if skip_genesis_validation => {
3406                info!(
3407                    stored_genesis = %header.hash(),
3408                    "Skipping genesis state validation; trusting the genesis header and state already stored in the datadir"
3409                );
3410                return Ok(());
3411            }
3412            Some(header) if header.hash() == genesis_hash => {
3413                info!("Received genesis file matching a previously stored one, nothing to do");
3414                return Ok(());
3415            }
3416            Some(_) => {
3417                error!(
3418                    "The chain configuration stored in the database is incompatible with the provided configuration. If you intended to switch networks, choose another datadir or clear the database (e.g., run `ethrex removedb`) and try again."
3419                );
3420                return Err(StoreError::IncompatibleChainConfig);
3421            }
3422            None => {
3423                self.add_block_header(genesis_hash, genesis_block.header.clone())
3424                    .await?
3425            }
3426        }
3427        // Store genesis accounts
3428        // TODO: Should we use this root instead of computing it before the block hash check?
3429        let genesis_state_root = self.setup_genesis_state_trie(genesis.alloc).await?;
3430        debug_assert_eq!(genesis_state_root, genesis_block.header.state_root);
3431
3432        // Store genesis block
3433        info!(hash = %genesis_hash, "Storing genesis block");
3434
3435        self.add_block(genesis_block).await?;
3436        self.update_earliest_block_number(genesis_block_number)
3437            .await?;
3438        // A new database tracks its history bounds from the first block, so it has none
3439        // from before the tracking to reconcile. Only this path marks one: the early
3440        // returns above are for a database that already holds a genesis, which may
3441        // predate the tracking. They need the genesis to be canonical, which only the
3442        // forkchoice update below makes it, so a stop before that repeats this path
3443        // and cannot leave a new database unmarked.
3444        self.mark_history_bounds_reconciled(None).await?;
3445        self.forkchoice_update(vec![], genesis_block_number, genesis_hash, None, None)
3446            .await?;
3447        Ok(())
3448    }
3449
3450    pub async fn load_initial_state(&self) -> Result<(), StoreError> {
3451        info!("Loading initial state from DB");
3452        let Some(latest) = self.load_latest_block_number().await? else {
3453            return Err(StoreError::MissingLatestBlockNumber);
3454        };
3455        // Use the same durable-head clamp as the node boot path so export and the
3456        // running node agree on the head. The persisted head is only rewritten when
3457        // it actually moved, so a plain export run does not mutate `CHAIN_DATA`.
3458        self.anchor_to_durable_head(latest).await?;
3459        Ok(())
3460    }
3461
3462    pub fn get_storage_at(
3463        &self,
3464        block_number: BlockNumber,
3465        address: Address,
3466        storage_key: H256,
3467    ) -> Result<Option<U256>, StoreError> {
3468        match self.get_block_header(block_number)? {
3469            Some(header) => self.get_storage_at_root(header.state_root, address, storage_key),
3470            None => Ok(None),
3471        }
3472    }
3473
3474    pub fn get_storage_at_root(
3475        &self,
3476        state_root: H256,
3477        address: Address,
3478        storage_key: H256,
3479    ) -> Result<Option<U256>, StoreError> {
3480        // Pre-acquire shared resources once for both trie opens
3481        let read_view = self.backend.begin_read()?;
3482        let cache = self.gated_snapshot(state_root)?;
3483        let last_written = self.last_written()?;
3484        self.storage_at_with(
3485            state_root,
3486            address,
3487            storage_key,
3488            read_view,
3489            cache,
3490            last_written,
3491        )
3492    }
3493
3494    /// [`Self::get_storage_at_root`] over resources the caller already holds,
3495    /// such as a [`StateView`]'s.
3496    fn storage_at_with(
3497        &self,
3498        state_root: H256,
3499        address: Address,
3500        storage_key: H256,
3501        read_view: Arc<dyn StorageReadView>,
3502        cache: Arc<TrieLayerCache>,
3503        last_written: Vec<u8>,
3504    ) -> Result<Option<U256>, StoreError> {
3505        let account_hash = hash_address_fixed(&address);
3506        // While a deep-reorg overlay serves this root, flat-KV reads must
3507        // go through the trie: journal entries written while the FKV generator was
3508        // running lack pre-images for keys past the generator frontier, so disk
3509        // flat-KV may hold the generator's stale values. `TrieWrapper` already
3510        // forces the trie-node read path in this window; mirror the gate here so
3511        // the EMPTY_TRIE_HASH shortcut doesn't bypass it.
3512        let use_fkv = Self::flatkeyvalue_computed_with_last_written(account_hash, &last_written)
3513            && !cache.overlay_serves(state_root);
3514
3515        let storage_root = if use_fkv {
3516            // We will use FKVs, we don't need the root
3517            EMPTY_TRIE_HASH
3518        } else {
3519            let state_trie = self.open_state_trie_shared(
3520                state_root,
3521                read_view.clone(),
3522                cache.clone(),
3523                last_written.clone(),
3524            )?;
3525            let Some(encoded_account) = state_trie.get(account_hash.as_bytes())? else {
3526                return Ok(None);
3527            };
3528            let account = AccountState::decode(&encoded_account)?;
3529            account.storage_root
3530        };
3531        let storage_trie = self.open_storage_trie_shared(
3532            account_hash,
3533            state_root,
3534            storage_root,
3535            read_view,
3536            cache,
3537            last_written,
3538        )?;
3539
3540        let hashed_key = hash_key_fixed(&storage_key);
3541        storage_trie
3542            .get(&hashed_key)?
3543            .map(|rlp| U256::decode(&rlp).map_err(StoreError::RLPDecode))
3544            .transpose()
3545    }
3546
3547    /// Gets storage value when the account hash and storage root are already known.
3548    ///
3549    /// This skips the state-trie account lookup and account RLP decode done by
3550    /// [`Self::get_storage_at_root`], and directly opens the account storage trie.
3551    pub fn get_storage_at_root_with_known_storage_root(
3552        &self,
3553        state_root: H256,
3554        account_hash: H256,
3555        storage_root: H256,
3556        storage_key: H256,
3557    ) -> Result<Option<U256>, StoreError> {
3558        let read_view = self.backend.begin_read()?;
3559        let cache = self.gated_snapshot(state_root)?;
3560        let last_written = self.last_written()?;
3561        // When FKV is active the real storage root is in the flatkeyvalue store,
3562        // not in the account's RLP-encoded storage_root field. Use EMPTY_TRIE_HASH
3563        // so open_storage_trie_shared falls through to the FKV path. While a
3564        // deep-reorg overlay serves this root, keep the real root instead:
3565        // disk flat-KV may hold stale generator values, so reads must go through
3566        // the trie (see `TrieWrapper::flatkeyvalue_computed`).
3567        let storage_root =
3568            if Self::flatkeyvalue_computed_with_last_written(account_hash, &last_written)
3569                && !cache.overlay_serves(state_root)
3570            {
3571                EMPTY_TRIE_HASH
3572            } else {
3573                storage_root
3574            };
3575        let storage_trie = self.open_storage_trie_shared(
3576            account_hash,
3577            state_root,
3578            storage_root,
3579            read_view,
3580            cache,
3581            last_written,
3582        )?;
3583
3584        let hashed_key = hash_key_fixed(&storage_key);
3585        storage_trie
3586            .get(&hashed_key)?
3587            .map(|rlp| U256::decode(&rlp).map_err(StoreError::RLPDecode))
3588            .transpose()
3589    }
3590
3591    pub fn get_chain_config(&self) -> ChainConfig {
3592        self.chain_config
3593    }
3594
3595    pub async fn get_latest_canonical_block_hash(&self) -> Result<Option<BlockHash>, StoreError> {
3596        Ok(Some(self.latest_block_header.get().hash()))
3597    }
3598
3599    /// Updates the canonical chain.
3600    /// Inserts new canonical blocks, removes blocks beyond the new head,
3601    /// and updates the head, safe, and finalized block pointers.
3602    /// All operations are performed in a single database transaction.
3603    pub async fn forkchoice_update(
3604        &self,
3605        new_canonical_blocks: Vec<(BlockNumber, BlockHash)>,
3606        head_number: BlockNumber,
3607        head_hash: BlockHash,
3608        safe: Option<BlockNumber>,
3609        finalized: Option<BlockNumber>,
3610    ) -> Result<(), StoreError> {
3611        // Serialize concurrent forkchoice updates. Without this, two callers
3612        // could interleave their `latest_block_header` cache updates with each
3613        // other's DB writes, leaving the cache inconsistent with the DB or
3614        // letting a later caller's write reorder relative to the cache update
3615        // order (see the TOCTOU discussion around canonical/latest drift).
3616        let _guard = self.fcu_lock.lock().await;
3617
3618        // Updates first the latest_block_header to avoid nonce inconsistencies #3927.
3619        // Snapshot the previous header so we can roll the cache back if the DB
3620        // write fails — otherwise the cache would point at a block the DB does
3621        // not consider canonical.
3622        let previous_head = self.latest_block_header.get();
3623        let new_head = self
3624            .get_block_header_by_hash(head_hash)?
3625            .ok_or_else(|| StoreError::MissingLatestBlockNumber)?;
3626        self.latest_block_header.update(new_head);
3627        if let Err(err) = self
3628            .forkchoice_update_inner(
3629                new_canonical_blocks,
3630                head_number,
3631                head_hash,
3632                safe,
3633                finalized,
3634            )
3635            .await
3636        {
3637            self.latest_block_header.update((*previous_head).clone());
3638            return Err(err);
3639        }
3640        self.notify_sync_status_changed();
3641
3642        // Refresh the canonical safe-commit root now that the canonical tables reflect the new
3643        // head. `None` (chain shorter than the threshold, e.g. genesis init at head 0) leaves the
3644        // cell unchanged so genesis-on-disk is never gated away.
3645        // No `latest_block_header` rollback on error here (unlike the `inner` failure above): the
3646        // only error is a poisoned safe-commit `RwLock`, which is an unrecoverable process state.
3647        if let Some(root) = self.compute_safe_commit_root(head_number)? {
3648            // Advancing the cell alone does not flush: the commit step (Phase 2) only runs
3649            // while blocks execute, so an execute-all-then-one-forkchoice flow (e.g. block
3650            // import) would accumulate every layer and never persist. When the safe-commit
3651            // root advances, poke the worker to flush the now-committable backlog up to it.
3652            if self.set_safe_commit_root(root)? {
3653                let tx = self.persist_tx.clone();
3654                let _ = tokio::task::spawn_blocking(move || tx.send(PersistMessage::Commit(root)))
3655                    .await;
3656            }
3657        }
3658
3659        Ok(())
3660    }
3661
3662    /// Updates the dedicated safe-commit-root cell with the given state root,
3663    /// returning `true` if the cell changed (so callers can skip a redundant flush).
3664    ///
3665    /// This is a plain synchronous function; it touches only the dedicated cell
3666    /// and is disjoint from the trie-cache Arc (no cache clone or replacement).
3667    /// Crate-private: only `forkchoice_update` (post-canonicalization) may set it,
3668    /// preserving the invariant that the cell only ever holds a canonical state root.
3669    pub(crate) fn set_safe_commit_root(&self, root: H256) -> Result<bool, StoreError> {
3670        let mut guard = self
3671            .safe_commit_root
3672            .write()
3673            .map_err(|_| StoreError::LockError)?;
3674        let changed = *guard != root;
3675        *guard = root;
3676        Ok(changed)
3677    }
3678
3679    /// Computes the canonical safe-commit state root: the state root of the canonical block
3680    /// `commit_threshold` layers below `head`.
3681    ///
3682    /// Returns `Ok(None)` when the chain is shorter than the threshold (underflow), or when the
3683    /// target block is not yet canonical / its header is absent. Synchronous getters only; no
3684    /// await and no lock guard held across one. The threshold is read from the trie cache to
3685    /// avoid duplicating the IN_MEMORY/DB selection that `from_backend` already made.
3686    /// Crate-private: only `forkchoice_update` consumes it.
3687    pub(crate) fn compute_safe_commit_root(
3688        &self,
3689        head: BlockNumber,
3690    ) -> Result<Option<H256>, StoreError> {
3691        let commit_threshold = self
3692            .trie_cache
3693            .read()
3694            .map_err(|_| StoreError::LockError)?
3695            .commit_threshold;
3696        let Some(target) = head.checked_sub(commit_threshold as u64) else {
3697            return Ok(None);
3698        };
3699        let Some(hash) = self.get_canonical_block_hash_sync(target)? else {
3700            return Ok(None);
3701        };
3702        let Some(header) = self.get_block_header_by_hash(hash)? else {
3703            return Ok(None);
3704        };
3705        Ok(Some(header.state_root))
3706    }
3707
3708    /// Obtain the storage trie for the given block
3709    pub fn state_trie(&self, block_hash: BlockHash) -> Result<Option<Trie>, StoreError> {
3710        let Some(header) = self.get_block_header_by_hash(block_hash)? else {
3711            return Ok(None);
3712        };
3713        Ok(Some(self.open_state_trie(header.state_root)?))
3714    }
3715
3716    /// Obtain the storage trie for the given account on the given block
3717    pub fn storage_trie(
3718        &self,
3719        block_hash: BlockHash,
3720        address: Address,
3721    ) -> Result<Option<Trie>, StoreError> {
3722        let Some(header) = self.get_block_header_by_hash(block_hash)? else {
3723            return Ok(None);
3724        };
3725        // Fetch Account from state_trie
3726        let Some(state_trie) = self.state_trie(block_hash)? else {
3727            return Ok(None);
3728        };
3729        let hashed_address = hash_address_fixed(&address);
3730        let Some(encoded_account) = state_trie.get(hashed_address.as_bytes())? else {
3731            return Ok(None);
3732        };
3733        let account = AccountState::decode(&encoded_account)?;
3734        // Open storage_trie
3735        let storage_root = account.storage_root;
3736        Ok(Some(self.open_storage_trie(
3737            hashed_address,
3738            header.state_root,
3739            storage_root,
3740        )?))
3741    }
3742
3743    pub async fn get_account_state(
3744        &self,
3745        block_number: BlockNumber,
3746        address: Address,
3747    ) -> Result<Option<AccountState>, StoreError> {
3748        let Some(block_hash) = self.get_canonical_block_hash(block_number).await? else {
3749            return Ok(None);
3750        };
3751        let Some(state_trie) = self.state_trie(block_hash)? else {
3752            return Ok(None);
3753        };
3754        self.get_account_state_from_trie(&state_trie, address)
3755    }
3756
3757    pub fn get_account_state_by_root(
3758        &self,
3759        state_root: H256,
3760        address: Address,
3761    ) -> Result<Option<AccountState>, StoreError> {
3762        let state_trie = self.open_state_trie(state_root)?;
3763        self.get_account_state_from_trie(&state_trie, address)
3764    }
3765
3766    pub fn get_account_state_from_trie(
3767        &self,
3768        state_trie: &Trie,
3769        address: Address,
3770    ) -> Result<Option<AccountState>, StoreError> {
3771        let hashed_address = hash_address_fixed(&address);
3772        let Some(encoded_state) = state_trie.get(hashed_address.as_bytes())? else {
3773            return Ok(None);
3774        };
3775        Ok(Some(AccountState::decode(&encoded_state)?))
3776    }
3777
3778    /// Batch lookup of account states by address against a given state root.
3779    ///
3780    /// Fast path: for addresses whose hashed path falls within the FKV cursor
3781    /// (and which are not present in the in-memory diff-layer cache), values
3782    /// are fetched in a single `multi_get` on `ACCOUNT_FLATKEYVALUE`. Other
3783    /// addresses fall back to per-address trie walks.
3784    ///
3785    /// Results are returned in the same order as the input addresses.
3786    pub fn get_account_states_batch_by_root(
3787        &self,
3788        state_root: H256,
3789        addresses: &[Address],
3790    ) -> Result<Vec<Option<AccountState>>, StoreError> {
3791        if addresses.is_empty() {
3792            return Ok(Vec::new());
3793        }
3794
3795        let last_written = self.last_written()?;
3796        let trie_cache = self
3797            .trie_cache
3798            .read()
3799            .map_err(|_| StoreError::LockError)?
3800            .clone();
3801
3802        let mut results: Vec<Option<AccountState>> = vec![None; addresses.len()];
3803        // Per-address leaf paths (nibbles + leaf flag). Length 65.
3804        let leaf_paths: Vec<Vec<u8>> = addresses
3805            .iter()
3806            .map(|addr| {
3807                let hashed = hash_address_fixed(addr);
3808                Nibbles::from_bytes(hashed.as_bytes()).into_vec()
3809            })
3810            .collect();
3811
3812        let mut fkv_indices: Vec<usize> = Vec::new();
3813        let mut trie_indices: Vec<usize> = Vec::new();
3814
3815        // Match `BackendTrieDB::flatkeyvalue_computed` semantics: a path is
3816        // covered by FKV iff `last_written >= path` as raw nibble bytes. This
3817        // is the same check `Trie::get` uses; the related helper
3818        // `Store::flatkeyvalue_computed_with_last_written` slices `[0..64]`
3819        // and is intentionally more conservative — using that here would
3820        // unnecessarily fall back to the trie when the cursor sits inside an
3821        // account's storage sweep (the account leaf is already in FKV at that
3822        // point; see `flatkeyvalue_generator`).
3823        //
3824        // While a deep-reorg overlay serves this root, skip the FKV fast
3825        // path entirely: this function never consults the overlay, and disk
3826        // flat-KV may hold values the generator computed against the chain being
3827        // reorged away (journal entries written during generation lack
3828        // past-frontier flat-KV pre-images). The per-address trie fallback goes
3829        // through `TrieWrapper`, which routes reads through the overlay.
3830        let overlay_active = trie_cache.overlay_serves(state_root);
3831        let fkv_cursor: &[u8] = last_written.as_slice();
3832        for (i, path) in leaf_paths.iter().enumerate() {
3833            if let Some(value) = trie_cache.get(state_root, path.as_slice()) {
3834                if !value.is_empty() {
3835                    results[i] = Some(AccountState::decode(&value)?);
3836                }
3837                continue;
3838            }
3839            if !overlay_active && fkv_cursor >= path.as_slice() {
3840                fkv_indices.push(i);
3841            } else {
3842                trie_indices.push(i);
3843            }
3844        }
3845
3846        if !fkv_indices.is_empty() {
3847            // Sort by the prefixed (hashed-order) key so adjacent accounts land
3848            // in the same RocksDB data blocks, then read the sorted keys in
3849            // contiguous shards concurrently. A single `multi_get` runs the whole
3850            // batch at queue depth 1 (async_io is off), which on a cold account-
3851            // heavy block serializes thousands of random reads (coldbench: ~13x
3852            // slower than this sharded path). Mirrors the storage FKV batch.
3853            fkv_indices.sort_unstable_by(|&a, &b| leaf_paths[a].cmp(&leaf_paths[b]));
3854            let read_view = self.backend.begin_read()?;
3855            let keys: Vec<&[u8]> = fkv_indices
3856                .iter()
3857                .map(|&i| leaf_paths[i].as_slice())
3858                .collect();
3859            let shards = shard_count(keys.len());
3860            let raw: Vec<Result<Option<Vec<u8>>, StoreError>> = if shards <= 1 {
3861                read_view.multi_get(ACCOUNT_FLATKEYVALUE, &keys)
3862            } else {
3863                let chunk = keys.len().div_ceil(shards);
3864                let rv = read_view.as_ref();
3865                std::thread::scope(|scope| {
3866                    let handles: Vec<_> = keys
3867                        .chunks(chunk)
3868                        .map(|ck| scope.spawn(move || rv.multi_get(ACCOUNT_FLATKEYVALUE, ck)))
3869                        .collect();
3870                    handles
3871                        .into_iter()
3872                        // A panicked shard yields one Err element rather than
3873                        // re-panicking the whole node; the consumer's `?` below
3874                        // surfaces it to the caller. Every caller of this batch
3875                        // treats a failed warm as best-effort, so the keys are
3876                        // simply left uncached and read normally later.
3877                        .flat_map(|h| {
3878                            h.join().unwrap_or_else(|_| {
3879                                vec![Err(StoreError::Custom(
3880                                    "account prefetch shard panicked".into(),
3881                                ))]
3882                            })
3883                        })
3884                        .collect()
3885                })
3886            };
3887            for (slot, res) in fkv_indices.iter().zip(raw.into_iter()) {
3888                let Some(encoded) = res? else { continue };
3889                if encoded.is_empty() {
3890                    continue;
3891                }
3892                results[*slot] = Some(AccountState::decode(&encoded)?);
3893            }
3894        }
3895
3896        if !trie_indices.is_empty() {
3897            // Fall back to the regular trie path for any addresses whose path
3898            // hasn't been swept by the FKV generator yet. Parallelized to
3899            // recover the per-address fan-out the pre-batch `par_iter` path
3900            // had, which matters during initial sync when most addresses
3901            // miss FKV.
3902            let state_trie = self.open_state_trie(state_root)?;
3903            let fetched: Result<Vec<(usize, Option<AccountState>)>, StoreError> = trie_indices
3904                .par_iter()
3905                .map(|&i| {
3906                    self.get_account_state_from_trie(&state_trie, addresses[i])
3907                        .map(|s| (i, s))
3908                })
3909                .collect();
3910            for (i, s) in fetched? {
3911                results[i] = s;
3912            }
3913        }
3914
3915        Ok(results)
3916    }
3917
3918    /// Batch lookup of storage slot values against a given state root.
3919    ///
3920    /// Each input tuple is `(account_hash, storage_root, slot)` where
3921    /// `account_hash` is the keccak hash of the account address and `slot` is
3922    /// the raw (un-hashed) storage key, matching the inputs available to
3923    /// [`Self::get_storage_at_root_with_known_storage_root`].
3924    ///
3925    /// Fast path: for slots whose prefixed FKV leaf path falls within the FKV
3926    /// cursor (and which are not present in the in-memory diff-layer cache),
3927    /// values are fetched in a single `multi_get` on `STORAGE_FLATKEYVALUE`.
3928    /// The batch is sorted by the prefixed FKV key (hashed order) before the
3929    /// `multi_get` so that adjacent slots share RocksDB data blocks, removing
3930    /// the random-order read amplification of per-slot lookups. Slots not yet
3931    /// swept by the FKV generator fall back to per-slot trie walks via
3932    /// [`Self::get_storage_at_root_with_known_storage_root`], which preserves the
3933    /// exact FKV / trie / diff-cache ordering of the single-slot path.
3934    ///
3935    /// Results are returned in the same order as the input slots. A missing slot
3936    /// (deleted or never written) yields `None`, identical to the single-get path.
3937    pub fn get_storage_values_batch_by_root(
3938        &self,
3939        state_root: H256,
3940        slots: &[(H256, H256, H256)],
3941    ) -> Result<Vec<Option<U256>>, StoreError> {
3942        if slots.is_empty() {
3943            return Ok(Vec::new());
3944        }
3945
3946        let last_written = self.last_written()?;
3947        let trie_cache = self
3948            .trie_cache
3949            .read()
3950            .map_err(|_| StoreError::LockError)?
3951            .clone();
3952
3953        let mut results: Vec<Option<U256>> = vec![None; slots.len()];
3954        // Per-slot prefixed FKV leaf paths, length 131: 64 account-hash nibbles
3955        // + 1 (account leaf flag) + 1 (separator) + 64 hashed-slot nibbles + 1
3956        // (storage leaf flag). This is the exact key
3957        // `BackendTrieDB::flatkeyvalue_computed` / `Trie::get` use for a storage
3958        // leaf (see `apply_prefix`).
3959        let leaf_paths: Vec<Vec<u8>> = slots
3960            .iter()
3961            .map(|(account_hash, _storage_root, slot)| {
3962                let hashed_slot = hash_key_fixed(slot);
3963                apply_prefix(Some(*account_hash), Nibbles::from_bytes(&hashed_slot)).into_vec()
3964            })
3965            .collect();
3966
3967        let mut fkv_indices: Vec<usize> = Vec::new();
3968        let mut trie_indices: Vec<usize> = Vec::new();
3969
3970        // Same watermark check as the account batch and `BackendTrieDB`: a path
3971        // is covered by FKV iff `last_written >= prefixed_path` compared as raw
3972        // nibble bytes. `Nibbles` orders by its inner `data` vec, so the raw
3973        // slice comparison is byte-identical to the `Nibbles >= Nibbles` check
3974        // in `BackendTrieDB::flatkeyvalue_computed`.
3975        //
3976        // While a deep-reorg overlay serves this root, skip the FKV fast path
3977        // entirely: this function never consults the overlay, and disk flat-KV may
3978        // hold values the generator computed against the chain being reorged away
3979        // (journal entries written during generation lack past-frontier flat-KV
3980        // pre-images). The per-slot trie fallback reads through `TrieWrapper`, which
3981        // routes through the overlay. Mirrors the gate in
3982        // `get_storage_at_root` and `get_account_states_batch_by_root`.
3983        let overlay_active = trie_cache.overlay_serves(state_root);
3984        let fkv_cursor: &[u8] = last_written.as_slice();
3985        for (i, path) in leaf_paths.iter().enumerate() {
3986            // Diff-layer cache holds the authoritative latest value for this
3987            // key at this state root, overriding both FKV and trie. Mirror the
3988            // cache-first semantics of `TrieWrapper::get` / the account batch:
3989            // an empty cached value means the slot was deleted -> None.
3990            if let Some(value) = trie_cache.get(state_root, path.as_slice()) {
3991                if !value.is_empty() {
3992                    results[i] = Some(U256::decode(&value).map_err(StoreError::RLPDecode)?);
3993                }
3994                continue;
3995            }
3996            if !overlay_active && fkv_cursor >= path.as_slice() {
3997                fkv_indices.push(i);
3998            } else {
3999                trie_indices.push(i);
4000            }
4001        }
4002
4003        if !fkv_indices.is_empty() {
4004            // Sort the FKV batch by the prefixed (hashed-order) key so adjacent
4005            // slots land in the same 4KB RocksDB data blocks. This is the whole
4006            // point of the batch: it removes the random-order amplification of
4007            // issuing one point lookup per slot in execution order.
4008            fkv_indices.sort_unstable_by(|&a, &b| leaf_paths[a].cmp(&leaf_paths[b]));
4009            let read_view = self.backend.begin_read()?;
4010            let keys: Vec<&[u8]> = fkv_indices
4011                .iter()
4012                .map(|&i| leaf_paths[i].as_slice())
4013                .collect();
4014            // Sharded parallel multi_get. A single `multi_get` runs the whole
4015            // batch serially inside RocksDB (async_io is OFF in our build, so
4016            // no io_uring => queue depth ~= 1), which on a cold NVMe is purely
4017            // read-latency-bound: it touches few blocks (sorted) but serializes
4018            // them. Splitting the SORTED keys into contiguous shards read by
4019            // separate blocking threads keeps the per-shard block sharing while
4020            // issuing the shards concurrently, so effective queue depth ~= shard
4021            // count. On a bloated-account cold read this is ~4.7x a single
4022            // multi_get and ~4.6x the per-slot `par_iter` baseline (coldbench).
4023            // Shard count scales with batch size and is capped; small batches
4024            // run a single in-line multi_get (no thread spawn). All shards share
4025            // one read view (one snapshot) so the reads stay consistent.
4026            let shards = shard_count(keys.len());
4027            let raw: Vec<Result<Option<Vec<u8>>, StoreError>> = if shards <= 1 {
4028                read_view.multi_get(STORAGE_FLATKEYVALUE, &keys)
4029            } else {
4030                let chunk = keys.len().div_ceil(shards);
4031                let rv = read_view.as_ref();
4032                std::thread::scope(|scope| {
4033                    let handles: Vec<_> = keys
4034                        .chunks(chunk)
4035                        .map(|ck| scope.spawn(move || rv.multi_get(STORAGE_FLATKEYVALUE, ck)))
4036                        .collect();
4037                    handles
4038                        .into_iter()
4039                        // A panicked shard yields one Err element rather than
4040                        // re-panicking the whole node; the consumer's `?` below
4041                        // surfaces it to the caller. Every caller of this batch
4042                        // treats a failed warm as best-effort, so the keys are
4043                        // simply left uncached and read normally later.
4044                        .flat_map(|h| {
4045                            h.join().unwrap_or_else(|_| {
4046                                vec![Err(StoreError::Custom(
4047                                    "storage prefetch shard panicked".into(),
4048                                ))]
4049                            })
4050                        })
4051                        .collect()
4052                })
4053            };
4054            for (slot_idx, res) in fkv_indices.iter().zip(raw.into_iter()) {
4055                let Some(encoded) = res? else { continue };
4056                if encoded.is_empty() {
4057                    continue;
4058                }
4059                results[*slot_idx] = Some(U256::decode(&encoded).map_err(StoreError::RLPDecode)?);
4060            }
4061        }
4062
4063        if !trie_indices.is_empty() {
4064            // Fall back to the regular single-slot path for any slot whose path
4065            // hasn't been swept by the FKV generator yet. Reusing
4066            // `get_storage_at_root_with_known_storage_root` guarantees the
4067            // trie-walk fallback is byte-identical to the unbatched read,
4068            // including its own per-slot FKV / EMPTY_TRIE_HASH handling.
4069            // Parallelized to recover the per-slot fan-out the pre-batch
4070            // `par_iter` prefetch path had.
4071            let fetched: Result<Vec<(usize, Option<U256>)>, StoreError> = trie_indices
4072                .par_iter()
4073                .map(|&i| {
4074                    let (account_hash, storage_root, slot) = slots[i];
4075                    self.get_storage_at_root_with_known_storage_root(
4076                        state_root,
4077                        account_hash,
4078                        storage_root,
4079                        slot,
4080                    )
4081                    .map(|v| (i, v))
4082                })
4083                .collect();
4084            for (i, v) in fetched? {
4085                results[i] = v;
4086            }
4087        }
4088
4089        Ok(results)
4090    }
4091
4092    /// Best-effort warming of the MPT *internal* nodes the merkleizer will walk,
4093    /// driven entirely by the BAL working set. The merkle phase reads trie nodes
4094    /// from `STORAGE_TRIE_NODES` / `ACCOUNT_TRIE_NODES` (see `BackendTrieDB::get`)
4095    /// by nibble path; the existing flat-KV prefetch warms only the leaf-value
4096    /// CFs that *execution* reads, so every merkle-walk node read is otherwise
4097    /// cold. This pulls those node blocks into the page/block cache up front so
4098    /// the subsequent walk runs warm.
4099    ///
4100    /// The keys are not discovered by walking (a walk is QD1 and serial): the
4101    /// internal nodes on the path to a leaf are all at *prefixes* of that leaf's
4102    /// nibble path, so for every BAL leaf we speculatively probe every prefix up
4103    /// to `MAX_PREFETCH_DEPTH`. Prefixes that are not real nodes are rejected by
4104    /// the CF bloom filter in RAM (no disk read; measured ~free), and the shallow
4105    /// prefixes collapse on dedup. This turns the cold merkle node reads into one
4106    /// sorted, sharded, high-queue-depth `multi_get` per CF — the same lever that
4107    /// fixed the flat-KV `sload` path, applied to the trie-node CFs.
4108    ///
4109    /// Results are discarded. Missing a node (e.g. one deeper than the probe
4110    /// band) is harmless: the merkleizer just cold-reads it. Run this
4111    /// synchronously up front (mirroring the flat-KV prefetch) so it never races
4112    /// the merkleizer; it touches different CFs than execution, so it does not
4113    /// contend with the executor either.
4114    /// Returns the number of probed keys that hit a real stored node (warmed).
4115    /// On the warm/no-op path this still reports coverage; a near-zero hit count
4116    /// against a non-empty working set signals a key-encoding mismatch (the
4117    /// effectiveness test asserts on this).
4118    pub fn prefetch_trie_nodes(
4119        &self,
4120        storage_slots: &[(Address, H256)],
4121        accounts: &[Address],
4122    ) -> Result<usize, StoreError> {
4123        // Probe band: nodes live at depth <= ~ceil(log16(trie_size)). 8 nibbles
4124        // covers tries up to ~16^8 entries near-fully; any deeper node is simply
4125        // cold-read by the walk, so under-covering only loses a little warming,
4126        // never correctness. Tunable.
4127        const MAX_PREFETCH_DEPTH: usize = 8;
4128
4129        // STORAGE_TRIE_NODES: prefixes of apply_prefix(hashed_addr, hashed_slot).
4130        // Each input pushes MAX_PREFETCH_DEPTH+1 prefixes (depths 0..=max_d).
4131        let mut storage_keys: Vec<Vec<u8>> =
4132            Vec::with_capacity(storage_slots.len() * (MAX_PREFETCH_DEPTH + 1));
4133        for (address, slot) in storage_slots {
4134            let hashed_address = hash_address_fixed(address);
4135            let hashed_slot = hash_key_fixed(slot);
4136            let slot_nibbles = Nibbles::from_bytes(&hashed_slot);
4137            let max_d = MAX_PREFETCH_DEPTH.min(slot_nibbles.len());
4138            for d in 0..=max_d {
4139                let prefix = apply_prefix(Some(hashed_address), slot_nibbles.slice(0, d));
4140                storage_keys.push(prefix.into_vec());
4141            }
4142        }
4143
4144        // ACCOUNT_TRIE_NODES: prefixes of the hashed address (no account prefix).
4145        let mut account_keys: Vec<Vec<u8>> =
4146            Vec::with_capacity(accounts.len() * (MAX_PREFETCH_DEPTH + 1));
4147        for address in accounts {
4148            let hashed_address = hash_address_fixed(address);
4149            let addr_nibbles = Nibbles::from_bytes(hashed_address.as_bytes());
4150            let max_d = MAX_PREFETCH_DEPTH.min(addr_nibbles.len());
4151            for d in 0..=max_d {
4152                account_keys.push(addr_nibbles.slice(0, d).into_vec());
4153            }
4154        }
4155
4156        let hits = self.warm_trie_node_keys(STORAGE_TRIE_NODES, storage_keys)?
4157            + self.warm_trie_node_keys(ACCOUNT_TRIE_NODES, account_keys)?;
4158        Ok(hits)
4159    }
4160
4161    /// Sorted, sharded, high-queue-depth `multi_get` over `keys` in `table`,
4162    /// discarding results. Sorting makes adjacent keys share RocksDB data blocks;
4163    /// sharding across blocking threads issues the reads at queue depth ~= shard
4164    /// count (async_io is off, so a single multi_get runs at QD1). Mirrors the
4165    /// storage flat-KV batch path. Dedups first so shared shallow prefixes are
4166    /// read once.
4167    fn warm_trie_node_keys(
4168        &self,
4169        table: &'static str,
4170        mut keys: Vec<Vec<u8>>,
4171    ) -> Result<usize, StoreError> {
4172        if keys.is_empty() {
4173            return Ok(0);
4174        }
4175        keys.sort_unstable();
4176        keys.dedup();
4177
4178        let shards = shard_count(keys.len());
4179        let read_view = self.backend.begin_read()?;
4180        let count_hits = |res: Vec<Result<Option<Vec<u8>>, StoreError>>| {
4181            res.into_iter().filter(|r| matches!(r, Ok(Some(_)))).count()
4182        };
4183        if shards <= 1 {
4184            let refs: Vec<&[u8]> = keys.iter().map(|k| k.as_slice()).collect();
4185            return Ok(count_hits(read_view.multi_get(table, &refs)));
4186        }
4187        let chunk = keys.len().div_ceil(shards);
4188        let rv = read_view.as_ref();
4189        let hits = std::thread::scope(|scope| {
4190            let handles: Vec<_> = keys
4191                .chunks(chunk)
4192                .map(|ck| {
4193                    scope.spawn(move || {
4194                        let refs: Vec<&[u8]> = ck.iter().map(|k| k.as_slice()).collect();
4195                        // Warm-only: keep cache population, just tally the hits.
4196                        count_hits(rv.multi_get(table, &refs))
4197                    })
4198                })
4199                .collect();
4200            handles
4201                .into_iter()
4202                // Best-effort warming: a panicked shard contributes 0 hits rather
4203                // than re-panicking. The caller treats this prefetch as best-effort
4204                // (missing nodes are just cold-read by the walk), so a shard hiccup
4205                // must not unwind block processing.
4206                .map(|h| h.join().unwrap_or(0))
4207                .sum::<usize>()
4208        });
4209        Ok(hits)
4210    }
4211
4212    /// Constructs a merkle proof for the given account address against a given state.
4213    /// If storage_keys are provided, also constructs the storage proofs for those keys.
4214    ///
4215    /// Returns `None` if the state trie is missing, otherwise returns the proof.
4216    pub async fn get_account_proof(
4217        &self,
4218        state_root: H256,
4219        address: Address,
4220        storage_keys: &[H256],
4221    ) -> Result<Option<AccountProof>, StoreError> {
4222        // TODO: check state root
4223        // let Some(state_trie) = self.open_state_trie(state_trie)? else {
4224        //     return Ok(None);
4225        // };
4226        let state_trie = self.open_state_trie(state_root)?;
4227        let address_path = hash_address_fixed(&address);
4228        let proof = state_trie.get_proof(address_path.as_bytes())?;
4229        let account_opt = state_trie
4230            .get(address_path.as_bytes())?
4231            .map(|encoded_state| AccountState::decode(&encoded_state))
4232            .transpose()?;
4233
4234        let mut storage_proof = Vec::with_capacity(storage_keys.len());
4235
4236        if let Some(account) = &account_opt {
4237            let storage_trie =
4238                self.open_storage_trie(address_path, state_root, account.storage_root)?;
4239
4240            for key in storage_keys {
4241                let hashed_key = hash_key(key);
4242                let proof = storage_trie.get_proof(&hashed_key)?;
4243                let value = storage_trie
4244                    .get(&hashed_key)?
4245                    .map(|rlp| U256::decode(&rlp).map_err(StoreError::RLPDecode))
4246                    .transpose()?
4247                    .unwrap_or_default();
4248
4249                let slot_proof = StorageSlotProof {
4250                    proof,
4251                    key: *key,
4252                    value,
4253                };
4254                storage_proof.push(slot_proof);
4255            }
4256        } else {
4257            storage_proof.extend(storage_keys.iter().map(|key| StorageSlotProof {
4258                proof: Vec::new(),
4259                key: *key,
4260                value: U256::zero(),
4261            }));
4262        }
4263        let account_proof = AccountProof {
4264            proof,
4265            account: account_opt,
4266            storage_proof,
4267        };
4268        Ok(Some(account_proof))
4269    }
4270
4271    // Returns an iterator across all accounts in the state trie given by the state_root
4272    // Does not check that the state_root is valid
4273    pub fn iter_accounts_from(
4274        &self,
4275        state_root: H256,
4276        starting_address: H256,
4277    ) -> Result<impl Iterator<Item = (H256, AccountState)>, StoreError> {
4278        let mut iter = self.open_locked_state_trie(state_root)?.into_iter();
4279        iter.advance(starting_address.0.to_vec())?;
4280        Ok(iter.content().map_while(|(path, value)| {
4281            Some((H256::from_slice(&path), AccountState::decode(&value).ok()?))
4282        }))
4283    }
4284
4285    // Returns an iterator across all accounts in the state trie given by the state_root
4286    // Does not check that the state_root is valid
4287    pub fn iter_accounts(
4288        &self,
4289        state_root: H256,
4290    ) -> Result<impl Iterator<Item = (H256, AccountState)>, StoreError> {
4291        self.iter_accounts_from(state_root, H256::zero())
4292    }
4293
4294    // Returns an iterator across all accounts in the state trie given by the state_root
4295    // Does not check that the state_root is valid
4296    pub fn iter_storage_from(
4297        &self,
4298        state_root: H256,
4299        hashed_address: H256,
4300        starting_slot: H256,
4301    ) -> Result<Option<impl Iterator<Item = (H256, U256)>>, StoreError> {
4302        let state_trie = self.open_locked_state_trie(state_root)?;
4303        let Some(account_rlp) = state_trie.get(hashed_address.as_bytes())? else {
4304            return Ok(None);
4305        };
4306        let storage_root = AccountState::decode(&account_rlp)?.storage_root;
4307        let mut iter = self
4308            .open_locked_storage_trie(hashed_address, state_root, storage_root)?
4309            .into_iter();
4310        iter.advance(starting_slot.0.to_vec())?;
4311        Ok(Some(iter.content().map_while(|(path, value)| {
4312            Some((H256::from_slice(&path), U256::decode(&value).ok()?))
4313        })))
4314    }
4315
4316    // Returns an iterator across all accounts in the state trie given by the state_root
4317    // Does not check that the state_root is valid
4318    pub fn iter_storage(
4319        &self,
4320        state_root: H256,
4321        hashed_address: H256,
4322    ) -> Result<Option<impl Iterator<Item = (H256, U256)>>, StoreError> {
4323        self.iter_storage_from(state_root, hashed_address, H256::zero())
4324    }
4325
4326    pub fn get_account_range_proof(
4327        &self,
4328        state_root: H256,
4329        starting_hash: H256,
4330        last_hash: Option<H256>,
4331    ) -> Result<Vec<Vec<u8>>, StoreError> {
4332        let state_trie = self.open_state_trie(state_root)?;
4333        let mut proof = state_trie.get_proof(starting_hash.as_bytes())?;
4334        if let Some(last_hash) = last_hash {
4335            proof.extend_from_slice(&state_trie.get_proof(last_hash.as_bytes())?);
4336        }
4337        Ok(proof)
4338    }
4339
4340    pub fn get_storage_range_proof(
4341        &self,
4342        state_root: H256,
4343        hashed_address: H256,
4344        starting_hash: H256,
4345        last_hash: Option<H256>,
4346    ) -> Result<Option<Vec<Vec<u8>>>, StoreError> {
4347        let state_trie = self.open_state_trie(state_root)?;
4348        let Some(account_rlp) = state_trie.get(hashed_address.as_bytes())? else {
4349            return Ok(None);
4350        };
4351        let storage_root = AccountState::decode(&account_rlp)?.storage_root;
4352        let storage_trie = self.open_storage_trie(hashed_address, state_root, storage_root)?;
4353        let mut proof = storage_trie.get_proof(starting_hash.as_bytes())?;
4354        if let Some(last_hash) = last_hash {
4355            proof.extend_from_slice(&storage_trie.get_proof(last_hash.as_bytes())?);
4356        }
4357        Ok(Some(proof))
4358    }
4359
4360    /// Receives the root of the state trie and a list of paths where the first path will correspond to a path in the state trie
4361    /// (aka a hashed account address) and the following paths will be paths in the account's storage trie (aka hashed storage keys)
4362    /// If only one hash (account) is received, then the state trie node containing the account will be returned.
4363    /// If more than one hash is received, then the storage trie nodes where each storage key is stored will be returned
4364    /// For more information check out snap capability message [`GetTrieNodes`](https://github.com/ethereum/devp2p/blob/master/caps/snap.md#gettrienodes-0x06)
4365    /// The paths can be either full paths (hash) or partial paths (compact-encoded nibbles), if a partial path is given for the account this method will not return storage nodes for it
4366    pub fn get_trie_nodes(
4367        &self,
4368        state_root: H256,
4369        paths: Vec<Vec<u8>>,
4370        byte_limit: u64,
4371    ) -> Result<Vec<Vec<u8>>, StoreError> {
4372        let Some(account_path) = paths.first() else {
4373            return Ok(vec![]);
4374        };
4375        let state_trie = self.open_state_trie(state_root)?;
4376        // State Trie Nodes Request
4377        if paths.len() == 1 {
4378            // Fetch state trie node
4379            let node = state_trie.get_node(account_path)?;
4380            return Ok(vec![node]);
4381        }
4382        // Storage Trie Nodes Request
4383        let Some(account_state) = state_trie
4384            .get(account_path)?
4385            .map(|ref rlp| AccountState::decode(rlp))
4386            .transpose()?
4387        else {
4388            return Ok(vec![]);
4389        };
4390        // We can't access the storage trie without the account's address hash
4391        let Ok(hashed_address) = account_path.clone().try_into().map(H256) else {
4392            return Ok(vec![]);
4393        };
4394        let storage_trie =
4395            self.open_storage_trie(hashed_address, state_root, account_state.storage_root)?;
4396        // Fetch storage trie nodes
4397        let mut nodes = vec![];
4398        let mut bytes_used = 0;
4399        // The number of sub-paths is bounded upstream by the snap server's per-request lookup
4400        // cap (`MAX_SERVE_LOOKUPS`), which truncates the pathset before this call; here the
4401        // byte budget only bounds response size.
4402        for path in paths.iter().skip(1) {
4403            if bytes_used >= byte_limit {
4404                break;
4405            }
4406            let node = storage_trie.get_node(path)?;
4407            bytes_used += node.len() as u64;
4408            nodes.push(node);
4409        }
4410        Ok(nodes)
4411    }
4412
4413    // Methods exclusive for trie management during snap-syncing
4414
4415    /// Snapshot the trie layer cache for reading at `state_root`, blocking until
4416    /// that root's diff layer has been installed if it is still in-flight (see
4417    /// [`PendingTrieRoots`]). This is the read barrier for deferred layer builds:
4418    /// taking it at trie-open time guarantees the snapshot contains the layer, so
4419    /// a just-added block's state is never read as stale. Roots that are not
4420    /// pending (already installed, historical/committed, genesis) never block.
4421    fn gated_snapshot(&self, state_root: H256) -> Result<Arc<TrieLayerCache>, StoreError> {
4422        self.pending_trie_roots.wait_until_ready(state_root)?;
4423        Ok(self
4424            .trie_cache
4425            .read()
4426            .map_err(|_| StoreError::LockError)?
4427            .clone())
4428    }
4429
4430    /// Obtain a state trie from the given state root
4431    /// Doesn't check if the state root is valid
4432    /// Used for internal store operations
4433    pub fn open_state_trie(&self, state_root: H256) -> Result<Trie, StoreError> {
4434        let trie_db = TrieWrapper::new(
4435            state_root,
4436            self.gated_snapshot(state_root)?,
4437            Box::new(BackendTrieDB::new_for_accounts(
4438                self.backend.clone(),
4439                self.last_written()?,
4440            )?),
4441            None,
4442        );
4443        Ok(Trie::open(Box::new(trie_db), state_root))
4444    }
4445
4446    /// Obtain a state trie from the given state root
4447    /// Doesn't check if the state root is valid
4448    /// Used for internal store operations
4449    pub fn open_direct_state_trie(&self, state_root: H256) -> Result<Trie, StoreError> {
4450        Ok(Trie::open(
4451            Box::new(BackendTrieDB::new_for_accounts(
4452                self.backend.clone(),
4453                self.last_written()?,
4454            )?),
4455            state_root,
4456        ))
4457    }
4458
4459    /// Obtain a state trie locked for reads from the given state root
4460    /// Doesn't check if the state root is valid
4461    /// Used for internal store operations
4462    pub fn open_locked_state_trie(&self, state_root: H256) -> Result<Trie, StoreError> {
4463        let trie_db = TrieWrapper::new(
4464            state_root,
4465            self.gated_snapshot(state_root)?,
4466            Box::new(state_trie_locked_backend(
4467                self.backend.as_ref(),
4468                self.last_written()?,
4469            )?),
4470            None,
4471        );
4472        Ok(Trie::open(Box::new(trie_db), state_root))
4473    }
4474
4475    /// Obtain a storage trie from the given address and storage_root.
4476    /// Doesn't check if the account is stored
4477    pub fn open_storage_trie(
4478        &self,
4479        account_hash: H256,
4480        state_root: H256,
4481        storage_root: H256,
4482    ) -> Result<Trie, StoreError> {
4483        let trie_db = TrieWrapper::new(
4484            state_root,
4485            self.gated_snapshot(state_root)?,
4486            Box::new(BackendTrieDB::new_for_storages(
4487                self.backend.clone(),
4488                self.last_written()?,
4489            )?),
4490            Some(account_hash),
4491        );
4492        Ok(Trie::open(Box::new(trie_db), storage_root))
4493    }
4494
4495    /// Open a state trie using pre-acquired shared resources.
4496    /// Avoids redundant RwLock acquisitions when multiple tries are opened
4497    /// in the same operation (e.g., state trie + storage trie in get_storage_at_root).
4498    fn open_state_trie_shared(
4499        &self,
4500        state_root: H256,
4501        read_view: Arc<dyn StorageReadView>,
4502        cache: Arc<TrieLayerCache>,
4503        last_written: Vec<u8>,
4504    ) -> Result<Trie, StoreError> {
4505        let trie_db = TrieWrapper::new(
4506            state_root,
4507            cache,
4508            Box::new(BackendTrieDB::new_for_accounts_with_view(
4509                self.backend.clone(),
4510                read_view,
4511                last_written,
4512            )?),
4513            None,
4514        );
4515        Ok(Trie::open(Box::new(trie_db), state_root))
4516    }
4517
4518    /// Open a storage trie using pre-acquired shared resources.
4519    fn open_storage_trie_shared(
4520        &self,
4521        account_hash: H256,
4522        state_root: H256,
4523        storage_root: H256,
4524        read_view: Arc<dyn StorageReadView>,
4525        cache: Arc<TrieLayerCache>,
4526        last_written: Vec<u8>,
4527    ) -> Result<Trie, StoreError> {
4528        let trie_db = TrieWrapper::new(
4529            state_root,
4530            cache,
4531            Box::new(BackendTrieDB::new_for_storages_with_view(
4532                self.backend.clone(),
4533                read_view,
4534                last_written,
4535            )?),
4536            Some(account_hash),
4537        );
4538        Ok(Trie::open(Box::new(trie_db), storage_root))
4539    }
4540
4541    /// Obtain a storage trie from the given address and storage_root.
4542    /// Doesn't check if the account is stored
4543    pub fn open_direct_storage_trie(
4544        &self,
4545        account_hash: H256,
4546        storage_root: H256,
4547    ) -> Result<Trie, StoreError> {
4548        Ok(Trie::open(
4549            Box::new(BackendTrieDB::new_for_account_storage(
4550                self.backend.clone(),
4551                account_hash,
4552                self.last_written()?,
4553            )?),
4554            storage_root,
4555        ))
4556    }
4557
4558    /// Obtain a read-locked storage trie from the given address and storage_root.
4559    /// Doesn't check if the account is stored
4560    pub fn open_locked_storage_trie(
4561        &self,
4562        account_hash: H256,
4563        state_root: H256,
4564        storage_root: H256,
4565    ) -> Result<Trie, StoreError> {
4566        let trie_db = TrieWrapper::new(
4567            state_root,
4568            self.gated_snapshot(state_root)?,
4569            Box::new(state_trie_locked_backend(
4570                self.backend.as_ref(),
4571                self.last_written()?,
4572            )?),
4573            Some(account_hash),
4574        );
4575        Ok(Trie::open(Box::new(trie_db), storage_root))
4576    }
4577
4578    pub fn has_state_root(&self, state_root: H256) -> Result<bool, StoreError> {
4579        // Empty state trie is always available
4580        if state_root == EMPTY_TRIE_HASH {
4581            return Ok(true);
4582        }
4583        let trie = self.open_state_trie(state_root)?;
4584        trie_holds_root(&trie, state_root)
4585    }
4586
4587    /// Opens a [`StateView`] of `state_root`, or `None` when the node does not
4588    /// hold that state.
4589    pub fn state_view(&self, state_root: H256) -> Result<Option<StateView>, StoreError> {
4590        // The order matters. The flat-key-value frontier only moves forward while
4591        // it is generated, so reading it before the snapshot never has reads skip
4592        // the trie for keys the snapshot has no flat value for yet. A commit
4593        // writes the disk before it drops the committed layer from the cache, so
4594        // taking the snapshot before the cache can pair an older disk with a newer
4595        // cache, where the root then reads as not held, but never a newer disk with
4596        // layers it has already absorbed, which would answer with newer state.
4597        let last_written = self.last_written()?;
4598        let read_view = self.backend.begin_snapshot_read()?;
4599        let cache = self.gated_snapshot(state_root)?;
4600        let state_trie = self.open_state_trie_shared(
4601            state_root,
4602            read_view.clone(),
4603            cache.clone(),
4604            last_written.clone(),
4605        )?;
4606        if state_root != EMPTY_TRIE_HASH && !trie_holds_root(&state_trie, state_root)? {
4607            return Ok(None);
4608        }
4609        Ok(Some(StateView {
4610            store: self.clone(),
4611            state_root,
4612            read_view,
4613            cache,
4614            last_written,
4615            state_trie,
4616        }))
4617    }
4618
4619    // ===========================================================================
4620    // Deep-reorg primitives (storage side).
4621    // ===========================================================================
4622
4623    /// Returns `true` if the in-memory layer cache currently has a layer with
4624    /// the given `state_root`. Used by the deep-reorg orchestrator to decide
4625    /// whether the head's state can be reached through forward execution (cache
4626    /// hit) or whether a deep-reorg path with overlay construction is required.
4627    pub fn is_state_in_layer_cache(&self, state_root: H256) -> Result<bool, StoreError> {
4628        let trie = self
4629            .trie_cache
4630            .read()
4631            .map_err(|_| StoreError::LockError)?
4632            .clone();
4633        Ok(trie.contains(state_root))
4634    }
4635
4636    /// Returns the highest block number with a `STATE_HISTORY` entry; the cache
4637    /// edge `D` (the deepest block whose post-state is on disk). Returns `None`
4638    /// if the journal is empty (no commits since boot, fully pruned by finality, or
4639    /// every layer committed since was already final; see `journal_skip_ceiling`).
4640    ///
4641    /// O(1) via reverse seek on the column family's last key.
4642    pub fn highest_state_history_block_number(&self) -> Result<Option<BlockNumber>, StoreError> {
4643        let read = self.backend.begin_read()?;
4644        let Some(key) = read.last_key(STATE_HISTORY)? else {
4645            return Ok(None);
4646        };
4647        let arr = <[u8; 8]>::try_from(key.as_slice()).map_err(|_| {
4648            StoreError::Custom(format!(
4649                "STATE_HISTORY key has unexpected length: {}",
4650                key.len()
4651            ))
4652        })?;
4653        Ok(Some(BlockNumber::from_be_bytes(arr)))
4654    }
4655
4656    /// Returns the hash of the block whose trie-layer commit the `STATE_HISTORY`
4657    /// entry at `block_number` journals, or `None` when there is no entry.
4658    ///
4659    /// While the journal is non-empty the persist worker stages one entry per
4660    /// committed layer (see `journal_skip_ceiling`), so the entry at
4661    /// [`Self::highest_state_history_block_number`] identifies the block whose
4662    /// post-state is the one on disk.
4663    pub fn get_state_history_block_hash(
4664        &self,
4665        block_number: BlockNumber,
4666    ) -> Result<Option<BlockHash>, StoreError> {
4667        let read = self.backend.begin_read()?;
4668        let Some(bytes) = read.get(STATE_HISTORY, &block_number.to_be_bytes())? else {
4669            return Ok(None);
4670        };
4671        JournalEntry::decode_block_hash(&bytes)
4672            .map(Some)
4673            .map_err(|e| StoreError::Custom(format!("STATE_HISTORY entry {block_number}: {e}")))
4674    }
4675
4676    /// Returns the lowest block number with a `STATE_HISTORY` entry. Returns `None`
4677    /// if the journal is empty (no commits since boot, or fully pruned by finality).
4678    ///
4679    /// O(1) via forward seek on the column family's first key.
4680    pub fn lowest_state_history_block_number(&self) -> Result<Option<BlockNumber>, StoreError> {
4681        let read = self.backend.begin_read()?;
4682        let Some(key) = read.first_key(STATE_HISTORY)? else {
4683            return Ok(None);
4684        };
4685        let arr = <[u8; 8]>::try_from(key.as_slice()).map_err(|_| {
4686            StoreError::Custom(format!(
4687                "STATE_HISTORY key has unexpected length: {}",
4688                key.len()
4689            ))
4690        })?;
4691        Ok(Some(BlockNumber::from_be_bytes(arr)))
4692    }
4693
4694    /// The in-memory diff-layer retention (the layer cache's commit threshold):
4695    /// the deepest reorg the node can serve straight from the layer cache, with no
4696    /// journal/overlay reconstruction. RocksDB default 128, in-memory 10000. Used by
4697    /// `compute_reorg_ceiling` as the physical floor when there is no finality signal.
4698    pub fn reorg_retention(&self) -> Result<u64, StoreError> {
4699        let cache = self.trie_cache.read().map_err(|_| StoreError::LockError)?;
4700        Ok(cache.commit_threshold() as u64)
4701    }
4702
4703    /// Test-only: inserts a pre-encoded `STATE_HISTORY` entry at the given block
4704    /// number. Lets integration tests seed the journal without running enough
4705    /// commits to trip the in-memory cache's flush threshold.
4706    #[doc(hidden)]
4707    pub fn put_state_history_entry_for_test(
4708        &self,
4709        block_number: BlockNumber,
4710        encoded: &[u8],
4711    ) -> Result<(), StoreError> {
4712        let mut tx = self.backend.begin_write()?;
4713        tx.put(STATE_HISTORY, &block_number.to_be_bytes(), encoded)?;
4714        tx.commit()?;
4715        Ok(())
4716    }
4717
4718    /// Atomically prepares the store for a deep-reorg apply pass.
4719    ///
4720    /// Builds an [`Overlay`] from journal entries in `[to_block, from_block]`
4721    /// (inclusive both ends), verifies each entry's `block_hash` against
4722    /// `expected_hash`, then swaps the in-memory layer cache for a fresh one
4723    /// with the overlay installed. After this call:
4724    ///
4725    /// - The layer cache contains zero forward layers.
4726    /// - The overlay is in place; subsequent `TrieWrapper::get` calls cascade
4727    ///   layer cache -> overlay -> disk.
4728    /// - The on-disk trie/flat-KV state is unchanged (still at the OLD chain's
4729    ///   edge `D`).
4730    ///
4731    /// Side-chain blocks `[pivot+1 .. new_head]` should now be executed in
4732    /// chain order through the normal `Blockchain::add_block` path; each
4733    /// block's reads cascade through the overlay, and each block's commit
4734    /// produces a new forward layer.
4735    ///
4736    /// Errors abort the swap: if overlay construction fails (missing entry,
4737    /// hash mismatch, decode error), the existing layer cache is left intact.
4738    pub fn install_overlay_for_reorg(
4739        &self,
4740        from_block: BlockNumber,
4741        to_block: BlockNumber,
4742        expected_hash: impl Fn(BlockNumber) -> Option<H256>,
4743    ) -> Result<(), StoreError> {
4744        // Build the overlay first so any failure aborts before mutating the cache.
4745        let overlay =
4746            Overlay::from_journal(self.backend.as_ref(), from_block, to_block, expected_hash)
4747                .map_err(|e| StoreError::Custom(format!("overlay construction failed: {e}")))?;
4748
4749        let threshold = {
4750            let current = self.trie_cache.read().map_err(|_| StoreError::LockError)?;
4751            current.commit_threshold()
4752        };
4753        // Share the Store's safe-commit-root cell so the canonical commit gate keeps
4754        // working after the cache swap (the cell only advances via forkchoice).
4755        let mut fresh =
4756            TrieLayerCache::new_with_safe_commit(threshold, self.safe_commit_root.clone());
4757        fresh.set_overlay(Arc::new(overlay));
4758
4759        // Wait for the persist worker to be idle before swapping the cache (see
4760        // [`Self::rendezvous_persist_worker`]).
4761        self.rendezvous_persist_worker("install_overlay_for_reorg")?;
4762
4763        let mut guard = self.trie_cache.write().map_err(|_| StoreError::LockError)?;
4764        *guard = Arc::new(fresh);
4765        Ok(())
4766    }
4767
4768    /// Waits for the persist worker to be idle before a layer-cache swap. That
4769    /// worker owns the trie-layer install (`apply_trie_phase1`, run from the
4770    /// `PersistMessage::Block` handler): it reads `trie_cache`, mutates a local
4771    /// clone, and RCU-writes it back; if it is mid-flight when we swap, its
4772    /// write-back can clobber the freshly swapped cache (e.g. drop a just-installed
4773    /// overlay, or install a side-chain layer over a base that no longer has the
4774    /// overlay underneath). `PersistMessage::Ping` carries an ack channel and the
4775    /// worker is FIFO, so its ack proves every earlier `Block` (and thus every
4776    /// earlier trie install) is fully processed and the worker is back at
4777    /// `rx.recv()`. This is the synchronous core of [`wait_for_persistence_idle`];
4778    /// we inline it here because callers are not async. The caller's subsequent
4779    /// `trie_cache.write()` serialising any future RCU makes the swap safe.
4780    fn rendezvous_persist_worker(&self, caller: &str) -> Result<(), StoreError> {
4781        let (ack_tx, ack_rx) = sync_channel::<Result<(), StoreError>>(1);
4782        self.persist_tx
4783            .send(PersistMessage::Ping(ack_tx))
4784            .map_err(|e| {
4785                StoreError::Custom(format!("{caller}: failed to ping persist worker: {e}"))
4786            })?;
4787        ack_rx.recv().map_err(|e| {
4788            StoreError::Custom(format!("{caller}: persist worker ping ack failed: {e}"))
4789        })??;
4790        Ok(())
4791    }
4792
4793    /// Returns `(entry_count, byte_size)` of the currently installed overlay, or
4794    /// `(0, 0)` when no overlay is installed. Used by the observability layer in
4795    /// `fork_choice.rs` immediately after `install_overlay_for_reorg` to emit
4796    /// `ethrex_reorg_overlay_entries` / `ethrex_reorg_overlay_bytes`.
4797    pub fn reorg_overlay_size_hint(&self) -> Result<(usize, usize), StoreError> {
4798        let guard = self.trie_cache.read().map_err(|_| StoreError::LockError)?;
4799        match guard.overlay() {
4800            Some(ov) => Ok((ov.len(), ov.byte_size())),
4801            None => Ok((0, 0)),
4802        }
4803    }
4804
4805    /// Pauses or resumes STATE_HISTORY pruning at finality advance (see the
4806    /// `journal_pruning_paused` field). Called by `Blockchain::enter_reorg` /
4807    /// `ReorgGuard::drop` to bracket a deep-reorg apply pass.
4808    pub fn set_journal_pruning_paused(&self, paused: bool) {
4809        self.journal_pruning_paused
4810            .store(paused, std::sync::atomic::Ordering::Release);
4811    }
4812
4813    /// Removes any installed overlay from the layer cache. Called by the
4814    /// reconciliation path after the first new-chain commit folds
4815    /// the overlay into disk. Idempotent.
4816    pub fn clear_reorg_overlay(&self) -> Result<(), StoreError> {
4817        let mut guard = self.trie_cache.write().map_err(|_| StoreError::LockError)?;
4818        let mut updated = (**guard).clone();
4819        updated.clear_overlay();
4820        *guard = Arc::new(updated);
4821        Ok(())
4822    }
4823
4824    /// Aborts an in-progress deep reorg and resets the layer cache to a fresh
4825    /// empty state with the same commit threshold. Both the overlay and any
4826    /// partially-built new-chain layers are discarded. On-disk state is
4827    /// untouched (still at the OLD chain's `D`), so subsequent FCU evaluations
4828    /// start from a clean foundation.
4829    pub fn abort_reorg(&self) -> Result<(), StoreError> {
4830        // Rendezvous with the persist worker before swapping, exactly like
4831        // `install_overlay_for_reorg`: the live-path ack fires BEFORE
4832        // `apply_trie_phase1` installs the layer, so the worker can still be
4833        // mid-flight with a pre-abort RCU snapshot. Without the rendezvous its
4834        // write-back could install a side-chain layer into the fresh cache with
4835        // no overlay underneath — reads at that root would then cascade into
4836        // old-chain disk state.
4837        self.rendezvous_persist_worker("abort_reorg")?;
4838        let mut guard = self.trie_cache.write().map_err(|_| StoreError::LockError)?;
4839        let threshold = guard.commit_threshold();
4840        *guard = Arc::new(TrieLayerCache::new_with_safe_commit(
4841            threshold,
4842            self.safe_commit_root.clone(),
4843        ));
4844        Ok(())
4845    }
4846
4847    /// Takes a block hash and returns an iterator to its ancestors. Block headers are returned
4848    /// in reverse order, starting from the given block and going up to the genesis block.
4849    pub fn ancestors(&self, block_hash: BlockHash) -> AncestorIterator {
4850        AncestorIterator {
4851            store: self.clone(),
4852            next_hash: block_hash,
4853        }
4854    }
4855
4856    /// Checks if a given block belongs to the current canonical chain. Returns false if the block is not known
4857    pub fn is_canonical_sync(&self, block_hash: BlockHash) -> Result<bool, StoreError> {
4858        let Some(block_number) = self.get_block_number_sync(block_hash)? else {
4859            return Ok(false);
4860        };
4861        Ok(self
4862            .get_canonical_block_hash_sync(block_number)?
4863            .is_some_and(|h| h == block_hash))
4864    }
4865
4866    pub fn generate_flatkeyvalue(&self) -> Result<(), StoreError> {
4867        self.flatkeyvalue_control_tx
4868            .send(FKVGeneratorControlMessage::Continue)
4869            .map_err(|_| StoreError::Custom("FlatKeyValue thread disconnected.".to_string()))
4870    }
4871
4872    pub fn create_checkpoint(&self, path: impl AsRef<Path>) -> Result<(), StoreError> {
4873        self.backend.create_checkpoint(path.as_ref())?;
4874        init_metadata_file(path.as_ref())?;
4875        Ok(())
4876    }
4877
4878    pub fn get_store_directory(&self) -> Result<PathBuf, StoreError> {
4879        Ok(self.db_path.clone())
4880    }
4881
4882    /// Loads the latest block number stored in the database, bypassing the latest block number cache
4883    async fn load_latest_block_number(&self) -> Result<Option<BlockNumber>, StoreError> {
4884        self.read_chain_data_block_number(ChainDataIndex::LatestBlockNumber)
4885            .await
4886    }
4887
4888    fn load_canonical_block_hash(
4889        &self,
4890        block_number: BlockNumber,
4891    ) -> Result<Option<BlockHash>, StoreError> {
4892        let txn = self.backend.begin_read()?;
4893        txn.get(
4894            CANONICAL_BLOCK_HASHES,
4895            block_number.to_le_bytes().as_slice(),
4896        )?
4897        .map(|bytes| H256::decode(bytes.as_slice()))
4898        .transpose()
4899        .map_err(StoreError::from)
4900    }
4901
4902    fn load_block_header(
4903        &self,
4904        block_number: BlockNumber,
4905    ) -> Result<Option<BlockHeader>, StoreError> {
4906        let Some(block_hash) = self.load_canonical_block_hash(block_number)? else {
4907            return Ok(None);
4908        };
4909        self.load_block_header_by_hash(block_hash)
4910    }
4911
4912    /// Load a block header, bypassing the latest header cache
4913    fn load_block_header_by_hash(
4914        &self,
4915        block_hash: BlockHash,
4916    ) -> Result<Option<BlockHeader>, StoreError> {
4917        let txn = self.backend.begin_read()?;
4918        let hash_key = block_hash.encode_to_vec();
4919        let header_value = txn.get(HEADERS, hash_key.as_slice())?;
4920        let mut header = header_value
4921            .map(|bytes| BlockHeaderRLP::from_bytes(bytes).to())
4922            .transpose()
4923            .map_err(StoreError::from)?;
4924        header.as_mut().inspect(|h| {
4925            // Set the hash so we avoid recomputing it later
4926            let _ = h.hash.set(block_hash);
4927        });
4928        Ok(header)
4929    }
4930
4931    pub fn last_written(&self) -> Result<Vec<u8>, StoreError> {
4932        let last_computed_flatkeyvalue = self
4933            .last_computed_flatkeyvalue
4934            .read()
4935            .map_err(|_| StoreError::LockError)?;
4936        Ok(last_computed_flatkeyvalue.clone())
4937    }
4938
4939    /// Returns `true` once the flat-key-value generator has finished its full pass.
4940    ///
4941    /// Completion is recorded by the 1-byte `[0xff]` sentinel the generator writes to
4942    /// `MISC_VALUES["last_written"]` on the final iteration (see `flatkeyvalue_generator`);
4943    /// every non-final frontier value is a real nibble path (bytes `0x00..=0x0f`), so the
4944    /// sentinel is unambiguous. Reads the durable marker rather than the in-memory frontier,
4945    /// which is expanded to `[0xff; 64]`/`[0xff; 131]` and would need length-aware handling.
4946    ///
4947    /// Used to gate journal-backed deep reorgs: entries journaled while generation is still
4948    /// in progress omit past-frontier flat-KV pre-images.
4949    pub fn flatkeyvalue_fully_generated(&self) -> Result<bool, StoreError> {
4950        let tx = self.backend.begin_read()?;
4951        let marker = tx.get(MISC_VALUES, "last_written".as_bytes())?;
4952        Ok(Self::flatkeyvalue_generation_complete(marker.as_deref()))
4953    }
4954
4955    /// Pure completeness test for the durable `last_written` marker: complete iff it is the
4956    /// exact 1-byte `[0xff]` sentinel. Any in-progress frontier is a nibble path (bytes
4957    /// `0x00..=0x0f`) and an unset marker is absent, so neither matches.
4958    fn flatkeyvalue_generation_complete(marker: Option<&[u8]>) -> bool {
4959        marker == Some([0xff].as_slice())
4960    }
4961
4962    fn flatkeyvalue_computed_with_last_written(account: H256, last_written: &[u8]) -> bool {
4963        let account_nibbles = Nibbles::from_bytes(account.as_bytes());
4964        &last_written[0..64] > account_nibbles.as_ref()
4965    }
4966
4967    /// Raises the `flushed_upto` marker to `block_number`, on disk and in the
4968    /// buffer's mirror, so the next start anchors at that height. The marker is a
4969    /// durability floor and only moves forward: a value at or below the current
4970    /// one is a no-op.
4971    ///
4972    /// Used when startup adopts a head above the recorded one (interrupted
4973    /// full-sync batch): the blocks were flushed by the persist worker before the
4974    /// interruption, but the failed starts in between walked the marker down.
4975    ///
4976    /// Must run while the persist worker is idle (at startup, before p2p and RPC
4977    /// exist): the buffer update is a read-clone-swap with no compare-and-swap,
4978    /// so a concurrent persist message could lose either mutation.
4979    pub fn advance_flushed_upto(&self, block_number: BlockNumber) -> Result<(), StoreError> {
4980        if self
4981            .read_flushed_upto_opt()?
4982            .is_some_and(|current| current >= block_number)
4983        {
4984            return Ok(());
4985        }
4986        let mut tx = self.backend.begin_write()?;
4987        write_flushed_upto(tx.as_mut(), block_number)?;
4988        tx.commit()?;
4989        mutate_block_buffer(&self.block_data_buffer, |b| {
4990            b.set_flushed_upto(block_number)
4991        })
4992    }
4993
4994    /// Returns the highest block number durably flushed to disk, or `0` when
4995    /// the marker is absent. Use [`Self::read_flushed_upto_opt`] when you need
4996    /// to distinguish "absent marker" (legacy DB, everything is durable) from
4997    /// "marker present and equal to 0".
4998    pub fn read_flushed_upto(&self) -> Result<BlockNumber, StoreError> {
4999        Ok(self.read_flushed_upto_opt()?.unwrap_or(0))
5000    }
5001
5002    /// Returns `None` when the marker has never been written — a legacy or fresh
5003    /// DB where everything is durable and the head must not be clamped to 0.
5004    fn read_flushed_upto_opt(&self) -> Result<Option<BlockNumber>, StoreError> {
5005        let tx = self.backend.begin_read()?;
5006        match tx.get(MISC_VALUES, FLUSHED_UPTO_KEY)? {
5007            Some(bytes) => Ok(Some(decode_flushed_upto(&bytes)?)),
5008            None => Ok(None),
5009        }
5010    }
5011
5012    /// Insert a block into the in-memory buffer without writing to disk.
5013    /// For testing only — gates production code off.
5014    #[cfg(any(test, feature = "testing"))]
5015    pub fn buffer_block_for_test(&self, block: &Block) {
5016        mutate_block_buffer(&self.block_data_buffer, |b| {
5017            b.insert(block.clone(), vec![], vec![])
5018        })
5019        .expect("block_data_buffer lock poisoned");
5020    }
5021
5022    /// Synchronously flush the block data buffer to disk.
5023    /// For testing only — gates production code off.
5024    #[cfg(any(test, feature = "testing"))]
5025    pub fn flush_block_data_for_test(&self) -> Result<(), StoreError> {
5026        flush_block_data(self.backend.as_ref(), &self.block_data_buffer)
5027    }
5028
5029    /// Read a raw trie node straight from the on-disk account/storage trie-node
5030    /// table by its committed key. For testing only — lets a reopen assert which
5031    /// trie diff-layers a shutdown flush did (or did not) commit to disk.
5032    #[cfg(any(test, feature = "testing"))]
5033    pub fn get_trie_node_for_test(
5034        &self,
5035        is_account: bool,
5036        key: &[u8],
5037    ) -> Result<Option<Vec<u8>>, StoreError> {
5038        let table = if is_account {
5039            ACCOUNT_TRIE_NODES
5040        } else {
5041            STORAGE_TRIE_NODES
5042        };
5043        self.backend.begin_read()?.get(table, key)
5044    }
5045
5046    /// Insert a block plus associated codes into the in-memory buffer without
5047    /// writing to disk.  For testing only — proves the buffer overlay resolves
5048    /// code that has not been persisted yet.
5049    #[cfg(any(test, feature = "testing"))]
5050    pub fn buffer_block_with_codes_for_test(&self, block: &Block, codes: Vec<(H256, Code)>) {
5051        mutate_block_buffer(&self.block_data_buffer, |b| {
5052            b.insert(block.clone(), vec![], codes)
5053        })
5054        .expect("block_data_buffer lock poisoned");
5055    }
5056
5057    /// Mark a state root as in-flight (build pending) without doing a build.
5058    /// For testing only — simulates the window where the persist worker has not
5059    /// yet installed the layer, so reads at this root must block in
5060    /// `gated_snapshot`.
5061    #[cfg(any(test, feature = "testing"))]
5062    pub fn register_pending_root_for_test(&self, root: H256) -> Result<(), StoreError> {
5063        self.pending_trie_roots.register(root)
5064    }
5065
5066    /// Clear an in-flight state root (simulates the worker having installed the
5067    /// layer), unblocking readers waiting in `gated_snapshot`. For testing only.
5068    #[cfg(any(test, feature = "testing"))]
5069    pub fn clear_pending_root_for_test(&self, root: H256) {
5070        self.pending_trie_roots.clear(root)
5071    }
5072
5073    /// Boot-time recovery: clamp `latest_block_header` to the durable head.
5074    ///
5075    /// Durable head = `min(flushed_upto, latest)` when the marker is present
5076    /// (buffered blocks past `flushed_upto` may be lost after a crash; the CL
5077    /// re-sends them via `newPayload`). When the marker is absent the DB
5078    /// predates deferred persistence and everything is on disk — use `latest`
5079    /// as-is, never rewind to 0. On first boot the marker is seeded so a later
5080    /// crash clamps against it rather than an absent (→ 0) marker.
5081    ///
5082    /// The marker tracks the max flushed *block number*, not which hash is
5083    /// canonical at that height. A tip reorg inside the flush window — `Na` at
5084    /// height N is flushed (marker = N), then `newPayload(Nb)` buffers a sibling
5085    /// and FCU durably repoints `canonical[N]` to the still-unflushed `Nb` — can
5086    /// leave `canonical[head]` resolving to a header that never reached disk if
5087    /// we crash before `Nb` flushes. So we walk `head` down to the highest height
5088    /// whose canonical hash actually resolves on disk rather than bricking with
5089    /// `MissingLatestBlockNumber`. A legacy DB (no marker) is exempt: everything
5090    /// there is durable, so a missing header is real corruption and must surface.
5091    async fn anchor_to_durable_head(&self, latest: BlockNumber) -> Result<(), StoreError> {
5092        let marker = self.read_flushed_upto_opt()?;
5093        let start = match marker {
5094            Some(flushed) => flushed.min(latest),
5095            None => latest,
5096        };
5097
5098        let mut head = start;
5099        let latest_block_header = loop {
5100            match self.load_block_header(head)? {
5101                Some(header) => break header,
5102                // Legacy/fresh DB: everything is supposed to be durable, so a
5103                // missing header is real corruption — surface it, don't rewind.
5104                None if marker.is_none() => return Err(StoreError::MissingLatestBlockNumber),
5105                None if head == 0 => return Err(StoreError::MissingLatestBlockNumber),
5106                None => {
5107                    warn!(
5108                        "durable head {head}: canonical hash has no on-disk header \
5109                         (reorg inside flush window); rewinding"
5110                    );
5111                    head -= 1;
5112                }
5113            }
5114        };
5115        self.latest_block_header.update(latest_block_header);
5116
5117        // Re-anchor the persisted head when we moved below `latest`, and (re)write
5118        // the marker to the resolved head: an absent marker is seeded to the
5119        // durable baseline, and a walked-down head lowers the marker so a later
5120        // crash clamps against a hash known to resolve.
5121        let reanchor = head != latest;
5122        let rewrite_marker = marker != Some(head);
5123        if reanchor || rewrite_marker {
5124            let mut tx = self.backend.begin_write()?;
5125            if reanchor {
5126                // Re-anchor the persisted head so `get_latest_block_number` and
5127                // every downstream consumer agree with the clamped head.
5128                let latest_key = chain_data_key(ChainDataIndex::LatestBlockNumber);
5129                tx.put(CHAIN_DATA, &latest_key, &head.to_le_bytes())?;
5130            }
5131            if rewrite_marker {
5132                write_flushed_upto(tx.as_mut(), head)?;
5133            }
5134            tx.commit()?;
5135        }
5136        Ok(())
5137    }
5138}
5139
5140/// Writes the `flushed_upto` block number into an open write batch.
5141///
5142/// The caller is responsible for committing `tx` afterward.
5143pub fn write_flushed_upto(
5144    tx: &mut dyn StorageWriteBatch,
5145    n: BlockNumber,
5146) -> Result<(), StoreError> {
5147    tx.put(MISC_VALUES, FLUSHED_UPTO_KEY, &n.to_le_bytes())
5148}
5149
5150/// Decode an 8-byte little-endian `flushed_upto` marker value.
5151///
5152/// Returns an error for a present-but-malformed value so on-disk corruption is
5153/// surfaced loudly rather than silently resetting the durable marker. Single
5154/// source of truth for both `from_backend` and [`Store::read_flushed_upto`].
5155/// Decodes a `STATE_HISTORY` key (`block_number.to_be_bytes()`). A length mismatch is
5156/// an error rather than a silent default, which could prune the wrong range.
5157fn state_history_key_number(key: &[u8]) -> Result<BlockNumber, StoreError> {
5158    let arr = <[u8; 8]>::try_from(key).map_err(|_| {
5159        StoreError::Custom(format!(
5160            "STATE_HISTORY key has unexpected length: {}",
5161            key.len()
5162        ))
5163    })?;
5164    Ok(BlockNumber::from_be_bytes(arr))
5165}
5166
5167fn decode_flushed_upto(bytes: &[u8]) -> Result<BlockNumber, StoreError> {
5168    let arr: [u8; 8] = bytes
5169        .try_into()
5170        .map_err(|_| StoreError::Custom("Invalid flushed_upto bytes".to_string()))?;
5171    Ok(BlockNumber::from_le_bytes(arr))
5172}
5173
5174/// RCU-swap the block-data buffer: read-clone-mutate-swap with no compare-and-swap,
5175/// so two concurrent callers lose one mutation. In production the persist worker
5176/// is the only caller while the node runs; [`Store::advance_flushed_upto`] also
5177/// calls it, but only at startup before the worker has any message in flight.
5178/// Test helpers call it on one thread.
5179fn mutate_block_buffer(
5180    buffer: &Arc<RwLock<Arc<BlockDataBuffer>>>,
5181    f: impl FnOnce(&mut BlockDataBuffer),
5182) -> Result<(), StoreError> {
5183    let mut new_buf = (*buffer.read().map_err(|_| StoreError::LockError)?.clone()).clone();
5184    f(&mut new_buf);
5185    *buffer.write().map_err(|_| StoreError::LockError)? = Arc::new(new_buf);
5186    Ok(())
5187}
5188
5189/// Default for [`StoreConfig::persist_channel_capacity`].
5190const DEFAULT_PERSIST_CHANNEL_CAPACITY: usize = 2;
5191
5192/// One unit of work for the persist worker: stage block(s), build the trie diff-layer,
5193/// flush to disk. `commit_depth` selects the commit gate (`None` = canonical safe-commit
5194/// root, `Some(depth)` = commit layers deeper than `depth`). `wait_for_flush` selects the
5195/// ack point independently: `false` acks after staging (carrying the prior flush result),
5196/// `true` acks after flush.
5197struct BlockPersist {
5198    blocks: Vec<(Block, Vec<Receipt>)>,
5199    codes: Vec<(H256, Code)>,
5200    parent_state_root: H256,
5201    child_state_root: H256,
5202    account_updates: TrieNodesUpdate,
5203    storage_updates: Vec<(H256, TrieNodesUpdate)>,
5204    commit_depth: Option<usize>,
5205    wait_for_flush: bool,
5206    /// Number of the block whose layer this update represents (the last block in
5207    /// the batch, matching `child_state_root`). Threaded into the trie layer so
5208    /// the committed-layer identity is available for the journal write path.
5209    ///
5210    /// On a multi-block batch this names only the LAST block, which is NOT a usable
5211    /// journal identity for the batch's layer. `wait_for_flush` does not make that
5212    /// safe: it decides when THIS message acks, whereas the layer it creates is
5213    /// journaled or not by whichever LATER commit sweeps it — `TrieLayerCache::commit`
5214    /// takes the target layer and every ancestor, so a per-block commit can reach a
5215    /// batch layer. Any journal entry must therefore be gated on the committed
5216    /// layer covering exactly one block, not on this message's ack mode.
5217    block_number: BlockNumber,
5218    /// Hash of the block whose layer this update represents (see `block_number`).
5219    block_hash: H256,
5220    ack: std::sync::mpsc::SyncSender<Result<(), StoreError>>,
5221}
5222
5223/// Messages for the persist worker. `Ping(ack)` is the idle handshake for
5224/// [`Store::wait_for_persistence_idle`]: the FIFO worker handles it only after
5225/// all earlier `Block` messages are fully processed.
5226enum PersistMessage {
5227    Block(Box<BlockPersist>),
5228    /// Flush the committable layer backlog up to and including this state root, then
5229    /// prune the flushed layers. Sent by `forkchoice_update` when the safe-commit root
5230    /// advances: the commit step otherwise only runs while blocks execute, so an
5231    /// execute-all-then-one-forkchoice flow (e.g. block import) would accumulate every
5232    /// layer and never persist anything to disk.
5233    Commit(H256),
5234    Ping(std::sync::mpsc::SyncSender<Result<(), StoreError>>),
5235    /// Graceful-shutdown handshake. Handled only after every earlier `Block`
5236    /// (FIFO), so it both drains in-flight work and force-flushes the block-data
5237    /// buffer to disk. The trie diff-layers are deliberately left in memory (see
5238    /// [`Store::shutdown`]). The worker acks and exits.
5239    Shutdown {
5240        ack: std::sync::mpsc::SyncSender<Result<(), StoreError>>,
5241    },
5242}
5243
5244/// Write one block's header, body, number, and tx locations into an open batch.
5245/// Shared by [`Store::add_blocks`] (sync import) and [`flush_block_data`]
5246/// (deferred flush) so the on-disk encoding stays in lockstep. Receipts and codes
5247/// are written by callers that need them (only `flush_block_data` does).
5248fn write_block_data(
5249    tx: &mut dyn StorageWriteBatch,
5250    number: BlockNumber,
5251    hash: BlockHash,
5252    header: &BlockHeader,
5253    body: &BlockBody,
5254) -> Result<(), StoreError> {
5255    let hash_key = hash.encode_to_vec();
5256    tx.put(
5257        HEADERS,
5258        &hash_key,
5259        BlockHeaderRLP::from(header.clone()).bytes(),
5260    )?;
5261    tx.put(
5262        BODIES,
5263        &hash_key,
5264        BlockBodyRLP::from_bytes(body.encode_to_vec()).bytes(),
5265    )?;
5266    tx.put(BLOCK_NUMBERS, &hash_key, &number.to_le_bytes())?;
5267    for (index, transaction) in body.transactions.iter().enumerate() {
5268        tx.merge(
5269            TRANSACTION_LOCATIONS,
5270            transaction.hash(&NativeCrypto).as_bytes(),
5271            &encode_tx_location_operand(number, hash, index as u64),
5272        )?;
5273    }
5274    Ok(())
5275}
5276
5277/// Write all unflushed blocks to disk in one tx, advance `flushed_upto`, then
5278/// evict. Eviction is gap-safe: blocks stay buffered until the commit succeeds.
5279fn flush_block_data(
5280    backend: &dyn StorageBackend,
5281    buffer: &Arc<RwLock<Arc<BlockDataBuffer>>>,
5282) -> Result<(), StoreError> {
5283    let snapshot = buffer.read().map_err(|_| StoreError::LockError)?.clone();
5284    let to_flush = snapshot.flushable();
5285    if to_flush.is_empty() {
5286        return Ok(());
5287    }
5288    let hashes: Vec<_> = to_flush.iter().map(|b| b.header.hash()).collect();
5289    let codes = snapshot.codes_for(&hashes);
5290    let mut max_number = snapshot.flushed_upto();
5291
5292    let mut tx = backend.begin_write()?;
5293    for b in &to_flush {
5294        let hash = b.header.hash();
5295        write_block_data(tx.as_mut(), b.number, hash, &b.header, &b.body)?;
5296        for (index, receipt) in b.receipts.iter().enumerate() {
5297            tx.put(
5298                RECEIPTS_V2,
5299                &receipt_key(&hash, index as u64),
5300                &receipt.encode_to_vec(),
5301            )?;
5302        }
5303        max_number = max_number.max(b.number);
5304    }
5305    for (code_hash, code) in codes {
5306        let buf = encode_code(&code);
5307        tx.put(ACCOUNT_CODES, code_hash.as_ref(), &buf)?;
5308        tx.put(
5309            ACCOUNT_CODE_METADATA,
5310            code_hash.as_ref(),
5311            &(code.len() as u64).to_be_bytes(),
5312        )?;
5313    }
5314    write_flushed_upto(tx.as_mut(), max_number)?;
5315    tx.commit()?;
5316
5317    // Phase 3: evict only after the commit succeeded (gap safety).
5318    mutate_block_buffer(buffer, |b| b.evict_flushed(max_number))
5319}
5320
5321type TrieNodesUpdate = Vec<(Nibbles, Vec<u8>)>;
5322
5323/// Tracks state roots whose trie diff-layer is in-flight (building but not yet
5324/// installed in `trie_cache`). `apply_updates` registers a root *before*
5325/// returning; the worker clears it *after* swapping the layer in. This ordering
5326/// is mandatory: a reader opening a trie at a pending root blocks until the
5327/// layer is installed, preventing stale on-disk reads.
5328#[derive(Debug, Default)]
5329struct PendingTrieRoots {
5330    /// Fast-path: when zero, nothing is in flight and readers skip the lock.
5331    count: AtomicUsize,
5332    roots: Mutex<HashSet<H256>>,
5333    ready: Condvar,
5334}
5335
5336impl PendingTrieRoots {
5337    /// Mark `root` as in-flight. MUST be called before the build is handed to
5338    /// the worker (so the worker's `clear` always finds it) and before the head
5339    /// can advance to `root` (so any reader that can reference it sees it pending).
5340    fn register(&self, root: H256) -> Result<(), StoreError> {
5341        let mut roots = self.roots.lock().map_err(|_| StoreError::LockError)?;
5342        if roots.insert(root) {
5343            self.count.fetch_add(1, Ordering::Release);
5344        }
5345        Ok(())
5346    }
5347
5348    /// Mark `root` as installed and wake any waiting readers. MUST be called only
5349    /// after the layer is swapped into `trie_cache`, so a woken reader sees it.
5350    /// Best-effort: a poisoned lock means a reader's `wait_until_ready` also errors,
5351    /// so no reader deadlocks.
5352    fn clear(&self, root: H256) {
5353        let Ok(mut roots) = self.roots.lock() else {
5354            return;
5355        };
5356        if roots.remove(&root) {
5357            self.count.fetch_sub(1, Ordering::Release);
5358            self.ready.notify_all();
5359        }
5360    }
5361
5362    /// Block until `root` is no longer in-flight (its layer is installed). Returns
5363    /// immediately on the fast path when nothing is pending.
5364    fn wait_until_ready(&self, root: H256) -> Result<(), StoreError> {
5365        if self.count.load(Ordering::Acquire) == 0 {
5366            return Ok(());
5367        }
5368        let mut roots = self.roots.lock().map_err(|_| StoreError::LockError)?;
5369        while roots.contains(&root) {
5370            roots = self.ready.wait(roots).map_err(|_| StoreError::LockError)?;
5371        }
5372        Ok(())
5373    }
5374}
5375
5376/// Whether `trie`, opened at `state_root`, actually holds that root: opening a
5377/// trie does not check it, and the path-keyed disk answers for any root.
5378fn trie_holds_root(trie: &Trie, state_root: H256) -> Result<bool, StoreError> {
5379    let Some(root) = trie.db().get(Nibbles::default())? else {
5380        return Ok(false);
5381    };
5382    let root_hash = ethrex_trie::Node::decode(&root)?
5383        .compute_hash(&NativeCrypto)
5384        .finalize(&NativeCrypto);
5385    Ok(state_root == root_hash)
5386}
5387
5388/// One block's state, read from a database snapshot and trie layer cache taken
5389/// together (see [`Store::state_view`]), so that a commit that lands while it is
5390/// read can neither prune it nor show newer state through it.
5391pub struct StateView {
5392    store: Store,
5393    state_root: H256,
5394    read_view: Arc<dyn StorageReadView>,
5395    cache: Arc<TrieLayerCache>,
5396    last_written: Vec<u8>,
5397    state_trie: Trie,
5398}
5399
5400impl StateView {
5401    /// The state root this view reads.
5402    pub fn state_root(&self) -> H256 {
5403        self.state_root
5404    }
5405
5406    /// The account at `address`, or `None` if it does not exist in this state.
5407    pub fn account_state(&self, address: Address) -> Result<Option<AccountState>, StoreError> {
5408        self.store
5409            .get_account_state_from_trie(&self.state_trie, address)
5410    }
5411
5412    /// The value of `address`'s storage slot `storage_key`, or `None` if unset.
5413    pub fn storage_at(
5414        &self,
5415        address: Address,
5416        storage_key: H256,
5417    ) -> Result<Option<U256>, StoreError> {
5418        self.store.storage_at_with(
5419            self.state_root,
5420            address,
5421            storage_key,
5422            self.read_view.clone(),
5423            self.cache.clone(),
5424            self.last_written.clone(),
5425        )
5426    }
5427}
5428
5429/// Build the trie diff-layer, RCU-swap it into `trie_cache`, then clear the
5430/// pending root. Swap MUST precede the clear so a woken reader sees the layer.
5431/// On swap failure the root is still cleared so gated readers error, not deadlock.
5432#[allow(clippy::too_many_arguments)]
5433fn apply_trie_phase1(
5434    trie_cache: &Arc<RwLock<Arc<TrieLayerCache>>>,
5435    pending_roots: &PendingTrieRoots,
5436    parent_state_root: H256,
5437    child_state_root: H256,
5438    block_number: BlockNumber,
5439    block_hash: H256,
5440    account_updates: TrieNodesUpdate,
5441    storage_updates: Vec<(H256, TrieNodesUpdate)>,
5442) -> Result<(), StoreError> {
5443    let build: Result<(), StoreError> = (|| {
5444        let new_layer = storage_updates
5445            .into_iter()
5446            .flat_map(|(account_hash, nodes)| {
5447                nodes
5448                    .into_iter()
5449                    .map(move |(path, node)| (apply_prefix(Some(account_hash), path), node))
5450            })
5451            .chain(account_updates)
5452            .collect();
5453        let trie = trie_cache
5454            .read()
5455            .map_err(|_| StoreError::LockError)?
5456            .clone();
5457        let mut trie_mut = (*trie).clone();
5458        trie_mut.put_batch(
5459            parent_state_root,
5460            child_state_root,
5461            block_number,
5462            block_hash,
5463            new_layer,
5464        );
5465        *trie_cache.write().map_err(|_| StoreError::LockError)? = Arc::new(trie_mut);
5466        Ok(())
5467    })();
5468    // Always clear the pending root, whether or not the swap succeeded: on success
5469    // readers see the installed layer; on failure (poisoning) the lock is poisoned
5470    // so gated readers error rather than read stale, and we must not leave them
5471    // blocked forever.
5472    pending_roots.clear(child_state_root);
5473    build
5474}
5475
5476/// Flush and prune the committable trie-layer backlog. No-ops when nothing is committable.
5477///
5478/// `commit_depth` selects the gate. `Some(depth)`: single-canonical-chain execution (batch
5479/// import, full sync, startup regeneration) commits by depth, because the canonical `head - 128`
5480/// safe-commit root never lands on a batch layer boundary; sound because these paths only ever
5481/// extend a single canonical chain (no competing forks to mis-commit). `None`: live block-by-block
5482/// execution uses the canonical safe-commit gate (`TrieLayerCache::get_commitable`) so non-canonical
5483/// `newPayload` state is never persisted.
5484///
5485/// `is_batch` is independent of the gate and only selects journaling (see
5486/// [`commit_to_disk`]). It tracks `wait_for_flush`, not `commit_depth.is_some()`, so every
5487/// per-block path journals (layers already final aside, see [`journal_skip_ceiling`]) and
5488/// only the bespoke batch path skips it. That keeps the full-sync tail and the import
5489/// tail journaling exactly as they did when `commit_depth` and `wait_for_flush` were a
5490/// single flag.
5491///
5492/// Startup state regeneration is the one path where this is new behavior rather than
5493/// preserved behavior: it runs before any forkchoice update, so the safe-commit cell is
5494/// still zero and the canonical gate committed nothing there, which is the unbounded-layer
5495/// problem the depth gate fixes. Now that it does commit, it also journals. Deriving
5496/// `is_batch` from `commit_depth` instead would suppress that, but it would also suppress
5497/// the full-sync and import tails, and it would leave the journal discontiguous with the
5498/// on-disk root: surviving entries below a non-journaled commit describe pre-images
5499/// relative to a root the disk has already moved past.
5500fn commit_trie_if_due(
5501    backend: &dyn StorageBackend,
5502    trie_cache: &Arc<RwLock<Arc<TrieLayerCache>>>,
5503    fkv_ctl: &SyncSender<FKVGeneratorControlMessage>,
5504    parent_state_root: H256,
5505    commit_depth: Option<usize>,
5506    is_batch: bool,
5507) -> Result<(), StoreError> {
5508    let trie = trie_cache
5509        .read()
5510        .map_err(|_| StoreError::LockError)?
5511        .clone();
5512    // Phase 2 + 3: flush and prune the committable backlog.
5513    let commitable = match commit_depth {
5514        Some(depth) => trie.get_commitable_by_depth(parent_state_root, depth),
5515        None => trie.get_commitable(parent_state_root),
5516    };
5517    let Some(root) = commitable else {
5518        // Nothing to commit to disk, move on.
5519        return Ok(());
5520    };
5521    commit_to_disk(backend, fkv_ctl, trie_cache, &trie, root, is_batch)
5522}
5523
5524/// Flush the layer at `root` and all older ancestors to disk, then prune them from the
5525/// in-memory cache (Phases 2 and 3 of the persistence pipeline).
5526///
5527/// `trie` must be the current cache snapshot and `root` a committable layer (as returned
5528/// by [`TrieLayerCache::get_commitable`]). A `root` that is not a layer commits nothing.
5529///
5530/// Reused by both the per-block path ([`commit_trie_if_due`]) and the forkchoice-driven
5531/// flush ([`PersistMessage::Commit`]): without the latter, an execute-all-then-one-forkchoice
5532/// flow (block import) would never persist, because the commit step only runs while blocks execute.
5533fn commit_to_disk(
5534    backend: &dyn StorageBackend,
5535    fkv_ctl: &SyncSender<FKVGeneratorControlMessage>,
5536    trie_cache: &Arc<RwLock<Arc<TrieLayerCache>>>,
5537    trie: &Arc<TrieLayerCache>,
5538    root: H256,
5539    is_batch: bool,
5540) -> Result<(), StoreError> {
5541    // `root` need not have a layer: the forkchoice `PersistMessage::Commit(root)` path
5542    // forwards the safe-commit root without consulting the cache, and `put_batch` skips
5543    // blocks whose state root equals their parent's. Bail before the side effects below.
5544    if !trie.has_layer(root) {
5545        debug!(
5546            root = ?root,
5547            layers = trie.layer_count(),
5548            is_batch,
5549            "Skipping trie commit: state root has no in-memory layer. Expected when the block \
5550             did not change the state root (empty L2 blocks) or the root was already flushed."
5551        );
5552        return Ok(());
5553    }
5554
5555    // Stop the flat-key-value generator thread, as the underlying trie is about to change.
5556    // Ignore the error, if the channel is closed it means there is no worker to notify.
5557    let _ = fkv_ctl.send(FKVGeneratorControlMessage::Stop);
5558
5559    // RCU to remove the bottom layer: update step needs to happen after disk layer is updated.
5560    let mut trie_mut = (**trie).clone();
5561
5562    // Open the read view BEFORE the write batch so each `.get()` sees disk as it was
5563    // before our writes. The journal records `(key, prev_value)` so a future rollback
5564    // can apply diffs directly without reading state.
5565    //
5566    // NOTE: `StorageReadView` does not currently promise true snapshot isolation
5567    // (see the trait docs in `api/mod.rs`). What makes the pre-image read safe here
5568    // is that `commit_to_disk` only ever runs on the single persist worker thread,
5569    // `write_tx` is a buffered batch that does not become visible until
5570    // `write_tx.commit()` at the end of the function, and the other writers to
5571    // these CFs touch disjoint key space: the flat-KV generator only writes keys
5572    // strictly past the committed `last_written` frontier, and snap-sync healing
5573    // completes before block execution commits layers. So every `.get()` below
5574    // sees on-disk state as of the begin_read call.
5575    let read_view = backend.begin_read()?;
5576    let last_written = read_view
5577        .get(MISC_VALUES, "last_written".as_bytes())?
5578        .unwrap_or_default();
5579
5580    let mut write_tx = backend.begin_write()?;
5581
5582    // Before encoding, accounts have only the account address as their path, while storage keys have
5583    // the account address (32 bytes) + storage path (up to 32 bytes).
5584
5585    // Snapshot the overlay (if any) BEFORE commit so reconciliation can fold its entries
5586    // into this write batch. After a deep reorg, the first
5587    // new-chain commit advances disk from the OLD chain's edge `D` directly to the new
5588    // chain's tip `T` in a single atomic write; the overlay supplies the bridge for keys
5589    // layer_T does not touch. Only meaningful when `!is_batch`: the legacy batch-store path
5590    // (`wait_for_flush == true`) is the one path that does not journal.
5591    let overlay_for_reconciliation = if !is_batch {
5592        trie.overlay().cloned()
5593    } else {
5594        None
5595    };
5596
5597    // While an overlay is installed, commit only the bottom layer per pass. The
5598    // The reconciliation below is defined for a single layer at the pivot
5599    // tip `T`: bridge entries are folded into that layer's writes, [T, D] is
5600    // delete_ranged, and T's journal entry records pre-images against the
5601    // old-chain disk state. A multi-layer sweep would journal upper layers'
5602    // pre-images against old-chain disk instead of the new-chain/bridge state
5603    // (the intra-batch pre-image map is not seeded with bridge values), silently
5604    // corrupting a future unwind. The backlog above `T` drains in later passes,
5605    // after this commit clears the overlay (see `trie_mut.clear_overlay` below).
5606    let root = if overlay_for_reconciliation.is_some() {
5607        trie.bottom_layer_root(root)
5608    } else {
5609        root
5610    };
5611
5612    // `commit` removes the committed layer(s) and returns one `CommittedLayer` per block
5613    // in oldest-first order. In normal block-by-block operation this is a single layer,
5614    // one commit-cadence behind the just-added block. A forkchoice-driven flush of an
5615    // accumulated backlog (e.g. block import) can return several layers at once, so we
5616    // write one journal entry per block below rather than merging diffs across blocks.
5617    //
5618    // `has_layer` above established `root` is a layer and `trie_mut` is a `Clone` that
5619    // preserves the map, so this must be `Some`. Reaching the error means the clone lost the
5620    // map, which is corruption, not the ordinary no-op handled above.
5621    let committed_layers = trie_mut.commit(root).ok_or_else(|| {
5622        StoreError::Custom(format!(
5623            "trie layer for state root {root:?} disappeared between the has_layer check and \
5624             commit (layers={}, is_batch={is_batch}): the TrieLayerCache clone lost the layer \
5625             map, so this block's state was not written",
5626            trie.layer_count(),
5627        ))
5628    })?;
5629
5630    // Deep-reorg reconciliation is a single new-chain commit advancing disk to the pivot
5631    // tip `T`; it must map to exactly one committed layer. A multi-layer commit with an
5632    // overlay installed would mean a backlog accumulated between overlay install and
5633    // flush, corrupting the [T, D] delete_range below.
5634    debug_assert!(
5635        overlay_for_reconciliation.is_none() || committed_layers.len() == 1,
5636        "overlay-backed reconciliation must commit exactly one layer (T), got {}",
5637        committed_layers.len()
5638    );
5639
5640    // Reconciliation: overlay entries the new chain has NOT rewritten must be
5641    // bridged onto disk so disk fully reflects the pivot->T transition. Keys any committed
5642    // layer touches are skipped (the layer wins, its value is the post-T state). Overlay-only
5643    // entries with `None` become an empty-value write -> deleted on disk, matching the
5644    // "absent at pivot" semantics.
5645    let extra_writes: Vec<(Vec<u8>, Vec<u8>)> = match &overlay_for_reconciliation {
5646        Some(overlay) => {
5647            let layer_keys: SeededHashSet<&Vec<u8>> = committed_layers
5648                .iter()
5649                .flat_map(|l| l.nodes.iter().map(|(k, _)| k))
5650                .collect();
5651            overlay
5652                .iter_all_entries()
5653                .filter(|(_, key, _)| !layer_keys.contains(key))
5654                .map(|(_, key, value)| (key.clone(), value.clone().unwrap_or_default()))
5655                .collect()
5656        }
5657        None => Vec::new(),
5658    };
5659    // Pivot heights (T, D) for the reconciliation commit; `None` in steady state.
5660    let reorg_heights = overlay_for_reconciliation
5661        .as_ref()
5662        .map(|ov| (ov.to_block(), ov.from_block()));
5663
5664    // Layers at or below finality are committed without a journal entry. An entry only
5665    // serves a reorg that unwinds its block, and finality pruning deletes every entry at
5666    // or below finality on the next advance, so this one could only serve a reorg across
5667    // finality that arrives before that advance. Finality is not a reorg limit (see
5668    // `compute_reorg_ceiling` in the blockchain crate), but the limit is computed from
5669    // the entries present, so such a reorg is rejected as too deep in that window instead
5670    // of served. Layers commit ~DB_COMMIT_THRESHOLD blocks behind the head, which on a
5671    // finalizing chain is already final (an L2 finalizes its head every block, L1
5672    // finality trails the head by two or three epochs), so otherwise every entry is
5673    // written only to be range-deleted. The reconciliation layer of a deep reorg always
5674    // journals. `None` journals every layer.
5675    let skip_journal_upto = if is_batch || overlay_for_reconciliation.is_some() {
5676        None
5677    } else {
5678        journal_skip_ceiling(read_view.as_ref())
5679    };
5680    let journals_layer = |block_number: BlockNumber| {
5681        !is_batch && skip_journal_upto.is_none_or(|upto| block_number > upto)
5682    };
5683    // Skipped layers come first (layers are oldest-first), and a journaled layer after them
5684    // must see their staged writes as its pre-images, so they still feed the overlay below.
5685    let track_overlay = committed_layers
5686        .iter()
5687        .any(|layer| journals_layer(layer.block_number));
5688
5689    // Intra-batch overlay of values already staged in THIS write batch, so each block's
5690    // reverse diff records the value as of the *previous* committed block's write, not
5691    // just the pre-batch on-disk value. `None` means an earlier block deleted the key.
5692    // For the common single-layer commit this stays empty and every pre-image comes
5693    // straight from `read_view`. Only maintained when some layer of this commit journals
5694    // (`track_overlay`).
5695    //
5696    // PERF: the first touch of each key does one synchronous `read_view.get(table, &key)`.
5697    // For large state diffs this is O(N) extra reads on the per-block critical path.
5698    // A follow-up could batch these via `multi_get_cf` if profiling shows it's significant.
5699    let mut overlay: HashMap<Vec<u8>, Option<Vec<u8>>> = HashMap::new();
5700
5701    let mut result = Ok(());
5702    'layers: for layer in &committed_layers {
5703        // Reverse-diff accumulators for this block's journal entry, one per CF. Each entry
5704        // stores the on-disk key as-is (storage CFs carry their nibble-encoded account-hash
5705        // prefix), so a future rollback applies diffs directly without interpretation. For
5706        // the legacy batch-store path (`is_batch == true`) and for layers at or below
5707        // `skip_journal_upto` no journal entry is written. Every other per-block commit
5708        // journals — including full sync through the unified pipeline, whose
5709        // interrupted-batch recovery at startup relies on the newest entry naming the
5710        // block whose state is on disk.
5711        let journal_layer = journals_layer(layer.block_number);
5712        let mut journal_account_trie: FlatDiff = Vec::new();
5713        let mut journal_storage_trie: FlatDiff = Vec::new();
5714        let mut journal_account_flat: FlatDiff = Vec::new();
5715        let mut journal_storage_flat: FlatDiff = Vec::new();
5716
5717        // The reconciliation commit is single-layer at `T`; fold the overlay bridge entries
5718        // into that layer's writes so they land in T's journal entry. `extra` is empty in
5719        // steady state (no overlay) and for any non-T layer.
5720        // With the bottom-layer-only rule above, a commit made while the overlay
5721        // is installed always contains exactly this one (bottom) layer, so it is
5722        // the reconciliation layer by construction. Matching by block number
5723        // (`layer.block_number == to_block`) would be fragile: root-preserving
5724        // blocks create no layer (L2 empty blocks), so the bottom layer can sit
5725        // above `to_block` and the bridge entries would be neither written nor
5726        // journaled before the overlay is cleared.
5727        let is_reconciliation_layer = overlay_for_reconciliation.is_some();
5728        let extra: &[(Vec<u8>, Vec<u8>)] = if is_reconciliation_layer {
5729            &extra_writes
5730        } else {
5731            &[]
5732        };
5733
5734        // Pre-images for the reconciliation layer must be taken at the pivot, not at the
5735        // old chain's edge `D`. `T`'s journal entry has to reverse disk back to the pivot
5736        // state, but this batch is built while disk still holds `D`, so `read_view` yields
5737        // `D`'s values for every key the old chain rewrote in `[T, D]`. The overlay *is*
5738        // the pivot-vs-`D` difference, so it wins over `read_view` for any key it carries.
5739        // `None` in the overlay means "absent at the pivot", which is exactly the journal's
5740        // "delete on rollback" entry.
5741        let pivot_overlay = overlay_for_reconciliation.as_ref();
5742
5743        for (key, value) in layer.nodes.iter().chain(extra.iter()) {
5744            let (is_leaf, is_account) = classify_trie_key(key.len());
5745
5746            // Keys past the flat-KV generator's frontier aren't written to disk yet, so
5747            // they must not be journaled either (a `Some(None)` entry recorded here
5748            // would cause a rollback to delete a key that was never put). The `continue`
5749            // jumps over both the write and the journal push below.
5750            if is_leaf && key.as_slice() > last_written.as_slice() {
5751                continue;
5752            }
5753            let table = if is_leaf {
5754                if is_account {
5755                    &ACCOUNT_FLATKEYVALUE
5756                } else {
5757                    &STORAGE_FLATKEYVALUE
5758                }
5759            } else if is_account {
5760                &ACCOUNT_TRIE_NODES
5761            } else {
5762                &STORAGE_TRIE_NODES
5763            };
5764
5765            // Pre-image: the intra-batch overlay wins over the pivot overlay, which wins
5766            // over disk, so multi-layer commits record each block's true pre-state and the
5767            // reconciliation layer records the pivot's. Skipped for layers that don't journal.
5768            let prev_value = if journal_layer {
5769                match overlay.get(key) {
5770                    Some(v) => Some(v.clone()),
5771                    None => match pivot_overlay
5772                        .and_then(|ov| ov.lookup(OverlayCf::classify_by_key_length(key.len()), key))
5773                    {
5774                        Some(v) => Some(v),
5775                        None => match read_view.get(table, key) {
5776                            Ok(v) => Some(v),
5777                            Err(e) => {
5778                                result = Err(e);
5779                                break 'layers;
5780                            }
5781                        },
5782                    },
5783                }
5784            } else {
5785                None
5786            };
5787
5788            let new_value = if value.is_empty() {
5789                result = write_tx.delete(table, key);
5790                None
5791            } else {
5792                result = write_tx.put(table, key, value);
5793                Some(value.clone())
5794            };
5795            if result.is_err() {
5796                break 'layers;
5797            }
5798
5799            // Record the reverse-diff entry after the put/delete is staged, so a write
5800            // error doesn't accumulate state we won't persist.
5801            if let Some(prev) = prev_value {
5802                let bucket = match (is_leaf, is_account) {
5803                    (false, true) => &mut journal_account_trie,
5804                    (false, false) => &mut journal_storage_trie,
5805                    (true, true) => &mut journal_account_flat,
5806                    (true, false) => &mut journal_storage_flat,
5807                };
5808                bucket.push((key.clone(), prev));
5809            }
5810            // Advance the overlay so a later block in this same commit sees this
5811            // block's write as its pre-image.
5812            if track_overlay {
5813                overlay.insert(key.clone(), new_value);
5814            }
5815        }
5816
5817        // Reconciliation: BEFORE writing this block's journal entry, wipe the
5818        // obsolete OLD-chain entries in `[T, D]` so the new T entry (below) isn't clobbered
5819        // by the range delete. Fires only for the single reconciliation layer at height T.
5820        // T = `overlay.to_block()`, D = `overlay.from_block()`.
5821        if !is_batch && let Some((t, d)) = reorg_heights {
5822            debug_assert_eq!(
5823                layer.block_number, t,
5824                "first new-chain commit must be at the pivot's T height (overlay.to_block)"
5825            );
5826            // Only reconcile when this committed layer is exactly the pivot height `t`.
5827            // The `delete_range` wipes the OLD-chain journal entries `[t, d]`; if the layer
5828            // is not at `t` the range delete would drop new-chain entries that belong in
5829            // `[t, d]` and leave gaps that break later reorg recovery. The debug_assert
5830            // catches this loudly in tests; in release we skip (and log) rather than corrupt
5831            // STATE_HISTORY.
5832            if layer.block_number == t {
5833                let start = t.to_be_bytes();
5834                let end = d.saturating_add(1).to_be_bytes();
5835                result = write_tx.delete_range(STATE_HISTORY, &start, &end);
5836                if result.is_err() {
5837                    break 'layers;
5838                }
5839            } else {
5840                error!(
5841                    block_number = layer.block_number,
5842                    t,
5843                    d,
5844                    "deep-reorg reconciliation skipped: committed layer not at pivot height; skipping STATE_HISTORY delete_range to avoid history gaps"
5845                );
5846            }
5847        }
5848
5849        // Stage this block's journal entry into the same write batch as the trie/flat-KV
5850        // overwrites. `put` is buffered until `commit`, so all CFs and every block's entry
5851        // land atomically (or none do on commit failure). Each entry is keyed and identified
5852        // by its own COMMITTED block, not the in-flight block whose insertion triggered this
5853        // commit (that block commits later, one cadence behind).
5854        if journal_layer {
5855            let entry = JournalEntry {
5856                block_hash: layer.block_hash,
5857                parent_state_root: layer.parent_state_root,
5858                account_trie_diff: journal_account_trie,
5859                storage_trie_diff: journal_storage_trie,
5860                account_flat_diff: journal_account_flat,
5861                storage_flat_diff: journal_storage_flat,
5862            };
5863            result = write_tx.put(
5864                STATE_HISTORY,
5865                &layer.block_number.to_be_bytes(),
5866                &entry.encode(),
5867            );
5868            if result.is_err() {
5869                break 'layers;
5870            }
5871        }
5872    }
5873
5874    if result.is_ok() {
5875        result = write_tx.commit();
5876    }
5877    // We want to send this message even if there was an error during the batch write
5878    let _ = fkv_ctl.send(FKVGeneratorControlMessage::Continue);
5879    result?;
5880
5881    // Reconciliation succeeded: drop the overlay from the cache. Subsequent
5882    // commits revert to the normal one-block path.
5883    if overlay_for_reconciliation.is_some() {
5884        trie_mut.clear_overlay();
5885    }
5886
5887    // Phase 3: update diff layers with the removal of bottom layer.
5888    //
5889    // SAFETY: `install_overlay_for_reorg` rendezvous-pings this worker before
5890    // swapping `trie_cache`, so no concurrent RCU can race the write-back here.
5891    // See the Ping comment in `install_overlay_for_reorg`.
5892    *trie_cache.write().map_err(|_| StoreError::LockError)? = Arc::new(trie_mut);
5893    Ok(())
5894}
5895
5896/// Highest block number whose layer [`commit_to_disk`] may commit without a journal
5897/// entry, or `None` to journal every layer.
5898///
5899/// A layer is skipped only when its block is at or below finality, at or below the head,
5900/// and the journal is empty. Together these leave `STATE_HISTORY` in a state it already
5901/// reaches without skipping (layers committed, then pruned by the next finality advance),
5902/// so no reader of the journal sees anything new:
5903/// - Finality: pruning deletes every entry at or below finality on the next advance, so
5904///   the entry could only serve a reorg across finality that arrives before that advance.
5905///   Finality is not a reorg limit (`compute_reorg_ceiling` trusts the CL's fork choice,
5906///   and the engine API tests reorg across it), but the limit is computed from the entries
5907///   present, so such a reorg is rejected as too deep in that window instead of served:
5908///   up to an epoch on L1, one block on L2.
5909/// - Head: interrupted-batch recovery adopts the newest entry only when it is above the
5910///   head, so it never needs a skipped one. Finality is normally at or below the head,
5911///   but a head rewound without a finality update (an L2 revert, a restart clamping the
5912///   head to the flushed blocks) can leave it above.
5913/// - Empty journal: a surviving entry below a skipped layer would hold pre-images against
5914///   a state the disk has moved past, and would no longer be the newest entry naming the
5915///   block whose state is on disk. Skipping resumes once finality pruning has cleared it.
5916///
5917/// A failed or malformed read journals, the conservative choice.
5918fn journal_skip_ceiling(read_view: &dyn StorageReadView) -> Option<BlockNumber> {
5919    let read_number = |index| {
5920        read_view
5921            .get(CHAIN_DATA, &chain_data_key(index))
5922            .ok()
5923            .flatten()
5924            .and_then(|bytes| <[u8; 8]>::try_from(bytes.as_slice()).ok())
5925            .map(BlockNumber::from_le_bytes)
5926    };
5927    let finalized = read_number(ChainDataIndex::FinalizedBlockNumber)?;
5928    let head = read_number(ChainDataIndex::LatestBlockNumber)?;
5929    match read_view.first_key(STATE_HISTORY) {
5930        Ok(None) => Some(finalized.min(head)),
5931        _ => None,
5932    }
5933}
5934
5935// NOTE: we don't receive `Store` here to avoid cyclic dependencies
5936// with the other end of `control_rx`
5937fn flatkeyvalue_generator(
5938    backend: &Arc<dyn StorageBackend>,
5939    last_computed_fkv: &RwLock<Vec<u8>>,
5940    control_rx: &std::sync::mpsc::Receiver<FKVGeneratorControlMessage>,
5941) -> Result<(), StoreError> {
5942    info!("Generation of FlatKeyValue started.");
5943    let initial_last_written = backend
5944        .begin_read()?
5945        .get(MISC_VALUES, "last_written".as_bytes())?
5946        .unwrap_or_default();
5947
5948    if initial_last_written.is_empty() {
5949        // First time generating the FKV. Remove all FKV entries just in case
5950        backend.clear_table(ACCOUNT_FLATKEYVALUE)?;
5951        backend.clear_table(STORAGE_FLATKEYVALUE)?;
5952    } else if initial_last_written == [0xff] {
5953        // FKV was already generated
5954        info!("FlatKeyValue already generated. Skipping.");
5955        return Ok(());
5956    }
5957
5958    loop {
5959        // Acquire a fresh read view per iteration so updates performed while the
5960        // generator is paused are visible after a Continue signal.
5961        let read_tx = backend.begin_read()?;
5962        let root = read_tx
5963            .get(ACCOUNT_TRIE_NODES, &[])?
5964            .ok_or(StoreError::MissingLatestBlockNumber)?;
5965        let root: Node = ethrex_trie::Node::decode(&root)?;
5966        let state_root = root.compute_hash(&NativeCrypto).finalize(&NativeCrypto);
5967
5968        let last_written = read_tx
5969            .get(MISC_VALUES, "last_written".as_bytes())?
5970            .unwrap_or_default();
5971        let last_written_account = last_written
5972            .get(0..64)
5973            .map(|v| Nibbles::from_hex(v.to_vec()))
5974            .unwrap_or_default();
5975        let mut last_written_storage = last_written
5976            .get(66..130)
5977            .map(|v| Nibbles::from_hex(v.to_vec()))
5978            .unwrap_or_default();
5979
5980        debug!("Starting FlatKeyValue loop pivot={last_written:?} SR={state_root:x}");
5981
5982        let mut ctr = 0;
5983        let mut write_txn = backend.begin_write()?;
5984        let mut iter = Trie::open(
5985            Box::new(BackendTrieDB::new_for_accounts_with_view(
5986                backend.clone(),
5987                read_tx.clone(),
5988                last_written.clone(),
5989            )?),
5990            state_root,
5991        )
5992        .into_iter();
5993        if last_written_account > Nibbles::default() {
5994            iter.advance(last_written_account.to_bytes())?;
5995        }
5996        let res = iter.try_for_each(|(path, node)| -> Result<(), StoreError> {
5997            let Node::Leaf(node) = node else {
5998                return Ok(());
5999            };
6000            let account_state = AccountState::decode(&node.value)?;
6001            let account_hash = H256::from_slice(&path.to_bytes());
6002            write_txn.put(MISC_VALUES, "last_written".as_bytes(), path.as_ref())?;
6003            write_txn.put(ACCOUNT_FLATKEYVALUE, path.as_ref(), &node.value)?;
6004            ctr += 1;
6005            if ctr > 10_000 {
6006                write_txn.commit()?;
6007                write_txn = backend.begin_write()?;
6008                *last_computed_fkv
6009                    .write()
6010                    .map_err(|_| StoreError::LockError)? = path.as_ref().to_vec();
6011                ctr = 0;
6012            }
6013
6014            let mut iter_inner = Trie::open(
6015                Box::new(BackendTrieDB::new_for_account_storage_with_view(
6016                    backend.clone(),
6017                    read_tx.clone(),
6018                    account_hash,
6019                    path.as_ref().to_vec(),
6020                )?),
6021                account_state.storage_root,
6022            )
6023            .into_iter();
6024            if last_written_storage > Nibbles::default() {
6025                iter_inner.advance(last_written_storage.to_bytes())?;
6026                last_written_storage = Nibbles::default();
6027            }
6028            iter_inner.try_for_each(|(path, node)| -> Result<(), StoreError> {
6029                let Node::Leaf(node) = node else {
6030                    return Ok(());
6031                };
6032                let key = apply_prefix(Some(account_hash), path);
6033                write_txn.put(MISC_VALUES, "last_written".as_bytes(), key.as_ref())?;
6034                write_txn.put(STORAGE_FLATKEYVALUE, key.as_ref(), &node.value)?;
6035                ctr += 1;
6036                if ctr > 10_000 {
6037                    write_txn.commit()?;
6038                    write_txn = backend.begin_write()?;
6039                    *last_computed_fkv
6040                        .write()
6041                        .map_err(|_| StoreError::LockError)? = key.into_vec();
6042                    ctr = 0;
6043                }
6044                fkv_check_for_stop_msg(control_rx)?;
6045                Ok(())
6046            })?;
6047            fkv_check_for_stop_msg(control_rx)?;
6048            Ok(())
6049        });
6050        match res {
6051            Err(StoreError::PivotChanged) => {
6052                match control_rx.recv() {
6053                    Ok(FKVGeneratorControlMessage::Continue) => {}
6054                    Ok(FKVGeneratorControlMessage::Stop) => {
6055                        return Err(StoreError::Custom("Unexpected Stop message".to_string()));
6056                    }
6057                    // If the channel was closed, we stop generation prematurely
6058                    Err(std::sync::mpsc::RecvError) => {
6059                        info!("Store closed, stopping FlatKeyValue generation.");
6060                        return Ok(());
6061                    }
6062                }
6063            }
6064            Err(err) => return Err(err),
6065            Ok(()) => {
6066                write_txn.put(MISC_VALUES, "last_written".as_bytes(), &[0xff])?;
6067                write_txn.commit()?;
6068                *last_computed_fkv
6069                    .write()
6070                    .map_err(|_| StoreError::LockError)? = vec![0xff; 131];
6071                info!("FlatKeyValue generation finished.");
6072                return Ok(());
6073            }
6074        };
6075    }
6076}
6077
6078fn fkv_check_for_stop_msg(
6079    control_rx: &std::sync::mpsc::Receiver<FKVGeneratorControlMessage>,
6080) -> Result<(), StoreError> {
6081    match control_rx.try_recv() {
6082        Ok(FKVGeneratorControlMessage::Stop) | Err(TryRecvError::Disconnected) => {
6083            return Err(StoreError::PivotChanged);
6084        }
6085        Ok(FKVGeneratorControlMessage::Continue) => {
6086            return Err(StoreError::Custom(
6087                "Unexpected Continue message".to_string(),
6088            ));
6089        }
6090        Err(TryRecvError::Empty) => {}
6091    }
6092    Ok(())
6093}
6094
6095fn state_trie_locked_backend(
6096    backend: &dyn StorageBackend,
6097    last_written: Vec<u8>,
6098) -> Result<BackendTrieDBLocked, StoreError> {
6099    // No address prefix for state trie
6100    BackendTrieDBLocked::new(backend, last_written)
6101}
6102
6103pub struct AccountProof {
6104    pub proof: Vec<NodeRLP>,
6105    /// `None` when the account is absent from the state trie.
6106    pub account: Option<AccountState>,
6107    pub storage_proof: Vec<StorageSlotProof>,
6108}
6109
6110pub struct StorageSlotProof {
6111    pub proof: Vec<NodeRLP>,
6112    pub key: H256,
6113    pub value: U256,
6114}
6115
6116pub struct AncestorIterator {
6117    store: Store,
6118    next_hash: BlockHash,
6119}
6120
6121impl Iterator for AncestorIterator {
6122    type Item = Result<(BlockHash, BlockHeader), StoreError>;
6123
6124    fn next(&mut self) -> Option<Self::Item> {
6125        let next_hash = self.next_hash;
6126        // Buffer-aware: a not-yet-flushed ancestor (e.g. on a side branch during
6127        // a reorg) must be visible here, or a BLOCKHASH opcode resolving through
6128        // this walk would wrongly reject a valid block.
6129        match self.store.get_block_header_by_hash(next_hash) {
6130            Ok(Some(header)) => {
6131                let ret_hash = self.next_hash;
6132                self.next_hash = header.parent_hash;
6133                Some(Ok((ret_hash, header)))
6134            }
6135            Ok(None) => None,
6136            Err(e) => Some(Err(e)),
6137        }
6138    }
6139}
6140
6141pub fn hash_address(address: &Address) -> Vec<u8> {
6142    keccak_hash(address.to_fixed_bytes()).to_vec()
6143}
6144
6145fn hash_address_fixed(address: &Address) -> H256 {
6146    keccak(address.to_fixed_bytes())
6147}
6148
6149pub fn hash_key(key: &H256) -> Vec<u8> {
6150    keccak_hash(key.to_fixed_bytes()).to_vec()
6151}
6152
6153pub fn hash_key_fixed(key: &H256) -> [u8; 32] {
6154    keccak_hash(key.to_fixed_bytes())
6155}
6156
6157fn chain_data_key(index: ChainDataIndex) -> Vec<u8> {
6158    (index as u8).encode_to_vec()
6159}
6160
6161/// Decodes a block number stored as little-endian bytes.
6162fn decode_block_number(bytes: Vec<u8>) -> Result<BlockNumber, StoreError> {
6163    let array: [u8; 8] = bytes
6164        .try_into()
6165        .map_err(|_| StoreError::Custom("Invalid BlockNumber bytes".to_string()))?;
6166    Ok(BlockNumber::from_le_bytes(array))
6167}
6168
6169fn snap_state_key(index: SnapStateIndex) -> Vec<u8> {
6170    (index as u8).encode_to_vec()
6171}
6172
6173/// Builds a fixed-width RECEIPTS key: block_hash (32B) || index (8B BE).
6174pub fn receipt_key(block_hash: &BlockHash, index: u64) -> Vec<u8> {
6175    let mut key = Vec::with_capacity(40);
6176    key.extend_from_slice(block_hash.as_bytes());
6177    key.extend_from_slice(&index.to_be_bytes());
6178    key
6179}
6180
6181pub fn encode_code(code: &Code) -> Vec<u8> {
6182    let jumpdests = code.jumpdests();
6183    let mut buf = Vec::with_capacity(6 + code.len() + jumpdests.len());
6184    code.code().encode(&mut buf);
6185    jumpdests.encode(&mut buf);
6186    buf
6187}
6188
6189/// Decodes the JUMPDEST bitmap stored after the bytecode in an [`ACCOUNT_CODES`] value.
6190///
6191/// Values written before the bitmap representation hold an RLP *list* of `u32` offsets
6192/// there instead. The RLP item header distinguishes a list from a byte string, so both
6193/// forms are readable: for the older one the bitmap is rebuilt from the bytecode, which
6194/// is cheaper than decoding the list.
6195/// Decodes the stored jump-destination bitmap. The bool is `true` when the value
6196/// was in the legacy RLP-list-of-`u32` format and had to be recomputed from
6197/// `code` — the caller uses it to self-heal the row to the bitmap format so the
6198/// recompute is paid at most once per entry rather than on every cold read.
6199fn decode_jumpdests(code: &[u8], encoded: &[u8]) -> Result<(Arc<[u8]>, bool), StoreError> {
6200    let (is_list, payload, _) = decode_rlp_item(encoded)?;
6201    if is_list {
6202        return Ok((Code::compute_jumpdests(code), true));
6203    }
6204    Ok((Arc::from(payload), false))
6205}
6206
6207#[derive(Debug, Default, Clone)]
6208struct LatestBlockHeaderCache {
6209    current: Arc<Mutex<Arc<BlockHeader>>>,
6210}
6211
6212impl LatestBlockHeaderCache {
6213    pub fn get(&self) -> Arc<BlockHeader> {
6214        self.current.lock().expect("poisoned mutex").clone()
6215    }
6216
6217    pub fn update(&self, header: BlockHeader) {
6218        let new = Arc::new(header);
6219        *self.current.lock().expect("poisoned mutex") = new;
6220    }
6221}
6222
6223#[derive(Debug, Serialize, Deserialize)]
6224pub struct StoreMetadata {
6225    pub schema_version: u64,
6226}
6227
6228impl StoreMetadata {
6229    pub fn new(schema_version: u64) -> Self {
6230        Self { schema_version }
6231    }
6232}
6233
6234/// Reads the schema version from the metadata file, if it exists.
6235///
6236/// Returns `Some(version)` when metadata.json is present and valid,
6237/// or `None` when the file does not exist.
6238fn read_store_schema_version(path: &Path) -> Result<Option<u64>, StoreError> {
6239    let metadata_path = path.join(STORE_METADATA_FILENAME);
6240    if !metadata_path.exists() {
6241        return Ok(None);
6242    }
6243    if !metadata_path.is_file() {
6244        return Err(StoreError::Custom(
6245            "store schema path exists but is not a file".to_string(),
6246        ));
6247    }
6248    let file_contents = std::fs::read_to_string(metadata_path)?;
6249    let metadata: StoreMetadata = serde_json::from_str(&file_contents)?;
6250    Ok(Some(metadata.schema_version))
6251}
6252
6253fn init_metadata_file(parent_path: &Path) -> Result<(), StoreError> {
6254    std::fs::create_dir_all(parent_path)?;
6255
6256    let metadata_path = parent_path.join(STORE_METADATA_FILENAME);
6257    let metadata = StoreMetadata::new(STORE_SCHEMA_VERSION);
6258    let serialized_metadata = serde_json::to_string_pretty(&metadata)?;
6259    let mut new_file = std::fs::File::create_new(metadata_path)?;
6260    new_file.write_all(serialized_metadata.as_bytes())?;
6261    Ok(())
6262}
6263
6264/// Returns `true` if `path` contains a *legacy* database — one written before
6265/// the metadata file existed, so it has no `metadata.json` to identify it.
6266/// Detected by RocksDB's own marker files, as opposed to unrelated files that
6267/// merely share the datadir. Only meaningful once metadata has been confirmed
6268/// absent; otherwise prefer `has_valid_db`, which keys off the metadata file.
6269///
6270/// Previously the caller treated *any* non-empty directory as such a legacy
6271/// database, which made startup fail when unrelated files lived alongside the DB
6272/// — e.g. EthDocker writes the JWT secret into the datadir (issue #5680). We
6273/// instead look for RocksDB's marker files, so a datadir that only contains such
6274/// unrelated files is correctly treated as fresh.
6275fn dir_contains_legacy_db(path: &Path) -> Result<bool, StoreError> {
6276    // `CURRENT` has a fixed name and is written by every RocksDB instance, so
6277    // check for it directly instead of scanning a datadir that may hold many
6278    // unrelated files.
6279    if path.join("CURRENT").is_file() {
6280        return Ok(true);
6281    }
6282    // The manifest has a numeric suffix (`MANIFEST-<n>`), so it can only be
6283    // found by scanning. Restrict to plain files: a directory that happens to
6284    // share the name is not a database marker.
6285    for entry in std::fs::read_dir(path)? {
6286        let entry = entry?;
6287        if !entry.file_type()?.is_file() {
6288            continue;
6289        }
6290        if entry.file_name().to_string_lossy().starts_with("MANIFEST-") {
6291            return Ok(true);
6292        }
6293    }
6294    Ok(false)
6295}
6296
6297/// Checks whether a valid (or migratable) database exists at the given path
6298/// by looking for a metadata.json file with a schema version between 1 and
6299/// `STORE_SCHEMA_VERSION` (inclusive).
6300pub fn has_valid_db(path: &Path) -> bool {
6301    let metadata_path = path.join(STORE_METADATA_FILENAME);
6302    if !metadata_path.is_file() {
6303        return false;
6304    }
6305    let Ok(contents) = std::fs::read_to_string(&metadata_path) else {
6306        return false;
6307    };
6308    let Ok(metadata) = serde_json::from_str::<StoreMetadata>(&contents) else {
6309        return false;
6310    };
6311    metadata.schema_version >= 1 && metadata.schema_version <= STORE_SCHEMA_VERSION
6312}
6313
6314/// Reads the chain ID from an existing database without performing a full
6315/// store initialization. Returns `None` if the database doesn't exist or
6316/// the chain config can't be read. Always returns `None` when compiled
6317/// without the `rocksdb` feature.
6318///
6319/// Each failure mode logs a warning so callers (and operators) can diagnose
6320/// why an existing database was not usable — previously every error was
6321/// silently swallowed by `.ok()?`.
6322pub fn read_chain_id_from_db(path: &Path) -> Option<u64> {
6323    if !has_valid_db(path) {
6324        return None;
6325    }
6326    #[cfg(feature = "rocksdb")]
6327    {
6328        // The cache size is irrelevant for this one-shot chain-id read (the LRU
6329        // is sized as a ceiling, not pre-allocated), so we use the ceiling.
6330        let backend = match RocksDBBackend::open(path, MAX_ROCKSDB_BLOCK_CACHE_SIZE_BYTES) {
6331            Ok(backend) => backend,
6332            Err(e) => {
6333                warn!("Failed to open RocksDB at {path:?} to read chain ID: {e}");
6334                return None;
6335            }
6336        };
6337        let read = match backend.begin_read() {
6338            Ok(read) => read,
6339            Err(e) => {
6340                warn!("Failed to begin read transaction at {path:?}: {e}");
6341                return None;
6342            }
6343        };
6344        let key = chain_data_key(ChainDataIndex::ChainConfig);
6345        let bytes = match read.get(CHAIN_DATA, &key) {
6346            Ok(Some(bytes)) => bytes,
6347            Ok(None) => {
6348                warn!("Chain config entry not found in database at {path:?}");
6349                return None;
6350            }
6351            Err(e) => {
6352                warn!("Failed to read chain config from database at {path:?}: {e}");
6353                return None;
6354            }
6355        };
6356        // Only extract chain_id here: the stored `ChainConfig` JSON may include
6357        // fields whose serialization changed across releases (e.g. pre-v10 wrote
6358        // `terminal_total_difficulty` as a plain number, v10 expects hex string).
6359        // Deserializing the full struct would reject otherwise-migratable v9 data.
6360        #[derive(serde::Deserialize)]
6361        #[serde(rename_all = "camelCase")]
6362        struct ChainIdOnly {
6363            chain_id: u64,
6364        }
6365        match serde_json::from_slice::<ChainIdOnly>(&bytes) {
6366            Ok(partial) => Some(partial.chain_id),
6367            Err(e) => {
6368                warn!("Failed to deserialize chain ID from database at {path:?}: {e}");
6369                None
6370            }
6371        }
6372    }
6373    #[cfg(not(feature = "rocksdb"))]
6374    {
6375        let _ = path;
6376        None
6377    }
6378}
6379
6380/// Decodes only the transaction at `index` of an RLP-encoded block body, or
6381/// `None` if the body has fewer transactions. The transactions before it are
6382/// skipped over by their RLP length prefix rather than decoded, so reading one
6383/// transaction does not cost decoding the whole body.
6384fn decode_body_transaction(
6385    body_rlp: &[u8],
6386    index: usize,
6387) -> Result<Option<Transaction>, RLPDecodeError> {
6388    let (is_list, body, _) = decode_rlp_item(body_rlp)?;
6389    if !is_list {
6390        return Err(RLPDecodeError::UnexpectedString);
6391    }
6392    let (is_list, mut transactions, _) = decode_rlp_item(body)?;
6393    if !is_list {
6394        return Err(RLPDecodeError::UnexpectedString);
6395    }
6396    for _ in 0..index {
6397        if transactions.is_empty() {
6398            return Ok(None);
6399        }
6400        (_, _, transactions) = decode_rlp_item(transactions)?;
6401    }
6402    if transactions.is_empty() {
6403        return Ok(None);
6404    }
6405    let (transaction, _) = Transaction::decode_unfinished(transactions)?;
6406    Ok(Some(transaction))
6407}
6408
6409#[cfg(test)]
6410mod body_transaction_tests {
6411    use super::*;
6412    use ethrex_common::types::{EIP1559Transaction, LegacyTransaction, TxKind, Withdrawal};
6413
6414    fn transactions() -> Vec<Transaction> {
6415        (0..6u64)
6416            .map(|nonce| {
6417                if nonce % 2 == 0 {
6418                    // Legacy transactions are encoded as RLP lists in a body.
6419                    Transaction::LegacyTransaction(LegacyTransaction {
6420                        nonce,
6421                        gas: 21_000,
6422                        to: TxKind::Call(Address::repeat_byte(nonce as u8)),
6423                        data: vec![nonce as u8; 60 * nonce as usize].into(),
6424                        v: U256::from(27),
6425                        r: U256::from(nonce + 1),
6426                        s: U256::from(nonce + 2),
6427                        ..Default::default()
6428                    })
6429                } else {
6430                    // Typed transactions are encoded as RLP strings in a body.
6431                    Transaction::EIP1559Transaction(EIP1559Transaction {
6432                        chain_id: 1,
6433                        nonce,
6434                        gas_limit: 21_000,
6435                        to: TxKind::Create,
6436                        data: vec![nonce as u8; 60 * nonce as usize].into(),
6437                        signature_r: U256::from(nonce + 1),
6438                        signature_s: U256::from(nonce + 2),
6439                        ..Default::default()
6440                    })
6441                }
6442            })
6443            .collect()
6444    }
6445
6446    #[test]
6447    fn decodes_the_same_transaction_as_the_whole_body() {
6448        let withdrawal = Withdrawal {
6449            index: 1,
6450            validator_index: 2,
6451            address: Address::repeat_byte(3),
6452            amount: 4,
6453        };
6454        for withdrawals in [None, Some(vec![withdrawal])] {
6455            let body = BlockBody {
6456                transactions: transactions(),
6457                ommers: vec![],
6458                withdrawals,
6459            };
6460            let rlp = body.encode_to_vec();
6461            let decoded = BlockBody::decode(&rlp).unwrap();
6462            for (index, expected) in decoded.transactions.iter().enumerate() {
6463                let transaction = decode_body_transaction(&rlp, index).unwrap().unwrap();
6464                assert_eq!(transaction.encode_to_vec(), expected.encode_to_vec());
6465                assert_eq!(
6466                    transaction.hash(&NativeCrypto),
6467                    expected.hash(&NativeCrypto)
6468                );
6469            }
6470            assert!(
6471                decode_body_transaction(&rlp, decoded.transactions.len())
6472                    .unwrap()
6473                    .is_none()
6474            );
6475        }
6476    }
6477
6478    #[test]
6479    fn a_body_without_transactions_has_none() {
6480        let rlp = BlockBody::default().encode_to_vec();
6481        assert!(decode_body_transaction(&rlp, 0).unwrap().is_none());
6482        assert!(decode_body_transaction(&rlp, 3).unwrap().is_none());
6483    }
6484
6485    #[tokio::test]
6486    async fn reads_a_stored_transaction_by_location() {
6487        let store = Store::new("", EngineType::InMemory).unwrap();
6488        let block = Block::new(
6489            BlockHeader {
6490                number: 1,
6491                ..Default::default()
6492            },
6493            BlockBody {
6494                transactions: transactions(),
6495                ommers: vec![],
6496                withdrawals: None,
6497            },
6498        );
6499        let hash = block.hash();
6500        let expected = block.body.transactions.clone();
6501        store.add_block(block).await.unwrap();
6502        for (index, transaction) in expected.iter().enumerate() {
6503            let stored = store
6504                .get_transaction_by_location(hash, index as u64)
6505                .await
6506                .unwrap()
6507                .unwrap();
6508            assert_eq!(stored.encode_to_vec(), transaction.encode_to_vec());
6509        }
6510        assert!(
6511            store
6512                .get_transaction_by_location(hash, expected.len() as u64)
6513                .await
6514                .unwrap()
6515                .is_none()
6516        );
6517        assert!(
6518            store
6519                .get_transaction_by_location(H256::repeat_byte(9), 0)
6520                .await
6521                .unwrap()
6522                .is_none()
6523        );
6524    }
6525}
6526
6527#[cfg(test)]
6528mod account_code_tests {
6529    use super::*;
6530
6531    const JUMPDEST: u8 = 0x5b;
6532    const PUSH1: u8 = 0x60;
6533
6534    /// `EXTCODESIZE` resolves a length through [`Store::get_code_metadata`], and
6535    /// execution runs on rayon workers, which are not inside a Tokio runtime. A hash
6536    /// with no metadata row SHALL still answer from the bytecode there rather than
6537    /// panicking on the backfill spawn. This test is deliberately NOT `#[tokio::test]`:
6538    /// the absence of a runtime is the condition under test.
6539    #[test]
6540    fn metadata_falls_back_to_the_bytecode_without_a_tokio_runtime() {
6541        use crate::backend::in_memory::InMemoryBackend;
6542
6543        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
6544        let dir = tempfile::tempdir().unwrap();
6545        let store = Store::from_backend(
6546            backend.clone(),
6547            dir.path().to_path_buf(),
6548            1,
6549            DEFAULT_PERSIST_CHANNEL_CAPACITY,
6550        )
6551        .unwrap();
6552
6553        // Code present, metadata row absent: the shape of any database written before
6554        // ACCOUNT_CODE_METADATA existed, which no migration backfills.
6555        let code = jumpdest_dense_code();
6556        let mut tx = backend.begin_write().unwrap();
6557        tx.put(ACCOUNT_CODES, code.hash.as_bytes(), &encode_code(&code))
6558            .unwrap();
6559        tx.commit().unwrap();
6560
6561        let metadata = store
6562            .get_code_metadata(code.hash)
6563            .expect("metadata read must not fail off-runtime");
6564        assert_eq!(metadata.map(|m| m.length), Some(code.len() as u64));
6565    }
6566
6567    /// A max-size contract that is almost entirely JUMPDESTs, the shape that makes the
6568    /// jump-destination representation matter: as a list of offsets it is ~4x the size
6569    /// of the bytecode it describes.
6570    fn jumpdest_dense_code() -> Code {
6571        let mut bytecode = vec![JUMPDEST; 24576];
6572        bytecode[0] = 0x00;
6573        Code::from_bytecode_unchecked(bytecode.into(), H256::zero())
6574    }
6575
6576    /// Encodes an `ACCOUNT_CODES` value the way it was written before the bitmap: the
6577    /// bytecode followed by an RLP list of `u32` JUMPDEST offsets.
6578    fn encode_code_legacy(code: &Code) -> Vec<u8> {
6579        let offsets: Vec<u32> = (0..code.len())
6580            .filter(|offset| code.is_valid_jumpdest(*offset))
6581            .map(|offset| offset as u32)
6582            .collect();
6583        let mut buf = Vec::new();
6584        code.code().encode(&mut buf);
6585        offsets.encode(&mut buf);
6586        buf
6587    }
6588
6589    #[test]
6590    fn encoded_value_carries_one_bitmap_bit_per_code_byte() {
6591        let code = jumpdest_dense_code();
6592        let encoded = encode_code(&code);
6593
6594        assert_eq!(encoded.len(), 6 + code.len() + code.len().div_ceil(8));
6595    }
6596
6597    #[test]
6598    fn round_trip_preserves_the_bitmap() {
6599        let code = jumpdest_dense_code();
6600        let encoded = encode_code(&code);
6601
6602        let (bytecode, jumpdests) = decode_bytes(&encoded).unwrap();
6603        assert_eq!(bytecode, code.code());
6604        let (rebuilt, was_legacy) = decode_jumpdests(bytecode, jumpdests).unwrap();
6605        assert_eq!(rebuilt.as_ref(), code.jumpdests());
6606        assert!(!was_legacy, "bitmap format must not be flagged legacy");
6607    }
6608
6609    /// Values written before the bitmap SHALL still decode, with the bitmap rebuilt from
6610    /// the bytecode, so an existing database needs no rewriting.
6611    ///
6612    /// The expectation is built from the offsets the legacy value itself names, not from
6613    /// `Code::compute_jumpdests`, so this pins the rebuilt bitmap against the old format
6614    /// rather than against the implementation that produces it.
6615    #[test]
6616    fn legacy_offset_list_values_decode_to_the_same_bitmap() {
6617        for (bytecode, offsets) in [
6618            (vec![0x00, JUMPDEST, 0x00, JUMPDEST], vec![1u32, 3]),
6619            // The byte after PUSH1 is its immediate, so only offset 2 is a destination.
6620            (vec![PUSH1, JUMPDEST, JUMPDEST], vec![2u32]),
6621            (vec![0x00; 32], vec![]),
6622        ] {
6623            let code = Code::from_bytecode_unchecked(bytecode.clone().into(), H256::zero());
6624            let legacy = encode_code_legacy(&code);
6625
6626            let mut expected = vec![0u8; bytecode.len().div_ceil(8)];
6627            for offset in &offsets {
6628                let index = usize::try_from(*offset).expect("offset fits usize");
6629                expected[index / 8] |= 1 << (index % 8);
6630            }
6631            // A jumpless contract stores no bitmap at all rather than an all-zero one.
6632            if offsets.is_empty() {
6633                expected.clear();
6634            }
6635
6636            let (decoded_bytecode, jumpdests) = decode_bytes(&legacy).unwrap();
6637            assert_eq!(decoded_bytecode, code.code());
6638            let (rebuilt, was_legacy) = decode_jumpdests(decoded_bytecode, jumpdests).unwrap();
6639            assert_eq!(
6640                rebuilt.as_ref(),
6641                expected.as_slice(),
6642                "rebuilt bitmap disagrees with the legacy offsets for {bytecode:?}"
6643            );
6644            assert!(
6645                was_legacy,
6646                "legacy RLP-list format must be flagged for self-heal"
6647            );
6648        }
6649    }
6650
6651    /// Re-inserting a cached hash SHALL NOT grow the accounted size, or the counter
6652    /// drifts up until the cache evicts entries that fit.
6653    #[test]
6654    fn repeated_inserts_do_not_inflate_the_accounted_size() {
6655        let code = jumpdest_dense_code();
6656        let mut cache = CodeCache::default();
6657
6658        cache.insert(&code).unwrap();
6659        let after_first = cache.cache_size;
6660        for _ in 0..8 {
6661            cache.insert(&code).unwrap();
6662        }
6663
6664        assert_eq!(cache.cache_size, after_first);
6665        assert_eq!(cache.entries.len(), 1);
6666    }
6667
6668    /// The accounted size SHALL include the bytecode itself, so the cache honors its
6669    /// memory budget instead of holding orders of magnitude more than it accounts for.
6670    #[test]
6671    fn accounted_size_covers_the_bytecode_and_bitmap() {
6672        let code = jumpdest_dense_code();
6673        let mut cache = CodeCache::default();
6674        cache.insert(&code).unwrap();
6675
6676        assert!(cache.cache_size >= (code.len() + code.jumpdests().len()) as u64);
6677    }
6678
6679    /// Fixed xorshift seed, so a failure of an eviction test reproduces.
6680    const TEST_RNG_SEED: u64 = 0x9E37_79B9_7F4A_7C15;
6681
6682    #[test]
6683    fn cache_evicts_down_to_its_budget() {
6684        let mut cache = CodeCache {
6685            max_size: 128 * 1024,
6686            rng: TEST_RNG_SEED,
6687            ..Default::default()
6688        };
6689
6690        for i in 0..16u8 {
6691            let mut bytecode = vec![JUMPDEST; 24576];
6692            bytecode[0] = i;
6693            cache
6694                .insert(&Code::from_bytecode_unchecked(
6695                    bytecode.into(),
6696                    H256::from_low_u64_be(i.into()),
6697                ))
6698                .unwrap();
6699        }
6700
6701        assert!(cache.cache_size <= cache.max_size);
6702        assert!(cache.entries.len() < 16);
6703    }
6704
6705    fn numbered_code(i: u64, len: usize) -> Code {
6706        let mut bytecode = vec![JUMPDEST; len];
6707        bytecode[..8].copy_from_slice(&i.to_be_bytes());
6708        Code::from_bytecode_unchecked(bytecode.into(), H256::from_low_u64_be(i))
6709    }
6710
6711    /// Blocks can read the same set of contracts in the same order again and again.
6712    /// Once that set outgrows the budget, the cache SHALL still serve most reads: an
6713    /// LRU serves none of them, because it evicts every entry just before its reuse.
6714    #[test]
6715    fn a_cyclic_scan_larger_than_the_budget_still_hits() {
6716        let entry_size = CodeCache::entry_size(&numbered_code(0, 4096));
6717        let mut cache = CodeCache {
6718            max_size: 400 * entry_size,
6719            rng: TEST_RNG_SEED,
6720            ..Default::default()
6721        };
6722        // 500 contracts against room for 400: the set is 1.25x the budget.
6723        let codes: Vec<Code> = (0..500).map(|i| numbered_code(i, 4096)).collect();
6724
6725        let (mut hits, mut reads) = (0u64, 0u64);
6726        for round in 0..20 {
6727            for code in &codes {
6728                let cached = cache.get(&code.hash).unwrap();
6729                if round >= 5 {
6730                    reads += 1;
6731                    hits += u64::from(cached.is_some());
6732                }
6733                if cached.is_none() {
6734                    cache.insert(code).unwrap();
6735                }
6736            }
6737        }
6738
6739        assert!(cache.cache_size <= cache.max_size);
6740        assert!(
6741            hits * 2 > reads,
6742            "only {hits} of {reads} reads hit once the scan outgrew the budget"
6743        );
6744    }
6745
6746    /// The entry being inserted SHALL stay cached, since its caller reads it next.
6747    #[test]
6748    fn eviction_keeps_the_entry_being_inserted() {
6749        let entry_size = CodeCache::entry_size(&numbered_code(0, 4096));
6750        let mut cache = CodeCache {
6751            max_size: 2 * entry_size,
6752            rng: TEST_RNG_SEED,
6753            ..Default::default()
6754        };
6755        for i in 0..64 {
6756            let code = numbered_code(i, 4096);
6757            cache.insert(&code).unwrap();
6758            assert!(cache.get(&code.hash).unwrap().is_some());
6759            assert!(cache.cache_size <= cache.max_size);
6760        }
6761    }
6762
6763    /// An entry larger than the whole budget SHALL NOT be cached, so the cache never
6764    /// holds more than its budget, and the entries already cached SHALL stay.
6765    #[test]
6766    fn an_entry_larger_than_the_budget_is_not_cached() {
6767        let small = numbered_code(0, 1024);
6768        let mut cache = CodeCache {
6769            max_size: 4 * CodeCache::entry_size(&small),
6770            rng: TEST_RNG_SEED,
6771            ..Default::default()
6772        };
6773        cache.insert(&small).unwrap();
6774
6775        let large = numbered_code(1, 8192);
6776        assert!(CodeCache::entry_size(&large) > cache.max_size);
6777        cache.insert(&large).unwrap();
6778
6779        assert!(!cache.contains(&large.hash));
6780        assert!(cache.contains(&small.hash));
6781        assert_eq!(cache.cache_size, CodeCache::entry_size(&small));
6782    }
6783
6784    /// Formatting the cache SHALL NOT print the cached code: `Store` derives `Debug`, and
6785    /// the cache can hold its whole budget of bytecode.
6786    #[test]
6787    fn debug_output_leaves_out_the_cached_code() {
6788        let mut cache = CodeCache::default();
6789        cache.insert(&numbered_code(7, 4096)).unwrap();
6790        let printed = format!("{cache:?}");
6791        assert!(printed.len() < 200, "{printed}");
6792    }
6793
6794    /// Small contracts SHALL be charged what an entry costs besides their bytes, so a cache
6795    /// full of them stays within its budget instead of holding nearly twice it.
6796    #[test]
6797    fn small_contracts_are_charged_their_entry_overhead() {
6798        let mut cache = CodeCache {
6799            max_size: 160 * 1024,
6800            rng: TEST_RNG_SEED,
6801            ..Default::default()
6802        };
6803        let mut charged = 0;
6804        for i in 0..4096u64 {
6805            let mut bytecode = vec![JUMPDEST; 32];
6806            bytecode[..8].copy_from_slice(&i.to_be_bytes());
6807            let code = Code::from_bytecode_unchecked(bytecode.into(), H256::from_low_u64_be(i));
6808            charged = code.size() as u64 + CODE_CACHE_ENTRY_OVERHEAD;
6809            cache.insert(&code).unwrap();
6810        }
6811
6812        assert!(cache.cache_size <= cache.max_size);
6813        assert_eq!(cache.entries.len() as u64, cache.max_size / charged);
6814    }
6815
6816    /// The default budget SHALL be the one the cache actually enforces, so a change to
6817    /// the constant cannot silently leave the cache unbounded.
6818    #[test]
6819    fn default_cache_uses_the_configured_budget() {
6820        assert_eq!(CodeCache::default().max_size, CODE_CACHE_MAX_SIZE);
6821    }
6822
6823    /// A store opened with an explicit code cache size SHALL enforce it, and one opened
6824    /// without SHALL keep the default budget.
6825    #[test]
6826    fn store_uses_the_configured_code_cache_budget() {
6827        let config = StoreConfig {
6828            code_cache_size: Some(300 * 1024 * 1024),
6829            ..StoreConfig::with_rocksdb_block_cache_size(MIN_ROCKSDB_BLOCK_CACHE_SIZE_BYTES)
6830        };
6831        let store = Store::new_with_config("", EngineType::InMemory, config).unwrap();
6832        assert_eq!(store.code_cache_budget_bytes(), 300 * 1024 * 1024);
6833
6834        let config = StoreConfig::with_rocksdb_block_cache_size(MIN_ROCKSDB_BLOCK_CACHE_SIZE_BYTES);
6835        let store = Store::new_with_config("", EngineType::InMemory, config).unwrap();
6836        assert_eq!(store.code_cache_budget_bytes(), CODE_CACHE_MAX_SIZE);
6837    }
6838}
6839
6840#[cfg(test)]
6841mod state_history_tests {
6842    use super::*;
6843    use crate::api::tables::STATE_HISTORY;
6844    use crate::backend::in_memory::InMemoryBackend;
6845    use crate::journal::JournalEntry;
6846    use ethrex_common::types::{BlockBody, BlockHeader};
6847    use ethrex_trie::Nibbles;
6848    use std::time::{Duration, Instant};
6849
6850    fn make_block(number: BlockNumber, parent_hash: H256, state_root: H256) -> Block {
6851        let header = BlockHeader {
6852            number,
6853            parent_hash,
6854            state_root,
6855            ..Default::default()
6856        };
6857        Block::new(header, BlockBody::default())
6858    }
6859
6860    /// Polls `STATE_HISTORY` for an entry at the given block number, up to `timeout`.
6861    /// The trie worker commits to disk asynchronously after `store_block_updates`
6862    /// returns, so a small wait window is required.
6863    fn await_journal_entry(
6864        backend: &Arc<dyn StorageBackend>,
6865        block_number: BlockNumber,
6866        timeout: Duration,
6867    ) -> Option<Vec<u8>> {
6868        let key = block_number.to_be_bytes();
6869        let deadline = Instant::now() + timeout;
6870        loop {
6871            let read = backend.begin_read().ok()?;
6872            if let Ok(Some(v)) = read.get(STATE_HISTORY, &key) {
6873                return Some(v);
6874            }
6875            if Instant::now() >= deadline {
6876                return None;
6877            }
6878            std::thread::sleep(Duration::from_millis(10));
6879        }
6880    }
6881
6882    /// Asserts no STATE_HISTORY entry materializes for `block_number` within the
6883    /// given window. Polls repeatedly; if an entry appears at any poll, fails
6884    /// loudly. Absence at every poll over the full window counts as verified.
6885    /// More robust than a single fixed sleep under CI load.
6886    fn assert_no_journal_entry(backend: &Arc<dyn StorageBackend>, block_number: BlockNumber) {
6887        let window = Duration::from_millis(500);
6888        let key = block_number.to_be_bytes();
6889        let deadline = Instant::now() + window;
6890        loop {
6891            let read = backend.begin_read().expect("read view");
6892            let v = read.get(STATE_HISTORY, &key).expect("get");
6893            assert!(
6894                v.is_none(),
6895                "expected no STATE_HISTORY entry for block {block_number}, got {v:?}"
6896            );
6897            if Instant::now() >= deadline {
6898                return;
6899            }
6900            std::thread::sleep(Duration::from_millis(20));
6901        }
6902    }
6903
6904    /// Live commits gate on the canonical safe-commit root cell (see `get_commitable`),
6905    /// which only advances via forkchoice. We simulate that by calling
6906    /// `set_safe_commit_root` to the parent block's state root before storing the next
6907    /// block: storing block N+1 then commits block N's layer to disk, producing one
6908    /// journal entry per committed block. We verify entries for block 1 and block 2.
6909    #[test]
6910    fn journal_entry_written_per_block_in_regular_mode() {
6911        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
6912        let dir = tempfile::tempdir().unwrap();
6913        let store = Store::from_backend(
6914            backend.clone(),
6915            dir.path().to_path_buf(),
6916            1,
6917            DEFAULT_PERSIST_CHANNEL_CAPACITY,
6918        )
6919        .unwrap();
6920
6921        let state_root_1 = H256::repeat_byte(0x11);
6922        let block1 = make_block(1, H256::zero(), state_root_1);
6923        let block1_hash = block1.hash();
6924        store
6925            .store_block_updates(UpdateBatch {
6926                account_updates: vec![(Nibbles::from_raw(&[0x00, 0x01], false), vec![0xab, 0xcd])],
6927                storage_updates: vec![],
6928                blocks: vec![block1],
6929                receipts: vec![],
6930                code_updates: vec![],
6931                commit_depth: None,
6932                wait_for_flush: false,
6933            })
6934            .unwrap();
6935
6936        // Advance the safe-commit root to block 1's state root, then store block 2:
6937        // the canonical gate now finds block 1's layer committable and flushes it.
6938        store.set_safe_commit_root(state_root_1).unwrap();
6939        let state_root_2 = H256::repeat_byte(0x22);
6940        let block2 = make_block(2, block1_hash, state_root_2);
6941        let block2_hash = block2.hash();
6942        store
6943            .store_block_updates(UpdateBatch {
6944                account_updates: vec![(Nibbles::from_raw(&[0x00, 0x02], false), vec![0xef, 0x11])],
6945                storage_updates: vec![],
6946                blocks: vec![block2],
6947                receipts: vec![],
6948                code_updates: vec![],
6949                commit_depth: None,
6950                wait_for_flush: false,
6951            })
6952            .unwrap();
6953
6954        let bytes = await_journal_entry(&backend, 1, Duration::from_secs(2))
6955            .expect("STATE_HISTORY entry for block 1 should appear after block 2 commits it");
6956        let entry = JournalEntry::decode(&bytes).unwrap();
6957        assert_eq!(entry.block_hash, block1_hash);
6958        assert_eq!(entry.parent_state_root, H256::zero());
6959        assert!(!entry.account_trie_diff.is_empty());
6960        let (path, prev) = &entry.account_trie_diff[0];
6961        assert_eq!(prev, &None, "first-time write means previous value is None");
6962        assert!(path.len() < 65);
6963
6964        // Advance the safe-commit root to block 2's state root, then store block 3:
6965        // block 2's layer is now committable.
6966        store.set_safe_commit_root(state_root_2).unwrap();
6967        let state_root_3 = H256::repeat_byte(0x33);
6968        let block3 = make_block(3, block2_hash, state_root_3);
6969        store
6970            .store_block_updates(UpdateBatch {
6971                account_updates: vec![(Nibbles::from_raw(&[0x00, 0x03], false), vec![0x77])],
6972                storage_updates: vec![],
6973                blocks: vec![block3],
6974                receipts: vec![],
6975                code_updates: vec![],
6976                commit_depth: None,
6977                wait_for_flush: false,
6978            })
6979            .unwrap();
6980
6981        let bytes = await_journal_entry(&backend, 2, Duration::from_secs(2))
6982            .expect("STATE_HISTORY entry for block 2 should appear after block 3 commits it");
6983        let entry = JournalEntry::decode(&bytes).unwrap();
6984        assert_eq!(entry.block_hash, block2_hash);
6985        assert_eq!(entry.parent_state_root, state_root_1);
6986        assert!(!entry.account_trie_diff.is_empty());
6987    }
6988
6989    /// A depth-gated commit that is NOT in batch mode SHALL journal, and its entries
6990    /// SHALL carry the committed layer's own identity and pre-image.
6991    ///
6992    /// `commit_depth: Some(d)` together with `wait_for_flush: false` — the startup
6993    /// regeneration and sync/import tail paths — is a combination that did not exist while
6994    /// the commit gate and the ack timing were a single flag, so no other test covers it.
6995    /// Journaling follows `wait_for_flush`, so deriving it from `commit_depth.is_some()`
6996    /// instead would silently stop journaling on exactly these paths; this test fails in
6997    /// that case.
6998    #[test]
6999    fn depth_gated_per_block_commit_journals_with_correct_pre_image() {
7000        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7001        let dir = tempfile::tempdir().unwrap();
7002        let store = Store::from_backend(
7003            backend.clone(),
7004            dir.path().to_path_buf(),
7005            1,
7006            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7007        )
7008        .unwrap();
7009
7010        // One shared key rewritten every block, so pre-images are checkable.
7011        let shared = Nibbles::from_raw(&[0x0a, 0x0b], false);
7012        let mut prev_hash = H256::zero();
7013        let mut hashes = vec![H256::zero()];
7014        let mut roots = vec![H256::zero()];
7015        for n in 1..=6u64 {
7016            let state_root = H256::repeat_byte(0xc0 | (n as u8));
7017            let block = make_block(n, prev_hash, state_root);
7018            prev_hash = block.hash();
7019            hashes.push(prev_hash);
7020            roots.push(state_root);
7021            store
7022                .store_block_updates(UpdateBatch {
7023                    account_updates: vec![(shared.clone(), vec![0xb0 | (n as u8)])],
7024                    storage_updates: vec![],
7025                    blocks: vec![block],
7026                    receipts: vec![],
7027                    code_updates: vec![],
7028                    commit_depth: Some(3),
7029                    wait_for_flush: false,
7030                })
7031                .unwrap();
7032        }
7033
7034        let bytes = await_journal_entry(&backend, 1, Duration::from_secs(2))
7035            .expect("a depth-gated per-block commit must journal");
7036        let entry = JournalEntry::decode(&bytes).unwrap();
7037        assert_eq!(
7038            entry.block_hash, hashes[1],
7039            "entry 1 carries block 1's identity"
7040        );
7041        assert_eq!(entry.parent_state_root, H256::zero());
7042        assert_eq!(
7043            entry.account_trie_diff[0].1, None,
7044            "block 1 first-writes the key, so its pre-image is absence"
7045        );
7046
7047        let bytes =
7048            await_journal_entry(&backend, 2, Duration::from_secs(2)).expect("entry for block 2");
7049        let entry = JournalEntry::decode(&bytes).unwrap();
7050        assert_eq!(
7051            entry.block_hash, hashes[2],
7052            "entry 2 carries block 2's identity"
7053        );
7054        assert_eq!(
7055            entry.parent_state_root, roots[1],
7056            "entry 2's parent_state_root is block 1's state root"
7057        );
7058        assert_eq!(
7059            entry.account_trie_diff[0].1,
7060            Some(vec![0xb0 | 1u8]),
7061            "block 2's pre-image is the value block 1 wrote"
7062        );
7063    }
7064
7065    /// The bespoke batch path SHALL skip the journal entirely. To actually exercise the
7066    /// gating we push enough batches to trigger a commit under
7067    /// `BATCH_COMMIT_THRESHOLD = 4`, then verify no STATE_HISTORY entry materializes
7068    /// despite the commit happening.
7069    ///
7070    /// That path is `wait_for_flush: true` with `commit_depth: Some(BATCH_COMMIT_THRESHOLD)`
7071    /// — the combination the single `batch_mode` flag used to stand for. Journaling follows
7072    /// `wait_for_flush`, so the depth-gated per-block paths are not covered here.
7073    #[test]
7074    fn journal_skipped_in_batch_mode() {
7075        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7076        let dir = tempfile::tempdir().unwrap();
7077        let store = Store::from_backend(
7078            backend.clone(),
7079            dir.path().to_path_buf(),
7080            1,
7081            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7082        )
7083        .unwrap();
7084
7085        let mut prev_hash = H256::zero();
7086        for n in 1..=5u64 {
7087            let state_root = H256::repeat_byte(0xa0 | (n as u8));
7088            let block = make_block(n, prev_hash, state_root);
7089            prev_hash = block.hash();
7090            store
7091                .store_block_updates(UpdateBatch {
7092                    account_updates: vec![(
7093                        Nibbles::from_raw(&[n as u8], false),
7094                        vec![0xde, 0xad, n as u8],
7095                    )],
7096                    storage_updates: vec![],
7097                    blocks: vec![block],
7098                    receipts: vec![],
7099                    code_updates: vec![],
7100                    commit_depth: Some(BATCH_COMMIT_THRESHOLD),
7101                    wait_for_flush: true,
7102                })
7103                .unwrap();
7104        }
7105
7106        for n in 1..=5u64 {
7107            assert_no_journal_entry(&backend, n);
7108        }
7109    }
7110
7111    /// Storage trie updates SHALL appear in `storage_trie_diff` (not
7112    /// `account_trie_diff`), with their on-disk keys as written.
7113    #[test]
7114    fn journal_storage_updates_appear_in_storage_diff() {
7115        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7116        let dir = tempfile::tempdir().unwrap();
7117        let store = Store::from_backend(
7118            backend.clone(),
7119            dir.path().to_path_buf(),
7120            1,
7121            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7122        )
7123        .unwrap();
7124
7125        let account_hash_a = H256::repeat_byte(0xa0);
7126        let account_hash_b = H256::repeat_byte(0xb0);
7127
7128        let state_root_1 = H256::repeat_byte(0x33);
7129        let block1 = make_block(1, H256::zero(), state_root_1);
7130        let block1_hash = block1.hash();
7131        store
7132            .store_block_updates(UpdateBatch {
7133                account_updates: vec![],
7134                storage_updates: vec![
7135                    (
7136                        account_hash_a,
7137                        vec![(Nibbles::from_raw(&[0x05], false), vec![0x01])],
7138                    ),
7139                    (
7140                        account_hash_b,
7141                        vec![(Nibbles::from_raw(&[0x06], false), vec![0x02])],
7142                    ),
7143                ],
7144                blocks: vec![block1],
7145                receipts: vec![],
7146                code_updates: vec![],
7147                commit_depth: None,
7148                wait_for_flush: false,
7149            })
7150            .unwrap();
7151
7152        // Advance the safe-commit root to block 1's state root, then store block 2:
7153        // block 1's layer is now committable and flushes to disk.
7154        store.set_safe_commit_root(state_root_1).unwrap();
7155        let state_root_2 = H256::repeat_byte(0x44);
7156        let block2 = make_block(2, block1_hash, state_root_2);
7157        store
7158            .store_block_updates(UpdateBatch {
7159                account_updates: vec![(Nibbles::from_raw(&[0xee], false), vec![0xff])],
7160                storage_updates: vec![],
7161                blocks: vec![block2],
7162                receipts: vec![],
7163                code_updates: vec![],
7164                commit_depth: None,
7165                wait_for_flush: false,
7166            })
7167            .unwrap();
7168
7169        let bytes = await_journal_entry(&backend, 1, Duration::from_secs(2))
7170            .expect("STATE_HISTORY entry for block 1");
7171        let entry = JournalEntry::decode(&bytes).unwrap();
7172        assert_eq!(entry.block_hash, block1_hash);
7173        assert_eq!(
7174            entry.storage_trie_diff.len(),
7175            2,
7176            "two distinct account hashes must produce two storage_trie entries"
7177        );
7178        for (_key, prev) in &entry.storage_trie_diff {
7179            assert_eq!(prev, &None, "first-time storage write has None pre-image");
7180        }
7181        assert!(entry.account_trie_diff.is_empty());
7182    }
7183
7184    fn seed_journal_entries(backend: &Arc<dyn StorageBackend>, block_numbers: &[BlockNumber]) {
7185        let mut tx = backend.begin_write().unwrap();
7186        for n in block_numbers {
7187            let entry = JournalEntry {
7188                block_hash: H256::repeat_byte(*n as u8),
7189                parent_state_root: H256::zero(),
7190                account_trie_diff: vec![(vec![*n as u8], None)],
7191                storage_trie_diff: vec![],
7192                account_flat_diff: vec![],
7193                storage_flat_diff: vec![],
7194            };
7195            tx.put(STATE_HISTORY, &n.to_be_bytes(), &entry.encode())
7196                .unwrap();
7197        }
7198        tx.commit().unwrap();
7199    }
7200
7201    fn journal_entry_exists(backend: &Arc<dyn StorageBackend>, block_number: BlockNumber) -> bool {
7202        backend
7203            .begin_read()
7204            .unwrap()
7205            .get(STATE_HISTORY, &block_number.to_be_bytes())
7206            .unwrap()
7207            .is_some()
7208    }
7209
7210    /// Finality advance SHALL prune every STATE_HISTORY entry at or below the
7211    /// new finalized number, in the same atomic txn as the finalized-number update.
7212    #[tokio::test]
7213    async fn finality_advance_prunes_journal_below_boundary() {
7214        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7215        let dir = tempfile::tempdir().unwrap();
7216        let store = Store::from_backend(
7217            backend.clone(),
7218            dir.path().to_path_buf(),
7219            1,
7220            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7221        )
7222        .unwrap();
7223
7224        seed_journal_entries(&backend, &(1..=10).collect::<Vec<_>>());
7225        for n in 1..=10 {
7226            assert!(journal_entry_exists(&backend, n), "seed entry {n} present");
7227        }
7228
7229        store
7230            .forkchoice_update_inner(vec![], 100, H256::zero(), None, Some(5))
7231            .await
7232            .unwrap();
7233
7234        for n in 1..=5 {
7235            assert!(
7236                !journal_entry_exists(&backend, n),
7237                "entry {n} should have been pruned (<= finalized)"
7238            );
7239        }
7240        for n in 6..=10 {
7241            assert!(
7242                journal_entry_exists(&backend, n),
7243                "entry {n} should remain (> finalized)"
7244            );
7245        }
7246    }
7247
7248    /// Forkchoice updates that don't advance finalized SHALL NOT prune the journal.
7249    #[tokio::test]
7250    async fn finality_no_op_does_not_prune() {
7251        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7252        let dir = tempfile::tempdir().unwrap();
7253        let store = Store::from_backend(
7254            backend.clone(),
7255            dir.path().to_path_buf(),
7256            1,
7257            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7258        )
7259        .unwrap();
7260
7261        store
7262            .forkchoice_update_inner(vec![], 100, H256::zero(), None, Some(5))
7263            .await
7264            .unwrap();
7265
7266        seed_journal_entries(&backend, &(6..=10).collect::<Vec<_>>());
7267
7268        // FCU re-asserting finalized = 5: must not prune anything.
7269        store
7270            .forkchoice_update_inner(vec![], 100, H256::zero(), None, Some(5))
7271            .await
7272            .unwrap();
7273
7274        for n in 6..=10 {
7275            assert!(
7276                journal_entry_exists(&backend, n),
7277                "entry {n} should still exist after no-op finality update"
7278            );
7279        }
7280
7281        // FCU with finalized = None: also a no-op for pruning.
7282        store
7283            .forkchoice_update_inner(vec![], 100, H256::zero(), None, None)
7284            .await
7285            .unwrap();
7286
7287        for n in 6..=10 {
7288            assert!(
7289                journal_entry_exists(&backend, n),
7290                "entry {n} should still exist when finalized is None"
7291            );
7292        }
7293    }
7294
7295    /// A malformed (wrong-length) `FinalizedBlockNumber` value SHALL surface as a
7296    /// hard error rather than a silent fallback to 0, which would over-prune the
7297    /// journal on the next FCU.
7298    #[tokio::test]
7299    async fn malformed_finalized_returns_error_not_silent_zero() {
7300        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7301        let dir = tempfile::tempdir().unwrap();
7302        let store = Store::from_backend(
7303            backend.clone(),
7304            dir.path().to_path_buf(),
7305            1,
7306            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7307        )
7308        .unwrap();
7309
7310        // Plant a 4-byte (instead of 8-byte) FinalizedBlockNumber value.
7311        let mut tx = backend.begin_write().unwrap();
7312        let finalized_key = chain_data_key(ChainDataIndex::FinalizedBlockNumber);
7313        tx.put(CHAIN_DATA, &finalized_key, &[0u8, 0, 0, 0]).unwrap();
7314        tx.commit().unwrap();
7315
7316        seed_journal_entries(&backend, &(1..=5).collect::<Vec<_>>());
7317
7318        let err = store
7319            .forkchoice_update_inner(vec![], 100, H256::zero(), None, Some(3))
7320            .await
7321            .expect_err("malformed finalized must surface as an error");
7322        let msg = format!("{err}");
7323        assert!(
7324            msg.contains("FinalizedBlockNumber has unexpected length"),
7325            "expected length-mismatch error, got: {msg}"
7326        );
7327
7328        // Journal must not have been pruned.
7329        for n in 1..=5 {
7330            assert!(
7331                journal_entry_exists(&backend, n),
7332                "entry {n} must NOT be pruned when finalized read failed"
7333            );
7334        }
7335    }
7336
7337    // -----------------------------------------------------------------------
7338    // Deep-reorg primitive tests.
7339    // -----------------------------------------------------------------------
7340
7341    /// `highest_state_history_block_number` SHALL return the max key present in
7342    /// `STATE_HISTORY`, or `None` when the table is empty.
7343    #[tokio::test]
7344    async fn highest_state_history_block_number_finds_max() {
7345        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7346        let dir = tempfile::tempdir().unwrap();
7347        let store = Store::from_backend(
7348            backend.clone(),
7349            dir.path().to_path_buf(),
7350            1,
7351            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7352        )
7353        .unwrap();
7354
7355        assert_eq!(store.highest_state_history_block_number().unwrap(), None);
7356
7357        seed_journal_entries(&backend, &[3, 7, 5, 11, 8]);
7358        assert_eq!(
7359            store.highest_state_history_block_number().unwrap(),
7360            Some(11),
7361            "max over present entries"
7362        );
7363    }
7364
7365    /// The interrupted-batch recovery at startup identifies the block whose state is
7366    /// on disk from the newest `STATE_HISTORY` entry, so the entry's block hash must
7367    /// read back exactly as journaled and an absent entry must read as `None`.
7368    #[tokio::test]
7369    async fn journaled_block_hash_reads_back() {
7370        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7371        let dir = tempfile::tempdir().unwrap();
7372        let store = Store::from_backend(
7373            backend.clone(),
7374            dir.path().to_path_buf(),
7375            1,
7376            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7377        )
7378        .unwrap();
7379
7380        seed_journal_entries(&backend, &[3, 11]);
7381        assert_eq!(
7382            store.get_state_history_block_hash(11).unwrap(),
7383            Some(H256::repeat_byte(11))
7384        );
7385        assert_eq!(store.get_state_history_block_hash(4).unwrap(), None);
7386    }
7387
7388    /// `flushed_upto` is a durability floor: `advance_flushed_upto` raises it and
7389    /// ignores a value at or below the current marker.
7390    #[tokio::test]
7391    async fn advance_flushed_upto_only_moves_forward() {
7392        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7393        let dir = tempfile::tempdir().unwrap();
7394        let store = Store::from_backend(
7395            backend,
7396            dir.path().to_path_buf(),
7397            1,
7398            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7399        )
7400        .unwrap();
7401
7402        store.advance_flushed_upto(10).unwrap();
7403        assert_eq!(store.read_flushed_upto().unwrap(), 10);
7404        store.advance_flushed_upto(5).unwrap();
7405        assert_eq!(store.read_flushed_upto().unwrap(), 10);
7406        store.advance_flushed_upto(12).unwrap();
7407        assert_eq!(store.read_flushed_upto().unwrap(), 12);
7408    }
7409
7410    /// `lowest_state_history_block_number` SHALL return the min key present in
7411    /// `STATE_HISTORY`, or `None` when the table is empty. Phase 2's cap fallback
7412    /// depends on this when no finalized hash is known.
7413    #[tokio::test]
7414    async fn lowest_state_history_block_number_finds_min() {
7415        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7416        let dir = tempfile::tempdir().unwrap();
7417        let store = Store::from_backend(
7418            backend.clone(),
7419            dir.path().to_path_buf(),
7420            1,
7421            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7422        )
7423        .unwrap();
7424
7425        assert_eq!(store.lowest_state_history_block_number().unwrap(), None);
7426
7427        seed_journal_entries(&backend, &[7, 3, 11, 5, 8]);
7428        assert_eq!(
7429            store.lowest_state_history_block_number().unwrap(),
7430            Some(3),
7431            "min over present entries"
7432        );
7433    }
7434
7435    /// `install_overlay_for_reorg` SHALL atomically swap the layer cache for a
7436    /// fresh empty one with the overlay installed; layer-cache hits in the OLD
7437    /// cache MUST NOT survive the swap.
7438    #[tokio::test]
7439    async fn install_overlay_replaces_cache_with_fresh_one() {
7440        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7441        let dir = tempfile::tempdir().unwrap();
7442        let store = Store::from_backend(
7443            backend.clone(),
7444            dir.path().to_path_buf(),
7445            4,
7446            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7447        )
7448        .unwrap();
7449
7450        seed_journal_entries(&backend, &[3, 4]);
7451
7452        // Pre-populate the cache with a sentinel layer to verify the swap discards it.
7453        {
7454            let mut guard = store.trie_cache.write().unwrap();
7455            let mut updated = (**guard).clone();
7456            updated.put_batch(
7457                H256::zero(),
7458                H256::repeat_byte(0xff),
7459                42,
7460                H256::repeat_byte(0x42),
7461                vec![],
7462            );
7463            *guard = Arc::new(updated);
7464        }
7465        assert!(
7466            store
7467                .is_state_in_layer_cache(H256::repeat_byte(0xff))
7468                .unwrap()
7469        );
7470
7471        store
7472            .install_overlay_for_reorg(4, 3, |_| None)
7473            .expect("install must succeed");
7474
7475        assert!(
7476            !store
7477                .is_state_in_layer_cache(H256::repeat_byte(0xff))
7478                .unwrap(),
7479            "old cache layer must be gone after swap"
7480        );
7481        let cache = store.trie_cache.read().unwrap().clone();
7482        assert!(cache.overlay().is_some(), "overlay must be installed");
7483        assert_eq!(
7484            cache.commit_threshold(),
7485            4,
7486            "fresh cache must inherit threshold"
7487        );
7488    }
7489
7490    /// `install_overlay_for_reorg` SHALL leave the existing cache intact when
7491    /// overlay construction fails (missing journal entry).
7492    #[tokio::test]
7493    async fn install_overlay_failure_preserves_cache() {
7494        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7495        let dir = tempfile::tempdir().unwrap();
7496        let store = Store::from_backend(
7497            backend.clone(),
7498            dir.path().to_path_buf(),
7499            4,
7500            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7501        )
7502        .unwrap();
7503
7504        // Only seed block 5; constructor will walk down through 4 and 3 and fail.
7505        seed_journal_entries(&backend, &[5]);
7506        {
7507            let mut guard = store.trie_cache.write().unwrap();
7508            let mut updated = (**guard).clone();
7509            updated.put_batch(
7510                H256::zero(),
7511                H256::repeat_byte(0xaa),
7512                7,
7513                H256::repeat_byte(0x77),
7514                vec![],
7515            );
7516            *guard = Arc::new(updated);
7517        }
7518        assert!(
7519            store
7520                .is_state_in_layer_cache(H256::repeat_byte(0xaa))
7521                .unwrap()
7522        );
7523
7524        let err = store
7525            .install_overlay_for_reorg(5, 3, |_| None)
7526            .expect_err("missing entries 3 and 4 must abort");
7527        let msg = format!("{err}");
7528        assert!(
7529            msg.contains("overlay construction failed"),
7530            "error should explain construction failure: {msg}"
7531        );
7532
7533        // Cache must be intact: the sentinel layer must still be there.
7534        assert!(
7535            store
7536                .is_state_in_layer_cache(H256::repeat_byte(0xaa))
7537                .unwrap(),
7538            "cache must survive a failed overlay install"
7539        );
7540        let cache = store.trie_cache.read().unwrap().clone();
7541        assert!(cache.overlay().is_none(), "no overlay should be installed");
7542    }
7543
7544    /// `abort_reorg` SHALL discard both the overlay and any partial new-chain
7545    /// layers, restoring the cache to a fresh empty state with the same
7546    /// commit threshold.
7547    #[tokio::test]
7548    async fn abort_reorg_resets_cache_to_fresh() {
7549        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7550        let dir = tempfile::tempdir().unwrap();
7551        let store = Store::from_backend(
7552            backend.clone(),
7553            dir.path().to_path_buf(),
7554            4,
7555            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7556        )
7557        .unwrap();
7558
7559        seed_journal_entries(&backend, &[3, 4]);
7560        store.install_overlay_for_reorg(4, 3, |_| None).unwrap();
7561        // Simulate partial new-chain layer.
7562        {
7563            let mut guard = store.trie_cache.write().unwrap();
7564            let mut updated = (**guard).clone();
7565            updated.put_batch(
7566                H256::zero(),
7567                H256::repeat_byte(0xbb),
7568                4,
7569                H256::repeat_byte(0xb4),
7570                vec![],
7571            );
7572            *guard = Arc::new(updated);
7573        }
7574        assert!(
7575            store
7576                .is_state_in_layer_cache(H256::repeat_byte(0xbb))
7577                .unwrap()
7578        );
7579
7580        store.abort_reorg().unwrap();
7581
7582        assert!(
7583            !store
7584                .is_state_in_layer_cache(H256::repeat_byte(0xbb))
7585                .unwrap(),
7586            "partial new-chain layer must be discarded"
7587        );
7588        let cache = store.trie_cache.read().unwrap().clone();
7589        assert!(cache.overlay().is_none(), "overlay must be cleared");
7590        assert_eq!(
7591            cache.commit_threshold(),
7592            4,
7593            "fresh cache must inherit threshold"
7594        );
7595    }
7596
7597    /// `clear_reorg_overlay` SHALL remove an installed overlay and SHALL be
7598    /// idempotent (safe to call when no overlay is installed).
7599    #[tokio::test]
7600    async fn clear_reorg_overlay_removes_overlay_and_is_idempotent() {
7601        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7602        let dir = tempfile::tempdir().unwrap();
7603        let store = Store::from_backend(
7604            backend.clone(),
7605            dir.path().to_path_buf(),
7606            4,
7607            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7608        )
7609        .unwrap();
7610
7611        // Idempotent when no overlay is installed.
7612        store.clear_reorg_overlay().unwrap();
7613        assert!(store.trie_cache.read().unwrap().overlay().is_none());
7614
7615        seed_journal_entries(&backend, &[7]);
7616        store.install_overlay_for_reorg(7, 7, |_| None).unwrap();
7617        assert!(store.trie_cache.read().unwrap().overlay().is_some());
7618
7619        store.clear_reorg_overlay().unwrap();
7620        assert!(store.trie_cache.read().unwrap().overlay().is_none());
7621
7622        // Calling again is still a no-op.
7623        store.clear_reorg_overlay().unwrap();
7624        assert!(store.trie_cache.read().unwrap().overlay().is_none());
7625    }
7626
7627    /// Regression test: journal entries written while the FKV generator
7628    /// was running lack flat-KV pre-images for keys past the generator frontier,
7629    /// and the generator's own flat-KV writes are never journaled. While an
7630    /// overlay serves the read's state root, every flat-KV fast path must be
7631    /// disabled so reads fall back to the (always journaled) trie nodes;
7632    /// otherwise they serve the generator's stale values for the chain being
7633    /// reorged away. Roots the overlay does not serve must keep the fast path.
7634    #[tokio::test]
7635    async fn deep_reorg_overlay_disables_flat_kv_fast_paths() {
7636        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7637
7638        // Simulate a finished FKV generation BEFORE the Store boots, so its
7639        // in-memory frontier starts at [0xff; 64] and every path counts as
7640        // "computed" (the Store expands the durable [0xff] sentinel at open).
7641        {
7642            let mut tx = backend.begin_write().unwrap();
7643            tx.put(MISC_VALUES, "last_written".as_bytes(), &[0xff])
7644                .unwrap();
7645            tx.commit().unwrap();
7646        }
7647
7648        let dir = tempfile::tempdir().unwrap();
7649        let store = Store::from_backend(
7650            backend.clone(),
7651            dir.path().to_path_buf(),
7652            1,
7653            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7654        )
7655        .unwrap();
7656
7657        // The pivot state is empty, so the correct value for every read at the
7658        // pivot root is None. The old chain created the account/slot after the
7659        // pivot; the generator then wrote their flat-KV leaves against the old
7660        // chain — writes that are never journaled.
7661        let address = Address::from_low_u64_be(0xbeef);
7662        let account_hash = hash_address_fixed(&address);
7663        let slot = H256::from_low_u64_be(1);
7664        let slot_hash = hash_key_fixed(&slot);
7665        let generator_account = AccountState {
7666            nonce: 7,
7667            balance: U256::from(999u64),
7668            storage_root: H256::zero(),
7669            code_hash: H256::zero(),
7670        };
7671        let generator_slot_value = U256::from(42u64);
7672        {
7673            let mut tx = backend.begin_write().unwrap();
7674            tx.put(
7675                ACCOUNT_FLATKEYVALUE,
7676                &Nibbles::from_bytes(account_hash.as_bytes()).into_vec(),
7677                &generator_account.encode_to_vec(),
7678            )
7679            .unwrap();
7680            tx.put(
7681                STORAGE_FLATKEYVALUE,
7682                &apply_prefix(Some(account_hash), Nibbles::from_bytes(&slot_hash)).into_vec(),
7683                &generator_slot_value.encode_to_vec(),
7684            )
7685            .unwrap();
7686            tx.commit().unwrap();
7687        }
7688
7689        // Journal entries for blocks 10 and 11 above the pivot (block 9), as
7690        // written DURING generation: flat diffs are empty because the keys were
7691        // past the frontier at commit time (the incomplete-journal hole). The pivot's state
7692        // root is the empty trie.
7693        let pivot_root = EMPTY_TRIE_HASH;
7694        {
7695            let mut tx = backend.begin_write().unwrap();
7696            for (n, parent_root) in [(10u64, pivot_root), (11, H256::repeat_byte(0x10))] {
7697                let entry = JournalEntry {
7698                    block_hash: H256::repeat_byte(n as u8),
7699                    parent_state_root: parent_root,
7700                    account_trie_diff: vec![],
7701                    storage_trie_diff: vec![],
7702                    account_flat_diff: vec![],
7703                    storage_flat_diff: vec![],
7704                };
7705                tx.put(STATE_HISTORY, &n.to_be_bytes(), &entry.encode())
7706                    .unwrap();
7707            }
7708            tx.commit().unwrap();
7709        }
7710
7711        store
7712            .install_overlay_for_reorg(11, 10, |_| None)
7713            .expect("overlay install must succeed");
7714
7715        // Reads at the pivot root must return the pivot state (account and slot
7716        // absent), NOT the generator's stale flat-KV values.
7717        let accounts = store
7718            .get_account_states_batch_by_root(pivot_root, &[address])
7719            .unwrap();
7720        assert_eq!(
7721            accounts,
7722            vec![None],
7723            "batch account read must not serve the generator's stale flat-KV value"
7724        );
7725
7726        let slot_value = store
7727            .get_storage_at_root(pivot_root, address, slot)
7728            .unwrap();
7729        assert_eq!(
7730            slot_value, None,
7731            "storage read must not serve the generator's stale flat-KV value"
7732        );
7733
7734        let batched_slots = store
7735            .get_storage_values_batch_by_root(
7736                pivot_root,
7737                &[(hash_address_fixed(&address), EMPTY_TRIE_HASH, slot)],
7738            )
7739            .unwrap();
7740        assert_eq!(
7741            batched_slots,
7742            vec![None],
7743            "batch storage read must not serve the generator's stale flat-KV value"
7744        );
7745
7746        let state_trie = store.open_state_trie(pivot_root).unwrap();
7747        assert_eq!(
7748            state_trie.get(account_hash.as_bytes()).unwrap(),
7749            None,
7750            "trie read must not serve the generator's stale flat-KV value"
7751        );
7752
7753        // Outside the overlay window the fast paths are untouched: a root the
7754        // overlay does not serve still reads flat-KV straight from disk.
7755        let unserved_root = H256::repeat_byte(0x99);
7756        let accounts = store
7757            .get_account_states_batch_by_root(unserved_root, &[address])
7758            .unwrap();
7759        assert_eq!(
7760            accounts,
7761            vec![Some(generator_account)],
7762            "unserved roots must keep the flat-KV fast path"
7763        );
7764        let slot_value = store
7765            .get_storage_at_root(unserved_root, address, slot)
7766            .unwrap();
7767        assert_eq!(
7768            slot_value,
7769            Some(generator_slot_value),
7770            "unserved roots must keep the flat-KV fast path"
7771        );
7772
7773        let batched_slots = store
7774            .get_storage_values_batch_by_root(
7775                unserved_root,
7776                &[(hash_address_fixed(&address), EMPTY_TRIE_HASH, slot)],
7777            )
7778            .unwrap();
7779        assert_eq!(
7780            batched_slots,
7781            vec![Some(generator_slot_value)],
7782            "unserved roots must keep the flat-KV fast path"
7783        );
7784    }
7785
7786    /// Adversarial regression for the multi-layer reconciliation finding: with an
7787    /// overlay installed, a commit targeting a root SEVERAL layers above the pivot
7788    /// must commit ONLY the bottom layer (the pivot tip `T`) per pass. Before the
7789    /// fix this swept every layer at once: the `debug_assert!(len == 1)` panicked in
7790    /// debug builds, and in release the upper layers' journal entries recorded
7791    /// pre-images against the OLD-chain disk state instead of the new-chain/bridge
7792    /// state — silent corruption for a future unwind.
7793    #[tokio::test]
7794    async fn overlay_backed_commit_only_commits_bottom_layer_per_pass() {
7795        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7796        let dir = tempfile::tempdir().unwrap();
7797        let store = Store::from_backend(
7798            backend.clone(),
7799            dir.path().to_path_buf(),
7800            4,
7801            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7802        )
7803        .unwrap();
7804
7805        // Pivot at block 9's root; journal entries for blocks 10 and 11 (the old
7806        // chain above the pivot). The overlay serves the pivot root.
7807        let pivot_root = H256::repeat_byte(0x09);
7808        {
7809            let mut tx = backend.begin_write().unwrap();
7810            for (n, parent_root) in [(10u64, pivot_root), (11, H256::repeat_byte(0x0a))] {
7811                let entry = JournalEntry {
7812                    block_hash: H256::repeat_byte(n as u8),
7813                    parent_state_root: parent_root,
7814                    account_trie_diff: vec![(vec![0x00, n as u8], None)],
7815                    storage_trie_diff: vec![],
7816                    account_flat_diff: vec![],
7817                    storage_flat_diff: vec![],
7818                };
7819                tx.put(STATE_HISTORY, &n.to_be_bytes(), &entry.encode())
7820                    .unwrap();
7821            }
7822            tx.commit().unwrap();
7823        }
7824        store.install_overlay_for_reorg(11, 10, |_| None).unwrap();
7825
7826        // Three new-chain layers above the pivot: blocks 10, 11, 12.
7827        let roots: Vec<H256> = (10..=12u8).map(H256::repeat_byte).collect();
7828        {
7829            let mut guard = store.trie_cache.write().unwrap();
7830            let mut updated = (**guard).clone();
7831            let mut parent = pivot_root;
7832            for (i, root) in roots.iter().enumerate() {
7833                let n = 10 + i as u64;
7834                updated.put_batch(
7835                    parent,
7836                    *root,
7837                    n,
7838                    H256::repeat_byte(n as u8),
7839                    vec![(Nibbles::from_raw(&[0x01, n as u8], false), vec![n as u8])],
7840                );
7841                parent = *root;
7842            }
7843            *guard = Arc::new(updated);
7844        }
7845
7846        // Commit targeting the TOP layer (3 deep). With the overlay installed this
7847        // MUST reduce to the bottom layer only.
7848        let trie = store.trie_cache.read().unwrap().clone();
7849        commit_to_disk(
7850            store.backend.as_ref(),
7851            &store.flatkeyvalue_control_tx,
7852            &store.trie_cache,
7853            &trie,
7854            roots[2],
7855            false,
7856        )
7857        .expect("bottom-layer commit must succeed (no debug_assert panic)");
7858
7859        // Only the bottom layer (block 10) is committed and pruned; 11 and 12 stay resident.
7860        assert!(
7861            !store.is_state_in_layer_cache(roots[0]).unwrap(),
7862            "bottom layer must be committed and pruned"
7863        );
7864        assert!(
7865            store.is_state_in_layer_cache(roots[1]).unwrap()
7866                && store.is_state_in_layer_cache(roots[2]).unwrap(),
7867            "upper layers must remain resident after the bottom-layer-only commit"
7868        );
7869        // The overlay was consumed by the reconciliation commit.
7870        assert!(
7871            store.trie_cache.read().unwrap().overlay().is_none(),
7872            "reconciliation must clear the overlay"
7873        );
7874        // Journal: an entry exists for block 10, none yet for 11/12.
7875        assert!(
7876            journal_entry_exists(&backend, 10),
7877            "bottom layer T must be journaled"
7878        );
7879        assert!(!journal_entry_exists(&backend, 11));
7880        assert!(!journal_entry_exists(&backend, 12));
7881
7882        // The reconciliation fold MUST land in the bottom layer's journal entry:
7883        // the overlay's bridge keys (untouched by the layer) appear with their
7884        // old-chain pre-images. This is what block-number-keyed reconciliation
7885        // matching loses when the bottom layer sits above `to_block`.
7886        let entry_bytes = backend
7887            .begin_read()
7888            .unwrap()
7889            .get(STATE_HISTORY, &10u64.to_be_bytes())
7890            .unwrap()
7891            .expect("journal entry for block 10");
7892        let entry = JournalEntry::decode(&entry_bytes).unwrap();
7893        let diff_keys: Vec<&Vec<u8>> = entry.account_trie_diff.iter().map(|(k, _)| k).collect();
7894        assert!(
7895            diff_keys.contains(&&vec![0x00, 10]) && diff_keys.contains(&&vec![0x00, 11]),
7896            "bridge keys from the overlay must be folded into T's journal entry, got {diff_keys:?}"
7897        );
7898
7899        // Second pass: with the overlay gone the remaining backlog commits normally.
7900        let trie = store.trie_cache.read().unwrap().clone();
7901        commit_to_disk(
7902            store.backend.as_ref(),
7903            &store.flatkeyvalue_control_tx,
7904            &store.trie_cache,
7905            &trie,
7906            roots[2],
7907            false,
7908        )
7909        .unwrap();
7910        assert!(!store.is_state_in_layer_cache(roots[1]).unwrap());
7911        assert!(!store.is_state_in_layer_cache(roots[2]).unwrap());
7912        assert!(journal_entry_exists(&backend, 11));
7913        assert!(journal_entry_exists(&backend, 12));
7914    }
7915
7916    /// Adversarial regression for the journal-pruning race: while a deep-reorg
7917    /// apply pass holds the pause flag, a finality advance must NOT prune
7918    /// STATE_HISTORY (a concurrent `Overlay::from_journal` reads entries with no
7919    /// snapshot isolation). Pruning must catch up once the pause is released.
7920    #[tokio::test]
7921    async fn journal_pruning_pauses_during_reorg_and_catches_up_after() {
7922        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
7923        let dir = tempfile::tempdir().unwrap();
7924        let store = Store::from_backend(
7925            backend.clone(),
7926            dir.path().to_path_buf(),
7927            1,
7928            DEFAULT_PERSIST_CHANNEL_CAPACITY,
7929        )
7930        .unwrap();
7931
7932        seed_journal_entries(&backend, &(1..=5).collect::<Vec<_>>());
7933
7934        // Paused: finality advance to 3 must not prune anything.
7935        store.set_journal_pruning_paused(true);
7936        store
7937            .forkchoice_update_inner(vec![], 100, H256::zero(), None, Some(3))
7938            .await
7939            .unwrap();
7940        for n in 1..=5 {
7941            assert!(
7942                journal_entry_exists(&backend, n),
7943                "entry {n} must survive pruning while the reorg pause is held"
7944            );
7945        }
7946
7947        // Released: the next advance prunes from the lowest surviving entry.
7948        store.set_journal_pruning_paused(false);
7949        store
7950            .forkchoice_update_inner(vec![], 100, H256::zero(), None, Some(4))
7951            .await
7952            .unwrap();
7953        for n in 1..=4 {
7954            assert!(
7955                !journal_entry_exists(&backend, n),
7956                "entry {n} must be pruned once the pause is released"
7957            );
7958        }
7959        assert!(journal_entry_exists(&backend, 5));
7960    }
7961
7962    /// `(start, end)` block numbers of each STATE_HISTORY `delete_range`, in order.
7963    type RecordedRanges = Arc<Mutex<Vec<(BlockNumber, BlockNumber)>>>;
7964
7965    /// Wraps a backend and records every `delete_range` issued on STATE_HISTORY, so
7966    /// tests can check which ranges finality pruning writes, not just its effect.
7967    #[derive(Debug)]
7968    struct RangeDeleteRecorder {
7969        inner: Arc<dyn StorageBackend>,
7970        ranges: RecordedRanges,
7971    }
7972
7973    struct RecordingWriteBatch {
7974        inner: Box<dyn StorageWriteBatch + 'static>,
7975        ranges: RecordedRanges,
7976    }
7977
7978    fn block_number_key(key: &[u8]) -> BlockNumber {
7979        BlockNumber::from_be_bytes(key.try_into().expect("8-byte STATE_HISTORY key"))
7980    }
7981
7982    impl StorageBackend for RangeDeleteRecorder {
7983        fn clear_table(&self, table: &'static str) -> Result<(), StoreError> {
7984            self.inner.clear_table(table)
7985        }
7986        fn begin_read(&self) -> Result<Arc<dyn StorageReadView>, StoreError> {
7987            self.inner.begin_read()
7988        }
7989        fn begin_write(&self) -> Result<Box<dyn StorageWriteBatch + 'static>, StoreError> {
7990            Ok(Box::new(RecordingWriteBatch {
7991                inner: self.inner.begin_write()?,
7992                ranges: self.ranges.clone(),
7993            }))
7994        }
7995        fn begin_locked(
7996            &self,
7997            table_name: &'static str,
7998        ) -> Result<Box<dyn crate::api::StorageLockedView + 'static>, StoreError> {
7999            self.inner.begin_locked(table_name)
8000        }
8001        fn create_checkpoint(&self, path: &std::path::Path) -> Result<(), StoreError> {
8002            self.inner.create_checkpoint(path)
8003        }
8004    }
8005
8006    impl StorageWriteBatch for RecordingWriteBatch {
8007        fn put_batch(
8008            &mut self,
8009            table: &'static str,
8010            batch: Vec<(Vec<u8>, Vec<u8>)>,
8011        ) -> Result<(), StoreError> {
8012            self.inner.put_batch(table, batch)
8013        }
8014        fn delete(&mut self, table: &'static str, key: &[u8]) -> Result<(), StoreError> {
8015            self.inner.delete(table, key)
8016        }
8017        fn delete_range(
8018            &mut self,
8019            table: &'static str,
8020            start: &[u8],
8021            end: &[u8],
8022        ) -> Result<(), StoreError> {
8023            if table == STATE_HISTORY {
8024                self.ranges
8025                    .lock()
8026                    .unwrap()
8027                    .push((block_number_key(start), block_number_key(end)));
8028            }
8029            self.inner.delete_range(table, start, end)
8030        }
8031        fn merge(
8032            &mut self,
8033            table: &'static str,
8034            key: &[u8],
8035            operand: &[u8],
8036        ) -> Result<(), StoreError> {
8037            self.inner.merge(table, key, operand)
8038        }
8039        fn commit(&mut self) -> Result<(), StoreError> {
8040            self.inner.commit()
8041        }
8042    }
8043
8044    fn recording_store() -> (
8045        Store,
8046        Arc<dyn StorageBackend>,
8047        RecordedRanges,
8048        tempfile::TempDir,
8049    ) {
8050        let ranges = Arc::new(Mutex::new(Vec::new()));
8051        let backend: Arc<dyn StorageBackend> = Arc::new(RangeDeleteRecorder {
8052            inner: Arc::new(InMemoryBackend::open().unwrap()),
8053            ranges: ranges.clone(),
8054        });
8055        let dir = tempfile::tempdir().unwrap();
8056        let store = Store::from_backend(
8057            backend.clone(),
8058            dir.path().to_path_buf(),
8059            1,
8060            DEFAULT_PERSIST_CHANNEL_CAPACITY,
8061        )
8062        .unwrap();
8063        (store, backend, ranges, dir)
8064    }
8065
8066    /// Finality pruning SHALL start each range at the lowest surviving entry, so the
8067    /// ranges it writes never overlap. Ranges anchored at 0 overlap pairwise, and
8068    /// RocksDB fragments unflushed range tombstones in time and memory quadratic in
8069    /// how many overlap.
8070    #[tokio::test]
8071    async fn finality_pruning_writes_disjoint_ranges() {
8072        let (store, backend, ranges, _dir) = recording_store();
8073        seed_journal_entries(&backend, &[3, 7, 9, 12]);
8074
8075        for finalized in [5, 8, 10] {
8076            store
8077                .forkchoice_update_inner(vec![], 100, H256::zero(), None, Some(finalized))
8078                .await
8079                .unwrap();
8080        }
8081
8082        assert_eq!(*ranges.lock().unwrap(), vec![(3, 6), (7, 9), (9, 11)]);
8083        assert!(journal_entry_exists(&backend, 12));
8084    }
8085
8086    /// A finality advance that expires no entry SHALL write no range delete at all,
8087    /// so a chain whose entries are sparse does not accumulate one tombstone per block.
8088    #[tokio::test]
8089    async fn finality_advance_without_expired_entries_writes_no_range() {
8090        let (store, backend, ranges, _dir) = recording_store();
8091
8092        // Empty STATE_HISTORY: nothing to prune.
8093        store
8094            .forkchoice_update_inner(vec![], 100, H256::zero(), None, Some(5))
8095            .await
8096            .unwrap();
8097
8098        // Every surviving entry is above the new finality boundary.
8099        seed_journal_entries(&backend, &[20]);
8100        store
8101            .forkchoice_update_inner(vec![], 100, H256::zero(), None, Some(10))
8102            .await
8103            .unwrap();
8104
8105        assert!(ranges.lock().unwrap().is_empty());
8106        assert!(journal_entry_exists(&backend, 20));
8107    }
8108
8109    /// Finality pruning SHALL write disjoint ranges when entries keep landing below
8110    /// finality, as on an L2: the commit worker writes the entry for
8111    /// `head - DB_COMMIT_THRESHOLD` while every FCU finalizes `head`.
8112    #[tokio::test]
8113    async fn finality_pruning_stays_disjoint_when_entries_land_below_finality() {
8114        let (store, backend, ranges, _dir) = recording_store();
8115        let lag = DB_COMMIT_THRESHOLD as u64;
8116        for head in 1..=(lag + 50) {
8117            if head > lag {
8118                seed_journal_entries(&backend, &[head - lag]);
8119            }
8120            store
8121                .forkchoice_update_inner(vec![], head, H256::zero(), None, Some(head))
8122                .await
8123                .unwrap();
8124        }
8125
8126        let ranges = ranges.lock().unwrap();
8127        assert_eq!(ranges.len(), 50);
8128        for pair in ranges.windows(2) {
8129            assert!(pair[0].1 <= pair[1].0, "overlapping ranges {pair:?}");
8130        }
8131    }
8132
8133    fn journal_store() -> (Store, Arc<dyn StorageBackend>, tempfile::TempDir) {
8134        let backend: Arc<dyn StorageBackend> = Arc::new(InMemoryBackend::open().unwrap());
8135        let dir = tempfile::tempdir().unwrap();
8136        let store = Store::from_backend(
8137            backend.clone(),
8138            dir.path().to_path_buf(),
8139            1,
8140            DEFAULT_PERSIST_CHANNEL_CAPACITY,
8141        )
8142        .unwrap();
8143        (store, backend, dir)
8144    }
8145
8146    /// Writes the head and finalized numbers the persist worker reads to decide which
8147    /// committed layers journal, as a forkchoice update would.
8148    fn set_head_and_finalized(
8149        backend: &Arc<dyn StorageBackend>,
8150        head: BlockNumber,
8151        finalized: BlockNumber,
8152    ) {
8153        let mut tx = backend.begin_write().unwrap();
8154        tx.put(
8155            CHAIN_DATA,
8156            &chain_data_key(ChainDataIndex::LatestBlockNumber),
8157            &head.to_le_bytes(),
8158        )
8159        .unwrap();
8160        tx.put(
8161            CHAIN_DATA,
8162            &chain_data_key(ChainDataIndex::FinalizedBlockNumber),
8163            &finalized.to_le_bytes(),
8164        )
8165        .unwrap();
8166        tx.commit().unwrap();
8167    }
8168
8169    /// Stores block `number` on top of `parent_hash`, rewriting `shared` to `[number]`,
8170    /// and returns the block's hash and state root.
8171    fn store_block_rewriting(
8172        store: &Store,
8173        number: BlockNumber,
8174        parent_hash: H256,
8175        shared: &Nibbles,
8176        commit_depth: Option<usize>,
8177    ) -> (H256, H256) {
8178        let state_root = H256::repeat_byte(0xc0 | number as u8);
8179        let block = make_block(number, parent_hash, state_root);
8180        let hash = block.hash();
8181        store
8182            .store_block_updates(UpdateBatch {
8183                account_updates: vec![(shared.clone(), vec![number as u8])],
8184                storage_updates: vec![],
8185                blocks: vec![block],
8186                receipts: vec![],
8187                code_updates: vec![],
8188                commit_depth,
8189                wait_for_flush: false,
8190            })
8191            .unwrap();
8192        (hash, state_root)
8193    }
8194
8195    /// Stores blocks `1..=count` rewriting `shared`. With `commit_depth: Some(1)`,
8196    /// storing block n commits block n-1, one layer per commit.
8197    fn store_chain(
8198        store: &Store,
8199        count: BlockNumber,
8200        shared: &Nibbles,
8201        commit_depth: Option<usize>,
8202    ) {
8203        let mut parent_hash = H256::zero();
8204        for number in 1..=count {
8205            (parent_hash, _) =
8206                store_block_rewriting(store, number, parent_hash, shared, commit_depth);
8207        }
8208    }
8209
8210    fn journal_entry(backend: &Arc<dyn StorageBackend>, block_number: BlockNumber) -> JournalEntry {
8211        let bytes = backend
8212            .begin_read()
8213            .unwrap()
8214            .get(STATE_HISTORY, &block_number.to_be_bytes())
8215            .unwrap()
8216            .unwrap_or_else(|| panic!("journal entry for block {block_number}"));
8217        JournalEntry::decode(&bytes).unwrap()
8218    }
8219
8220    /// A layer committed at or below finality (and the head) SHALL get no journal entry:
8221    /// no reorg can unwind it. The first layer above finality SHALL journal, with the
8222    /// pre-image the skipped layer left on disk.
8223    #[tokio::test]
8224    async fn final_layers_are_committed_without_journal_entries() {
8225        let (store, backend, _dir) = journal_store();
8226        set_head_and_finalized(&backend, 100, 3);
8227        let shared = Nibbles::from_raw(&[0x0a, 0x0b], false);
8228
8229        store_chain(&store, 6, &shared, Some(1));
8230        store.wait_for_persistence_idle().await.unwrap();
8231
8232        for n in 1..=3 {
8233            assert!(!journal_entry_exists(&backend, n), "block {n} is final");
8234        }
8235        for n in 4..=5 {
8236            assert!(journal_entry_exists(&backend, n), "block {n} is not final");
8237        }
8238        let entry = journal_entry(&backend, 4);
8239        assert_eq!(entry.account_trie_diff.len(), 1);
8240        assert_eq!(
8241            entry.account_trie_diff[0].1,
8242            Some(vec![3]),
8243            "block 4's pre-image is what skipped block 3 wrote"
8244        );
8245    }
8246
8247    /// A single commit spanning finality SHALL skip its final layers yet journal the
8248    /// layers above them with pre-images that include the skipped layers' writes. Those
8249    /// are staged in the same write batch, so disk does not have them yet.
8250    #[tokio::test]
8251    async fn layer_journaled_after_skipped_ones_in_one_commit_sees_their_writes() {
8252        let (store, backend, _dir) = journal_store();
8253        set_head_and_finalized(&backend, 100, 2);
8254        let shared = Nibbles::from_raw(&[0x0a, 0x0b], false);
8255
8256        // No safe-commit root yet, so blocks 1..=4 stay in memory.
8257        let mut parent_hash = H256::zero();
8258        let mut roots = vec![H256::zero()];
8259        for number in 1..=4 {
8260            let (hash, root) = store_block_rewriting(&store, number, parent_hash, &shared, None);
8261            parent_hash = hash;
8262            roots.push(root);
8263        }
8264        // With block 3 as the safe-commit root, storing block 5 commits layers 1, 2 and 3
8265        // in one write batch.
8266        store.set_safe_commit_root(roots[3]).unwrap();
8267        store_block_rewriting(&store, 5, parent_hash, &shared, None);
8268        store.wait_for_persistence_idle().await.unwrap();
8269
8270        assert!(!journal_entry_exists(&backend, 1));
8271        assert!(!journal_entry_exists(&backend, 2));
8272        let entry = journal_entry(&backend, 3);
8273        assert_eq!(entry.account_trie_diff.len(), 1);
8274        assert_eq!(
8275            entry.account_trie_diff[0].1,
8276            Some(vec![2]),
8277            "block 3's pre-image is what skipped block 2 staged in the same batch"
8278        );
8279    }
8280
8281    /// A head rewound below finality without a finality update SHALL NOT leave layers
8282    /// above the head unjournaled, final or not: interrupted-batch recovery needs the
8283    /// newest entry above the head to name the block whose state is on disk.
8284    #[tokio::test]
8285    async fn layers_above_the_head_are_journaled_even_when_final() {
8286        let (store, backend, _dir) = journal_store();
8287        set_head_and_finalized(&backend, 2, 100);
8288        let shared = Nibbles::from_raw(&[0x0a, 0x0b], false);
8289
8290        store_chain(&store, 6, &shared, Some(1));
8291        store.wait_for_persistence_idle().await.unwrap();
8292
8293        for n in 1..=2 {
8294            assert!(
8295                !journal_entry_exists(&backend, n),
8296                "block {n} is final and not above the head"
8297            );
8298        }
8299        for n in 3..=5 {
8300            assert!(
8301                journal_entry_exists(&backend, n),
8302                "block {n} is above the head"
8303            );
8304        }
8305    }
8306
8307    /// While older entries survive, every committed layer SHALL journal, final or not, so
8308    /// the newest entry keeps naming the block whose state is on disk and no surviving
8309    /// entry holds pre-images against a state the disk has moved past.
8310    #[tokio::test]
8311    async fn final_layers_are_journaled_while_older_entries_survive() {
8312        let (store, backend, _dir) = journal_store();
8313        seed_journal_entries(&backend, &[0]);
8314        set_head_and_finalized(&backend, 100, 100);
8315        let shared = Nibbles::from_raw(&[0x0a, 0x0b], false);
8316
8317        store_chain(&store, 4, &shared, Some(1));
8318        store.wait_for_persistence_idle().await.unwrap();
8319
8320        for n in 1..=3 {
8321            assert!(
8322                journal_entry_exists(&backend, n),
8323                "block {n} follows a surviving entry"
8324            );
8325        }
8326    }
8327
8328    /// On an L2, which finalizes its head every block, every layer is final by the time
8329    /// it commits. The journal SHALL stay empty and finality pruning SHALL write no range
8330    /// delete.
8331    #[tokio::test]
8332    async fn chain_finalizing_its_head_writes_no_journal_and_no_range_deletes() {
8333        let (store, backend, ranges, _dir) = recording_store();
8334        let shared = Nibbles::from_raw(&[0x0a, 0x0b], false);
8335
8336        let mut parent_hash = H256::zero();
8337        for number in 1..=20 {
8338            let (hash, _) = store_block_rewriting(&store, number, parent_hash, &shared, Some(4));
8339            store
8340                .forkchoice_update_inner(vec![], number, hash, None, Some(number))
8341                .await
8342                .unwrap();
8343            parent_hash = hash;
8344        }
8345        store.wait_for_persistence_idle().await.unwrap();
8346
8347        for n in 1..=20 {
8348            assert!(
8349                !journal_entry_exists(&backend, n),
8350                "block {n} was final when committed"
8351            );
8352        }
8353        assert!(ranges.lock().unwrap().is_empty());
8354    }
8355}
8356
8357#[cfg(test)]
8358mod merge_tests {
8359    use super::*;
8360
8361    fn h256(b: u8) -> H256 {
8362        H256::from_low_u64_be(b as u64)
8363    }
8364
8365    fn op(bn: BlockNumber, bh: H256, idx: Index) -> Vec<u8> {
8366        encode_tx_location_operand(bn, bh, idx)
8367    }
8368
8369    fn decode(v: &[u8]) -> Vec<(BlockNumber, BlockHash, Index)> {
8370        <Vec<(BlockNumber, BlockHash, Index)>>::decode(v).unwrap()
8371    }
8372
8373    #[test]
8374    fn single_operand_on_empty_base() {
8375        let out = tx_locations_merge(None, vec![op(100, h256(0x10), 0)]).unwrap();
8376        assert_eq!(decode(&out), vec![(100, h256(0x10), 0)]);
8377    }
8378
8379    #[test]
8380    fn operand_appended_to_existing_base() {
8381        let base = vec![(100u64, h256(0x10), 0u64)].encode_to_vec();
8382        let out = tx_locations_merge(Some(&base), vec![op(101, h256(0x11), 5)]).unwrap();
8383        let mut got = decode(&out);
8384        got.sort();
8385        let mut want = vec![(100, h256(0x10), 0), (101, h256(0x11), 5)];
8386        want.sort();
8387        assert_eq!(got, want);
8388    }
8389
8390    #[test]
8391    fn multiple_operands_combined() {
8392        let out = tx_locations_merge(
8393            None,
8394            vec![
8395                op(100, h256(0x10), 0),
8396                op(100, h256(0x11), 1),
8397                op(101, h256(0x12), 2),
8398            ],
8399        )
8400        .unwrap();
8401        assert_eq!(decode(&out).len(), 3);
8402    }
8403
8404    #[test]
8405    fn same_block_hash_is_deduped() {
8406        // Two operands with the same block_hash: the later one replaces the earlier.
8407        let out =
8408            tx_locations_merge(None, vec![op(100, h256(0x10), 0), op(100, h256(0x10), 7)]).unwrap();
8409        assert_eq!(decode(&out), vec![(100, h256(0x10), 7)]);
8410    }
8411
8412    #[test]
8413    fn malformed_operand_aborts_merge() {
8414        // Fail loud: a malformed operand must abort the merge (return None), not
8415        // silently drop it and commit a partial result.
8416        let out = tx_locations_merge(None, vec![vec![0xff, 0xff], op(100, h256(0x10), 0)]);
8417        assert!(out.is_none(), "merge must abort on a malformed operand");
8418    }
8419
8420    #[test]
8421    fn malformed_base_value_aborts_merge() {
8422        let out = tx_locations_merge(Some(&[0xff, 0xff]), vec![op(100, h256(0x10), 0)]);
8423        assert!(out.is_none(), "merge must abort on a corrupt base value");
8424    }
8425
8426    /// Regression for the associative-merge format bug: a PartialMerge result
8427    /// must be re-mergeable as an operand. RocksDB folds operands together
8428    /// without a base value during compaction, then feeds that result back into
8429    /// a later merge. If the operand format differed from the output format,
8430    /// the re-fed result would fail to decode and entries would be dropped
8431    /// (observed as 1664 silent drops during a compaction pass on mainnet).
8432    #[test]
8433    fn partial_merge_result_is_a_valid_operand() {
8434        // Step 1: PartialMerge — combine operands with NO base value.
8435        let partial =
8436            tx_locations_merge(None, vec![op(100, h256(0x10), 0), op(101, h256(0x11), 1)]).unwrap();
8437
8438        // Step 2: the partial result is now itself an operand in a later merge,
8439        // on top of an existing base value. This is the path that used to drop
8440        // entries.
8441        let base = vec![(99u64, h256(0x09), 9u64)].encode_to_vec();
8442        let out = tx_locations_merge(Some(&base), vec![partial]).unwrap();
8443
8444        let mut got = decode(&out);
8445        got.sort();
8446        let mut want = vec![
8447            (99, h256(0x09), 9),
8448            (100, h256(0x10), 0),
8449            (101, h256(0x11), 1),
8450        ];
8451        want.sort();
8452        assert_eq!(
8453            got, want,
8454            "no entries may be lost when re-merging a partial result"
8455        );
8456    }
8457
8458    /// Operand and stored-value encodings must be byte-identical types, so a
8459    /// freshly-encoded operand round-trips through the value decoder.
8460    #[test]
8461    fn operand_encoding_matches_value_encoding() {
8462        let operand = op(100, h256(0x10), 3);
8463        // Decoding the operand as the stored Vec type must succeed.
8464        assert_eq!(decode(&operand), vec![(100, h256(0x10), 3)]);
8465    }
8466
8467    /// Chained PartialMerges (operand-only folds applied repeatedly) stay valid.
8468    #[test]
8469    fn chained_partial_merges() {
8470        let p1 = tx_locations_merge(None, vec![op(1, h256(0x01), 0)]).unwrap();
8471        let p2 = tx_locations_merge(None, vec![p1, op(2, h256(0x02), 0)]).unwrap();
8472        let p3 = tx_locations_merge(None, vec![p2, op(3, h256(0x03), 0)]).unwrap();
8473        let out = tx_locations_merge(None, vec![p3]).unwrap();
8474        assert_eq!(decode(&out).len(), 3);
8475    }
8476}
8477
8478#[cfg(test)]
8479mod backfill_write_tests {
8480    use super::*;
8481    use ethrex_common::types::{EIP1559Transaction, TxType};
8482
8483    fn test_header(number: BlockNumber) -> BlockHeader {
8484        BlockHeader {
8485            number,
8486            ..Default::default()
8487        }
8488    }
8489
8490    fn test_tx(nonce: u64) -> Transaction {
8491        Transaction::EIP1559Transaction(EIP1559Transaction {
8492            nonce,
8493            ..Default::default()
8494        })
8495    }
8496
8497    fn test_receipt() -> Receipt {
8498        Receipt {
8499            tx_type: TxType::EIP1559,
8500            succeeded: true,
8501            cumulative_gas_used: 21_000,
8502            logs: vec![],
8503            payer: None,
8504            frame_receipts: None,
8505        }
8506    }
8507
8508    /// `add_backfilled_blocks` writes the body + receipts + transaction index and
8509    /// lowers the frontier (`earliest_block_number`) in one shot; the indexed tx
8510    /// is then locatable for its (canonical) block.
8511    #[tokio::test]
8512    async fn writes_data_indexes_txs_and_lowers_frontier() {
8513        let store = Store::new("", EngineType::InMemory).expect("in-memory store");
8514        store.update_earliest_block_number(100).await.unwrap();
8515
8516        let header = test_header(99);
8517        let hash = header.hash();
8518        let tx = test_tx(7);
8519        let body = BlockBody {
8520            transactions: vec![tx.clone()],
8521            ommers: vec![],
8522            withdrawals: Some(vec![]),
8523        };
8524        // In production the header is already stored and canonical from snap
8525        // header backfill; mirror the canonical mapping so the tx-index lookup
8526        // (which is canonical-filtered) can resolve.
8527        store.add_block_headers(vec![header.clone()]).await.unwrap();
8528        store
8529            .forkchoice_update(vec![(99, hash)], 99, hash, None, None)
8530            .await
8531            .unwrap();
8532
8533        store
8534            .add_backfilled_blocks(
8535                vec![BackfilledBlock {
8536                    header,
8537                    body,
8538                    receipts: vec![test_receipt()],
8539                    index_transactions: true,
8540                }],
8541                99,
8542            )
8543            .await
8544            .unwrap();
8545
8546        assert_eq!(
8547            store.get_earliest_block_number().await.unwrap(),
8548            99,
8549            "frontier must be lowered atomically with the data write"
8550        );
8551        assert!(
8552            store.get_block_body_by_hash(hash).await.unwrap().is_some(),
8553            "body must be stored"
8554        );
8555        assert_eq!(
8556            store.get_receipts_for_block(&hash).await.unwrap().len(),
8557            1,
8558            "receipts must be stored"
8559        );
8560        assert_eq!(
8561            store
8562                .get_transaction_location(tx.hash(&NativeCrypto))
8563                .await
8564                .unwrap(),
8565            Some((99, hash, 0)),
8566            "indexed transaction must be locatable"
8567        );
8568    }
8569
8570    /// With `index_transactions = false` (a block outside the
8571    /// `--history.transactions` horizon) the body and receipts are still written,
8572    /// but the transaction index is skipped.
8573    #[tokio::test]
8574    async fn skips_tx_index_when_disabled() {
8575        let store = Store::new("", EngineType::InMemory).expect("in-memory store");
8576        store.update_earliest_block_number(100).await.unwrap();
8577
8578        let header = test_header(99);
8579        let hash = header.hash();
8580        let tx = test_tx(7);
8581        let body = BlockBody {
8582            transactions: vec![tx.clone()],
8583            ommers: vec![],
8584            withdrawals: Some(vec![]),
8585        };
8586        store.add_block_headers(vec![header.clone()]).await.unwrap();
8587        store
8588            .forkchoice_update(vec![(99, hash)], 99, hash, None, None)
8589            .await
8590            .unwrap();
8591
8592        store
8593            .add_backfilled_blocks(
8594                vec![BackfilledBlock {
8595                    header,
8596                    body,
8597                    receipts: vec![test_receipt()],
8598                    index_transactions: false,
8599                }],
8600                99,
8601            )
8602            .await
8603            .unwrap();
8604
8605        assert!(
8606            store.get_block_body_by_hash(hash).await.unwrap().is_some(),
8607            "body must still be stored"
8608        );
8609        assert_eq!(
8610            store.get_receipts_for_block(&hash).await.unwrap().len(),
8611            1,
8612            "receipts must still be stored"
8613        );
8614        assert_eq!(
8615            store
8616                .get_transaction_location(tx.hash(&NativeCrypto))
8617                .await
8618                .unwrap(),
8619            None,
8620            "transaction index must be skipped when index_transactions is false"
8621        );
8622        assert_eq!(
8623            store.get_tx_index_floor().await.unwrap(),
8624            Some(100),
8625            "the tx index floor must rise above the unindexed block"
8626        );
8627    }
8628
8629    #[tokio::test]
8630    async fn tx_index_floor_tracks_highest_unindexed_block() {
8631        let store = Store::new("", EngineType::InMemory).expect("in-memory store");
8632        store.update_earliest_block_number(100).await.unwrap();
8633        let backfilled = |number: u64, index_transactions: bool| BackfilledBlock {
8634            header: test_header(number),
8635            body: BlockBody {
8636                transactions: vec![test_tx(number)],
8637                ommers: vec![],
8638                withdrawals: Some(vec![]),
8639            },
8640            receipts: vec![test_receipt()],
8641            index_transactions,
8642        };
8643
8644        store
8645            .add_backfilled_blocks(
8646                vec![
8647                    backfilled(100, false),
8648                    backfilled(99, true),
8649                    backfilled(98, true),
8650                ],
8651                98,
8652            )
8653            .await
8654            .unwrap();
8655        assert_eq!(
8656            store.get_tx_index_floor().await.unwrap(),
8657            None,
8658            "the re-fetched frontier block must not raise the floor"
8659        );
8660
8661        store
8662            .add_backfilled_blocks(vec![backfilled(97, true), backfilled(96, false)], 96)
8663            .await
8664            .unwrap();
8665        assert_eq!(store.get_tx_index_floor().await.unwrap(), Some(97));
8666
8667        store
8668            .add_backfilled_blocks(vec![backfilled(95, false)], 95)
8669            .await
8670            .unwrap();
8671        assert_eq!(store.get_tx_index_floor().await.unwrap(), Some(97));
8672
8673        // An empty block has nothing to index, so it does not raise the floor.
8674        let empty = BackfilledBlock {
8675            header: test_header(98),
8676            body: BlockBody {
8677                transactions: vec![],
8678                ommers: vec![],
8679                withdrawals: Some(vec![]),
8680            },
8681            receipts: vec![],
8682            index_transactions: false,
8683        };
8684        let store = Store::new("", EngineType::InMemory).expect("in-memory store");
8685        store.update_earliest_block_number(99).await.unwrap();
8686        store
8687            .add_backfilled_blocks(vec![empty, backfilled(97, false)], 97)
8688            .await
8689            .unwrap();
8690        assert_eq!(store.get_tx_index_floor().await.unwrap(), Some(98));
8691    }
8692
8693    /// End-to-end at the storage/RPC boundary: the getters the RPC handlers use
8694    /// (`get_block_body`, `get_transaction_by_hash`, `get_receipt`) return nothing
8695    /// for a headers-only (post-snap) block and real data after backfill.
8696    #[tokio::test]
8697    async fn historical_getters_transition_from_null_to_present() {
8698        let store = Store::new("", EngineType::InMemory).expect("in-memory store");
8699        store.update_earliest_block_number(100).await.unwrap();
8700
8701        let header = test_header(99);
8702        let hash = header.hash();
8703        let tx = test_tx(7);
8704        let tx_hash = tx.hash(&NativeCrypto);
8705        let body = BlockBody {
8706            transactions: vec![tx],
8707            ommers: vec![],
8708            withdrawals: Some(vec![]),
8709        };
8710        // Post-snap state: header stored and canonical, but no body/receipts.
8711        store.add_block_headers(vec![header.clone()]).await.unwrap();
8712        store
8713            .forkchoice_update(vec![(99, hash)], 99, hash, None, None)
8714            .await
8715            .unwrap();
8716
8717        // Previously-null historical queries.
8718        assert!(
8719            store.get_block_body(99).await.unwrap().is_none(),
8720            "body absent before backfill"
8721        );
8722        assert!(
8723            store
8724                .get_transaction_by_hash(tx_hash)
8725                .await
8726                .unwrap()
8727                .is_none(),
8728            "tx unlocatable before backfill"
8729        );
8730        assert!(
8731            store.get_receipt(99, 0).await.unwrap().is_none(),
8732            "receipt absent before backfill"
8733        );
8734
8735        store
8736            .add_backfilled_blocks(
8737                vec![BackfilledBlock {
8738                    header,
8739                    body,
8740                    receipts: vec![test_receipt()],
8741                    index_transactions: true,
8742                }],
8743                99,
8744            )
8745            .await
8746            .unwrap();
8747
8748        // The same queries now return real data.
8749        assert!(
8750            store.get_block_body(99).await.unwrap().is_some(),
8751            "body present after backfill"
8752        );
8753        assert!(
8754            store
8755                .get_transaction_by_hash(tx_hash)
8756                .await
8757                .unwrap()
8758                .is_some(),
8759            "tx locatable after backfill"
8760        );
8761        assert!(
8762            store.get_receipt(99, 0).await.unwrap().is_some(),
8763            "receipt present after backfill"
8764        );
8765    }
8766
8767    /// Backfill fills downward in batches; the frontier lowers after each batch,
8768    /// persists (doubling as the resume cursor), and leaves no gaps.
8769    #[tokio::test]
8770    async fn resume_fills_contiguously_without_gaps() {
8771        let store = Store::new("", EngineType::InMemory).expect("in-memory store");
8772        store.update_earliest_block_number(100).await.unwrap();
8773
8774        let make_batch = |range: std::ops::Range<u64>| -> Vec<BackfilledBlock> {
8775            range
8776                .rev()
8777                .map(|n| BackfilledBlock {
8778                    header: test_header(n),
8779                    body: BlockBody {
8780                        transactions: vec![],
8781                        ommers: vec![],
8782                        withdrawals: Some(vec![]),
8783                    },
8784                    receipts: vec![],
8785                    index_transactions: false,
8786                })
8787                .collect()
8788        };
8789
8790        // Batch 1: fill [90, 99], lowering the frontier to 90.
8791        store
8792            .add_backfilled_blocks(make_batch(90..100), 90)
8793            .await
8794            .unwrap();
8795        assert_eq!(store.get_earliest_block_number().await.unwrap(), 90);
8796
8797        // Simulate a restart: the task resumes from the persisted frontier.
8798        let resume_from = store.get_earliest_block_number().await.unwrap();
8799        assert_eq!(resume_from, 90, "resume reads the persisted frontier");
8800
8801        // Batch 2: fill [80, 89], lowering the frontier to 80.
8802        store
8803            .add_backfilled_blocks(make_batch(80..90), 80)
8804            .await
8805            .unwrap();
8806        assert_eq!(store.get_earliest_block_number().await.unwrap(), 80);
8807
8808        // No gaps: every block in [80, 99] has a stored body.
8809        for n in 80..100 {
8810            assert!(
8811                store
8812                    .get_block_body_by_hash(test_header(n).hash())
8813                    .await
8814                    .unwrap()
8815                    .is_some(),
8816                "block {n} must have a body (no gap left by resume)"
8817            );
8818        }
8819    }
8820
8821    /// The index is asked about a block by hash, whether or not the block is canonical:
8822    /// a block is indexed when it is stored, before forkchoice makes it canonical.
8823    #[tokio::test]
8824    async fn a_stored_block_is_indexed_before_it_is_canonical() {
8825        let store = Store::new("", EngineType::InMemory).expect("in-memory store");
8826        let header = test_header(1);
8827        let hash = header.hash();
8828        let tx = test_tx(7);
8829        let tx_hash = tx.hash(&NativeCrypto);
8830        let body = BlockBody {
8831            transactions: vec![tx],
8832            ommers: vec![],
8833            withdrawals: Some(vec![]),
8834        };
8835        store.add_block(Block::new(header, body)).await.unwrap();
8836
8837        assert_eq!(store.get_transaction_location(tx_hash).await.unwrap(), None);
8838        assert!(
8839            store
8840                .is_transaction_indexed_in(tx_hash, hash)
8841                .await
8842                .unwrap()
8843        );
8844        let other_block = test_header(2).hash();
8845        assert!(
8846            !store
8847                .is_transaction_indexed_in(tx_hash, other_block)
8848                .await
8849                .unwrap()
8850        );
8851        assert!(
8852            !store
8853                .is_transaction_indexed_in(test_tx(8).hash(&NativeCrypto), hash)
8854                .await
8855                .unwrap()
8856        );
8857
8858        // A block still in the buffer, which is where a new payload waits to be flushed.
8859        let buffered_header = test_header(3);
8860        let buffered_hash = buffered_header.hash();
8861        let buffered_tx = test_tx(9);
8862        let buffered_tx_hash = buffered_tx.hash(&NativeCrypto);
8863        let buffered_body = BlockBody {
8864            transactions: vec![buffered_tx],
8865            ommers: vec![],
8866            withdrawals: Some(vec![]),
8867        };
8868        store.buffer_block_for_test(&Block::new(buffered_header, buffered_body));
8869        assert!(
8870            store
8871                .is_transaction_indexed_in(buffered_tx_hash, buffered_hash)
8872                .await
8873                .unwrap()
8874        );
8875    }
8876
8877    /// Opening a database marks its history bounds as reconciled only when it is new.
8878    /// One that already holds a genesis may predate the bounds, and is left for the
8879    /// reconciliation to correct and mark.
8880    #[tokio::test]
8881    async fn only_a_new_database_starts_with_reconciled_history_bounds() {
8882        let mut new = Store::new("", EngineType::InMemory).expect("in-memory store");
8883        new.add_initial_state(Genesis::default()).await.unwrap();
8884        assert!(new.history_bounds_reconciled().await.unwrap());
8885
8886        // The same genesis stored without the marker, as before the bounds were tracked.
8887        let mut existing = Store::new("", EngineType::InMemory).expect("in-memory store");
8888        let genesis_block = Genesis::default().get_block();
8889        let genesis_hash = genesis_block.hash();
8890        existing.add_block(genesis_block).await.unwrap();
8891        existing.update_earliest_block_number(0).await.unwrap();
8892        existing
8893            .forkchoice_update(vec![], 0, genesis_hash, None, None)
8894            .await
8895            .unwrap();
8896        existing
8897            .add_initial_state(Genesis::default())
8898            .await
8899            .unwrap();
8900        assert!(!existing.history_bounds_reconciled().await.unwrap());
8901    }
8902}
8903
8904/// The schema-version guard runs before any backend is opened, so these tests need
8905/// a persistent `EngineType` but never touch RocksDB itself.
8906#[cfg(test)]
8907#[cfg(feature = "rocksdb")]
8908mod schema_version_guard_tests {
8909    use super::*;
8910
8911    fn write_marker(dir: &Path, schema_version: u64) {
8912        let metadata = StoreMetadata::new(schema_version);
8913        std::fs::write(
8914            dir.join(STORE_METADATA_FILENAME),
8915            serde_json::to_string_pretty(&metadata).unwrap(),
8916        )
8917        .unwrap();
8918    }
8919
8920    fn read_marker(dir: &Path) -> u64 {
8921        read_store_schema_version(dir).unwrap().unwrap()
8922    }
8923
8924    #[test]
8925    fn a_database_ahead_of_the_binary_is_refused_and_left_untouched() {
8926        // The scenario behind this test: a datadir opened once by a newer build
8927        // (which stamps its own schema version) and then handed back to an older
8928        // one. The older build must refuse with a version error — not a
8929        // "migration failed" — and must not rewrite the marker, so the newer
8930        // build can still open the database.
8931        let dir = tempfile::tempdir().unwrap();
8932        let newer = STORE_SCHEMA_VERSION + 1;
8933        write_marker(dir.path(), newer);
8934
8935        let result =
8936            Store::new_with_config(dir.path(), EngineType::RocksDB, StoreConfig::default());
8937
8938        assert!(
8939            matches!(
8940                result,
8941                Err(StoreError::IncompatibleDBVersion { found, expected })
8942                    if found == newer && expected == STORE_SCHEMA_VERSION
8943            ),
8944            "expected IncompatibleDBVersion, got {:?}",
8945            result.err()
8946        );
8947        assert_eq!(read_marker(dir.path()), newer);
8948    }
8949
8950    #[test]
8951    fn a_zero_schema_version_is_incompatible_not_a_failed_migration() {
8952        // No ethrex ever writes v0; the marker is corrupt. Nothing was migrated,
8953        // so the error must not claim a migration failed.
8954        let dir = tempfile::tempdir().unwrap();
8955        write_marker(dir.path(), 0);
8956
8957        let result =
8958            Store::new_with_config(dir.path(), EngineType::RocksDB, StoreConfig::default());
8959
8960        assert!(
8961            matches!(
8962                result,
8963                Err(StoreError::IncompatibleDBVersion { found: 0, expected })
8964                    if expected == STORE_SCHEMA_VERSION
8965            ),
8966            "expected IncompatibleDBVersion, got {:?}",
8967            result.err()
8968        );
8969    }
8970}
8971
8972#[cfg(test)]
8973mod datadir_tests {
8974    use super::*;
8975    use std::fs;
8976
8977    #[test]
8978    fn empty_dir_has_no_existing_db() {
8979        let dir = tempfile::tempdir().unwrap();
8980        assert!(!dir_contains_legacy_db(dir.path()).unwrap());
8981    }
8982
8983    #[test]
8984    fn dir_with_only_unrelated_files_has_no_existing_db() {
8985        // Regression for #5680: a JWT secret (or any unrelated file) in the
8986        // datadir must not be mistaken for an existing database.
8987        let dir = tempfile::tempdir().unwrap();
8988        fs::write(dir.path().join("jwt.hex"), "0xdeadbeef").unwrap();
8989        fs::write(dir.path().join("LOG"), "noise").unwrap();
8990        assert!(!dir_contains_legacy_db(dir.path()).unwrap());
8991    }
8992
8993    #[test]
8994    fn dir_with_rocksdb_markers_has_existing_db() {
8995        // A `CURRENT` file (and, separately, a `MANIFEST-*` file) marks a real DB.
8996        let dir = tempfile::tempdir().unwrap();
8997        fs::write(dir.path().join("CURRENT"), "MANIFEST-000001\n").unwrap();
8998        assert!(dir_contains_legacy_db(dir.path()).unwrap());
8999
9000        let dir2 = tempfile::tempdir().unwrap();
9001        fs::write(dir2.path().join("MANIFEST-000007"), "x").unwrap();
9002        assert!(dir_contains_legacy_db(dir2.path()).unwrap());
9003    }
9004
9005    #[test]
9006    fn dir_with_marker_named_subdirectories_has_no_existing_db() {
9007        // A *directory* named like a marker file must not be mistaken for a DB;
9008        // RocksDB only ever visits these as plain files.
9009        let dir = tempfile::tempdir().unwrap();
9010        fs::create_dir(dir.path().join("CURRENT")).unwrap();
9011        fs::create_dir(dir.path().join("MANIFEST-000001")).unwrap();
9012        assert!(!dir_contains_legacy_db(dir.path()).unwrap());
9013    }
9014}
9015
9016#[cfg(test)]
9017mod flatkeyvalue_completeness_tests {
9018    use super::*;
9019
9020    /// The `last_written` marker signals a finished FKV pass ONLY as the exact 1-byte
9021    /// `[0xff]` sentinel. This gates journal-backed deep reorgs, so the
9022    /// boundary must be exact: an unset marker, the initial all-zero frontier, and any
9023    /// mid-generation nibble path must all read as "not complete".
9024    #[test]
9025    fn only_the_one_byte_ff_sentinel_counts_as_complete() {
9026        // Complete: the durable completion sentinel the generator writes.
9027        assert!(Store::flatkeyvalue_generation_complete(Some(&[0xff])));
9028
9029        // Not complete:
9030        assert!(!Store::flatkeyvalue_generation_complete(None)); // marker never written
9031        assert!(!Store::flatkeyvalue_generation_complete(Some(&[]))); // empty
9032        assert!(!Store::flatkeyvalue_generation_complete(Some(&[0u8; 64]))); // initial frontier
9033        assert!(!Store::flatkeyvalue_generation_complete(Some(&[0x0a; 64]))); // mid-gen nibble path
9034        // The in-memory frontier is expanded to all-0xff (64/131 bytes), but that is never
9035        // the durable marker; only the 1-byte form means complete, so these read false.
9036        assert!(!Store::flatkeyvalue_generation_complete(Some(&[0xff; 64])));
9037        assert!(!Store::flatkeyvalue_generation_complete(Some(&[
9038            0xff, 0xff
9039        ])));
9040    }
9041}
9042
9043#[cfg(test)]
9044mod cgroup_memory_limit_tests {
9045    use super::*;
9046    use std::fs;
9047
9048    /// Builds `<root>/<relative>` and writes `contents` into the `file` of every
9049    /// directory the map names, keyed by path relative to `root` ("" is the root).
9050    fn cgroup_tree(root: &Path, relative: &str, file: &str, limits: &[(&str, &str)]) {
9051        fs::create_dir_all(root.join(relative)).expect("create cgroup tree");
9052        for (dir, contents) in limits {
9053            fs::write(root.join(dir).join(file), contents).expect("write limit");
9054        }
9055    }
9056
9057    /// A limit set on an ancestor cgroup (a systemd slice, a pod's parent) applies to
9058    /// the process, so it must be found even though the process's own cgroup is
9059    /// unlimited and the mount root reports `max`.
9060    #[test]
9061    fn ancestor_limit_applies() {
9062        let tmp = tempfile::tempdir().expect("tempdir");
9063        let root = tmp.path();
9064        cgroup_tree(
9065            root,
9066            "system.slice/ethrex.service",
9067            "memory.max",
9068            &[("", "max"), ("system.slice", "4294967296")],
9069        );
9070
9071        assert_eq!(
9072            cgroup_limit_up_to_root(root, "/system.slice/ethrex.service", "memory.max"),
9073            Some(4 * 1024 * 1024 * 1024)
9074        );
9075    }
9076
9077    /// With limits at several levels the tightest one is what the kernel enforces.
9078    #[test]
9079    fn smallest_limit_in_the_chain_wins() {
9080        let tmp = tempfile::tempdir().expect("tempdir");
9081        let root = tmp.path();
9082        cgroup_tree(
9083            root,
9084            "kubepods/pod123/container",
9085            "memory.max",
9086            &[
9087                ("kubepods", "8589934592"),
9088                ("kubepods/pod123", "2147483648"),
9089                ("kubepods/pod123/container", "4294967296"),
9090            ],
9091        );
9092
9093        assert_eq!(
9094            cgroup_limit_up_to_root(root, "kubepods/pod123/container", "memory.max"),
9095            Some(2 * 1024 * 1024 * 1024)
9096        );
9097    }
9098
9099    /// An unlimited chain is "unknown", not zero: v2 writes the literal `max` and v1 a
9100    /// sentinel near `u64::MAX`, and absent files must not count either.
9101    #[test]
9102    fn unlimited_chain_yields_no_limit() {
9103        let tmp = tempfile::tempdir().expect("tempdir");
9104        let root = tmp.path();
9105        cgroup_tree(root, "docker/abc", "memory.max", &[("", "max")]);
9106
9107        assert_eq!(
9108            cgroup_limit_up_to_root(root, "docker/abc", "memory.max"),
9109            None
9110        );
9111        // A cgroup path that does not exist under this mount (a v1 controller that is
9112        // not mounted, a stale line in /proc/self/cgroup) reads as unknown too.
9113        assert_eq!(
9114            cgroup_limit_up_to_root(root, "not/here", "memory.max"),
9115            None
9116        );
9117    }
9118
9119    /// The root cgroup is itself a level: a limit set there still applies.
9120    #[test]
9121    fn root_limit_applies_to_the_root_cgroup() {
9122        let tmp = tempfile::tempdir().expect("tempdir");
9123        let root = tmp.path();
9124        cgroup_tree(root, "", "memory.limit_in_bytes", &[("", "536870912")]);
9125
9126        assert_eq!(
9127            cgroup_limit_up_to_root(root, "/", "memory.limit_in_bytes"),
9128            Some(512 * 1024 * 1024)
9129        );
9130    }
9131}
9132
9133#[cfg(test)]
9134mod in_memory_receipts_tests {
9135    use super::*;
9136    use ethrex_common::types::TxType;
9137
9138    /// Receipts read back from the in-memory backend, the one `--datadir memory` uses:
9139    /// every receipt of the block from the requested index on, and none of the next
9140    /// block's.
9141    #[tokio::test]
9142    async fn in_memory_store_returns_every_receipt_of_a_block() {
9143        let store = Store::new("", EngineType::InMemory).expect("in-memory store");
9144        let receipt = |gas| Receipt::new(TxType::Legacy, true, gas, vec![]);
9145        let block = BlockHash::repeat_byte(1);
9146        let next_block = BlockHash::repeat_byte(2);
9147        store
9148            .add_receipts(block, vec![receipt(1), receipt(2), receipt(3)])
9149            .await
9150            .unwrap();
9151        store
9152            .add_receipts(next_block, vec![receipt(4)])
9153            .await
9154            .unwrap();
9155
9156        let gas = |receipts: Vec<Receipt>| {
9157            receipts
9158                .iter()
9159                .map(|receipt| receipt.cumulative_gas_used)
9160                .collect::<Vec<_>>()
9161        };
9162        assert_eq!(
9163            gas(store.get_receipts_for_block(&block).await.unwrap()),
9164            [1, 2, 3]
9165        );
9166        assert_eq!(
9167            gas(store
9168                .get_receipts_for_block_from_index(&block, 1, None)
9169                .await
9170                .unwrap()),
9171            [2, 3]
9172        );
9173        assert_eq!(
9174            gas(store
9175                .get_receipts_for_block_from_index(&block, 1, Some(1))
9176                .await
9177                .unwrap()),
9178            [2]
9179        );
9180        assert_eq!(
9181            gas(store.get_receipts_for_block(&next_block).await.unwrap()),
9182            [4]
9183        );
9184    }
9185}
9186
9187#[cfg(test)]
9188mod witness_pruning_tests {
9189    use super::*;
9190
9191    /// Storing a witness prunes those more than `MAX_WITNESSES` blocks behind it, in one
9192    /// pass: every block from the oldest kept one up to the threshold, every fork of those
9193    /// blocks, and nothing above the threshold.
9194    #[test]
9195    fn storing_a_witness_prunes_every_block_below_the_window() {
9196        let store = Store::new("", EngineType::InMemory).expect("in-memory store");
9197        let fork = BlockHash::repeat_byte;
9198        let store_at = |number: u64, hash: BlockHash| {
9199            store
9200                .store_witness(hash, number, ExecutionWitness::default())
9201                .unwrap()
9202        };
9203        let kept = |number: u64, hash: BlockHash| {
9204            store
9205                .get_witness_json_bytes(number, hash)
9206                .unwrap()
9207                .is_some()
9208        };
9209
9210        for (number, hash) in [(2, fork(1)), (3, fork(1)), (3, fork(2)), (4, fork(1))] {
9211            store_at(number, hash);
9212        }
9213        // The first cleanup past the window only records where the next one starts,
9214        // block 2, without deleting anything.
9215        store_at(MAX_WITNESSES + 1, fork(1));
9216        assert!(kept(2, fork(1)) && kept(3, fork(1)) && kept(3, fork(2)) && kept(4, fork(1)));
9217
9218        // The window now starts at block 4: blocks 2 and 3 go, both forks of block 3
9219        // included, and the scan stops at block 4.
9220        store_at(MAX_WITNESSES + 3, fork(1));
9221        assert!(!kept(2, fork(1)));
9222        assert!(!kept(3, fork(1)));
9223        assert!(!kept(3, fork(2)));
9224        assert!(kept(4, fork(1)));
9225        assert!(kept(MAX_WITNESSES + 1, fork(1)));
9226        assert!(kept(MAX_WITNESSES + 3, fork(1)));
9227    }
9228}
9229
9230#[cfg(test)]
9231mod state_view_tests {
9232    use super::*;
9233
9234    /// Writes `address` with `nonce` into the on-disk state trie at `root` and
9235    /// returns the new root. Like a commit, it rewrites the path-keyed disk in
9236    /// place, so the previous root's nodes are gone afterwards.
9237    fn write_account_nonce(store: &Store, root: H256, address: Address, nonce: u64) -> H256 {
9238        let mut trie = store.open_direct_state_trie(root).unwrap();
9239        let account = AccountState {
9240            nonce,
9241            ..Default::default()
9242        };
9243        trie.insert(
9244            hash_address_fixed(&address).as_bytes().to_vec(),
9245            account.encode_to_vec(),
9246        )
9247        .unwrap();
9248        trie.commit(&NativeCrypto).unwrap();
9249        trie.hash_no_commit(&NativeCrypto)
9250    }
9251
9252    /// A `StateView` keeps reading the state it was checked against after a commit
9253    /// rewrites the disk under it, while the root itself is no longer held.
9254    fn state_view_is_pinned_across_a_commit(store: Store) {
9255        let address = Address::from_low_u64_be(0xabcd);
9256        let root = write_account_nonce(&store, EMPTY_TRIE_HASH, address, 1);
9257        let view = store
9258            .state_view(root)
9259            .unwrap()
9260            .expect("the state was just written");
9261
9262        let newer_root = write_account_nonce(&store, root, address, 2);
9263        assert_ne!(newer_root, root);
9264        assert!(!store.has_state_root(root).unwrap());
9265        assert!(store.state_view(root).unwrap().is_none());
9266        assert_eq!(view.account_state(address).unwrap().unwrap().nonce, 1);
9267        let newer = store.state_view(newer_root).unwrap().unwrap();
9268        assert_eq!(newer.account_state(address).unwrap().unwrap().nonce, 2);
9269    }
9270
9271    #[test]
9272    fn state_view_is_pinned_across_a_commit_in_memory() {
9273        state_view_is_pinned_across_a_commit(Store::new("", EngineType::InMemory).unwrap());
9274    }
9275
9276    #[cfg(feature = "rocksdb")]
9277    #[test]
9278    fn state_view_is_pinned_across_a_commit_rocksdb() {
9279        let dir = tempfile::tempdir().unwrap();
9280        state_view_is_pinned_across_a_commit(Store::new(dir.path(), EngineType::RocksDB).unwrap());
9281    }
9282}