reflect.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. // Copyright 2016 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 abi
  17. import (
  18. "fmt"
  19. "reflect"
  20. "strings"
  21. )
  22. // indirect recursively dereferences the value until it either gets the value
  23. // or finds a big.Int
  24. func indirect(v reflect.Value) reflect.Value {
  25. if v.Kind() == reflect.Ptr && v.Elem().Type() != derefbigT {
  26. return indirect(v.Elem())
  27. }
  28. return v
  29. }
  30. // indirectInterfaceOrPtr recursively dereferences the value until value is not interface.
  31. func indirectInterfaceOrPtr(v reflect.Value) reflect.Value {
  32. if (v.Kind() == reflect.Interface || v.Kind() == reflect.Ptr) && v.Elem().IsValid() {
  33. return indirect(v.Elem())
  34. }
  35. return v
  36. }
  37. // reflectIntType returns the reflect using the given size and
  38. // unsignedness.
  39. func reflectIntType(unsigned bool, size int) reflect.Type {
  40. if unsigned {
  41. switch size {
  42. case 8:
  43. return uint8T
  44. case 16:
  45. return uint16T
  46. case 32:
  47. return uint32T
  48. case 64:
  49. return uint64T
  50. }
  51. }
  52. switch size {
  53. case 8:
  54. return int8T
  55. case 16:
  56. return int16T
  57. case 32:
  58. return int32T
  59. case 64:
  60. return int64T
  61. }
  62. return bigT
  63. }
  64. // mustArrayToBytesSlice creates a new byte slice with the exact same size as value
  65. // and copies the bytes in value to the new slice.
  66. func mustArrayToByteSlice(value reflect.Value) reflect.Value {
  67. slice := reflect.MakeSlice(reflect.TypeOf([]byte{}), value.Len(), value.Len())
  68. reflect.Copy(slice, value)
  69. return slice
  70. }
  71. // set attempts to assign src to dst by either setting, copying or otherwise.
  72. //
  73. // set is a bit more lenient when it comes to assignment and doesn't force an as
  74. // strict ruleset as bare `reflect` does.
  75. func set(dst, src reflect.Value) error {
  76. dstType, srcType := dst.Type(), src.Type()
  77. switch {
  78. case dstType.Kind() == reflect.Interface && dst.Elem().IsValid():
  79. return set(dst.Elem(), src)
  80. case dstType.Kind() == reflect.Ptr && dstType.Elem() != derefbigT:
  81. return set(dst.Elem(), src)
  82. case srcType.AssignableTo(dstType) && dst.CanSet():
  83. dst.Set(src)
  84. case dstType.Kind() == reflect.Slice && srcType.Kind() == reflect.Slice && dst.CanSet():
  85. setSlice(dst, src)
  86. default:
  87. return fmt.Errorf("abi: cannot unmarshal %v in to %v", src.Type(), dst.Type())
  88. }
  89. return nil
  90. }
  91. // setSlice attempts to assign src to dst when slices are not assignable by default
  92. // e.g. src: [][]byte -> dst: [][15]byte
  93. // setSlice ignores if we cannot copy all of src' elements.
  94. func setSlice(dst, src reflect.Value) {
  95. slice := reflect.MakeSlice(dst.Type(), src.Len(), src.Len())
  96. for i := 0; i < src.Len(); i++ {
  97. reflect.Copy(slice.Index(i), src.Index(i))
  98. }
  99. dst.Set(slice)
  100. }
  101. // requireAssignable assures that `dest` is a pointer and it's not an interface.
  102. func requireAssignable(dst, src reflect.Value) error {
  103. if dst.Kind() != reflect.Ptr && dst.Kind() != reflect.Interface {
  104. return fmt.Errorf("abi: cannot unmarshal %v into %v", src.Type(), dst.Type())
  105. }
  106. return nil
  107. }
  108. // requireUnpackKind verifies preconditions for unpacking `args` into `kind`
  109. func requireUnpackKind(v reflect.Value, minLength int, args Arguments) error {
  110. switch v.Kind() {
  111. case reflect.Struct:
  112. case reflect.Slice, reflect.Array:
  113. if v.Len() < minLength {
  114. return fmt.Errorf("abi: insufficient number of elements in the list/array for unpack, want %d, got %d",
  115. minLength, v.Len())
  116. }
  117. default:
  118. return fmt.Errorf("abi: cannot unmarshal tuple into %v", v.Type())
  119. }
  120. return nil
  121. }
  122. // mapArgNamesToStructFields maps a slice of argument names to struct fields.
  123. // first round: for each Exportable field that contains a `abi:""` tag
  124. // and this field name exists in the given argument name list, pair them together.
  125. // second round: for each argument name that has not been already linked,
  126. // find what variable is expected to be mapped into, if it exists and has not been
  127. // used, pair them.
  128. // Note this function assumes the given value is a struct value.
  129. func mapArgNamesToStructFields(argNames []string, value reflect.Value) (map[string]string, error) {
  130. typ := value.Type()
  131. abi2struct := make(map[string]string)
  132. struct2abi := make(map[string]string)
  133. // first round ~~~
  134. for i := 0; i < typ.NumField(); i++ {
  135. structFieldName := typ.Field(i).Name
  136. // skip private struct fields.
  137. if structFieldName[:1] != strings.ToUpper(structFieldName[:1]) {
  138. continue
  139. }
  140. // skip fields that have no abi:"" tag.
  141. tagName, ok := typ.Field(i).Tag.Lookup("abi")
  142. if !ok {
  143. continue
  144. }
  145. // check if tag is empty.
  146. if tagName == "" {
  147. return nil, fmt.Errorf("struct: abi tag in '%s' is empty", structFieldName)
  148. }
  149. // check which argument field matches with the abi tag.
  150. found := false
  151. for _, arg := range argNames {
  152. if arg == tagName {
  153. if abi2struct[arg] != "" {
  154. return nil, fmt.Errorf("struct: abi tag in '%s' already mapped", structFieldName)
  155. }
  156. // pair them
  157. abi2struct[arg] = structFieldName
  158. struct2abi[structFieldName] = arg
  159. found = true
  160. }
  161. }
  162. // check if this tag has been mapped.
  163. if !found {
  164. return nil, fmt.Errorf("struct: abi tag '%s' defined but not found in abi", tagName)
  165. }
  166. }
  167. // second round ~~~
  168. for _, argName := range argNames {
  169. structFieldName := ToCamelCase(argName)
  170. if structFieldName == "" {
  171. return nil, fmt.Errorf("abi: purely underscored output cannot unpack to struct")
  172. }
  173. // this abi has already been paired, skip it... unless there exists another, yet unassigned
  174. // struct field with the same field name. If so, raise an error:
  175. // abi: [ { "name": "value" } ]
  176. // struct { Value *big.Int , Value1 *big.Int `abi:"value"`}
  177. if abi2struct[argName] != "" {
  178. if abi2struct[argName] != structFieldName &&
  179. struct2abi[structFieldName] == "" &&
  180. value.FieldByName(structFieldName).IsValid() {
  181. return nil, fmt.Errorf("abi: multiple variables maps to the same abi field '%s'", argName)
  182. }
  183. continue
  184. }
  185. // return an error if this struct field has already been paired.
  186. if struct2abi[structFieldName] != "" {
  187. return nil, fmt.Errorf("abi: multiple outputs mapping to the same struct field '%s'", structFieldName)
  188. }
  189. if value.FieldByName(structFieldName).IsValid() {
  190. // pair them
  191. abi2struct[argName] = structFieldName
  192. struct2abi[structFieldName] = argName
  193. } else {
  194. // not paired, but annotate as used, to detect cases like
  195. // abi : [ { "name": "value" }, { "name": "_value" } ]
  196. // struct { Value *big.Int }
  197. struct2abi[structFieldName] = argName
  198. }
  199. }
  200. return abi2struct, nil
  201. }