json.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. "errors"
  20. "fmt"
  21. "math/big"
  22. "strconv"
  23. )
  24. var (
  25. jsonNull = []byte("null")
  26. jsonZero = []byte(`"0x0"`)
  27. errNonString = errors.New("cannot unmarshal non-string as hex data")
  28. errNegativeBigInt = errors.New("hexutil.Big: can't marshal negative integer")
  29. )
  30. // Bytes marshals/unmarshals as a JSON string with 0x prefix.
  31. // The empty slice marshals as "0x".
  32. type Bytes []byte
  33. // MarshalJSON implements json.Marshaler.
  34. func (b Bytes) MarshalJSON() ([]byte, error) {
  35. result := make([]byte, len(b)*2+4)
  36. copy(result, `"0x`)
  37. hex.Encode(result[3:], b)
  38. result[len(result)-1] = '"'
  39. return result, nil
  40. }
  41. // UnmarshalJSON implements json.Unmarshaler.
  42. func (b *Bytes) UnmarshalJSON(input []byte) error {
  43. raw, err := checkJSON(input)
  44. if err != nil {
  45. return err
  46. }
  47. dec := make([]byte, len(raw)/2)
  48. if _, err = hex.Decode(dec, raw); err != nil {
  49. err = mapError(err)
  50. } else {
  51. *b = dec
  52. }
  53. return err
  54. }
  55. // String returns the hex encoding of b.
  56. func (b Bytes) String() string {
  57. return Encode(b)
  58. }
  59. // UnmarshalJSON decodes input as a JSON string with 0x prefix. The length of out
  60. // determines the required input length. This function is commonly used to implement the
  61. // UnmarshalJSON method for fixed-size types:
  62. //
  63. // type Foo [8]byte
  64. //
  65. // func (f *Foo) UnmarshalJSON(input []byte) error {
  66. // return hexutil.UnmarshalJSON("Foo", input, f[:])
  67. // }
  68. func UnmarshalJSON(typname string, input, out []byte) error {
  69. raw, err := checkJSON(input)
  70. if err != nil {
  71. return err
  72. }
  73. if len(raw)/2 != len(out) {
  74. return fmt.Errorf("hex string has length %d, want %d for %s", len(raw), len(out)*2, typname)
  75. }
  76. // Pre-verify syntax before modifying out.
  77. for _, b := range raw {
  78. if decodeNibble(b) == badNibble {
  79. return ErrSyntax
  80. }
  81. }
  82. hex.Decode(out, raw)
  83. return nil
  84. }
  85. // Big marshals/unmarshals as a JSON string with 0x prefix. The zero value marshals as
  86. // "0x0". Negative integers are not supported at this time. Attempting to marshal them
  87. // will return an error.
  88. type Big big.Int
  89. // MarshalJSON implements json.Marshaler.
  90. func (b *Big) MarshalJSON() ([]byte, error) {
  91. if b == nil {
  92. return jsonNull, nil
  93. }
  94. bigint := (*big.Int)(b)
  95. if bigint.Sign() == -1 {
  96. return nil, errNegativeBigInt
  97. }
  98. nbits := bigint.BitLen()
  99. if nbits == 0 {
  100. return jsonZero, nil
  101. }
  102. enc := make([]byte, 3, (nbits/8)*2+4)
  103. copy(enc, `"0x`)
  104. for i := len(bigint.Bits()) - 1; i >= 0; i-- {
  105. enc = strconv.AppendUint(enc, uint64(bigint.Bits()[i]), 16)
  106. }
  107. enc = append(enc, '"')
  108. return enc, nil
  109. }
  110. // UnmarshalJSON implements json.Unmarshaler.
  111. func (b *Big) UnmarshalJSON(input []byte) error {
  112. raw, err := checkNumberJSON(input)
  113. if err != nil {
  114. return err
  115. }
  116. words := make([]big.Word, len(raw)/bigWordNibbles+1)
  117. end := len(raw)
  118. for i := range words {
  119. start := end - bigWordNibbles
  120. if start < 0 {
  121. start = 0
  122. }
  123. for ri := start; ri < end; ri++ {
  124. nib := decodeNibble(raw[ri])
  125. if nib == badNibble {
  126. return ErrSyntax
  127. }
  128. words[i] *= 16
  129. words[i] += big.Word(nib)
  130. }
  131. end = start
  132. }
  133. var dec big.Int
  134. dec.SetBits(words)
  135. *b = (Big)(dec)
  136. return nil
  137. }
  138. // ToInt converts b to a big.Int.
  139. func (b *Big) ToInt() *big.Int {
  140. return (*big.Int)(b)
  141. }
  142. // String returns the hex encoding of b.
  143. func (b *Big) String() string {
  144. return EncodeBig(b.ToInt())
  145. }
  146. // Uint64 marshals/unmarshals as a JSON string with 0x prefix.
  147. // The zero value marshals as "0x0".
  148. type Uint64 uint64
  149. // MarshalJSON implements json.Marshaler.
  150. func (b Uint64) MarshalJSON() ([]byte, error) {
  151. buf := make([]byte, 3, 12)
  152. copy(buf, `"0x`)
  153. buf = strconv.AppendUint(buf, uint64(b), 16)
  154. buf = append(buf, '"')
  155. return buf, nil
  156. }
  157. // UnmarshalJSON implements json.Unmarshaler.
  158. func (b *Uint64) UnmarshalJSON(input []byte) error {
  159. raw, err := checkNumberJSON(input)
  160. if err != nil {
  161. return err
  162. }
  163. if len(raw) > 16 {
  164. return ErrUint64Range
  165. }
  166. var dec uint64
  167. for _, byte := range raw {
  168. nib := decodeNibble(byte)
  169. if nib == badNibble {
  170. return ErrSyntax
  171. }
  172. dec *= 16
  173. dec += uint64(nib)
  174. }
  175. *b = Uint64(dec)
  176. return nil
  177. }
  178. // String returns the hex encoding of b.
  179. func (b Uint64) String() string {
  180. return EncodeUint64(uint64(b))
  181. }
  182. // Uint marshals/unmarshals as a JSON string with 0x prefix.
  183. // The zero value marshals as "0x0".
  184. type Uint uint
  185. // MarshalJSON implements json.Marshaler.
  186. func (b Uint) MarshalJSON() ([]byte, error) {
  187. return Uint64(b).MarshalJSON()
  188. }
  189. // UnmarshalJSON implements json.Unmarshaler.
  190. func (b *Uint) UnmarshalJSON(input []byte) error {
  191. var u64 Uint64
  192. err := u64.UnmarshalJSON(input)
  193. if err != nil {
  194. return err
  195. } else if u64 > Uint64(^uint(0)) {
  196. return ErrUintRange
  197. }
  198. *b = Uint(u64)
  199. return nil
  200. }
  201. // String returns the hex encoding of b.
  202. func (b Uint) String() string {
  203. return EncodeUint64(uint64(b))
  204. }
  205. func isString(input []byte) bool {
  206. return len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"'
  207. }
  208. func bytesHave0xPrefix(input []byte) bool {
  209. return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X')
  210. }
  211. func checkJSON(input []byte) (raw []byte, err error) {
  212. if !isString(input) {
  213. return nil, errNonString
  214. }
  215. if len(input) == 2 {
  216. return nil, nil // empty strings are allowed
  217. }
  218. if !bytesHave0xPrefix(input[1:]) {
  219. return nil, ErrMissingPrefix
  220. }
  221. input = input[3 : len(input)-1]
  222. if len(input)%2 != 0 {
  223. return nil, ErrOddLength
  224. }
  225. return input, nil
  226. }
  227. func checkNumberJSON(input []byte) (raw []byte, err error) {
  228. if !isString(input) {
  229. return nil, errNonString
  230. }
  231. input = input[1 : len(input)-1]
  232. if len(input) == 0 {
  233. return nil, nil // empty strings are allowed
  234. }
  235. if !bytesHave0xPrefix(input) {
  236. return nil, ErrMissingPrefix
  237. }
  238. input = input[2:]
  239. if len(input) == 0 {
  240. return nil, ErrEmptyNumber
  241. }
  242. if len(input) > 1 && input[0] == '0' {
  243. return nil, ErrLeadingZero
  244. }
  245. return input, nil
  246. }