Skip to content

Commit

Permalink
cmd/geth: support string (non-hex) keys in db get/put/delete (ethereu…
Browse files Browse the repository at this point in the history
…m#23744)

Adds suppor for passing regular strings to db `put`/`get`/`delete`, to avoid having to hex-encode when operating on fixed-key items like `SnapshotSyncStatus`, `SnapshotRecovery`  etc.


Signed-off-by: Maxim Zhiburt <zhiburt@gmail.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
  • Loading branch information
2 people authored and zzyalbert committed Nov 26, 2021
1 parent 69dcc51 commit 98b93f2
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions cmd/geth/dbcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package main

import (
"errors"
"fmt"
"os"
"path/filepath"
Expand Down Expand Up @@ -319,14 +320,15 @@ func dbGet(ctx *cli.Context) error {
db := utils.MakeChainDatabase(ctx, stack, true)
defer db.Close()

key, err := hexutil.Decode(ctx.Args().Get(0))
key, err := parseHexOrString(ctx.Args().Get(0))
if err != nil {
log.Info("Could not decode the key", "error", err)
return err
}

data, err := db.Get(key)
if err != nil {
log.Info("Get operation failed", "error", err)
log.Info("Get operation failed", "key", fmt.Sprintf("0x%#x", key), "error", err)
return err
}
fmt.Printf("key %#x: %#x\n", key, data)
Expand All @@ -344,7 +346,7 @@ func dbDelete(ctx *cli.Context) error {
db := utils.MakeChainDatabase(ctx, stack, false)
defer db.Close()

key, err := hexutil.Decode(ctx.Args().Get(0))
key, err := parseHexOrString(ctx.Args().Get(0))
if err != nil {
log.Info("Could not decode the key", "error", err)
return err
Expand All @@ -354,7 +356,7 @@ func dbDelete(ctx *cli.Context) error {
fmt.Printf("Previous value: %#x\n", data)
}
if err = db.Delete(key); err != nil {
log.Info("Delete operation returned an error", "error", err)
log.Info("Delete operation returned an error", "key", fmt.Sprintf("0x%#x", key), "error", err)
return err
}
return nil
Expand All @@ -377,7 +379,7 @@ func dbPut(ctx *cli.Context) error {
data []byte
err error
)
key, err = hexutil.Decode(ctx.Args().Get(0))
key, err = parseHexOrString(ctx.Args().Get(0))
if err != nil {
log.Info("Could not decode the key", "error", err)
return err
Expand Down Expand Up @@ -483,3 +485,12 @@ func freezerInspect(ctx *cli.Context) error {
}
return nil
}

// ParseHexOrString tries to hexdecode b, but if the prefix is missing, it instead just returns the raw bytes
func parseHexOrString(str string) ([]byte, error) {
b, err := hexutil.Decode(str)
if errors.Is(err, hexutil.ErrMissingPrefix) {
return []byte(str), nil
}
return b, err
}

0 comments on commit 98b93f2

Please sign in to comment.