common: introduce IsHexHash and use it (#32998)

This commit is contained in:
maskpp 2025-11-04 21:09:36 +08:00 committed by GitHub
parent d39af344dc
commit 19aa8020a9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 16 additions and 8 deletions

View file

@ -35,7 +35,6 @@ import (
"github.com/ethereum/go-ethereum/beacon/blsync"
"github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth/catalyst"
"github.com/ethereum/go-ethereum/eth/ethconfig"
@ -273,11 +272,11 @@ func makeFullNode(ctx *cli.Context) *node.Node {
// Configure synchronization override service
var synctarget common.Hash
if ctx.IsSet(utils.SyncTargetFlag.Name) {
hex := hexutil.MustDecode(ctx.String(utils.SyncTargetFlag.Name))
if len(hex) != common.HashLength {
utils.Fatalf("invalid sync target length: have %d, want %d", len(hex), common.HashLength)
target := ctx.String(utils.SyncTargetFlag.Name)
if !common.IsHexHash(target) {
utils.Fatalf("sync target hash is not a valid hex hash: %s", target)
}
synctarget = common.BytesToHash(hex)
synctarget = common.HexToHash(target)
}
utils.RegisterSyncOverrideService(stack, eth, synctarget, ctx.Bool(utils.ExitWhenSyncedFlag.Name))

View file

@ -639,11 +639,11 @@ func snapshotExportPreimages(ctx *cli.Context) error {
var root common.Hash
if ctx.NArg() > 1 {
rootBytes := common.FromHex(ctx.Args().Get(1))
if len(rootBytes) != common.HashLength {
hash := ctx.Args().Get(1)
if !common.IsHexHash(hash) {
return fmt.Errorf("invalid hash: %s", ctx.Args().Get(1))
}
root = common.BytesToHash(rootBytes)
root = common.HexToHash(hash)
} else {
headBlock := rawdb.ReadHeadBlock(chaindb)
if headBlock == nil {

View file

@ -71,6 +71,15 @@ func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) }
// If b is larger than len(h), b will be cropped from the left.
func HexToHash(s string) Hash { return BytesToHash(FromHex(s)) }
// IsHexHash verifies whether a string can represent a valid hex-encoded
// Ethereum hash or not.
func IsHexHash(s string) bool {
if has0xPrefix(s) {
s = s[2:]
}
return len(s) == 2*HashLength && isHex(s)
}
// Cmp compares two hashes.
func (h Hash) Cmp(other Hash) int {
return bytes.Compare(h[:], other[:])