abi.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 fourbyte
  17. import (
  18. "bytes"
  19. "encoding/json"
  20. "fmt"
  21. "regexp"
  22. "strings"
  23. "github.com/ethereum/go-ethereum/accounts/abi"
  24. "github.com/ethereum/go-ethereum/common"
  25. )
  26. // decodedCallData is an internal type to represent a method call parsed according
  27. // to an ABI method signature.
  28. type decodedCallData struct {
  29. signature string
  30. name string
  31. inputs []decodedArgument
  32. }
  33. // decodedArgument is an internal type to represent an argument parsed according
  34. // to an ABI method signature.
  35. type decodedArgument struct {
  36. soltype abi.Argument
  37. value interface{}
  38. }
  39. // String implements stringer interface, tries to use the underlying value-type
  40. func (arg decodedArgument) String() string {
  41. var value string
  42. switch val := arg.value.(type) {
  43. case fmt.Stringer:
  44. value = val.String()
  45. default:
  46. value = fmt.Sprintf("%v", val)
  47. }
  48. return fmt.Sprintf("%v: %v", arg.soltype.Type.String(), value)
  49. }
  50. // String implements stringer interface for decodedCallData
  51. func (cd decodedCallData) String() string {
  52. args := make([]string, len(cd.inputs))
  53. for i, arg := range cd.inputs {
  54. args[i] = arg.String()
  55. }
  56. return fmt.Sprintf("%s(%s)", cd.name, strings.Join(args, ","))
  57. }
  58. // verifySelector checks whether the ABI encoded data blob matches the requested
  59. // function signature.
  60. func verifySelector(selector string, calldata []byte) (*decodedCallData, error) {
  61. // Parse the selector into an ABI JSON spec
  62. abidata, err := parseSelector(selector)
  63. if err != nil {
  64. return nil, err
  65. }
  66. // Parse the call data according to the requested selector
  67. return parseCallData(calldata, string(abidata))
  68. }
  69. // selectorRegexp is used to validate that a 4byte database selector corresponds
  70. // to a valid ABI function declaration.
  71. //
  72. // Note, although uppercase letters are not part of the ABI spec, this regexp
  73. // still accepts it as the general format is valid. It will be rejected later
  74. // by the type checker.
  75. var selectorRegexp = regexp.MustCompile(`^([^\)]+)\(([A-Za-z0-9,\[\]]*)\)`)
  76. // parseSelector converts a method selector into an ABI JSON spec. The returned
  77. // data is a valid JSON string which can be consumed by the standard abi package.
  78. func parseSelector(unescapedSelector string) ([]byte, error) {
  79. // Define a tiny fake ABI struct for JSON marshalling
  80. type fakeArg struct {
  81. Type string `json:"type"`
  82. }
  83. type fakeABI struct {
  84. Name string `json:"name"`
  85. Type string `json:"type"`
  86. Inputs []fakeArg `json:"inputs"`
  87. }
  88. // Validate the unescapedSelector and extract it's components
  89. groups := selectorRegexp.FindStringSubmatch(unescapedSelector)
  90. if len(groups) != 3 {
  91. return nil, fmt.Errorf("invalid selector %q (%v matches)", unescapedSelector, len(groups))
  92. }
  93. name := groups[1]
  94. args := groups[2]
  95. // Reassemble the fake ABI and constuct the JSON
  96. arguments := make([]fakeArg, 0)
  97. if len(args) > 0 {
  98. for _, arg := range strings.Split(args, ",") {
  99. arguments = append(arguments, fakeArg{arg})
  100. }
  101. }
  102. return json.Marshal([]fakeABI{{name, "function", arguments}})
  103. }
  104. // parseCallData matches the provided call data against the ABI definition and
  105. // returns a struct containing the actual go-typed values.
  106. func parseCallData(calldata []byte, unescapedAbidata string) (*decodedCallData, error) {
  107. // Validate the call data that it has the 4byte prefix and the rest divisible by 32 bytes
  108. if len(calldata) < 4 {
  109. return nil, fmt.Errorf("invalid call data, incomplete method signature (%d bytes < 4)", len(calldata))
  110. }
  111. sigdata := calldata[:4]
  112. argdata := calldata[4:]
  113. if len(argdata)%32 != 0 {
  114. return nil, fmt.Errorf("invalid call data; length should be a multiple of 32 bytes (was %d)", len(argdata))
  115. }
  116. // Validate the called method and upack the call data accordingly
  117. abispec, err := abi.JSON(strings.NewReader(unescapedAbidata))
  118. if err != nil {
  119. return nil, fmt.Errorf("invalid method signature (%q): %v", unescapedAbidata, err)
  120. }
  121. method, err := abispec.MethodById(sigdata)
  122. if err != nil {
  123. return nil, err
  124. }
  125. values, err := method.Inputs.UnpackValues(argdata)
  126. if err != nil {
  127. return nil, fmt.Errorf("signature %q matches, but arguments mismatch: %v", method.String(), err)
  128. }
  129. // Everything valid, assemble the call infos for the signer
  130. decoded := decodedCallData{signature: method.Sig, name: method.RawName}
  131. for i := 0; i < len(method.Inputs); i++ {
  132. decoded.inputs = append(decoded.inputs, decodedArgument{
  133. soltype: method.Inputs[i],
  134. value: values[i],
  135. })
  136. }
  137. // We're finished decoding the data. At this point, we encode the decoded data
  138. // to see if it matches with the original data. If we didn't do that, it would
  139. // be possible to stuff extra data into the arguments, which is not detected
  140. // by merely decoding the data.
  141. encoded, err := method.Inputs.PackValues(values)
  142. if err != nil {
  143. return nil, err
  144. }
  145. if !bytes.Equal(encoded, argdata) {
  146. was := common.Bytes2Hex(encoded)
  147. exp := common.Bytes2Hex(argdata)
  148. return nil, fmt.Errorf("WARNING: Supplied data is stuffed with extra data. \nWant %s\nHave %s\nfor method %v", exp, was, method.Sig)
  149. }
  150. return &decoded, nil
  151. }