Skip to main content

reth_cli_commands/db/
get.rs

1use alloy_primitives::{hex, Address, BlockHash, B256};
2use clap::Parser;
3use reth_db::{
4    static_file::{
5        AccountChangesetMask, ColumnSelectorOne, ColumnSelectorTwo, HeaderWithHashMask,
6        ReceiptMask, TransactionMask, TransactionSenderMask,
7    },
8    RawDupSort,
9};
10use reth_db_api::{
11    cursor::{DbCursorRO, DbDupCursorRO},
12    database::Database,
13    models::{storage_sharded_key::StorageShardedKey, ShardedKey},
14    table::{Decompress, DupSort, Encode, Table},
15    tables,
16    transaction::DbTx,
17    RawKey, RawTable, TableRawRow, TableViewer,
18};
19use reth_db_common::DbTool;
20use reth_node_api::{HeaderTy, ReceiptTy, TxTy};
21use reth_node_builder::NodeTypesWithDB;
22use reth_primitives_traits::ValueWithSubKey;
23use reth_provider::{
24    providers::ProviderNodeTypes, ChangeSetReader, RocksDBProviderFactory,
25    StaticFileProviderFactory,
26};
27use reth_static_file_types::StaticFileSegment;
28use reth_storage_api::{StorageChangeSetReader, StorageSettingsCache};
29use reth_trie_db::TrieTableAdapter;
30use tracing::error;
31
32/// The arguments for the `reth db get` command
33#[derive(Parser, Debug)]
34pub struct Command {
35    #[command(subcommand)]
36    subcommand: Subcommand,
37}
38
39#[derive(clap::Subcommand, Debug)]
40enum Subcommand {
41    /// Gets the content of a database table for the given key
42    Mdbx {
43        table: tables::Tables,
44
45        /// The key to get content for
46        #[arg(value_parser = maybe_json_value_parser)]
47        key: String,
48
49        /// The subkey to get content for
50        #[arg(value_parser = maybe_json_value_parser)]
51        subkey: Option<String>,
52
53        /// Optional end key for range query (exclusive upper bound)
54        #[arg(value_parser = maybe_json_value_parser)]
55        end_key: Option<String>,
56
57        /// Optional end subkey for range query (exclusive upper bound)
58        #[arg(value_parser = maybe_json_value_parser)]
59        end_subkey: Option<String>,
60
61        /// Output bytes instead of human-readable decoded value
62        #[arg(long)]
63        raw: bool,
64    },
65    /// Gets the content of a static file segment for the given key
66    StaticFile {
67        segment: StaticFileSegment,
68
69        /// The key to get content for
70        #[arg(value_parser = maybe_json_value_parser)]
71        key: String,
72
73        /// The subkey to get content for, for example address in changeset
74        #[arg(value_parser = maybe_json_value_parser)]
75        subkey: Option<String>,
76
77        /// Output bytes instead of human-readable decoded value
78        #[arg(long)]
79        raw: bool,
80    },
81    /// Gets the content of a RocksDB table for the given key
82    ///
83    /// For history tables (accounts-history, storages-history), you can pass a plain address
84    /// instead of a full JSON ShardedKey. Use --block to query a specific block number
85    /// (seeks to the shard containing that block), or --all-shards to list all shards for
86    /// the address.
87    ///
88    /// Examples:
89    ///   reth db get rocksdb accounts-history 0xdBBE3D8c2d2b22A2611c5A94A9a12C2fCD49Eb29
90    ///   reth db get rocksdb accounts-history 0xdBBE...Eb29 --block 1000000
91    ///   reth db get rocksdb accounts-history 0xdBBE...Eb29 --all-shards
92    ///   reth db get rocksdb storages-history 0xdBBE...Eb29 --storage-key 0x0000...0003
93    Rocksdb {
94        /// The RocksDB table
95        #[arg(value_enum)]
96        table: RocksDbTable,
97
98        /// The key to get content for. For history tables, this can be a plain address.
99        #[arg(value_parser = maybe_json_value_parser)]
100        key: String,
101
102        /// Target block number for history tables. Seeks to the shard containing this block.
103        /// Defaults to the latest shard if not specified.
104        #[arg(long)]
105        block: Option<u64>,
106
107        /// Storage key for storages-history table lookups.
108        #[arg(long)]
109        storage_key: Option<String>,
110
111        /// List all shards for the given key (history tables only).
112        #[arg(long)]
113        all_shards: bool,
114
115        /// Output bytes instead of human-readable decoded value
116        #[arg(long)]
117        raw: bool,
118    },
119}
120
121/// RocksDB tables that can be queried.
122#[derive(Debug, Clone, Copy, clap::ValueEnum)]
123pub enum RocksDbTable {
124    /// Transaction hash to transaction number mapping
125    TransactionHashNumbers,
126    /// Account history indices
127    AccountsHistory,
128    /// Storage history indices
129    StoragesHistory,
130}
131
132impl Command {
133    /// Execute `db get` command
134    pub fn execute<N: ProviderNodeTypes>(self, tool: &DbTool<N>) -> eyre::Result<()> {
135        match self.subcommand {
136            Subcommand::Mdbx { table, key, subkey, end_key, end_subkey, raw } => {
137                let viewer = GetValueViewer { tool, key, subkey, end_key, end_subkey, raw };
138                match table {
139                    tables::Tables::AccountsTrie => {
140                        reth_trie_db::with_adapter!(tool.provider_factory, |A| {
141                            viewer.view::<<A as TrieTableAdapter>::AccountTrieTable>()
142                        })
143                    }
144                    tables::Tables::StoragesTrie => {
145                        reth_trie_db::with_adapter!(tool.provider_factory, |A| {
146                            viewer.view_dupsort::<<A as TrieTableAdapter>::StorageTrieTable>()
147                        })
148                    }
149                    _ => table.view(&viewer),
150                }?;
151            }
152            Subcommand::Rocksdb { table, key, block, storage_key, all_shards, raw } => {
153                get_rocksdb(tool, table, &key, block, storage_key.as_deref(), all_shards, raw)?;
154            }
155            Subcommand::StaticFile { segment, key, subkey, raw } => {
156                if let StaticFileSegment::StorageChangeSets = segment {
157                    let storage_key = subkey
158                        .as_deref()
159                        .map(table_subkey::<tables::StorageChangeSets>)
160                        .transpose()?;
161                    let key = table_key::<tables::StorageChangeSets>(&key)?;
162
163                    let provider = tool.provider_factory.static_file_provider();
164
165                    if let Some(storage_key) = storage_key {
166                        let entry = provider.get_storage_before_block(
167                            key.block_number(),
168                            key.address(),
169                            storage_key,
170                        )?;
171
172                        if let Some(entry) = entry {
173                            let se: reth_primitives_traits::StorageEntry = entry;
174                            println!("{}", serde_json::to_string_pretty(&se)?);
175                        } else {
176                            error!(target: "reth::cli", "No content for the given table key.");
177                        }
178                        return Ok(());
179                    }
180
181                    let changesets = provider.storage_changeset(key.block_number())?;
182                    let serializable: Vec<_> = changesets
183                        .into_iter()
184                        .map(|(addr, entry)| {
185                            let se: reth_primitives_traits::StorageEntry = entry;
186                            (addr, se)
187                        })
188                        .collect();
189                    println!("{}", serde_json::to_string_pretty(&serializable)?);
190                    return Ok(());
191                }
192
193                let (key, subkey, mask): (u64, _, _) = match segment {
194                    StaticFileSegment::Headers => (
195                        table_key::<tables::Headers>(&key)?,
196                        None,
197                        <HeaderWithHashMask<HeaderTy<N>>>::MASK,
198                    ),
199                    StaticFileSegment::Transactions => (
200                        table_key::<tables::Transactions>(&key)?,
201                        None,
202                        <TransactionMask<TxTy<N>>>::MASK,
203                    ),
204                    StaticFileSegment::Receipts => (
205                        table_key::<tables::Receipts>(&key)?,
206                        None,
207                        <ReceiptMask<ReceiptTy<N>>>::MASK,
208                    ),
209                    StaticFileSegment::TransactionSenders => (
210                        table_key::<tables::TransactionSenders>(&key)?,
211                        None,
212                        TransactionSenderMask::MASK,
213                    ),
214                    StaticFileSegment::AccountChangeSets => {
215                        let subkey = subkey
216                            .as_deref()
217                            .map(table_subkey::<tables::AccountChangeSets>)
218                            .transpose()?;
219                        (
220                            table_key::<tables::AccountChangeSets>(&key)?,
221                            subkey,
222                            AccountChangesetMask::MASK,
223                        )
224                    }
225                    StaticFileSegment::StorageChangeSets => {
226                        unreachable!("storage changesets handled above");
227                    }
228                };
229
230                // handle account changesets differently if a subkey is provided.
231                if let StaticFileSegment::AccountChangeSets = segment {
232                    let Some(subkey) = subkey else {
233                        // get all changesets for the block
234                        let changesets = tool
235                            .provider_factory
236                            .static_file_provider()
237                            .account_block_changeset(key)?;
238
239                        println!("{}", serde_json::to_string_pretty(&changesets)?);
240                        return Ok(())
241                    };
242
243                    let account = tool
244                        .provider_factory
245                        .static_file_provider()
246                        .get_account_before_block(key, subkey)?;
247
248                    if let Some(account) = account {
249                        println!("{}", serde_json::to_string_pretty(&account)?);
250                    } else {
251                        error!(target: "reth::cli", "No content for the given table key.");
252                    }
253
254                    return Ok(())
255                }
256
257                let content = tool.provider_factory.static_file_provider().find_static_file(
258                    segment,
259                    |provider| {
260                        let mut cursor = provider.cursor()?;
261                        cursor.get(key.into(), mask).map(|result| {
262                            result.map(|vec| {
263                                vec.iter().map(|slice| slice.to_vec()).collect::<Vec<_>>()
264                            })
265                        })
266                    },
267                )?;
268
269                match content {
270                    Some(content) => {
271                        if raw {
272                            println!("{}", hex::encode_prefixed(&content[0]));
273                        } else {
274                            match segment {
275                                StaticFileSegment::Headers => {
276                                    let header = HeaderTy::<N>::decompress(content[0].as_slice())?;
277                                    let block_hash = BlockHash::decompress(content[1].as_slice())?;
278                                    println!(
279                                        "Header\n{}\n\nBlockHash\n{}",
280                                        serde_json::to_string_pretty(&header)?,
281                                        serde_json::to_string_pretty(&block_hash)?
282                                    );
283                                }
284                                StaticFileSegment::Transactions => {
285                                    let transaction = TxTy::<N>::decompress(content[0].as_slice())?;
286                                    println!("{}", serde_json::to_string_pretty(&transaction)?);
287                                }
288                                StaticFileSegment::Receipts => {
289                                    let receipt =
290                                        ReceiptTy::<N>::decompress(content[0].as_slice())?;
291                                    println!("{}", serde_json::to_string_pretty(&receipt)?);
292                                }
293                                StaticFileSegment::TransactionSenders => {
294                                    let sender =
295                                        <<tables::TransactionSenders as Table>::Value>::decompress(
296                                            content[0].as_slice(),
297                                        )?;
298                                    println!("{}", serde_json::to_string_pretty(&sender)?);
299                                }
300                                StaticFileSegment::AccountChangeSets => {
301                                    unreachable!("account changeset static files are special cased before this match")
302                                }
303                                StaticFileSegment::StorageChangeSets => {
304                                    unreachable!("storage changeset static files are special cased before this match")
305                                }
306                            }
307                        }
308                    }
309                    None => {
310                        error!(target: "reth::cli", "No content for the given table key.");
311                    }
312                };
313            }
314        }
315
316        Ok(())
317    }
318}
319
320/// Gets a value from a RocksDB table by key.
321fn get_rocksdb<N: ProviderNodeTypes>(
322    tool: &DbTool<N>,
323    table: RocksDbTable,
324    key: &str,
325    block: Option<u64>,
326    storage_key: Option<&str>,
327    all_shards: bool,
328    raw: bool,
329) -> eyre::Result<()> {
330    let rocksdb = tool.provider_factory.rocksdb_provider();
331
332    match table {
333        RocksDbTable::TransactionHashNumbers => {
334            if block.is_some() || all_shards || storage_key.is_some() {
335                return Err(eyre::eyre!(
336                    "--block, --all-shards, and --storage-key are only supported for history tables"
337                ));
338            }
339            get_rocksdb_table::<tables::TransactionHashNumbers>(&rocksdb, key, raw)
340        }
341        RocksDbTable::AccountsHistory => {
342            if storage_key.is_some() {
343                return Err(eyre::eyre!("--storage-key is only supported for storages-history"));
344            }
345            get_rocksdb_account_history(&rocksdb, key, block, all_shards, raw)
346        }
347        RocksDbTable::StoragesHistory => {
348            get_rocksdb_storage_history(&rocksdb, key, storage_key, block, all_shards, raw)
349        }
350    }
351}
352
353/// Try to parse a key string as a plain address, falling back to JSON `ShardedKey` parsing.
354fn parse_address(key: &str) -> eyre::Result<Address> {
355    // Strip surrounding quotes that `maybe_json_value_parser` may have added
356    let stripped = key.trim_matches('"');
357    stripped.parse::<Address>().map_err(|e| eyre::eyre!("failed to parse address: {e}"))
358}
359
360/// Returns true if the key is shaped like a hex address, so a parse failure is a typo rather than
361/// a JSON key.
362fn looks_like_address(key: &str) -> bool {
363    key.trim_matches('"').starts_with("0x")
364}
365
366/// Gets account history from RocksDB with ergonomic key parsing.
367///
368/// Accepts a plain address and uses seek to find the relevant shard.
369fn get_rocksdb_account_history(
370    rocksdb: &reth_provider::providers::RocksDBProvider,
371    key: &str,
372    block: Option<u64>,
373    all_shards: bool,
374    raw: bool,
375) -> eyre::Result<()> {
376    // Try parsing as a plain address first, fall back to full JSON ShardedKey
377    match parse_address(key) {
378        Ok(address) => {
379            let block_number = block.unwrap_or(u64::MAX);
380            let seek_key = ShardedKey::new(address, block_number);
381
382            if all_shards {
383                // Iterate all shards: seek from (address, 0) until address changes
384                let start = ShardedKey::new(address, 0);
385                let iter = rocksdb.iter_from::<tables::AccountsHistory>(start)?;
386                for result in iter {
387                    let (k, v) = result?;
388                    if k.key != address {
389                        break;
390                    }
391                    println!(
392                        "{}",
393                        serde_json::to_string_pretty(&serde_json::json!({
394                            "highest_block_number": k.highest_block_number,
395                            "value": v,
396                        }))?
397                    );
398                }
399            } else {
400                // Seek to the first shard with highest_block_number >= target
401                let mut iter = rocksdb.iter_from::<tables::AccountsHistory>(seek_key)?;
402                match iter.next() {
403                    Some(Ok((k, v))) if k.key == address => {
404                        if raw {
405                            let raw_val = rocksdb.get_raw::<tables::AccountsHistory>(k)?;
406                            if let Some(bytes) = raw_val {
407                                println!("{}", hex::encode_prefixed(&bytes));
408                            }
409                        } else {
410                            println!("{}", serde_json::to_string_pretty(&v)?);
411                        }
412                    }
413                    Some(Err(e)) => return Err(e.into()),
414                    _ => {
415                        error!(target: "reth::cli", "No content for the given table key.");
416                    }
417                }
418            }
419            Ok(())
420        }
421        Err(e) if looks_like_address(key) => Err(e),
422        Err(_) => {
423            // Fall back to full JSON key parsing (e.g.
424            // `{"key":"0x...","highest_block_number":...}`)
425            if all_shards || block.is_some() {
426                return Err(eyre::eyre!(
427                    "--block and --all-shards require a plain address, not a JSON key"
428                ));
429            }
430            get_rocksdb_table::<tables::AccountsHistory>(rocksdb, key, raw)
431        }
432    }
433}
434
435/// Gets storage history from RocksDB with ergonomic key parsing.
436///
437/// Accepts a plain address + optional `--storage-key` and uses seek.
438fn get_rocksdb_storage_history(
439    rocksdb: &reth_provider::providers::RocksDBProvider,
440    key: &str,
441    storage_key: Option<&str>,
442    block: Option<u64>,
443    all_shards: bool,
444    raw: bool,
445) -> eyre::Result<()> {
446    match parse_address(key) {
447        Ok(address) => {
448            let storage_key = storage_key
449                .map(|s| s.trim_matches('"').parse::<B256>())
450                .transpose()
451                .map_err(|e| eyre::eyre!("failed to parse storage key: {e}"))?
452                .unwrap_or_default();
453            let block_number = block.unwrap_or(u64::MAX);
454            let seek_key = StorageShardedKey::new(address, storage_key, block_number);
455
456            if all_shards {
457                let start = StorageShardedKey::new(address, storage_key, 0);
458                let iter = rocksdb.iter_from::<tables::StoragesHistory>(start)?;
459                for result in iter {
460                    let (k, v) = result?;
461                    if k.address != address || k.sharded_key.key != storage_key {
462                        break;
463                    }
464                    println!(
465                        "{}",
466                        serde_json::to_string_pretty(&serde_json::json!({
467                            "highest_block_number": k.sharded_key.highest_block_number,
468                            "value": v,
469                        }))?
470                    );
471                }
472            } else {
473                let mut iter = rocksdb.iter_from::<tables::StoragesHistory>(seek_key)?;
474                match iter.next() {
475                    Some(Ok((k, v)))
476                        if k.address == address && k.sharded_key.key == storage_key =>
477                    {
478                        if raw {
479                            let raw_val = rocksdb.get_raw::<tables::StoragesHistory>(k)?;
480                            if let Some(bytes) = raw_val {
481                                println!("{}", hex::encode_prefixed(&bytes));
482                            }
483                        } else {
484                            println!("{}", serde_json::to_string_pretty(&v)?);
485                        }
486                    }
487                    Some(Err(e)) => return Err(e.into()),
488                    _ => {
489                        error!(target: "reth::cli", "No content for the given table key.");
490                    }
491                }
492            }
493            Ok(())
494        }
495        Err(e) if looks_like_address(key) => Err(e),
496        Err(_) => {
497            if all_shards || block.is_some() || storage_key.is_some() {
498                return Err(eyre::eyre!(
499                    "--block, --all-shards, and --storage-key require a plain address, not a JSON key"
500                ));
501            }
502            get_rocksdb_table::<tables::StoragesHistory>(rocksdb, key, raw)
503        }
504    }
505}
506
507/// Gets a value from a specific RocksDB table by exact key and prints it.
508fn get_rocksdb_table<T: Table>(
509    rocksdb: &reth_provider::providers::RocksDBProvider,
510    key_str: &str,
511    raw: bool,
512) -> eyre::Result<()> {
513    let key = table_key::<T>(key_str)?;
514
515    if raw {
516        let content = rocksdb.get_raw::<T>(key)?;
517        match content {
518            Some(bytes) => println!("{}", hex::encode_prefixed(&bytes)),
519            None => error!(target: "reth::cli", "No content for the given table key."),
520        }
521    } else {
522        let content = rocksdb.get::<T>(key)?;
523        match content {
524            Some(value) => println!("{}", serde_json::to_string_pretty(&value)?),
525            None => error!(target: "reth::cli", "No content for the given table key."),
526        }
527    }
528
529    Ok(())
530}
531
532/// Get an instance of key for given table
533pub(crate) fn table_key<T: Table>(key: &str) -> Result<T::Key, eyre::Error> {
534    serde_json::from_str(key).map_err(|e| eyre::eyre!(e))
535}
536
537/// Get an instance of subkey for given dupsort table
538fn table_subkey<T: DupSort>(subkey: &str) -> Result<T::SubKey, eyre::Error> {
539    serde_json::from_str(subkey).map_err(|e| eyre::eyre!(e))
540}
541
542struct GetValueViewer<'a, N: NodeTypesWithDB> {
543    tool: &'a DbTool<N>,
544    key: String,
545    subkey: Option<String>,
546    end_key: Option<String>,
547    end_subkey: Option<String>,
548    raw: bool,
549}
550
551impl<N: ProviderNodeTypes> TableViewer<()> for GetValueViewer<'_, N> {
552    type Error = eyre::Report;
553
554    fn view<T: Table>(&self) -> Result<(), Self::Error> {
555        let key = table_key::<T>(&self.key)?;
556
557        // A non-dupsort table cannot have subkeys. The `subkey` arg becomes the `end_key`. First we
558        // check that `end_key` and `end_subkey` weren't previously given, as that wouldn't be
559        // valid.
560        if self.end_key.is_some() || self.end_subkey.is_some() {
561            return Err(eyre::eyre!("Only END_KEY can be given for non-DUPSORT tables"));
562        }
563
564        let end_key = self.subkey.clone();
565
566        // Check if we're doing a range query
567        if let Some(ref end_key_str) = end_key {
568            let end_key = table_key::<T>(end_key_str)?;
569
570            // Use walk_range to iterate over the range
571            let tx = self.tool.provider_factory.db_ref().tx()?;
572            let mut cursor = tx.cursor_read::<RawTable<T>>()?;
573            for result in cursor.walk_range(RawKey::from(key)..RawKey::from(end_key))? {
574                print_row::<T>(result?, self.raw)?;
575            }
576            tx.commit()?;
577        } else {
578            // Single key lookup
579            let content = if self.raw {
580                self.tool
581                    .get::<RawTable<T>>(RawKey::from(key))?
582                    .map(|content| hex::encode_prefixed(content.raw_value()))
583            } else {
584                self.tool.get::<T>(key)?.as_ref().map(serde_json::to_string_pretty).transpose()?
585            };
586
587            print_content(content, "key");
588        }
589
590        Ok(())
591    }
592
593    fn view_dupsort<T: DupSort>(&self) -> Result<(), Self::Error>
594    where
595        T::Value: ValueWithSubKey<SubKey = T::SubKey>,
596    {
597        // get a key for given table
598        let key = table_key::<T>(&self.key)?;
599
600        // Check if we're doing a range query
601        if let Some(ref end_key_str) = self.end_key {
602            let key = RawKey::from(key);
603            let end_key = RawKey::from(table_key::<T>(end_key_str)?);
604            let Some(start_subkey) = self.subkey.as_deref() else {
605                eyre::bail!("a subkey is required when end_key is given");
606            };
607            let start_subkey = RawKey::from(table_subkey::<T>(start_subkey)?);
608            let end_subkey =
609                self.end_subkey.as_deref().map(table_subkey::<T>).transpose()?.map(Encode::encode);
610            let end_subkey = end_subkey.as_ref().map(AsRef::as_ref).unwrap_or_default();
611
612            let tx = self.tool.provider_factory.db_ref().tx()?;
613            let mut cursor = tx.cursor_dup_read::<RawDupSort<T>>()?;
614
615            // A duplicate seek stays within one key. On a miss, resume at the next distinct key.
616            let mut current = match cursor.seek_by_key_subkey(key.clone(), start_subkey)? {
617                Some(value) => Some((key, value)),
618                None => match cursor.seek(key.clone())? {
619                    Some((found, _)) if found == key => cursor.next_no_dup()?,
620                    row => row,
621                },
622            };
623
624            while let Some((key, value)) = current {
625                // Each value starts with its fixed-width subkey. An empty end subkey excludes
626                // every duplicate of the end key.
627                if (&key, value.raw_value()) >= (&end_key, end_subkey) {
628                    break;
629                }
630                print_row::<T>((key, value), self.raw)?;
631                current = cursor.next()?;
632            }
633            tx.commit()?;
634        } else {
635            // Single key/subkey lookup
636            let Some(subkey) = self.subkey.as_deref() else {
637                eyre::bail!("a subkey is required for dupsort tables");
638            };
639            let encoded_subkey = table_subkey::<T>(subkey)?.encode();
640            let subkey = encoded_subkey.as_ref();
641
642            // MDBX can return the next duplicate. Each table encodes its full, fixed-width subkey
643            // at the start of the value, so raw reads can check it without decoding the payload.
644            let value = self
645                .tool
646                .get_dup::<RawDupSort<T>>(key.into(), RawKey::from_vec(subkey.to_vec()))?
647                .filter(|value| value.raw_value().starts_with(subkey));
648            match value {
649                Some(value) if self.raw => println!("{}", hex::encode_prefixed(value.raw_value())),
650                Some(value) => println!("{}", serde_json::to_string_pretty(&value.value()?)?),
651                None => print_content(None, "subkey"),
652            }
653        }
654        Ok(())
655    }
656}
657
658/// Prints a range row, preserving the stored bytes for raw output.
659fn print_row<T: Table>((key, value): TableRawRow<T>, raw: bool) -> eyre::Result<()> {
660    let (key, val) = if raw {
661        (hex::encode_prefixed(key.raw_key()).into(), hex::encode_prefixed(value.raw_value()).into())
662    } else {
663        (serde_json::to_value(key.key()?)?, serde_json::to_value(value.value()?)?)
664    };
665    println!("{}", serde_json::to_string_pretty(&serde_json::json!({ "key": key, "val": val }))?);
666    Ok(())
667}
668
669/// Prints the looked up content, or logs that nothing exists for the given `key` or `subkey`.
670fn print_content(content: Option<String>, missing: &str) {
671    match content {
672        Some(content) => println!("{content}"),
673        None => error!(target: "reth::cli", "No content for the given table {missing}."),
674    }
675}
676
677/// Map the user input value to json
678pub(crate) fn maybe_json_value_parser(value: &str) -> Result<String, eyre::Error> {
679    if serde_json::from_str::<serde::de::IgnoredAny>(value).is_ok() {
680        Ok(value.to_string())
681    } else {
682        serde_json::to_string(&value).map_err(|e| eyre::eyre!(e))
683    }
684}
685
686#[cfg(test)]
687mod tests {
688
689    use super::*;
690    use alloy_primitives::{address, b256, B256};
691    use clap::{Args, Parser};
692    use reth_db_api::{
693        models::{storage_sharded_key::StorageShardedKey, ShardedKey},
694        AccountsHistory, HashedAccounts, Headers, StageCheckpoints, StoragesHistory,
695    };
696
697    /// A helper type to parse Args more easily
698    #[derive(Parser)]
699    struct CommandParser<T: Args> {
700        #[command(flatten)]
701        args: T,
702    }
703
704    #[test]
705    fn parse_numeric_key_args() {
706        assert_eq!(table_key::<Headers>("123").unwrap(), 123);
707        assert_eq!(
708            table_key::<HashedAccounts>(
709                "\"0x0ac361fe774b78f8fc4e86c1916930d150865c3fc2e21dca2e58833557608bac\""
710            )
711            .unwrap(),
712            b256!("0x0ac361fe774b78f8fc4e86c1916930d150865c3fc2e21dca2e58833557608bac")
713        );
714    }
715
716    #[test]
717    fn parse_string_key_args() {
718        assert_eq!(
719            table_key::<StageCheckpoints>("\"MerkleExecution\"").unwrap(),
720            "MerkleExecution"
721        );
722    }
723
724    #[test]
725    fn parse_json_key_args() {
726        assert_eq!(
727            table_key::<StoragesHistory>(r#"{ "address": "0x01957911244e546ce519fbac6f798958fafadb41", "sharded_key": { "key": "0x0000000000000000000000000000000000000000000000000000000000000003", "highest_block_number": 18446744073709551615 } }"#).unwrap(),
728            StorageShardedKey::new(
729                address!("0x01957911244e546ce519fbac6f798958fafadb41"),
730                B256::with_last_byte(3),
731                18446744073709551615
732            )
733        );
734    }
735
736    #[test]
737    fn parse_json_key_for_account_history() {
738        assert_eq!(
739            table_key::<AccountsHistory>(r#"{ "key": "0x4448e1273fd5a8bfdb9ed111e96889c960eee145", "highest_block_number": 18446744073709551615 }"#).unwrap(),
740            ShardedKey::new(
741                address!("0x4448e1273fd5a8bfdb9ed111e96889c960eee145"),
742                18446744073709551615
743            )
744        );
745    }
746}