signed_data.go 28 KB

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