signed_data.go 30 KB

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