From 4cafe63ab7dd2be3eb80fd1e9e5ece593157df96 Mon Sep 17 00:00:00 2001 From: Dmitry Shulyak Date: Fri, 24 May 2019 13:22:13 +0300 Subject: [PATCH] Unmarshall wrapped into string integers as string (#1470) --- services/typeddata/hash.go | 20 ++++++++++++++---- services/typeddata/hash_test.go | 37 +++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/services/typeddata/hash.go b/services/typeddata/hash.go index 43e2eb4b4..fe9b0f53e 100644 --- a/services/typeddata/hash.go +++ b/services/typeddata/hash.go @@ -17,6 +17,8 @@ import ( var ( bytes32Type, _ = abi.NewType("bytes32", nil) int256Type, _ = abi.NewType("int256", nil) + + errNotInteger = errors.New("not an integer") ) // ValidateAndHash generates a hash of TypedData and verifies that chainId in the typed data matches currently selected chain. @@ -171,11 +173,21 @@ func toFixedBytes(f Field, data json.RawMessage) (rst [32]byte, typ abi.Type, er } func toInt(f Field, data json.RawMessage) (val *big.Int, typ abi.Type, err error) { - var rst big.Int - if err = json.Unmarshal(data, &rst); err != nil { - return + val = new(big.Int) + if err = json.Unmarshal(data, &val); err != nil { + var buf string + err = json.Unmarshal(data, &buf) + if err != nil { + return + } + var ok bool + val, ok = val.SetString(buf, 0) + if !ok { + err = errNotInteger + return + } } - return &rst, int256Type, nil + return val, int256Type, nil } func toAddress(f Field, data json.RawMessage) (rst common.Address, err error) { diff --git a/services/typeddata/hash_test.go b/services/typeddata/hash_test.go index 525a20831..eedfb42a5 100644 --- a/services/typeddata/hash_test.go +++ b/services/typeddata/hash_test.go @@ -2,6 +2,7 @@ package typeddata import ( "encoding/json" + "fmt" "math/big" "testing" @@ -271,3 +272,39 @@ func TestEncodeDataErrors(t *testing.T) { }) } } + +func TestEncodeInt(t *testing.T) { + example := new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil) + for _, tc := range []struct { + description string + data []byte + expected *big.Int + err error + }{ + { + description: "AsString", + data: []byte(example.String()), + expected: example, + }, + { + description: "WrappedIntoString", + data: []byte(fmt.Sprintf("\"%s\"", example.String())), + expected: example, + }, + { + description: "NotAnInteger", + data: []byte("\"xzy\""), + err: errNotInteger, + }, + } { + t.Run(tc.description, func(t *testing.T) { + rst, _, err := toInt(Field{}, tc.data) + if tc.err == nil { + require.NoError(t, err) + require.Equal(t, tc.expected, rst) + } else { + require.EqualError(t, err, tc.err.Error()) + } + }) + } +}