signer: more hard types

This commit is contained in:
Martin Holst Swende 2018-12-06 14:08:47 +01:00
parent 7bbe49e8d0
commit 2f33a65abd
No known key found for this signature in database
GPG key ID: 683B438C05A5DDF0
2 changed files with 198 additions and 133 deletions

View file

@ -21,6 +21,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"github.com/ethereum/go-ethereum/common/math"
"math/big" "math/big"
"mime" "mime"
"reflect" "reflect"
@ -76,9 +77,30 @@ type TypedData struct {
Message TypedDataMessage `json:"message"` Message TypedDataMessage `json:"message"`
} }
type Type []map[string]string type Type struct {
Name string `json:"name"`
Type string `json:"type"`
}
type Types map[string]Type func (t *Type) isArray() bool {
return strings.HasSuffix(t.Type, "[]")
}
// typeName returns the canonical name of the type. If the type is 'Person[]', then
// this method returns 'Person'
func (t *Type) typeName() string {
if strings.HasSuffix(t.Type, "[]") {
return strings.TrimSuffix(t.Type, "[]")
}
return t.Type
}
func (t *Type) isReferenceType() bool {
// Reference types must have a leading uppercase characer
return unicode.IsUpper([]rune(t.Type)[0])
}
type Types map[string][]Type
type TypePriority struct { type TypePriority struct {
Type string Type string
@ -331,7 +353,7 @@ func (typedData *TypedData) Dependencies(primaryType string, found []string) []s
} }
found = append(found, primaryType) found = append(found, primaryType)
for _, field := range typedData.Types[primaryType] { for _, field := range typedData.Types[primaryType] {
for _, dep := range typedData.Dependencies(field["type"], found) { for _, dep := range typedData.Dependencies(field.Type, found) {
if !includes(found, dep) { if !includes(found, dep) {
found = append(found, dep) found = append(found, dep)
} }
@ -357,9 +379,9 @@ func (typedData *TypedData) EncodeType(primaryType string) hexutil.Bytes {
buffer.WriteString(dep) buffer.WriteString(dep)
buffer.WriteString("(") buffer.WriteString("(")
for _, obj := range typedData.Types[dep] { for _, obj := range typedData.Types[dep] {
buffer.WriteString(obj["type"]) buffer.WriteString(obj.Type)
buffer.WriteString(" ") buffer.WriteString(" ")
buffer.WriteString(obj["name"]) buffer.WriteString(obj.Name)
buffer.WriteString(",") buffer.WriteString(",")
} }
buffer.Truncate(buffer.Len() - 1) buffer.Truncate(buffer.Len() - 1)
@ -389,8 +411,8 @@ func (typedData *TypedData) EncodeData(primaryType string, data map[string]inter
// Add field contents. Structs and arrays have special handlers. // Add field contents. Structs and arrays have special handlers.
for _, field := range typedData.Types[primaryType] { for _, field := range typedData.Types[primaryType] {
encType := field["type"] encType := field.Type
encValue := data[field["name"]] encValue := data[field.Name]
if encType[len(encType)-1:] == "]" { if encType[len(encType)-1:] == "]" {
arrayValue, ok := encValue.([]interface{}) arrayValue, ok := encValue.([]interface{})
if !ok { if !ok {
@ -411,11 +433,7 @@ func (typedData *TypedData) EncodeData(primaryType string, data map[string]inter
} }
arrayBuffer.Write(encodedData) arrayBuffer.Write(encodedData)
} else { } else {
encValue, err := typedData.EncodePrimitiveValue(encType, encValue, depth) bytesValue, err := typedData.EncodePrimitiveValue(encType, encValue, depth)
if err != nil {
return nil, err
}
bytesValue, err := bytesValueOf(encValue)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -424,28 +442,22 @@ func (typedData *TypedData) EncodeData(primaryType string, data map[string]inter
} }
buffer.Write(crypto.Keccak256(arrayBuffer.Bytes())) buffer.Write(crypto.Keccak256(arrayBuffer.Bytes()))
} else if typedData.Types[field["type"]] != nil { } else if typedData.Types[field.Type] != nil {
mapValue, ok := encValue.(map[string]interface{}) mapValue, ok := encValue.(map[string]interface{})
if !ok { if !ok {
return nil, dataMismatchError(encType, encValue) return nil, dataMismatchError(encType, encValue)
} }
encodedData, err := typedData.EncodeData(field.Type, mapValue, depth+1)
encodedData, err := typedData.EncodeData(field["type"], mapValue, depth+1)
if err != nil { if err != nil {
return nil, err return nil, err
} }
buffer.Write(crypto.Keccak256(encodedData)) buffer.Write(crypto.Keccak256(encodedData))
} else { } else {
primitiveEncValue, err := typedData.EncodePrimitiveValue(encType, encValue, depth) byteValue, err := typedData.EncodePrimitiveValue(encType, encValue, depth)
if err != nil { if err != nil {
return nil, err return nil, err
} }
bytesValue, err := bytesValueOf(primitiveEncValue) buffer.Write(byteValue)
if err != nil {
return nil, err
}
buffer.Write(bytesValue)
} }
} }
return buffer.Bytes(), nil return buffer.Bytes(), nil
@ -453,64 +465,64 @@ func (typedData *TypedData) EncodeData(primaryType string, data map[string]inter
// EncodePrimitiveValue deals with the primitive values found // EncodePrimitiveValue deals with the primitive values found
// while searching through the typed data // while searching through the typed data
func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue interface{}, depth int) (interface{}, error) { func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue interface{}, depth int) ([]byte, error) {
var primitiveEncValue interface{}
switch encType { switch encType {
case "address": case "address":
bytesValue := hexutil.Bytes{}
for i := 0; i < 12; i++ {
bytesValue = append(bytesValue, 0)
}
stringValue, ok := encValue.(string) stringValue, ok := encValue.(string)
if !ok || !common.IsHexAddress(stringValue) { if !ok || !common.IsHexAddress(stringValue) {
return nil, dataMismatchError(encType, encValue) return nil, dataMismatchError(encType, encValue)
} }
addressValue := common.HexToAddress(stringValue) retval := make([]byte, 32)
for _, _byte := range addressValue { copy(retval[12:], common.HexToAddress(stringValue).Bytes())
bytesValue = append(bytesValue, _byte) return retval, nil
}
primitiveEncValue = bytesValue
case "bool": case "bool":
var int64Val int64
boolValue, ok := encValue.(bool) boolValue, ok := encValue.(bool)
if !ok { if !ok {
return nil, dataMismatchError(encType, encValue) return nil, dataMismatchError(encType, encValue)
} }
if boolValue { if boolValue {
int64Val = 1 return math.PaddedBigBytes(common.Big1, 32), nil
} }
primitiveEncValue = abi.U256(big.NewInt(int64Val)) return math.PaddedBigBytes(common.Big0, 32), nil
case "bytes", "string": case "string":
bytesValue, err := bytesValueOf(encValue) strVal, ok := encValue.(string)
if err != nil { if !ok {
return nil, dataMismatchError(encType, encValue) return nil, dataMismatchError(encType, encValue)
} }
primitiveEncValue = crypto.Keccak256(bytesValue) return crypto.Keccak256([]byte(strVal)), nil
default: case "bytes":
bytesValue, ok := encValue.([]byte)
if !ok {
return nil, dataMismatchError(encType, encValue)
}
return crypto.Keccak256(bytesValue), nil
}
// bytes32 etc
if strings.HasPrefix(encType, "bytes") { if strings.HasPrefix(encType, "bytes") {
sizeStr := strings.TrimPrefix(encType, "bytes") sizeStr := strings.TrimPrefix(encType, "bytes")
size, _ := strconv.Atoi(sizeStr) size, err := strconv.Atoi(sizeStr)
bytesValue := hexutil.Bytes{} if err != nil {
for i := 0; i < 32-size; i++ { return nil, fmt.Errorf("invalid size on bytes: %v", sizeStr)
bytesValue = append(bytesValue, 0)
} }
if _, ok := encValue.(hexutil.Bytes); !ok { if size < 0 || size > 32 {
return nil, fmt.Errorf("invalid size on bytes: %d", size)
}
if byteval, ok := encValue.(hexutil.Bytes); !ok {
return nil, dataMismatchError(encType, encValue) return nil, dataMismatchError(encType, encValue)
} else {
return math.PaddedBigBytes(new(big.Int).SetBytes(byteval), 32), nil
} }
bytesValue = append(bytesValue, encValue.(hexutil.Bytes)...) }
primitiveEncValue = bytesValue if strings.HasPrefix(encType, "uint") || strings.HasPrefix(encType, "int") {
} else if strings.HasPrefix(encType, "uint") || strings.HasPrefix(encType, "int") {
bigIntValue, ok := encValue.(*big.Int) bigIntValue, ok := encValue.(*big.Int)
if !ok { if !ok {
return nil, dataMismatchError(encType, encValue) return nil, dataMismatchError(encType, encValue)
} }
primitiveEncValue = abi.U256(bigIntValue) return abi.U256(bigIntValue), nil
} else { }
return nil, fmt.Errorf("unrecognized type '%s'", encType) return nil, fmt.Errorf("unrecognized type '%s'", encType)
}
}
return primitiveEncValue, nil
} }
// dataMismatchError generates an error for a mismatch between // dataMismatchError generates an error for a mismatch between
@ -519,29 +531,6 @@ func dataMismatchError(encType string, encValue interface{}) error {
return fmt.Errorf("provided data '%v' doesn't match type '%s'", encValue, encType) return fmt.Errorf("provided data '%v' doesn't match type '%s'", encValue, encType)
} }
// bytesValuesOf returns the bytes value of the given interface
func bytesValueOf(_interface interface{}) (hexutil.Bytes, error) {
bytesValue, ok := _interface.(hexutil.Bytes)
if ok {
return bytesValue, nil
}
switch reflect.TypeOf(_interface) {
case reflect.TypeOf(hexutil.Bytes{}):
return _interface.(hexutil.Bytes), nil
case reflect.TypeOf([]byte{}):
return hexutil.Bytes(_interface.([]byte)), nil
case reflect.TypeOf([]uint8{}):
return _interface.([]uint8), nil
case reflect.TypeOf(string("")):
return hexutil.Bytes(_interface.(string)), nil
default:
break
}
return nil, fmt.Errorf("unrecognized type '%T'", _interface)
}
// EcRecover recovers the address associated with the given sig. // EcRecover recovers the address associated with the given sig.
// Only compatible with `text/plain` // Only compatible with `text/plain`
func (api *SignerAPI) EcRecover(ctx context.Context, data hexutil.Bytes, sig hexutil.Bytes) (common.Address, error) { func (api *SignerAPI) EcRecover(ctx context.Context, data hexutil.Bytes, sig hexutil.Bytes) (common.Address, error) {
@ -660,32 +649,31 @@ func (typedData *TypedData) formatData(primaryType string, data map[string]inter
// Add field contents. Structs and arrays have special handlers. // Add field contents. Structs and arrays have special handlers.
for _, field := range typedData.Types[primaryType] { for _, field := range typedData.Types[primaryType] {
encType := field["type"] encName := field.Name
encName := field["name"]
encValue := data[encName] encValue := data[encName]
item := &NameValueType{ item := &NameValueType{
Name: encName, Name: encName,
Typ: encType, Typ: field.Type,
} }
if encType[len(encType)-1:] == "]" { if field.isArray() {
arrayValue, _ := encValue.([]interface{}) arrayValue, _ := encValue.([]interface{})
parsedType := strings.Split(encType, "[")[0] parsedType := field.typeName()
for _, v := range arrayValue { for _, v := range arrayValue {
if typedData.Types[parsedType] != nil { if typedData.Types[parsedType] != nil {
mapValue, _ := v.(map[string]interface{}) mapValue, _ := v.(map[string]interface{})
mapOutput := typedData.formatData(parsedType, mapValue) mapOutput := typedData.formatData(parsedType, mapValue)
item.Value = mapOutput item.Value = mapOutput
} else { } else {
primitiveOutput := formatPrimitiveValue(encType, encValue) primitiveOutput := formatPrimitiveValue(field.Type, encValue)
item.Value = primitiveOutput item.Value = primitiveOutput
} }
} }
} else if typedData.Types[field["type"]] != nil { } else if typedData.Types[field.Type] != nil {
mapValue, _ := encValue.(map[string]interface{}) mapValue, _ := encValue.(map[string]interface{})
mapOutput := typedData.formatData(field["type"], mapValue) mapOutput := typedData.formatData(field.Type, mapValue)
item.Value = mapOutput item.Value = mapOutput
} else { } else {
primitiveOutput := formatPrimitiveValue(encType, encValue) primitiveOutput := formatPrimitiveValue(field.Type, encValue)
item.Value = primitiveOutput item.Value = primitiveOutput
} }
output = append(output, item) output = append(output, item)
@ -739,30 +727,22 @@ func (nvt *NameValueType) Pprint(depth int) string {
} }
// Validate checks if the types object is conformant to the specs // Validate checks if the types object is conformant to the specs
func (types *Types) Validate() error { func (t Types) Validate() error {
for typeKey, typeArr := range *types { for typeKey, typeArr := range t {
for _, typeObj := range typeArr { for _, typeObj := range typeArr {
typeVal := typeObj["type"] if typeKey == typeObj.Type {
if typeKey == typeVal { return fmt.Errorf("type '%s' cannot reference itself", typeObj.Type)
return fmt.Errorf("type '%s' cannot reference itself", typeVal)
} }
firstChar := []rune(typeVal)[0] if typeObj.isReferenceType() {
if unicode.IsUpper(firstChar) { if _, exist := t[typeObj.Type]; !exist {
if (*types)[typeVal] != nil { return fmt.Errorf("reference type '%s' is undefined", typeObj.Type)
if !typedDataReferenceTypeRegexp.MatchString(typeVal) {
return fmt.Errorf("unknown reference type '%s", typeVal)
}
} else {
return fmt.Errorf("reference type '%s' is undefined", typeVal)
}
} else {
if !typedDataRegexp.MatchString(typeVal) {
if (*types)[typeVal] != nil {
return fmt.Errorf("reference type '%s' must be capitalized", typeVal)
} else {
return fmt.Errorf("unknown type '%s'", typeVal)
} }
if !typedDataReferenceTypeRegexp.MatchString(typeObj.Type) {
return fmt.Errorf("unknown reference type '%s", typeObj.Type)
} }
} else if !typedDataRegexp.MatchString(typeObj.Type) {
return fmt.Errorf("unknown type '%s'", typeObj.Type)
} }
} }
} }

View file

@ -31,44 +31,44 @@ import (
var typesStandard = Types{ var typesStandard = Types{
"EIP712Domain": { "EIP712Domain": {
{ {
"name": "name", Name: "name",
"type": "string", Type: "string",
}, },
{ {
"name": "version", Name: "version",
"type": "string", Type: "string",
}, },
{ {
"name": "chainId", Name: "chainId",
"type": "uint256", Type: "uint256",
}, },
{ {
"name": "verifyingContract", Name: "verifyingContract",
"type": "address", Type: "address",
}, },
}, },
"Person": { "Person": {
{ {
"name": "name", Name: "name",
"type": "string", Type: "string",
}, },
{ {
"name": "wallet", Name: "wallet",
"type": "address", Type: "address",
}, },
}, },
"Mail": { "Mail": {
{ {
"name": "from", Name: "from",
"type": "Person", Type: "Person",
}, },
{ {
"name": "to", Name: "to",
"type": "Person", Type: "Person",
}, },
{ {
"name": "contents", Name: "contents",
"type": "string", Type: "string",
}, },
}, },
} }
@ -461,7 +461,7 @@ func TestMalformedData2(t *testing.T) {
t.Errorf("Expected `provided data 'Hello, Bob!' doesn't match type 'Person'`, got %v", err) t.Errorf("Expected `provided data 'Hello, Bob!' doesn't match type 'Person'`, got %v", err)
} }
malformedTypedData.Types["Mail"][2]["type"] = "Blahonga" malformedTypedData.Types["Mail"][2].Type = "Blahonga"
err = malformedTypedData.Validate() err = malformedTypedData.Validate()
if err == nil || err.Error() != "reference type 'Blahonga' is undefined" { if err == nil || err.Error() != "reference type 'Blahonga' is undefined" {
t.Fatalf("Expected `reference type 'Blahonga' is undefined`, got %v", err) t.Fatalf("Expected `reference type 'Blahonga' is undefined`, got %v", err)
@ -559,7 +559,7 @@ func TestMalformedData3(t *testing.T) {
t.Fatalf("Expected `unknown type 'uint256 ... and now for something completely different'`, got %v", err) t.Fatalf("Expected `unknown type 'uint256 ... and now for something completely different'`, got %v", err)
} }
malformedTypedData.Types["EIP712Domain"][2]["type"] = "uint256" malformedTypedData.Types["EIP712Domain"][2].Type = "uint256"
malformedTypedData.Message["blahonga"] = "zonk bonk" malformedTypedData.Message["blahonga"] = "zonk bonk"
_, err = malformedTypedData.HashStruct(malformedTypedData.PrimaryType, malformedTypedData.Message) _, err = malformedTypedData.HashStruct(malformedTypedData.PrimaryType, malformedTypedData.Message)
if err == nil || err.Error() != "there is extra data provided in the message" { if err == nil || err.Error() != "there is extra data provided in the message" {
@ -628,3 +628,88 @@ func TestFormatter(t *testing.T) {
fmt.Printf("%v\n", string(j)) fmt.Printf("%v\n", string(j))
} }
func TestMalformedData5(t *testing.T) {
var jsonTypedData = `
{
"types": {
"EIP712Domain": [
{
"name": "name",
"type": "string"
},
{
"name": "version",
"type": "string"
},
{
"name": "chainId",
"type": "uint256"
},
{
"name": "verifyingContract",
"type": "address"
}
],
"Person": [
{
"name": "name",
"type": "string"
},
{
"name": "wallet",
"type": "address"
}
],
"Person[]": [
{
"name": "baz",
"type": "string"
}],
"Mail": [
{
"name": "from",
"type": "Person"
},
{
"name": "to",
"type": "Person[]"
},
{
"name": "contents",
"type": "string"
}
]
},
"primaryType": "Mail",
"domain": {
"name": "Ether Mail",
"version": "1",
"chainId": 1,
"verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"
},
"message": {
"from": {
"name": "Cow",
"wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"
},
"to": {"baz": "foo"},
"contents": "Hello, Bob!"
}
}
`
var malformedTypedData TypedData
err := json.Unmarshal([]byte(jsonTypedData), &malformedTypedData)
if err != nil {
t.Fatalf("unmarshalling failed %v", err)
}
err = malformedTypedData.Validate()
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
_, err = malformedTypedData.HashStruct("EIP712Domain", malformedTypedData.Domain.Map())
if err == nil {
t.Errorf("Expected an error, got %v", err)
}
}