diff --git a/common/bytes.go b/common/bytes.go index d1f5c6c995..2dd86f3d76 100644 --- a/common/bytes.go +++ b/common/bytes.go @@ -20,6 +20,7 @@ package common import ( "encoding/hex" "errors" + "strings" "github.com/ethereum/go-ethereum/common/hexutil" ) @@ -27,10 +28,10 @@ import ( // FromHex returns the bytes represented by the hexadecimal string s. // s may be prefixed with "0x". func FromHex(s string) []byte { - if has0xPrefix(s) { + if len(s) >= 2 && strings.HasPrefix(strings.ToLower(s), "0x") { s = s[2:] } - if len(s)%2 == 1 { + if len(s)&1 == 1 { s = "0" + s } return Hex2Bytes(s) @@ -47,27 +48,13 @@ func CopyBytes(b []byte) (copiedBytes []byte) { return } -// has0xPrefix validates str begins with '0x' or '0X'. -func has0xPrefix(str string) bool { - return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X') -} - -// isHexCharacter returns bool of c being a valid hexadecimal. -func isHexCharacter(c byte) bool { - return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') -} - // isHex validates whether each byte is valid hexadecimal string. func isHex(str string) bool { if len(str)%2 != 0 { return false } - for _, c := range []byte(str) { - if !isHexCharacter(c) { - return false - } - } - return true + _, err := hex.DecodeString(str) + return err == nil } // Bytes2Hex returns the hexadecimal encoding of d. diff --git a/common/types.go b/common/types.go index db4de8bcbd..13dc65d8a3 100644 --- a/common/types.go +++ b/common/types.go @@ -231,7 +231,7 @@ func HexToAddress(s string) Address { return BytesToAddress(FromHex(s)) } // IsHexAddress verifies whether a string can represent a valid hex-encoded // Ethereum address or not. func IsHexAddress(s string) bool { - if has0xPrefix(s) { + if len(s) >= 2 && strings.HasPrefix(strings.ToLower(s), "0x") { s = s[2:] } return len(s) == 2*AddressLength && isHex(s)