Skip to main content

reth_stages/stages/execution/
slot_preimages.rs

1use alloy_genesis::Genesis;
2use alloy_primitives::{keccak256, map::HashSet, B256};
3use eyre::Context;
4use reth_chainspec::{ChainSpecProvider, EthChainSpec};
5use reth_concurrency::sync::rayon::prelude::ParallelSliceMut;
6use reth_db::tables;
7use reth_db_api::{
8    cursor::{DbCursorRO, DbDupCursorRO},
9    transaction::DbTx,
10};
11use reth_libmdbx::{
12    DatabaseFlags, Environment, EnvironmentFlags, Geometry, Mode, SyncMode, WriteFlags, RO,
13};
14use reth_provider::{DBProvider, ExecutionOutcome};
15use reth_stages_api::StageError;
16use reth_trie::bundle_state::{AccountRevert, RevertToSlot};
17use std::path::Path;
18use tracing::trace;
19
20/// Separate MDBX environment for storing `keccak256(slot) → slot` preimage mappings.
21///
22/// Used during [`super::ExecutionStage`] for pre-Cancun selfdestruct handling where
23/// the original storage slot keys must be recovered from their hashed representation.
24///
25/// Also usable by downstream state-dump importers (e.g. `op-reth init-state`) to seed
26/// the database when state is imported from a snapshot rather than executed block-by-block.
27///
28/// The database is append-only and not unwound — duplicate inserts are silently skipped.
29/// After Cancun (where `SELFDESTRUCT` no longer destroys storage) the database can be pruned.
30#[derive(Debug)]
31pub struct SlotPreimages {
32    env: Environment,
33}
34
35impl SlotPreimages {
36    /// Opens (or creates) the slot-preimage MDBX environment at the given directory `path`.
37    ///
38    /// Uses subdir mode (`no_sub_dir = false`), so MDBX creates `mdbx.dat` / `mdbx.lck`
39    /// under the directory (e.g. `db/preimage/mdbx.dat`).
40    pub fn open(path: &Path) -> eyre::Result<Self> {
41        Self::open_with_genesis(path, None)
42    }
43
44    fn open_with_genesis(path: &Path, genesis: Option<&Genesis>) -> eyre::Result<Self> {
45        // Slot hashes are 32 bytes, so this metadata key cannot collide with a preimage.
46        const GENESIS_SEEDED: &[u8] = b"genesis-seeded";
47        const GIGABYTE: usize = 1024 * 1024 * 1024;
48        const TERABYTE: usize = GIGABYTE * 1024;
49
50        let mut builder = Environment::builder();
51        builder.set_max_dbs(1);
52        let os_page_size = page_size::get().clamp(4096, 0x10000);
53        builder.set_geometry(Geometry {
54            size: Some(0..(8 * TERABYTE)),
55            growth_step: Some(4 * GIGABYTE as isize),
56            shrink_threshold: Some(0),
57            page_size: Some(reth_libmdbx::PageSize::Set(os_page_size)),
58        });
59        builder.write_map();
60        builder.set_flags(EnvironmentFlags {
61            no_sub_dir: false,
62            no_rdahead: true,
63            mode: Mode::ReadWrite { sync_mode: SyncMode::Durable },
64            ..Default::default()
65        });
66
67        let env = builder.open(path).wrap_err_with(|| {
68            format!("failed to open slot-preimage MDBX env at {}", path.display())
69        })?;
70
71        // Seed the imported allocation before the first pre-Cancun wipe, including on upgrades
72        // from databases that only recorded slots touched during execution.
73        {
74            let tx = env.begin_rw_txn()?;
75            let db = tx.create_db(None, DatabaseFlags::empty())?;
76            if let Some(genesis) = genesis &&
77                tx.get::<[u8; 1]>(db.dbi(), GENESIS_SEEDED)?.is_none()
78            {
79                for storage in genesis.alloc.values().filter_map(|account| account.storage.as_ref())
80                {
81                    for slot in storage.keys() {
82                        tx.put(db.dbi(), keccak256(slot), slot, WriteFlags::empty())?;
83                    }
84                }
85                tx.put(db.dbi(), GENESIS_SEEDED, [1], WriteFlags::empty())?;
86            }
87            tx.commit()?;
88        }
89
90        trace!(target: "stages::slot_preimages", ?path, "Opened slot-preimage store");
91
92        Ok(Self { env })
93    }
94
95    /// Batch-insert `hashed_slot → plain_slot` preimage entries.
96    ///
97    /// Entries should be pre-sorted by key for optimal insert performance.
98    /// Unsorted entries are still inserted correctly but will be slower due to
99    /// loss of btree cursor locality.
100    /// Existing keys are silently skipped.
101    pub fn insert_preimages(&self, entries: &[(B256, B256)]) -> eyre::Result<()> {
102        let tx = self.env.begin_rw_txn()?;
103        let db = tx.open_db(None)?;
104        let mut cursor = tx.cursor(db.dbi())?;
105
106        for (hashed_slot, plain_slot) in entries {
107            if cursor.set_key::<[u8; 32], [u8; 32]>(hashed_slot.as_slice())?.is_some() {
108                continue;
109            }
110            cursor.put(hashed_slot.as_slice(), plain_slot.as_slice(), WriteFlags::empty())?;
111        }
112
113        tx.commit()?;
114
115        trace!(target: "stages::slot_preimages", count = entries.len(), "Inserted slot preimages");
116
117        Ok(())
118    }
119
120    /// Opens a read-only transaction for batch lookups.
121    ///
122    /// Reuse the returned [`SlotPreimagesReader`] for multiple `get` calls to avoid
123    /// the overhead of opening a new RO transaction per lookup.
124    pub fn reader(&self) -> eyre::Result<SlotPreimagesReader> {
125        let tx = self.env.begin_ro_txn()?;
126        let dbi = tx.open_db(None)?.dbi();
127        Ok(SlotPreimagesReader { tx, dbi })
128    }
129}
130
131/// Read-only handle for batch slot-preimage lookups within a single MDBX transaction.
132#[derive(Debug)]
133pub struct SlotPreimagesReader {
134    tx: reth_libmdbx::Transaction<RO>,
135    dbi: reth_libmdbx::ffi::MDBX_dbi,
136}
137
138impl SlotPreimagesReader {
139    /// Point-lookup of a slot preimage by its keccak256 hash.
140    pub fn get(&self, hashed_slot: &B256) -> eyre::Result<Option<B256>> {
141        let result: Option<[u8; 32]> = self.tx.get(self.dbi, hashed_slot.as_ref())?;
142        Ok(result.map(B256::from))
143    }
144}
145
146/// Collects `keccak256(slot) → slot` preimage entries from the bundle state and stores
147/// them in the auxiliary preimage database, then rewrites wipe reverts for self-destructed
148/// accounts to use plain slot keys instead of relying on the hashed-storage DB walk.
149///
150/// This eliminates the need for the changeset writer to read from `HashedStorages` during
151/// storage wipes, keeping all changeset keys in plain format.
152pub(super) fn inject_plain_wipe_slots<P: DBProvider + ChainSpecProvider, R>(
153    slot_preimages_path: &Path,
154    provider: &P,
155    state: &mut ExecutionOutcome<R>,
156) -> Result<(), StageError> {
157    // Collect preimage entries from bundle state and reverts.
158    // StorageKey in revm is U256, representing a plain EVM slot index.
159    let mut preimage_entries = Vec::new();
160    let mut seen_hashes = HashSet::new();
161    for account in state.bundle.state().values() {
162        for &slot_key in account.storage.keys() {
163            let plain = B256::from(slot_key);
164            let hashed = keccak256(plain);
165            if seen_hashes.insert(hashed) {
166                preimage_entries.push((hashed, plain));
167            }
168        }
169    }
170    for block_reverts in state.bundle.reverts.iter() {
171        for (_, revert) in block_reverts {
172            for &slot_key in revert.storage.keys() {
173                let plain = B256::from(slot_key);
174                let hashed = keccak256(plain);
175                if seen_hashes.insert(hashed) {
176                    preimage_entries.push((hashed, plain));
177                }
178            }
179        }
180    }
181
182    // Pre-sort entries by hash key for optimal MDBX insert performance.
183    preimage_entries.par_sort_unstable_by_key(|(hash, _)| *hash);
184
185    // Lazily open the preimage store and insert entries.
186    let preimages = SlotPreimages::open_with_genesis(
187        slot_preimages_path,
188        Some(provider.chain_spec().genesis()),
189    )
190    .map_err(fatal)?;
191
192    if !preimage_entries.is_empty() {
193        preimages.insert_preimages(&preimage_entries).map_err(fatal)?;
194    }
195
196    // Find all wipe reverts (self-destructed accounts) and inject plain slot keys.
197
198    // Open a single RO transaction for all preimage lookups in this batch.
199    let reader = preimages.reader().map_err(fatal)?;
200
201    for block_reverts in state.bundle.reverts.iter_mut() {
202        for (address, revert) in block_reverts.iter_mut() {
203            if !revert.wipe_storage {
204                continue;
205            }
206
207            // Walk all hashed storage slots for this account in the DB and look up
208            // their plain-key preimages.
209            let addr = *address;
210            let hashed_address = keccak256(addr);
211            let mut cursor = provider.tx_ref().cursor_dup_read::<tables::HashedStorages>()?;
212
213            if let Some((_, entry)) = cursor.seek_exact(hashed_address)? {
214                inject_preimage_entry(&reader, revert, addr, entry.key, entry.value)?;
215                while let Some(entry) = cursor.next_dup_val()? {
216                    inject_preimage_entry(&reader, revert, addr, entry.key, entry.value)?;
217                }
218            }
219        }
220    }
221
222    Ok(())
223}
224
225/// Looks up the plain-key preimage for a single hashed storage slot and inserts it
226/// into the account revert if not already present.
227fn inject_preimage_entry(
228    reader: &SlotPreimagesReader,
229    revert: &mut AccountRevert,
230    address: alloy_primitives::Address,
231    hashed_slot: B256,
232    value: alloy_primitives::U256,
233) -> Result<(), StageError> {
234    let plain_slot = reader.get(&hashed_slot).map_err(fatal)?.ok_or_else(|| {
235        fatal(eyre::eyre!("missing slot preimage for {hashed_slot:?} (addr={address:?})"))
236    })?;
237
238    // Convert B256 plain slot to U256 StorageKey for the revert map.
239    let plain_key = alloy_primitives::U256::from_be_bytes(plain_slot.0);
240    // When a contract is selfdestructed and then re-created at the same address via
241    // CREATE2 in the same block, revm treats the new contract as fresh and never reads
242    // the slot's original DB value. Slots touched by the new contract are marked as
243    // `Destroyed` instead of `Some(previous_value)`. We must overwrite these with the
244    // actual DB value here, otherwise `to_previous_value()` resolves them to zero.
245    revert
246        .storage
247        .entry(plain_key)
248        .and_modify(|slot| {
249            if matches!(slot, RevertToSlot::Destroyed) {
250                *slot = RevertToSlot::Some(value);
251            }
252        })
253        .or_insert(RevertToSlot::Some(value));
254    Ok(())
255}
256
257#[inline]
258fn fatal<E>(err: E) -> StageError
259where
260    E: Into<Box<dyn std::error::Error + Send + Sync>>,
261{
262    StageError::Fatal(err.into())
263}