json.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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 hexutil
  17. import (
  18. "encoding/hex"
  19. "encoding/json"
  20. "fmt"
  21. "math/big"
  22. "reflect"
  23. "strconv"
  24. )
  25. var (
  26. bytesT = reflect.TypeOf(Bytes(nil))
  27. bigT = reflect.TypeOf((*Big)(nil))
  28. uintT = reflect.TypeOf(Uint(0))
  29. uint64T = reflect.TypeOf(Uint64(0))
  30. )
  31. // Bytes marshals/unmarshals as a JSON string with 0x prefix.
  32. // The empty slice marshals as "0x".
  33. type Bytes []byte
  34. // MarshalText implements encoding.TextMarshaler
  35. func (b Bytes) MarshalText() ([]byte, error) {
  36. result := make([]byte, len(b)*2+2)
  37. copy(result, `0x`)
  38. hex.Encode(result[2:], b)
  39. return result, nil
  40. }
  41. // UnmarshalJSON implements json.Unmarshaler.
  42. func (b *Bytes) UnmarshalJSON(input []byte) error {
  43. if !isString(input) {
  44. return errNonString(bytesT)
  45. }
  46. return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), bytesT)
  47. }
  48. // UnmarshalText implements encoding.TextUnmarshaler.
  49. func (b *Bytes) UnmarshalText(input []byte) error {
  50. raw, err := checkText(input, true)
  51. if err != nil {
  52. return err
  53. }
  54. dec := make([]byte, len(raw)/2)
  55. if _, err = hex.Decode(dec, raw); err != nil {
  56. err = mapError(err)
  57. } else {
  58. *b = dec
  59. }
  60. return err
  61. }
  62. // String returns the hex encoding of b.
  63. func (b Bytes) String() string {
  64. return Encode(b)
  65. }
  66. // ImplementsGraphQLType returns true if Bytes implements the specified GraphQL type.
  67. func (b Bytes) ImplementsGraphQLType(name string) bool { return name == "Bytes" }
  68. // UnmarshalGraphQL unmarshals the provided GraphQL query data.
  69. func (b *Bytes) UnmarshalGraphQL(input interface{}) error {
  70. var err error
  71. switch input := input.(type) {
  72. case string:
  73. data, err := Decode(input)
  74. if err != nil {
  75. return err
  76. }
  77. *b = data
  78. default:
  79. err = fmt.Errorf("unexpected type %T for Bytes", input)
  80. }
  81. return err
  82. }
  83. // UnmarshalFixedJSON decodes the input as a string with 0x prefix. The length of out
  84. // determines the required input length. This function is commonly used to implement the
  85. // UnmarshalJSON method for fixed-size types.
  86. func UnmarshalFixedJSON(typ reflect.Type, input, out []byte) error {
  87. if !isString(input) {
  88. return errNonString(typ)
  89. }
  90. return wrapTypeError(UnmarshalFixedText(typ.String(), input[1:len(input)-1], out), typ)
  91. }
  92. // UnmarshalFixedText decodes the input as a string with 0x prefix. The length of out
  93. // determines the required input length. This function is commonly used to implement the
  94. // UnmarshalText method for fixed-size types.
  95. func UnmarshalFixedText(typname string, input, out []byte) error {
  96. raw, err := checkText(input, true)
  97. if err != nil {
  98. return err
  99. }
  100. if len(raw)/2 != len(out) {
  101. return fmt.Errorf("hex string has length %d, want %d for %s", len(raw), len(out)*2, typname)
  102. }
  103. // Pre-verify syntax before modifying out.
  104. for _, b := range raw {
  105. if decodeNibble(b) == badNibble {
  106. return ErrSyntax
  107. }
  108. }
  109. hex.Decode(out, raw)
  110. return nil
  111. }
  112. // UnmarshalFixedUnprefixedText decodes the input as a string with optional 0x prefix. The
  113. // length of out determines the required input length. This function is commonly used to
  114. // implement the UnmarshalText method for fixed-size types.
  115. func UnmarshalFixedUnprefixedText(typname string, input, out []byte) error {
  116. raw, err := checkText(input, false)
  117. if err != nil {
  118. return err
  119. }
  120. if len(raw)/2 != len(out) {
  121. return fmt.Errorf("hex string has length %d, want %d for %s", len(raw), len(out)*2, typname)
  122. }
  123. // Pre-verify syntax before modifying out.
  124. for _, b := range raw {
  125. if decodeNibble(b) == badNibble {
  126. return ErrSyntax
  127. }
  128. }
  129. hex.Decode(out, raw)
  130. return nil
  131. }
  132. // Big marshals/unmarshals as a JSON string with 0x prefix.
  133. // The zero value marshals as "0x0".
  134. //
  135. // Negative integers are not supported at this time. Attempting to marshal them will
  136. // return an error. Values larger than 256bits are rejected by Unmarshal but will be
  137. // marshaled without error.
  138. type Big big.Int
  139. // MarshalText implements encoding.TextMarshaler
  140. func (b Big) MarshalText() ([]byte, error) {
  141. return []byte(EncodeBig((*big.Int)(&b))), nil
  142. }
  143. // UnmarshalJSON implements json.Unmarshaler.
  144. func (b *Big) UnmarshalJSON(input []byte) error {
  145. if !isString(input) {
  146. return errNonString(bigT)
  147. }
  148. return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), bigT)
  149. }
  150. // UnmarshalText implements encoding.TextUnmarshaler
  151. func (b *Big) UnmarshalText(input []byte) error {
  152. raw, err := checkNumberText(input)
  153. if err != nil {
  154. return err
  155. }
  156. if len(raw) > 64 {
  157. return ErrBig256Range
  158. }
  159. words := make([]big.Word, len(raw)/bigWordNibbles+1)
  160. end := len(raw)
  161. for i := range words {
  162. start := end - bigWordNibbles
  163. if start < 0 {
  164. start = 0
  165. }
  166. for ri := start; ri < end; ri++ {
  167. nib := decodeNibble(raw[ri])
  168. if nib == badNibble {
  169. return ErrSyntax
  170. }
  171. words[i] *= 16
  172. words[i] += big.Word(nib)
  173. }
  174. end = start
  175. }
  176. var dec big.Int
  177. dec.SetBits(words)
  178. *b = (Big)(dec)
  179. return nil
  180. }
  181. // ToInt converts b to a big.Int.
  182. func (b *Big) ToInt() *big.Int {
  183. return (*big.Int)(b)
  184. }
  185. // String returns the hex encoding of b.
  186. func (b *Big) String() string {
  187. return EncodeBig(b.ToInt())
  188. }
  189. // ImplementsGraphQLType returns true if Big implements the provided GraphQL type.
  190. func (b Big) ImplementsGraphQLType(name string) bool { return name == "BigInt" }
  191. // UnmarshalGraphQL unmarshals the provided GraphQL query data.
  192. func (b *Big) UnmarshalGraphQL(input interface{}) error {
  193. var err error
  194. switch input := input.(type) {
  195. case string:
  196. return b.UnmarshalText([]byte(input))
  197. case int32:
  198. var num big.Int
  199. num.SetInt64(int64(input))
  200. *b = Big(num)
  201. default:
  202. err = fmt.Errorf("unexpected type %T for BigInt", input)
  203. }
  204. return err
  205. }
  206. // Uint64 marshals/unmarshals as a JSON string with 0x prefix.
  207. // The zero value marshals as "0x0".
  208. type Uint64 uint64
  209. // MarshalText implements encoding.TextMarshaler.
  210. func (b Uint64) MarshalText() ([]byte, error) {
  211. buf := make([]byte, 2, 10)
  212. copy(buf, `0x`)
  213. buf = strconv.AppendUint(buf, uint64(b), 16)
  214. return buf, nil
  215. }
  216. // UnmarshalJSON implements json.Unmarshaler.
  217. func (b *Uint64) UnmarshalJSON(input []byte) error {
  218. if !isString(input) {
  219. return errNonString(uint64T)
  220. }
  221. return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), uint64T)
  222. }
  223. // UnmarshalText implements encoding.TextUnmarshaler
  224. func (b *Uint64) UnmarshalText(input []byte) error {
  225. raw, err := checkNumberText(input)
  226. if err != nil {
  227. return err
  228. }
  229. if len(raw) > 16 {
  230. return ErrUint64Range
  231. }
  232. var dec uint64
  233. for _, byte := range raw {
  234. nib := decodeNibble(byte)
  235. if nib == badNibble {
  236. return ErrSyntax
  237. }
  238. dec *= 16
  239. dec += nib
  240. }
  241. *b = Uint64(dec)
  242. return nil
  243. }
  244. // String returns the hex encoding of b.
  245. func (b Uint64) String() string {
  246. return EncodeUint64(uint64(b))
  247. }
  248. // ImplementsGraphQLType returns true if Uint64 implements the provided GraphQL type.
  249. func (b Uint64) ImplementsGraphQLType(name string) bool { return name == "Long" }
  250. // UnmarshalGraphQL unmarshals the provided GraphQL query data.
  251. func (b *Uint64) UnmarshalGraphQL(input interface{}) error {
  252. var err error
  253. switch input := input.(type) {
  254. case string:
  255. return b.UnmarshalText([]byte(input))
  256. case int32:
  257. *b = Uint64(input)
  258. default:
  259. err = fmt.Errorf("unexpected type %T for Long", input)
  260. }
  261. return err
  262. }
  263. // Uint marshals/unmarshals as a JSON string with 0x prefix.
  264. // The zero value marshals as "0x0".
  265. type Uint uint
  266. // MarshalText implements encoding.TextMarshaler.
  267. func (b Uint) MarshalText() ([]byte, error) {
  268. return Uint64(b).MarshalText()
  269. }
  270. // UnmarshalJSON implements json.Unmarshaler.
  271. func (b *Uint) UnmarshalJSON(input []byte) error {
  272. if !isString(input) {
  273. return errNonString(uintT)
  274. }
  275. return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), uintT)
  276. }
  277. // UnmarshalText implements encoding.TextUnmarshaler.
  278. func (b *Uint) UnmarshalText(input []byte) error {
  279. var u64 Uint64
  280. err := u64.UnmarshalText(input)
  281. if u64 > Uint64(^uint(0)) || err == ErrUint64Range {
  282. return ErrUintRange
  283. } else if err != nil {
  284. return err
  285. }
  286. *b = Uint(u64)
  287. return nil
  288. }
  289. // String returns the hex encoding of b.
  290. func (b Uint) String() string {
  291. return EncodeUint64(uint64(b))
  292. }
  293. func isString(input []byte) bool {
  294. return len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"'
  295. }
  296. func bytesHave0xPrefix(input []byte) bool {
  297. return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X')
  298. }
  299. func checkText(input []byte, wantPrefix bool) ([]byte, error) {
  300. if len(input) == 0 {
  301. return nil, nil // empty strings are allowed
  302. }
  303. if bytesHave0xPrefix(input) {
  304. input = input[2:]
  305. } else if wantPrefix {
  306. return nil, ErrMissingPrefix
  307. }
  308. if len(input)%2 != 0 {
  309. return nil, ErrOddLength
  310. }
  311. return input, nil
  312. }
  313. func checkNumberText(input []byte) (raw []byte, err error) {
  314. if len(input) == 0 {
  315. return nil, nil // empty strings are allowed
  316. }
  317. if !bytesHave0xPrefix(input) {
  318. return nil, ErrMissingPrefix
  319. }
  320. input = input[2:]
  321. if len(input) == 0 {
  322. return nil, ErrEmptyNumber
  323. }
  324. if len(input) > 1 && input[0] == '0' {
  325. return nil, ErrLeadingZero
  326. }
  327. return input, nil
  328. }
  329. func wrapTypeError(err error, typ reflect.Type) error {
  330. if _, ok := err.(*decError); ok {
  331. return &json.UnmarshalTypeError{Value: err.Error(), Type: typ}
  332. }
  333. return err
  334. }
  335. func errNonString(typ reflect.Type) error {
  336. return &json.UnmarshalTypeError{Value: "non-string", Type: typ}
  337. }