diff --git a/hex/hex.go b/hex/hex.go index d6a1468f17..4699eb208a 100644 --- a/hex/hex.go +++ b/hex/hex.go @@ -40,6 +40,12 @@ func DecodeString(str string) ([]byte, error) { func DecodeHex(str string) ([]byte, error) { str = strings.TrimPrefix(str, "0x") + // Check if the string has an odd length + if len(str)%2 != 0 { + // Prepend a '0' to make it even-length + str = "0" + str + } + return hex.DecodeString(str) } diff --git a/hex/hex_test.go b/hex/hex_test.go index 12e6e44048..da86da3589 100644 --- a/hex/hex_test.go +++ b/hex/hex_test.go @@ -1,11 +1,13 @@ package hex import ( + "encoding/hex" "math" "math/big" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestEncodeDecodeBig(t *testing.T) { @@ -14,3 +16,37 @@ func TestEncodeDecodeBig(t *testing.T) { d := DecodeBig(e) assert.Equal(t, b.Uint64(), d.Uint64()) } + +// Define a struct for test cases +type TestCase struct { + input string + output []byte + err error +} + +// Unit test function +func TestDecodeHex(t *testing.T) { + testCases := []TestCase{ + {"0", []byte{0}, nil}, + {"00", []byte{0}, nil}, + {"0x0", []byte{0}, nil}, + {"0x00", []byte{0}, nil}, + {"1", []byte{1}, nil}, + {"01", []byte{1}, nil}, + {"", []byte{}, hex.ErrLength}, + {"0x", []byte{}, hex.ErrLength}, + {"zz", []byte{}, hex.InvalidByteError('z')}, + } + + for _, tc := range testCases { + t.Run(tc.input, func(t *testing.T) { + output, err := DecodeHex(tc.input) + if tc.err != nil { + require.Error(t, tc.err, err) + } else { + require.NoError(t, err) + } + require.Equal(t, output, tc.output) + }) + } +}