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