reflect.go 6.9 KB

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