reflect.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. "errors"
  19. "fmt"
  20. "math/big"
  21. "reflect"
  22. "strings"
  23. )
  24. // ConvertType converts an interface of a runtime type into a interface of the
  25. // given type
  26. // e.g. turn
  27. // var fields []reflect.StructField
  28. // fields = append(fields, reflect.StructField{
  29. // Name: "X",
  30. // Type: reflect.TypeOf(new(big.Int)),
  31. // Tag: reflect.StructTag("json:\"" + "x" + "\""),
  32. // }
  33. // into
  34. // type TupleT struct { X *big.Int }
  35. func ConvertType(in interface{}, proto interface{}) interface{} {
  36. protoType := reflect.TypeOf(proto)
  37. if reflect.TypeOf(in).ConvertibleTo(protoType) {
  38. return reflect.ValueOf(in).Convert(protoType).Interface()
  39. }
  40. // Use set as a last ditch effort
  41. if err := set(reflect.ValueOf(proto), reflect.ValueOf(in)); err != nil {
  42. panic(err)
  43. }
  44. return proto
  45. }
  46. // indirect recursively dereferences the value until it either gets the value
  47. // or finds a big.Int
  48. func indirect(v reflect.Value) reflect.Value {
  49. if v.Kind() == reflect.Ptr && v.Elem().Type() != reflect.TypeOf(big.Int{}) {
  50. return indirect(v.Elem())
  51. }
  52. return v
  53. }
  54. // reflectIntType returns the reflect using the given size and
  55. // unsignedness.
  56. func reflectIntType(unsigned bool, size int) reflect.Type {
  57. if unsigned {
  58. switch size {
  59. case 8:
  60. return reflect.TypeOf(uint8(0))
  61. case 16:
  62. return reflect.TypeOf(uint16(0))
  63. case 32:
  64. return reflect.TypeOf(uint32(0))
  65. case 64:
  66. return reflect.TypeOf(uint64(0))
  67. }
  68. }
  69. switch size {
  70. case 8:
  71. return reflect.TypeOf(int8(0))
  72. case 16:
  73. return reflect.TypeOf(int16(0))
  74. case 32:
  75. return reflect.TypeOf(int32(0))
  76. case 64:
  77. return reflect.TypeOf(int64(0))
  78. }
  79. return reflect.TypeOf(&big.Int{})
  80. }
  81. // mustArrayToByteSlice creates a new byte slice with the exact same size as value
  82. // and copies the bytes in value to the new slice.
  83. func mustArrayToByteSlice(value reflect.Value) reflect.Value {
  84. slice := reflect.MakeSlice(reflect.TypeOf([]byte{}), value.Len(), value.Len())
  85. reflect.Copy(slice, value)
  86. return slice
  87. }
  88. // set attempts to assign src to dst by either setting, copying or otherwise.
  89. //
  90. // set is a bit more lenient when it comes to assignment and doesn't force an as
  91. // strict ruleset as bare `reflect` does.
  92. func set(dst, src reflect.Value) error {
  93. dstType, srcType := dst.Type(), src.Type()
  94. switch {
  95. case dstType.Kind() == reflect.Interface && dst.Elem().IsValid():
  96. return set(dst.Elem(), src)
  97. case dstType.Kind() == reflect.Ptr && dstType.Elem() != reflect.TypeOf(big.Int{}):
  98. return set(dst.Elem(), src)
  99. case srcType.AssignableTo(dstType) && dst.CanSet():
  100. dst.Set(src)
  101. case dstType.Kind() == reflect.Slice && srcType.Kind() == reflect.Slice && dst.CanSet():
  102. return setSlice(dst, src)
  103. case dstType.Kind() == reflect.Array:
  104. return setArray(dst, src)
  105. case dstType.Kind() == reflect.Struct:
  106. return setStruct(dst, src)
  107. default:
  108. return fmt.Errorf("abi: cannot unmarshal %v in to %v", src.Type(), dst.Type())
  109. }
  110. return nil
  111. }
  112. // setSlice attempts to assign src to dst when slices are not assignable by default
  113. // e.g. src: [][]byte -> dst: [][15]byte
  114. // setSlice ignores if we cannot copy all of src' elements.
  115. func setSlice(dst, src reflect.Value) error {
  116. slice := reflect.MakeSlice(dst.Type(), src.Len(), src.Len())
  117. for i := 0; i < src.Len(); i++ {
  118. if src.Index(i).Kind() == reflect.Struct {
  119. if err := set(slice.Index(i), src.Index(i)); err != nil {
  120. return err
  121. }
  122. } else {
  123. // e.g. [][32]uint8 to []common.Hash
  124. if err := set(slice.Index(i), src.Index(i)); err != nil {
  125. return err
  126. }
  127. }
  128. }
  129. if dst.CanSet() {
  130. dst.Set(slice)
  131. return nil
  132. }
  133. return errors.New("Cannot set slice, destination not settable")
  134. }
  135. func setArray(dst, src reflect.Value) error {
  136. if src.Kind() == reflect.Ptr {
  137. return set(dst, indirect(src))
  138. }
  139. array := reflect.New(dst.Type()).Elem()
  140. min := src.Len()
  141. if src.Len() > dst.Len() {
  142. min = dst.Len()
  143. }
  144. for i := 0; i < min; i++ {
  145. if err := set(array.Index(i), src.Index(i)); err != nil {
  146. return err
  147. }
  148. }
  149. if dst.CanSet() {
  150. dst.Set(array)
  151. return nil
  152. }
  153. return errors.New("Cannot set array, destination not settable")
  154. }
  155. func setStruct(dst, src reflect.Value) error {
  156. for i := 0; i < src.NumField(); i++ {
  157. srcField := src.Field(i)
  158. dstField := dst.Field(i)
  159. if !dstField.IsValid() || !srcField.IsValid() {
  160. return fmt.Errorf("Could not find src field: %v value: %v in destination", srcField.Type().Name(), srcField)
  161. }
  162. if err := set(dstField, srcField); err != nil {
  163. return err
  164. }
  165. }
  166. return nil
  167. }
  168. // mapArgNamesToStructFields maps a slice of argument names to struct fields.
  169. // first round: for each Exportable field that contains a `abi:""` tag
  170. // and this field name exists in the given argument name list, pair them together.
  171. // second round: for each argument name that has not been already linked,
  172. // find what variable is expected to be mapped into, if it exists and has not been
  173. // used, pair them.
  174. // Note this function assumes the given value is a struct value.
  175. func mapArgNamesToStructFields(argNames []string, value reflect.Value) (map[string]string, error) {
  176. typ := value.Type()
  177. abi2struct := make(map[string]string)
  178. struct2abi := make(map[string]string)
  179. // first round ~~~
  180. for i := 0; i < typ.NumField(); i++ {
  181. structFieldName := typ.Field(i).Name
  182. // skip private struct fields.
  183. if structFieldName[:1] != strings.ToUpper(structFieldName[:1]) {
  184. continue
  185. }
  186. // skip fields that have no abi:"" tag.
  187. tagName, ok := typ.Field(i).Tag.Lookup("abi")
  188. if !ok {
  189. continue
  190. }
  191. // check if tag is empty.
  192. if tagName == "" {
  193. return nil, fmt.Errorf("struct: abi tag in '%s' is empty", structFieldName)
  194. }
  195. // check which argument field matches with the abi tag.
  196. found := false
  197. for _, arg := range argNames {
  198. if arg == tagName {
  199. if abi2struct[arg] != "" {
  200. return nil, fmt.Errorf("struct: abi tag in '%s' already mapped", structFieldName)
  201. }
  202. // pair them
  203. abi2struct[arg] = structFieldName
  204. struct2abi[structFieldName] = arg
  205. found = true
  206. }
  207. }
  208. // check if this tag has been mapped.
  209. if !found {
  210. return nil, fmt.Errorf("struct: abi tag '%s' defined but not found in abi", tagName)
  211. }
  212. }
  213. // second round ~~~
  214. for _, argName := range argNames {
  215. structFieldName := ToCamelCase(argName)
  216. if structFieldName == "" {
  217. return nil, fmt.Errorf("abi: purely underscored output cannot unpack to struct")
  218. }
  219. // this abi has already been paired, skip it... unless there exists another, yet unassigned
  220. // struct field with the same field name. If so, raise an error:
  221. // abi: [ { "name": "value" } ]
  222. // struct { Value *big.Int , Value1 *big.Int `abi:"value"`}
  223. if abi2struct[argName] != "" {
  224. if abi2struct[argName] != structFieldName &&
  225. struct2abi[structFieldName] == "" &&
  226. value.FieldByName(structFieldName).IsValid() {
  227. return nil, fmt.Errorf("abi: multiple variables maps to the same abi field '%s'", argName)
  228. }
  229. continue
  230. }
  231. // return an error if this struct field has already been paired.
  232. if struct2abi[structFieldName] != "" {
  233. return nil, fmt.Errorf("abi: multiple outputs mapping to the same struct field '%s'", structFieldName)
  234. }
  235. if value.FieldByName(structFieldName).IsValid() {
  236. // pair them
  237. abi2struct[argName] = structFieldName
  238. struct2abi[structFieldName] = argName
  239. } else {
  240. // not paired, but annotate as used, to detect cases like
  241. // abi : [ { "name": "value" }, { "name": "_value" } ]
  242. // struct { Value *big.Int }
  243. struct2abi[structFieldName] = argName
  244. }
  245. }
  246. return abi2struct, nil
  247. }