signed_data.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. //
  17. package core
  18. import (
  19. "bytes"
  20. "context"
  21. "errors"
  22. "fmt"
  23. "math/big"
  24. "mime"
  25. "regexp"
  26. "sort"
  27. "strconv"
  28. "strings"
  29. "unicode"
  30. "github.com/ethereum/go-ethereum/accounts"
  31. "github.com/ethereum/go-ethereum/accounts/abi"
  32. "github.com/ethereum/go-ethereum/common"
  33. "github.com/ethereum/go-ethereum/common/hexutil"
  34. "github.com/ethereum/go-ethereum/common/math"
  35. "github.com/ethereum/go-ethereum/consensus/clique"
  36. "github.com/ethereum/go-ethereum/core/types"
  37. "github.com/ethereum/go-ethereum/crypto"
  38. "github.com/ethereum/go-ethereum/rlp"
  39. )
  40. type SigFormat struct {
  41. Mime string
  42. ByteVersion byte
  43. }
  44. var (
  45. TextValidator = SigFormat{
  46. accounts.MimetypeTextWithValidator,
  47. 0x00,
  48. }
  49. DataTyped = SigFormat{
  50. accounts.MimetypeTypedData,
  51. 0x01,
  52. }
  53. ApplicationClique = SigFormat{
  54. accounts.MimetypeClique,
  55. 0x02,
  56. }
  57. TextPlain = SigFormat{
  58. accounts.MimetypeTextPlain,
  59. 0x45,
  60. }
  61. )
  62. type ValidatorData struct {
  63. Address common.Address
  64. Message hexutil.Bytes
  65. }
  66. type TypedData struct {
  67. Types Types `json:"types"`
  68. PrimaryType string `json:"primaryType"`
  69. Domain TypedDataDomain `json:"domain"`
  70. Message TypedDataMessage `json:"message"`
  71. }
  72. type Type struct {
  73. Name string `json:"name"`
  74. Type string `json:"type"`
  75. }
  76. func (t *Type) isArray() bool {
  77. return strings.HasSuffix(t.Type, "[]")
  78. }
  79. // typeName returns the canonical name of the type. If the type is 'Person[]', then
  80. // this method returns 'Person'
  81. func (t *Type) typeName() string {
  82. if strings.HasSuffix(t.Type, "[]") {
  83. return strings.TrimSuffix(t.Type, "[]")
  84. }
  85. return t.Type
  86. }
  87. func (t *Type) isReferenceType() bool {
  88. // Reference types must have a leading uppercase characer
  89. return unicode.IsUpper([]rune(t.Type)[0])
  90. }
  91. type Types map[string][]Type
  92. type TypePriority struct {
  93. Type string
  94. Value uint
  95. }
  96. type TypedDataMessage = map[string]interface{}
  97. type TypedDataDomain struct {
  98. Name string `json:"name"`
  99. Version string `json:"version"`
  100. ChainId *big.Int `json:"chainId"`
  101. VerifyingContract string `json:"verifyingContract"`
  102. Salt string `json:"salt"`
  103. }
  104. var typedDataReferenceTypeRegexp = regexp.MustCompile(`^[A-Z](\w*)(\[\])?$`)
  105. // sign receives a request and produces a signature
  106. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  107. // where the V value will be 27 or 28 for legacy reasons.
  108. func (api *SignerAPI) sign(addr common.MixedcaseAddress, req *SignDataRequest) (hexutil.Bytes, error) {
  109. // We make the request prior to looking up if we actually have the account, to prevent
  110. // account-enumeration via the API
  111. res, err := api.UI.ApproveSignData(req)
  112. if err != nil {
  113. return nil, err
  114. }
  115. if !res.Approved {
  116. return nil, ErrRequestDenied
  117. }
  118. // Look up the wallet containing the requested signer
  119. account := accounts.Account{Address: addr.Address()}
  120. wallet, err := api.am.Find(account)
  121. if err != nil {
  122. return nil, err
  123. }
  124. // Sign the data with the wallet
  125. signature, err := wallet.SignDataWithPassphrase(account, res.Password, req.ContentType, req.Hash)
  126. if err != nil {
  127. return nil, err
  128. }
  129. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  130. return signature, nil
  131. }
  132. // SignData signs the hash of the provided data, but does so differently
  133. // depending on the content-type specified.
  134. //
  135. // Different types of validation occur.
  136. func (api *SignerAPI) SignData(ctx context.Context, contentType string, addr common.MixedcaseAddress, data interface{}) (hexutil.Bytes, error) {
  137. var req, err = api.determineSignatureFormat(ctx, contentType, addr, data)
  138. if err != nil {
  139. return nil, err
  140. }
  141. signature, err := api.sign(addr, req)
  142. if err != nil {
  143. api.UI.ShowError(err.Error())
  144. return nil, err
  145. }
  146. return signature, nil
  147. }
  148. // determineSignatureFormat determines which signature method should be used based upon the mime type
  149. // In the cases where it matters ensure that the charset is handled. The charset
  150. // resides in the 'params' returned as the second returnvalue from mime.ParseMediaType
  151. // charset, ok := params["charset"]
  152. // As it is now, we accept any charset and just treat it as 'raw'.
  153. // This method returns the mimetype for signing along with the request
  154. func (api *SignerAPI) determineSignatureFormat(ctx context.Context, contentType string, addr common.MixedcaseAddress, data interface{}) (*SignDataRequest, error) {
  155. var req *SignDataRequest
  156. mediaType, _, err := mime.ParseMediaType(contentType)
  157. if err != nil {
  158. return nil, err
  159. }
  160. switch mediaType {
  161. case TextValidator.Mime:
  162. // Data with an intended validator
  163. validatorData, err := UnmarshalValidatorData(data)
  164. if err != nil {
  165. return nil, err
  166. }
  167. sighash, msg := SignTextValidator(validatorData)
  168. message := []*NameValueType{
  169. {
  170. Name: "message",
  171. Typ: "text",
  172. Value: msg,
  173. },
  174. }
  175. req = &SignDataRequest{ContentType: mediaType, Rawdata: []byte(msg), Message: message, Hash: sighash}
  176. case ApplicationClique.Mime:
  177. // Clique is the Ethereum PoA standard
  178. stringData, ok := data.(string)
  179. if !ok {
  180. return nil, fmt.Errorf("input for %v plain must be an hex-encoded string", ApplicationClique.Mime)
  181. }
  182. cliqueData, err := hexutil.Decode(stringData)
  183. if err != nil {
  184. return nil, err
  185. }
  186. header := &types.Header{}
  187. if err := rlp.DecodeBytes(cliqueData, header); err != nil {
  188. return nil, err
  189. }
  190. // Get back the rlp data, encoded by us
  191. cliqueData = clique.CliqueRLP(header)
  192. sighash, err := SignCliqueHeader(header)
  193. if err != nil {
  194. return nil, err
  195. }
  196. message := []*NameValueType{
  197. {
  198. Name: "Clique block",
  199. Typ: "clique",
  200. Value: fmt.Sprintf("clique block %d [0x%x]", header.Number, header.Hash()),
  201. },
  202. }
  203. req = &SignDataRequest{ContentType: mediaType, Rawdata: cliqueData, Message: message, Hash: sighash}
  204. default: // also case TextPlain.Mime:
  205. // Calculates an Ethereum ECDSA signature for:
  206. // hash = keccak256("\x19${byteVersion}Ethereum Signed Message:\n${message length}${message}")
  207. // We expect it to be a string
  208. stringData, ok := data.(string)
  209. if !ok {
  210. return nil, fmt.Errorf("input for text/plain must be a string")
  211. }
  212. //plainData, err := hexutil.Decode(stringdata)
  213. //if err != nil {
  214. // return nil, err
  215. //}
  216. sighash, msg := accounts.TextAndHash([]byte(stringData))
  217. message := []*NameValueType{
  218. {
  219. Name: "message",
  220. Typ: "text/plain",
  221. Value: msg,
  222. },
  223. }
  224. req = &SignDataRequest{ContentType: mediaType, Rawdata: []byte(msg), Message: message, Hash: sighash}
  225. }
  226. req.Address = addr
  227. req.Meta = MetadataFromContext(ctx)
  228. return req, nil
  229. }
  230. // SignTextWithValidator signs the given message which can be further recovered
  231. // with the given validator.
  232. // hash = keccak256("\x19\x00"${address}${data}).
  233. func SignTextValidator(validatorData ValidatorData) (hexutil.Bytes, string) {
  234. msg := fmt.Sprintf("\x19\x00%s%s", string(validatorData.Address.Bytes()), string(validatorData.Message))
  235. fmt.Printf("SignTextValidator:%s\n", msg)
  236. return crypto.Keccak256([]byte(msg)), msg
  237. }
  238. // SignCliqueHeader returns the hash which is used as input for the proof-of-authority
  239. // signing. It is the hash of the entire header apart from the 65 byte signature
  240. // contained at the end of the extra data.
  241. //
  242. // The method requires the extra data to be at least 65 bytes -- the original implementation
  243. // in clique.go panics if this is the case, thus it's been reimplemented here to avoid the panic
  244. // and simply return an error instead
  245. func SignCliqueHeader(header *types.Header) (hexutil.Bytes, error) {
  246. //hash := common.Hash{}
  247. if len(header.Extra) < 65 {
  248. return nil, fmt.Errorf("clique header extradata too short, %d < 65", len(header.Extra))
  249. }
  250. hash := clique.SealHash(header)
  251. return hash.Bytes(), nil
  252. }
  253. // SignTypedData signs EIP-712 conformant typed data
  254. // hash = keccak256("\x19${byteVersion}${domainSeparator}${hashStruct(message)}")
  255. func (api *SignerAPI) SignTypedData(ctx context.Context, addr common.MixedcaseAddress, typedData TypedData) (hexutil.Bytes, error) {
  256. domainSeparator, err := typedData.HashStruct("EIP712Domain", typedData.Domain.Map())
  257. if err != nil {
  258. return nil, err
  259. }
  260. typedDataHash, err := typedData.HashStruct(typedData.PrimaryType, typedData.Message)
  261. if err != nil {
  262. return nil, err
  263. }
  264. rawData := []byte(fmt.Sprintf("\x19\x01%s%s", string(domainSeparator), string(typedDataHash)))
  265. sighash := crypto.Keccak256(rawData)
  266. message := typedData.Format()
  267. req := &SignDataRequest{ContentType: DataTyped.Mime, Rawdata: rawData, Message: message, Hash: sighash}
  268. signature, err := api.sign(addr, req)
  269. if err != nil {
  270. api.UI.ShowError(err.Error())
  271. return nil, err
  272. }
  273. return signature, nil
  274. }
  275. // HashStruct generates a keccak256 hash of the encoding of the provided data
  276. func (typedData *TypedData) HashStruct(primaryType string, data TypedDataMessage) (hexutil.Bytes, error) {
  277. encodedData, err := typedData.EncodeData(primaryType, data, 1)
  278. if err != nil {
  279. return nil, err
  280. }
  281. return crypto.Keccak256(encodedData), nil
  282. }
  283. // Dependencies returns an array of custom types ordered by their hierarchical reference tree
  284. func (typedData *TypedData) Dependencies(primaryType string, found []string) []string {
  285. includes := func(arr []string, str string) bool {
  286. for _, obj := range arr {
  287. if obj == str {
  288. return true
  289. }
  290. }
  291. return false
  292. }
  293. if includes(found, primaryType) {
  294. return found
  295. }
  296. if typedData.Types[primaryType] == nil {
  297. return found
  298. }
  299. found = append(found, primaryType)
  300. for _, field := range typedData.Types[primaryType] {
  301. for _, dep := range typedData.Dependencies(field.Type, found) {
  302. if !includes(found, dep) {
  303. found = append(found, dep)
  304. }
  305. }
  306. }
  307. return found
  308. }
  309. // EncodeType generates the following encoding:
  310. // `name ‖ "(" ‖ member₁ ‖ "," ‖ member₂ ‖ "," ‖ … ‖ memberₙ ")"`
  311. //
  312. // each member is written as `type ‖ " " ‖ name` encodings cascade down and are sorted by name
  313. func (typedData *TypedData) EncodeType(primaryType string) hexutil.Bytes {
  314. // Get dependencies primary first, then alphabetical
  315. deps := typedData.Dependencies(primaryType, []string{})
  316. slicedDeps := deps[1:]
  317. sort.Strings(slicedDeps)
  318. deps = append([]string{primaryType}, slicedDeps...)
  319. // Format as a string with fields
  320. var buffer bytes.Buffer
  321. for _, dep := range deps {
  322. buffer.WriteString(dep)
  323. buffer.WriteString("(")
  324. for _, obj := range typedData.Types[dep] {
  325. buffer.WriteString(obj.Type)
  326. buffer.WriteString(" ")
  327. buffer.WriteString(obj.Name)
  328. buffer.WriteString(",")
  329. }
  330. buffer.Truncate(buffer.Len() - 1)
  331. buffer.WriteString(")")
  332. }
  333. return buffer.Bytes()
  334. }
  335. // TypeHash creates the keccak256 hash of the data
  336. func (typedData *TypedData) TypeHash(primaryType string) hexutil.Bytes {
  337. return crypto.Keccak256(typedData.EncodeType(primaryType))
  338. }
  339. // EncodeData generates the following encoding:
  340. // `enc(value₁) ‖ enc(value₂) ‖ … ‖ enc(valueₙ)`
  341. //
  342. // each encoded member is 32-byte long
  343. func (typedData *TypedData) EncodeData(primaryType string, data map[string]interface{}, depth int) (hexutil.Bytes, error) {
  344. if err := typedData.validate(); err != nil {
  345. return nil, err
  346. }
  347. buffer := bytes.Buffer{}
  348. // Verify extra data
  349. if len(typedData.Types[primaryType]) < len(data) {
  350. return nil, errors.New("there is extra data provided in the message")
  351. }
  352. // Add typehash
  353. buffer.Write(typedData.TypeHash(primaryType))
  354. // Add field contents. Structs and arrays have special handlers.
  355. for _, field := range typedData.Types[primaryType] {
  356. encType := field.Type
  357. encValue := data[field.Name]
  358. if encType[len(encType)-1:] == "]" {
  359. arrayValue, ok := encValue.([]interface{})
  360. if !ok {
  361. return nil, dataMismatchError(encType, encValue)
  362. }
  363. arrayBuffer := bytes.Buffer{}
  364. parsedType := strings.Split(encType, "[")[0]
  365. for _, item := range arrayValue {
  366. if typedData.Types[parsedType] != nil {
  367. mapValue, ok := item.(map[string]interface{})
  368. if !ok {
  369. return nil, dataMismatchError(parsedType, item)
  370. }
  371. encodedData, err := typedData.EncodeData(parsedType, mapValue, depth+1)
  372. if err != nil {
  373. return nil, err
  374. }
  375. arrayBuffer.Write(encodedData)
  376. } else {
  377. bytesValue, err := typedData.EncodePrimitiveValue(parsedType, item, depth)
  378. if err != nil {
  379. return nil, err
  380. }
  381. arrayBuffer.Write(bytesValue)
  382. }
  383. }
  384. buffer.Write(crypto.Keccak256(arrayBuffer.Bytes()))
  385. } else if typedData.Types[field.Type] != nil {
  386. mapValue, ok := encValue.(map[string]interface{})
  387. if !ok {
  388. return nil, dataMismatchError(encType, encValue)
  389. }
  390. encodedData, err := typedData.EncodeData(field.Type, mapValue, depth+1)
  391. if err != nil {
  392. return nil, err
  393. }
  394. buffer.Write(crypto.Keccak256(encodedData))
  395. } else {
  396. byteValue, err := typedData.EncodePrimitiveValue(encType, encValue, depth)
  397. if err != nil {
  398. return nil, err
  399. }
  400. buffer.Write(byteValue)
  401. }
  402. }
  403. return buffer.Bytes(), nil
  404. }
  405. // EncodePrimitiveValue deals with the primitive values found
  406. // while searching through the typed data
  407. func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue interface{}, depth int) ([]byte, error) {
  408. switch encType {
  409. case "address":
  410. stringValue, ok := encValue.(string)
  411. if !ok || !common.IsHexAddress(stringValue) {
  412. return nil, dataMismatchError(encType, encValue)
  413. }
  414. retval := make([]byte, 32)
  415. copy(retval[12:], common.HexToAddress(stringValue).Bytes())
  416. return retval, nil
  417. case "bool":
  418. boolValue, ok := encValue.(bool)
  419. if !ok {
  420. return nil, dataMismatchError(encType, encValue)
  421. }
  422. if boolValue {
  423. return math.PaddedBigBytes(common.Big1, 32), nil
  424. }
  425. return math.PaddedBigBytes(common.Big0, 32), nil
  426. case "string":
  427. strVal, ok := encValue.(string)
  428. if !ok {
  429. return nil, dataMismatchError(encType, encValue)
  430. }
  431. return crypto.Keccak256([]byte(strVal)), nil
  432. case "bytes":
  433. bytesValue, ok := encValue.([]byte)
  434. if !ok {
  435. return nil, dataMismatchError(encType, encValue)
  436. }
  437. return crypto.Keccak256(bytesValue), nil
  438. }
  439. if strings.HasPrefix(encType, "bytes") {
  440. lengthStr := strings.TrimPrefix(encType, "bytes")
  441. length, err := strconv.Atoi(lengthStr)
  442. if err != nil {
  443. return nil, fmt.Errorf("invalid size on bytes: %v", lengthStr)
  444. }
  445. if length < 0 || length > 32 {
  446. return nil, fmt.Errorf("invalid size on bytes: %d", length)
  447. }
  448. if byteValue, ok := encValue.(hexutil.Bytes); !ok {
  449. return nil, dataMismatchError(encType, encValue)
  450. } else {
  451. return math.PaddedBigBytes(new(big.Int).SetBytes(byteValue), 32), nil
  452. }
  453. }
  454. if strings.HasPrefix(encType, "int") || strings.HasPrefix(encType, "uint") {
  455. length := 0
  456. if encType == "int" || encType == "uint" {
  457. length = 256
  458. } else {
  459. lengthStr := ""
  460. if strings.HasPrefix(encType, "uint") {
  461. lengthStr = strings.TrimPrefix(encType, "uint")
  462. } else {
  463. lengthStr = strings.TrimPrefix(encType, "int")
  464. }
  465. atoiSize, err := strconv.Atoi(lengthStr)
  466. if err != nil {
  467. return nil, fmt.Errorf("invalid size on integer: %v", lengthStr)
  468. }
  469. length = atoiSize
  470. }
  471. bigIntValue, ok := encValue.(*big.Int)
  472. if bigIntValue.BitLen() > length {
  473. return nil, fmt.Errorf("integer larger than '%v'", encType)
  474. }
  475. if !ok {
  476. return nil, dataMismatchError(encType, encValue)
  477. }
  478. return abi.U256(bigIntValue), nil
  479. }
  480. return nil, fmt.Errorf("unrecognized type '%s'", encType)
  481. }
  482. // dataMismatchError generates an error for a mismatch between
  483. // the provided type and data
  484. func dataMismatchError(encType string, encValue interface{}) error {
  485. return fmt.Errorf("provided data '%v' doesn't match type '%s'", encValue, encType)
  486. }
  487. // EcRecover recovers the address associated with the given sig.
  488. // Only compatible with `text/plain`
  489. func (api *SignerAPI) EcRecover(ctx context.Context, data hexutil.Bytes, sig hexutil.Bytes) (common.Address, error) {
  490. // Returns the address for the Account that was used to create the signature.
  491. //
  492. // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
  493. // the address of:
  494. // hash = keccak256("\x19${byteVersion}Ethereum Signed Message:\n${message length}${message}")
  495. // addr = ecrecover(hash, signature)
  496. //
  497. // Note, the signature must conform to the secp256k1 curve R, S and V values, where
  498. // the V value must be be 27 or 28 for legacy reasons.
  499. //
  500. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
  501. if len(sig) != 65 {
  502. return common.Address{}, fmt.Errorf("signature must be 65 bytes long")
  503. }
  504. if sig[64] != 27 && sig[64] != 28 {
  505. return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
  506. }
  507. sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1
  508. hash := accounts.TextHash(data)
  509. rpk, err := crypto.SigToPub(hash, sig)
  510. if err != nil {
  511. return common.Address{}, err
  512. }
  513. return crypto.PubkeyToAddress(*rpk), nil
  514. }
  515. // UnmarshalValidatorData converts the bytes input to typed data
  516. func UnmarshalValidatorData(data interface{}) (ValidatorData, error) {
  517. raw, ok := data.(map[string]interface{})
  518. if !ok {
  519. return ValidatorData{}, errors.New("validator input is not a map[string]interface{}")
  520. }
  521. addr, ok := raw["address"].(string)
  522. if !ok {
  523. return ValidatorData{}, errors.New("validator address is not sent as a string")
  524. }
  525. addrBytes, err := hexutil.Decode(addr)
  526. if err != nil {
  527. return ValidatorData{}, err
  528. }
  529. if !ok || len(addrBytes) == 0 {
  530. return ValidatorData{}, errors.New("validator address is undefined")
  531. }
  532. message, ok := raw["message"].(string)
  533. if !ok {
  534. return ValidatorData{}, errors.New("message is not sent as a string")
  535. }
  536. messageBytes, err := hexutil.Decode(message)
  537. if err != nil {
  538. return ValidatorData{}, err
  539. }
  540. if !ok || len(messageBytes) == 0 {
  541. return ValidatorData{}, errors.New("message is undefined")
  542. }
  543. return ValidatorData{
  544. Address: common.BytesToAddress(addrBytes),
  545. Message: messageBytes,
  546. }, nil
  547. }
  548. // validate makes sure the types are sound
  549. func (typedData *TypedData) validate() error {
  550. if err := typedData.Types.validate(); err != nil {
  551. return err
  552. }
  553. if err := typedData.Domain.validate(); err != nil {
  554. return err
  555. }
  556. return nil
  557. }
  558. // Map generates a map version of the typed data
  559. func (typedData *TypedData) Map() map[string]interface{} {
  560. dataMap := map[string]interface{}{
  561. "types": typedData.Types,
  562. "domain": typedData.Domain.Map(),
  563. "primaryType": typedData.PrimaryType,
  564. "message": typedData.Message,
  565. }
  566. return dataMap
  567. }
  568. // PrettyPrint generates a nice output to help the users
  569. // of clef present data in their apps
  570. func (typedData *TypedData) PrettyPrint() string {
  571. output := bytes.Buffer{}
  572. formatted := typedData.Format()
  573. for _, item := range formatted {
  574. output.WriteString(fmt.Sprintf("%v\n", item.Pprint(0)))
  575. }
  576. return output.String()
  577. }
  578. // Format returns a representation of typedData, which can be easily displayed by a user-interface
  579. // without in-depth knowledge about 712 rules
  580. func (typedData *TypedData) Format() []*NameValueType {
  581. var nvts []*NameValueType
  582. nvts = append(nvts, &NameValueType{
  583. Name: "EIP712Domain",
  584. Value: typedData.formatData("EIP712Domain", typedData.Domain.Map()),
  585. Typ: "domain",
  586. })
  587. nvts = append(nvts, &NameValueType{
  588. Name: typedData.PrimaryType,
  589. Value: typedData.formatData(typedData.PrimaryType, typedData.Message),
  590. Typ: "primary type",
  591. })
  592. return nvts
  593. }
  594. func (typedData *TypedData) formatData(primaryType string, data map[string]interface{}) []*NameValueType {
  595. var output []*NameValueType
  596. // Add field contents. Structs and arrays have special handlers.
  597. for _, field := range typedData.Types[primaryType] {
  598. encName := field.Name
  599. encValue := data[encName]
  600. item := &NameValueType{
  601. Name: encName,
  602. Typ: field.Type,
  603. }
  604. if field.isArray() {
  605. arrayValue, _ := encValue.([]interface{})
  606. parsedType := field.typeName()
  607. for _, v := range arrayValue {
  608. if typedData.Types[parsedType] != nil {
  609. mapValue, _ := v.(map[string]interface{})
  610. mapOutput := typedData.formatData(parsedType, mapValue)
  611. item.Value = mapOutput
  612. } else {
  613. primitiveOutput := formatPrimitiveValue(field.Type, encValue)
  614. item.Value = primitiveOutput
  615. }
  616. }
  617. } else if typedData.Types[field.Type] != nil {
  618. mapValue, _ := encValue.(map[string]interface{})
  619. mapOutput := typedData.formatData(field.Type, mapValue)
  620. item.Value = mapOutput
  621. } else {
  622. primitiveOutput := formatPrimitiveValue(field.Type, encValue)
  623. item.Value = primitiveOutput
  624. }
  625. output = append(output, item)
  626. }
  627. return output
  628. }
  629. func formatPrimitiveValue(encType string, encValue interface{}) string {
  630. switch encType {
  631. case "address":
  632. stringValue, _ := encValue.(string)
  633. return common.HexToAddress(stringValue).String()
  634. case "bool":
  635. boolValue, _ := encValue.(bool)
  636. return fmt.Sprintf("%t", boolValue)
  637. case "bytes", "string":
  638. return fmt.Sprintf("%s", encValue)
  639. }
  640. if strings.HasPrefix(encType, "bytes") {
  641. return fmt.Sprintf("%s", encValue)
  642. } else if strings.HasPrefix(encType, "uint") || strings.HasPrefix(encType, "int") {
  643. bigIntValue, _ := encValue.(*big.Int)
  644. return fmt.Sprintf("%d (0x%x)", bigIntValue, bigIntValue)
  645. }
  646. return "NA"
  647. }
  648. // NameValueType is a very simple struct with Name, Value and Type. It's meant for simple
  649. // json structures used to communicate signing-info about typed data with the UI
  650. type NameValueType struct {
  651. Name string `json:"name"`
  652. Value interface{} `json:"value"`
  653. Typ string `json:"type"`
  654. }
  655. // Pprint returns a pretty-printed version of nvt
  656. func (nvt *NameValueType) Pprint(depth int) string {
  657. output := bytes.Buffer{}
  658. output.WriteString(strings.Repeat("\u00a0", depth*2))
  659. output.WriteString(fmt.Sprintf("%s [%s]: ", nvt.Name, nvt.Typ))
  660. if nvts, ok := nvt.Value.([]*NameValueType); ok {
  661. output.WriteString("\n")
  662. for _, next := range nvts {
  663. sublevel := next.Pprint(depth + 1)
  664. output.WriteString(sublevel)
  665. }
  666. } else {
  667. output.WriteString(fmt.Sprintf("%s\n", nvt.Value))
  668. }
  669. return output.String()
  670. }
  671. // Validate checks if the types object is conformant to the specs
  672. func (t Types) validate() error {
  673. for typeKey, typeArr := range t {
  674. for _, typeObj := range typeArr {
  675. if typeKey == typeObj.Type {
  676. return fmt.Errorf("type '%s' cannot reference itself", typeObj.Type)
  677. }
  678. if typeObj.isReferenceType() {
  679. if _, exist := t[typeObj.Type]; !exist {
  680. return fmt.Errorf("reference type '%s' is undefined", typeObj.Type)
  681. }
  682. if !typedDataReferenceTypeRegexp.MatchString(typeObj.Type) {
  683. return fmt.Errorf("unknown reference type '%s", typeObj.Type)
  684. }
  685. } else if !isPrimitiveTypeValid(typeObj.Type) {
  686. return fmt.Errorf("unknown type '%s'", typeObj.Type)
  687. }
  688. }
  689. }
  690. return nil
  691. }
  692. // Checks if the primitive value is valid
  693. func isPrimitiveTypeValid(primitiveType string) bool {
  694. if primitiveType == "address" ||
  695. primitiveType == "address[]" ||
  696. primitiveType == "bool" ||
  697. primitiveType == "bool[]" ||
  698. primitiveType == "string" ||
  699. primitiveType == "string[]" {
  700. return true
  701. }
  702. if primitiveType == "bytes" ||
  703. primitiveType == "bytes[]" ||
  704. primitiveType == "bytes1" ||
  705. primitiveType == "bytes1[]" ||
  706. primitiveType == "bytes2" ||
  707. primitiveType == "bytes2[]" ||
  708. primitiveType == "bytes3" ||
  709. primitiveType == "bytes3[]" ||
  710. primitiveType == "bytes4" ||
  711. primitiveType == "bytes4[]" ||
  712. primitiveType == "bytes5" ||
  713. primitiveType == "bytes5[]" ||
  714. primitiveType == "bytes6" ||
  715. primitiveType == "bytes6[]" ||
  716. primitiveType == "bytes7" ||
  717. primitiveType == "bytes7[]" ||
  718. primitiveType == "bytes8" ||
  719. primitiveType == "bytes8[]" ||
  720. primitiveType == "bytes9" ||
  721. primitiveType == "bytes9[]" ||
  722. primitiveType == "bytes10" ||
  723. primitiveType == "bytes10[]" ||
  724. primitiveType == "bytes11" ||
  725. primitiveType == "bytes11[]" ||
  726. primitiveType == "bytes12" ||
  727. primitiveType == "bytes12[]" ||
  728. primitiveType == "bytes13" ||
  729. primitiveType == "bytes13[]" ||
  730. primitiveType == "bytes14" ||
  731. primitiveType == "bytes14[]" ||
  732. primitiveType == "bytes15" ||
  733. primitiveType == "bytes15[]" ||
  734. primitiveType == "bytes16" ||
  735. primitiveType == "bytes16[]" ||
  736. primitiveType == "bytes17" ||
  737. primitiveType == "bytes17[]" ||
  738. primitiveType == "bytes18" ||
  739. primitiveType == "bytes18[]" ||
  740. primitiveType == "bytes19" ||
  741. primitiveType == "bytes19[]" ||
  742. primitiveType == "bytes20" ||
  743. primitiveType == "bytes20[]" ||
  744. primitiveType == "bytes21" ||
  745. primitiveType == "bytes21[]" ||
  746. primitiveType == "bytes22" ||
  747. primitiveType == "bytes22[]" ||
  748. primitiveType == "bytes23" ||
  749. primitiveType == "bytes23[]" ||
  750. primitiveType == "bytes24" ||
  751. primitiveType == "bytes24[]" ||
  752. primitiveType == "bytes25" ||
  753. primitiveType == "bytes25[]" ||
  754. primitiveType == "bytes26" ||
  755. primitiveType == "bytes26[]" ||
  756. primitiveType == "bytes27" ||
  757. primitiveType == "bytes27[]" ||
  758. primitiveType == "bytes28" ||
  759. primitiveType == "bytes28[]" ||
  760. primitiveType == "bytes29" ||
  761. primitiveType == "bytes29[]" ||
  762. primitiveType == "bytes30" ||
  763. primitiveType == "bytes30[]" ||
  764. primitiveType == "bytes31" ||
  765. primitiveType == "bytes31[]" {
  766. return true
  767. }
  768. if primitiveType == "int" ||
  769. primitiveType == "int[]" ||
  770. primitiveType == "int8" ||
  771. primitiveType == "int8[]" ||
  772. primitiveType == "int16" ||
  773. primitiveType == "int16[]" ||
  774. primitiveType == "int32" ||
  775. primitiveType == "int32[]" ||
  776. primitiveType == "int64" ||
  777. primitiveType == "int64[]" ||
  778. primitiveType == "int128" ||
  779. primitiveType == "int128[]" ||
  780. primitiveType == "int256" ||
  781. primitiveType == "int256[]" {
  782. return true
  783. }
  784. if primitiveType == "uint" ||
  785. primitiveType == "uint[]" ||
  786. primitiveType == "uint8" ||
  787. primitiveType == "uint8[]" ||
  788. primitiveType == "uint16" ||
  789. primitiveType == "uint16[]" ||
  790. primitiveType == "uint32" ||
  791. primitiveType == "uint32[]" ||
  792. primitiveType == "uint64" ||
  793. primitiveType == "uint64[]" ||
  794. primitiveType == "uint128" ||
  795. primitiveType == "uint128[]" ||
  796. primitiveType == "uint256" ||
  797. primitiveType == "uint256[]" {
  798. return true
  799. }
  800. return false
  801. }
  802. // validate checks if the given domain is valid, i.e. contains at least
  803. // the minimum viable keys and values
  804. func (domain *TypedDataDomain) validate() error {
  805. if domain.ChainId == big.NewInt(0) {
  806. return errors.New("chainId must be specified according to EIP-155")
  807. }
  808. if len(domain.Name) == 0 && len(domain.Version) == 0 && len(domain.VerifyingContract) == 0 && len(domain.Salt) == 0 {
  809. return errors.New("domain is undefined")
  810. }
  811. return nil
  812. }
  813. // Map is a helper function to generate a map version of the domain
  814. func (domain *TypedDataDomain) Map() map[string]interface{} {
  815. dataMap := map[string]interface{}{
  816. "chainId": domain.ChainId,
  817. }
  818. if len(domain.Name) > 0 {
  819. dataMap["name"] = domain.Name
  820. }
  821. if len(domain.Version) > 0 {
  822. dataMap["version"] = domain.Version
  823. }
  824. if len(domain.VerifyingContract) > 0 {
  825. dataMap["verifyingContract"] = domain.VerifyingContract
  826. }
  827. if len(domain.Salt) > 0 {
  828. dataMap["salt"] = domain.Salt
  829. }
  830. return dataMap
  831. }