Dmitry Shulyak db786ef1d2
Sign typed data implementation (#1250)
* Implement EIP 712

* Cover majority of cases with tests

* Add solidity and signer tests and cover integer edges case

* Add thin api to sign type data using selected status account

* All integers are extended to int256 and marshalled into big.Int

* Document how deps works

* Fix linter

* Fix errors test

* Add validation tests

* Unmarshal every atomic type in separate functions
2018-11-06 07:26:12 +01:00

44 lines
1.1 KiB
Go

package typeddata
import (
"crypto/ecdsa"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
)
var (
// x19 to avoid collision with rlp encode. x01 version byte defined in EIP-191
messagePadding = []byte{0x19, 0x01}
)
func encodeData(typed TypedData) (rst common.Hash, err error) {
domainSeparator, err := hashStruct(eip712Domain, typed.Domain, typed.Types)
if err != nil {
return rst, err
}
primary, err := hashStruct(typed.PrimaryType, typed.Message, typed.Types)
if err != nil {
return rst, err
}
return crypto.Keccak256Hash(messagePadding, domainSeparator[:], primary[:]), nil
}
// Sign TypedData with a given private key. Verify that chainId in the typed data matches currently selected chain.
func Sign(typed TypedData, prv *ecdsa.PrivateKey, chain *big.Int) ([]byte, error) {
if err := typed.ValidateChainID(chain); err != nil {
return nil, err
}
hash, err := encodeData(typed)
if err != nil {
return nil, err
}
sig, err := crypto.Sign(hash[:], prv)
if err != nil {
return nil, err
}
sig[64] += 27
return sig, nil
}