Skip to main content

reth_cli_commands/db/
state.rs

1use alloy_primitives::{keccak256, Address, BlockNumber, B256, U256};
2use clap::Parser;
3use reth_concurrency::sync::{
4    parking_lot::Mutex,
5    thread,
6    time::{Duration, Instant},
7};
8use reth_db_api::{
9    cursor::{DbCursorRO, DbDupCursorRO},
10    database::Database,
11    tables,
12    transaction::DbTx,
13};
14use reth_db_common::DbTool;
15use reth_provider::{
16    providers::{BlockchainProvider, ProviderNodeTypes},
17    StaticFileProviderFactory,
18};
19use reth_storage_api::{BlockNumReader, StateProvider, StateProviderFactory, StorageSettingsCache};
20use reth_tasks::spawn_scoped_thread;
21use std::collections::BTreeSet;
22use tracing::info;
23
24/// Log progress every 30 seconds
25const LOG_INTERVAL: Duration = Duration::from_secs(30);
26
27/// The arguments for the `reth db state` command
28#[derive(Parser, Debug)]
29pub struct Command {
30    /// The account address to get state for
31    address: Address,
32
33    /// Block number to query state at (uses current state if not provided)
34    #[arg(long, short)]
35    block: Option<BlockNumber>,
36
37    /// Maximum number of storage slots to display
38    #[arg(long, short, default_value = "100")]
39    limit: usize,
40
41    /// Output format (table, json, csv)
42    #[arg(long, short, default_value = "table")]
43    format: OutputFormat,
44}
45
46impl Command {
47    /// Execute `db state` command
48    pub fn execute<N: ProviderNodeTypes>(self, tool: &DbTool<N>) -> eyre::Result<()> {
49        let address = self.address;
50        let limit = self.limit;
51
52        if let Some(block) = self.block {
53            self.execute_historical(tool, address, block, limit)
54        } else {
55            self.execute_current(tool, address, limit)
56        }
57    }
58
59    fn execute_current<N: ProviderNodeTypes>(
60        &self,
61        tool: &DbTool<N>,
62        address: Address,
63        limit: usize,
64    ) -> eyre::Result<()> {
65        let use_hashed_state = tool.provider_factory.cached_storage_settings().use_hashed_state();
66
67        let entries = tool.provider_factory.db_ref().view(|tx| {
68            let (account, walker_entries) = if use_hashed_state {
69                let hashed_address = keccak256(address);
70                let account = tx.get::<tables::HashedAccounts>(hashed_address)?;
71                let mut cursor = tx.cursor_dup_read::<tables::HashedStorages>()?;
72                let walker = cursor.walk_dup(Some(hashed_address), None)?;
73                let mut entries = Vec::new();
74                let mut last_log = Instant::now();
75                for (idx, entry) in walker.enumerate() {
76                    let (_, storage_entry) = entry?;
77                    if !storage_entry.value.is_zero() {
78                        entries.push((storage_entry.key, storage_entry.value));
79                    }
80                    if entries.len() >= limit {
81                        break;
82                    }
83                    if last_log.elapsed() >= LOG_INTERVAL {
84                        info!(
85                            target: "reth::cli",
86                            address = %address,
87                            slots_scanned = idx,
88                            "Scanning storage slots"
89                        );
90                        last_log = Instant::now();
91                    }
92                }
93                (account, entries)
94            } else {
95                // Get account info
96                let account = tx.get::<tables::PlainAccountState>(address)?;
97                // Get storage entries
98                let mut cursor = tx.cursor_dup_read::<tables::PlainStorageState>()?;
99                let walker = cursor.walk_dup(Some(address), None)?;
100                let mut entries = Vec::new();
101                let mut last_log = Instant::now();
102                for (idx, entry) in walker.enumerate() {
103                    let (_, storage_entry) = entry?;
104                    if !storage_entry.value.is_zero() {
105                        entries.push((storage_entry.key, storage_entry.value));
106                    }
107                    if entries.len() >= limit {
108                        break;
109                    }
110                    if last_log.elapsed() >= LOG_INTERVAL {
111                        info!(
112                            target: "reth::cli",
113                            address = %address,
114                            slots_scanned = idx,
115                            "Scanning storage slots"
116                        );
117                        last_log = Instant::now();
118                    }
119                }
120                (account, entries)
121            };
122
123            Ok::<_, eyre::Report>((account, walker_entries))
124        })??;
125
126        let (account, storage_entries) = entries;
127
128        self.print_results(address, None, account, &storage_entries);
129
130        Ok(())
131    }
132
133    fn execute_historical<N: ProviderNodeTypes>(
134        &self,
135        tool: &DbTool<N>,
136        address: Address,
137        block: BlockNumber,
138        limit: usize,
139    ) -> eyre::Result<()> {
140        let provider = BlockchainProvider::new(tool.provider_factory.clone())?
141            .history_by_block_number(block)?;
142
143        // Get account info at that block
144        let account = provider.basic_account(&address)?;
145
146        // Check storage settings to determine where history is stored
147        let storage_settings = tool.provider_factory.cached_storage_settings();
148        let history_in_rocksdb = storage_settings.storage_v2;
149
150        // For historical queries, enumerate keys from history indices only
151        // (not PlainStorageState, which reflects current state)
152        let mut storage_keys = BTreeSet::new();
153
154        if history_in_rocksdb {
155            self.collect_staticfile_storage_keys(tool, address, &mut storage_keys)?;
156        } else {
157            self.collect_mdbx_storage_keys_parallel(tool, address, &mut storage_keys)?;
158        }
159
160        info!(
161            target: "reth::cli",
162            address = %address,
163            block = block,
164            total_keys = storage_keys.len(),
165            "Found storage keys to query"
166        );
167
168        // Now query each key at the historical block using the StateProvider
169        // This handles both MDBX and RocksDB backends transparently
170        let mut entries = Vec::new();
171        let mut last_log = Instant::now();
172
173        for (idx, key) in storage_keys.iter().enumerate() {
174            match provider.storage(address, *key) {
175                Ok(Some(value)) if !value.is_zero() => {
176                    entries.push((*key, value));
177                }
178                _ => {}
179            }
180
181            if entries.len() >= limit {
182                break;
183            }
184
185            if last_log.elapsed() >= LOG_INTERVAL {
186                info!(
187                    target: "reth::cli",
188                    address = %address,
189                    block = block,
190                    keys_total = storage_keys.len(),
191                    slots_scanned = idx,
192                    slots_found = entries.len(),
193                    "Scanning historical storage slots"
194                );
195                last_log = Instant::now();
196            }
197        }
198
199        self.print_results(address, Some(block), account, &entries);
200
201        Ok(())
202    }
203
204    /// Collects storage keys from static file StorageChangeSets (storage_v2).
205    fn collect_staticfile_storage_keys<N: ProviderNodeTypes>(
206        &self,
207        tool: &DbTool<N>,
208        address: Address,
209        keys: &mut BTreeSet<B256>,
210    ) -> eyre::Result<()> {
211        let tip = tool.provider_factory.provider()?.best_block_number()?;
212
213        if tip == 0 {
214            return Ok(());
215        }
216
217        info!(
218            target: "reth::cli",
219            address = %address,
220            tip,
221            "Scanning static file storage changesets"
222        );
223
224        let static_file_provider = tool.provider_factory.static_file_provider();
225        let walker = static_file_provider.walk_storage_changeset_range(0..=tip);
226
227        let mut total_scanned = 0usize;
228        let mut last_log = Instant::now();
229
230        for changeset_result in walker {
231            let (block_addr, storage_entry) = changeset_result?;
232            total_scanned += 1;
233
234            if block_addr.address() == address {
235                keys.insert(storage_entry.key);
236            }
237
238            if last_log.elapsed() >= LOG_INTERVAL {
239                info!(
240                    target: "reth::cli",
241                    address = %address,
242                    entries_scanned = total_scanned,
243                    unique_keys = keys.len(),
244                    "Scanning static file storage changesets"
245                );
246                last_log = Instant::now();
247            }
248        }
249
250        info!(
251            target: "reth::cli",
252            address = %address,
253            total_entries = total_scanned,
254            unique_keys = keys.len(),
255            "Finished static file storage changeset scan"
256        );
257
258        Ok(())
259    }
260
261    /// Collects storage keys from MDBX StorageChangeSets using parallel block range scanning.
262    fn collect_mdbx_storage_keys_parallel<N: ProviderNodeTypes>(
263        &self,
264        tool: &DbTool<N>,
265        address: Address,
266        keys: &mut BTreeSet<B256>,
267    ) -> eyre::Result<()> {
268        const CHUNK_SIZE: u64 = 500_000; // 500k blocks per thread
269        let num_threads =
270            thread::available_parallelism().map(|p| p.get().saturating_sub(1).max(1)).unwrap_or(4);
271
272        // Get the current tip block
273        let tip = tool.provider_factory.provider()?.best_block_number()?;
274
275        if tip == 0 {
276            return Ok(());
277        }
278
279        info!(
280            target: "reth::cli",
281            address = %address,
282            tip,
283            chunk_size = CHUNK_SIZE,
284            num_threads,
285            "Starting parallel MDBX changeset scan"
286        );
287
288        // Shared state for collecting keys
289        let collected_keys: Mutex<BTreeSet<B256>> = Mutex::new(BTreeSet::new());
290        let total_entries_scanned = Mutex::new(0usize);
291
292        // Create chunk ranges
293        let mut chunks: Vec<(u64, u64)> = Vec::new();
294        let mut start = 0u64;
295        while start <= tip {
296            let end = (start + CHUNK_SIZE - 1).min(tip);
297            chunks.push((start, end));
298            start = end + 1;
299        }
300
301        let chunks_ref = &chunks;
302        let next_chunk = Mutex::new(0usize);
303        let next_chunk_ref = &next_chunk;
304        let collected_keys_ref = &collected_keys;
305        let total_entries_ref = &total_entries_scanned;
306
307        thread::scope(|s| {
308            let handles: Vec<_> = (0..num_threads)
309                .map(|thread_id| {
310                    spawn_scoped_thread(s, "db-state-worker", move || {
311                        loop {
312                            // Get next chunk to process
313                            let chunk_idx = {
314                                let mut idx = next_chunk_ref.lock();
315                                if *idx >= chunks_ref.len() {
316                                    return Ok::<_, eyre::Report>(());
317                                }
318                                let current = *idx;
319                                *idx += 1;
320                                current
321                            };
322
323                            let (chunk_start, chunk_end) = chunks_ref[chunk_idx];
324
325                            // Open a new read transaction for this chunk
326                            tool.provider_factory.db_ref().view(|tx| {
327                                tx.disable_long_read_transaction_safety();
328
329                                let mut changeset_cursor =
330                                    tx.cursor_read::<tables::StorageChangeSets>()?;
331                                let start_key =
332                                    reth_db_api::models::BlockNumberAddress((chunk_start, address));
333                                let end_key =
334                                    reth_db_api::models::BlockNumberAddress((chunk_end, address));
335
336                                let mut local_keys = BTreeSet::new();
337                                let mut entries_in_chunk = 0usize;
338
339                                for entry in changeset_cursor.walk_range(start_key..=end_key)? {
340                                    let (block_addr, storage_entry) = entry?;
341                                    if block_addr.address() == address {
342                                        local_keys.insert(storage_entry.key);
343                                    }
344                                    entries_in_chunk += 1;
345                                }
346
347                                // Merge into global state
348                                collected_keys_ref.lock().extend(local_keys);
349                                *total_entries_ref.lock() += entries_in_chunk;
350
351                                info!(
352                                    target: "reth::cli",
353                                    thread_id,
354                                    chunk_start,
355                                    chunk_end,
356                                    entries_in_chunk,
357                                    "Thread completed chunk"
358                                );
359
360                                Ok::<_, eyre::Report>(())
361                            })??;
362                        }
363                    })
364                })
365                .collect();
366
367            for handle in handles {
368                handle.join().map_err(|_| eyre::eyre!("Thread panicked"))??;
369            }
370
371            Ok::<_, eyre::Report>(())
372        })?;
373
374        let final_keys = collected_keys.into_inner();
375        let total = *total_entries_scanned.lock();
376
377        info!(
378            target: "reth::cli",
379            address = %address,
380            total_entries = total,
381            unique_keys = final_keys.len(),
382            "Finished parallel MDBX changeset scan"
383        );
384
385        keys.extend(final_keys);
386        Ok(())
387    }
388
389    fn print_results(
390        &self,
391        address: Address,
392        block: Option<BlockNumber>,
393        account: Option<reth_primitives_traits::Account>,
394        storage: &[(alloy_primitives::B256, U256)],
395    ) {
396        match self.format {
397            OutputFormat::Table => {
398                println!("Account: {address}");
399                if let Some(b) = block {
400                    println!("Block: {b}");
401                } else {
402                    println!("Block: latest");
403                }
404                println!();
405
406                if let Some(acc) = account {
407                    println!("Nonce: {}", acc.nonce);
408                    println!("Balance: {} wei", acc.balance);
409                    if let Some(code_hash) = acc.bytecode_hash {
410                        println!("Code hash: {code_hash}");
411                    }
412                } else {
413                    println!("Account not found");
414                }
415
416                println!();
417                println!("Storage ({} slots):", storage.len());
418                println!("{:-<130}", "");
419                println!("{:<66} | {:<64}", "Slot", "Value");
420                println!("{:-<130}", "");
421                for (key, value) in storage {
422                    println!("{key} | {value:#066x}");
423                }
424            }
425            OutputFormat::Json => {
426                let output = serde_json::json!({
427                    "address": address.to_string(),
428                    "block": block,
429                    "account": account.map(|a| serde_json::json!({
430                        "nonce": a.nonce,
431                        "balance": a.balance.to_string(),
432                        "code_hash": a.bytecode_hash.map(|h| h.to_string()),
433                    })),
434                    "storage": storage.iter().map(|(k, v)| {
435                        serde_json::json!({
436                            "key": k.to_string(),
437                            "value": format!("{v:#066x}"),
438                        })
439                    }).collect::<Vec<_>>(),
440                });
441                println!("{}", serde_json::to_string_pretty(&output).unwrap());
442            }
443            OutputFormat::Csv => {
444                println!("slot,value");
445                for (key, value) in storage {
446                    println!("{key},{value:#066x}");
447                }
448            }
449        }
450    }
451}
452
453#[derive(Debug, Clone, Default, clap::ValueEnum)]
454pub enum OutputFormat {
455    #[default]
456    Table,
457    Json,
458    Csv,
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464    use alloy_primitives::address;
465
466    #[test]
467    fn parse_state_args() {
468        let cmd = Command::try_parse_from([
469            "state",
470            "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
471            "--block",
472            "1000000",
473        ])
474        .unwrap();
475        assert_eq!(cmd.address, address!("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"));
476        assert_eq!(cmd.block, Some(1000000));
477    }
478
479    #[test]
480    fn parse_state_args_no_block() {
481        let cmd = Command::try_parse_from(["state", "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"])
482            .unwrap();
483        assert_eq!(cmd.block, None);
484    }
485}