Unmarshall wrapped into string integers as string (#1470)

This commit is contained in:
Dmitry Shulyak 2019-05-24 13:22:13 +03:00 committed by GitHub
parent d32cd18c09
commit 4cafe63ab7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 53 additions and 4 deletions

View File

@ -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 {
val = new(big.Int)
if err = json.Unmarshal(data, &val); err != nil {
var buf string
err = json.Unmarshal(data, &buf)
if err != nil {
return
}
return &rst, int256Type, nil
var ok bool
val, ok = val.SetString(buf, 0)
if !ok {
err = errNotInteger
return
}
}
return val, int256Type, nil
}
func toAddress(f Field, data json.RawMessage) (rst common.Address, err error) {

View File

@ -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())
}
})
}
}