Skip to content

Commit 19aa802

Browse files
authored
common: introduce IsHexHash and use it (#32998)
1 parent d39af34 commit 19aa802

File tree

3 files changed

+16
-8
lines changed

3 files changed

+16
-8
lines changed

cmd/geth/config.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ import (
3535
"github.com/ethereum/go-ethereum/beacon/blsync"
3636
"github.com/ethereum/go-ethereum/cmd/utils"
3737
"github.com/ethereum/go-ethereum/common"
38-
"github.com/ethereum/go-ethereum/common/hexutil"
3938
"github.com/ethereum/go-ethereum/crypto"
4039
"github.com/ethereum/go-ethereum/eth/catalyst"
4140
"github.com/ethereum/go-ethereum/eth/ethconfig"
@@ -273,11 +272,11 @@ func makeFullNode(ctx *cli.Context) *node.Node {
273272
// Configure synchronization override service
274273
var synctarget common.Hash
275274
if ctx.IsSet(utils.SyncTargetFlag.Name) {
276-
hex := hexutil.MustDecode(ctx.String(utils.SyncTargetFlag.Name))
277-
if len(hex) != common.HashLength {
278-
utils.Fatalf("invalid sync target length: have %d, want %d", len(hex), common.HashLength)
275+
target := ctx.String(utils.SyncTargetFlag.Name)
276+
if !common.IsHexHash(target) {
277+
utils.Fatalf("sync target hash is not a valid hex hash: %s", target)
279278
}
280-
synctarget = common.BytesToHash(hex)
279+
synctarget = common.HexToHash(target)
281280
}
282281
utils.RegisterSyncOverrideService(stack, eth, synctarget, ctx.Bool(utils.ExitWhenSyncedFlag.Name))
283282

cmd/geth/snapshot.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -639,11 +639,11 @@ func snapshotExportPreimages(ctx *cli.Context) error {
639639

640640
var root common.Hash
641641
if ctx.NArg() > 1 {
642-
rootBytes := common.FromHex(ctx.Args().Get(1))
643-
if len(rootBytes) != common.HashLength {
642+
hash := ctx.Args().Get(1)
643+
if !common.IsHexHash(hash) {
644644
return fmt.Errorf("invalid hash: %s", ctx.Args().Get(1))
645645
}
646-
root = common.BytesToHash(rootBytes)
646+
root = common.HexToHash(hash)
647647
} else {
648648
headBlock := rawdb.ReadHeadBlock(chaindb)
649649
if headBlock == nil {

common/types.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,15 @@ func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) }
7171
// If b is larger than len(h), b will be cropped from the left.
7272
func HexToHash(s string) Hash { return BytesToHash(FromHex(s)) }
7373

74+
// IsHexHash verifies whether a string can represent a valid hex-encoded
75+
// Ethereum hash or not.
76+
func IsHexHash(s string) bool {
77+
if has0xPrefix(s) {
78+
s = s[2:]
79+
}
80+
return len(s) == 2*HashLength && isHex(s)
81+
}
82+
7483
// Cmp compares two hashes.
7584
func (h Hash) Cmp(other Hash) int {
7685
return bytes.Compare(h[:], other[:])

0 commit comments

Comments
 (0)