reflect.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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() && (dst.Elem().Type().Kind() == reflect.Ptr || dst.Elem().CanSet()):
  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 err := set(slice.Index(i), src.Index(i)); err != nil {
  119. return err
  120. }
  121. }
  122. if dst.CanSet() {
  123. dst.Set(slice)
  124. return nil
  125. }
  126. return errors.New("Cannot set slice, destination not settable")
  127. }
  128. func setArray(dst, src reflect.Value) error {
  129. if src.Kind() == reflect.Ptr {
  130. return set(dst, indirect(src))
  131. }
  132. array := reflect.New(dst.Type()).Elem()
  133. min := src.Len()
  134. if src.Len() > dst.Len() {
  135. min = dst.Len()
  136. }
  137. for i := 0; i < min; i++ {
  138. if err := set(array.Index(i), src.Index(i)); err != nil {
  139. return err
  140. }
  141. }
  142. if dst.CanSet() {
  143. dst.Set(array)
  144. return nil
  145. }
  146. return errors.New("Cannot set array, destination not settable")
  147. }
  148. func setStruct(dst, src reflect.Value) error {
  149. for i := 0; i < src.NumField(); i++ {
  150. srcField := src.Field(i)
  151. dstField := dst.Field(i)
  152. if !dstField.IsValid() || !srcField.IsValid() {
  153. return fmt.Errorf("Could not find src field: %v value: %v in destination", srcField.Type().Name(), srcField)
  154. }
  155. if err := set(dstField, srcField); err != nil {
  156. return err
  157. }
  158. }
  159. return nil
  160. }
  161. // mapArgNamesToStructFields maps a slice of argument names to struct fields.
  162. // first round: for each Exportable field that contains a `abi:""` tag
  163. // and this field name exists in the given argument name list, pair them together.
  164. // second round: for each argument name that has not been already linked,
  165. // find what variable is expected to be mapped into, if it exists and has not been
  166. // used, pair them.
  167. // Note this function assumes the given value is a struct value.
  168. func mapArgNamesToStructFields(argNames []string, value reflect.Value) (map[string]string, error) {
  169. typ := value.Type()
  170. abi2struct := make(map[string]string)
  171. struct2abi := make(map[string]string)
  172. // first round ~~~
  173. for i := 0; i < typ.NumField(); i++ {
  174. structFieldName := typ.Field(i).Name
  175. // skip private struct fields.
  176. if structFieldName[:1] != strings.ToUpper(structFieldName[:1]) {
  177. continue
  178. }
  179. // skip fields that have no abi:"" tag.
  180. tagName, ok := typ.Field(i).Tag.Lookup("abi")
  181. if !ok {
  182. continue
  183. }
  184. // check if tag is empty.
  185. if tagName == "" {
  186. return nil, fmt.Errorf("struct: abi tag in '%s' is empty", structFieldName)
  187. }
  188. // check which argument field matches with the abi tag.
  189. found := false
  190. for _, arg := range argNames {
  191. if arg == tagName {
  192. if abi2struct[arg] != "" {
  193. return nil, fmt.Errorf("struct: abi tag in '%s' already mapped", structFieldName)
  194. }
  195. // pair them
  196. abi2struct[arg] = structFieldName
  197. struct2abi[structFieldName] = arg
  198. found = true
  199. }
  200. }
  201. // check if this tag has been mapped.
  202. if !found {
  203. return nil, fmt.Errorf("struct: abi tag '%s' defined but not found in abi", tagName)
  204. }
  205. }
  206. // second round ~~~
  207. for _, argName := range argNames {
  208. structFieldName := ToCamelCase(argName)
  209. if structFieldName == "" {
  210. return nil, fmt.Errorf("abi: purely underscored output cannot unpack to struct")
  211. }
  212. // this abi has already been paired, skip it... unless there exists another, yet unassigned
  213. // struct field with the same field name. If so, raise an error:
  214. // abi: [ { "name": "value" } ]
  215. // struct { Value *big.Int , Value1 *big.Int `abi:"value"`}
  216. if abi2struct[argName] != "" {
  217. if abi2struct[argName] != structFieldName &&
  218. struct2abi[structFieldName] == "" &&
  219. value.FieldByName(structFieldName).IsValid() {
  220. return nil, fmt.Errorf("abi: multiple variables maps to the same abi field '%s'", argName)
  221. }
  222. continue
  223. }
  224. // return an error if this struct field has already been paired.
  225. if struct2abi[structFieldName] != "" {
  226. return nil, fmt.Errorf("abi: multiple outputs mapping to the same struct field '%s'", structFieldName)
  227. }
  228. if value.FieldByName(structFieldName).IsValid() {
  229. // pair them
  230. abi2struct[argName] = structFieldName
  231. struct2abi[structFieldName] = argName
  232. } else {
  233. // not paired, but annotate as used, to detect cases like
  234. // abi : [ { "name": "value" }, { "name": "_value" } ]
  235. // struct { Value *big.Int }
  236. struct2abi[structFieldName] = argName
  237. }
  238. }
  239. return abi2struct, nil
  240. }