signed_data.go 30 KB

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