json.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. // UnmarshalFixedJSON decodes the input as a string with 0x prefix. The length of out
  67. // determines the required input length. This function is commonly used to implement the
  68. // UnmarshalJSON method for fixed-size types.
  69. func UnmarshalFixedJSON(typ reflect.Type, input, out []byte) error {
  70. if !isString(input) {
  71. return errNonString(typ)
  72. }
  73. return wrapTypeError(UnmarshalFixedText(typ.String(), input[1:len(input)-1], out), typ)
  74. }
  75. // UnmarshalFixedText decodes the input as a string with 0x prefix. The length of out
  76. // determines the required input length. This function is commonly used to implement the
  77. // UnmarshalText method for fixed-size types.
  78. func UnmarshalFixedText(typname string, input, out []byte) error {
  79. raw, err := checkText(input, true)
  80. if err != nil {
  81. return err
  82. }
  83. if len(raw)/2 != len(out) {
  84. return fmt.Errorf("hex string has length %d, want %d for %s", len(raw), len(out)*2, typname)
  85. }
  86. // Pre-verify syntax before modifying out.
  87. for _, b := range raw {
  88. if decodeNibble(b) == badNibble {
  89. return ErrSyntax
  90. }
  91. }
  92. hex.Decode(out, raw)
  93. return nil
  94. }
  95. // UnmarshalFixedUnprefixedText decodes the input as a string with optional 0x prefix. The
  96. // length of out determines the required input length. This function is commonly used to
  97. // implement the UnmarshalText method for fixed-size types.
  98. func UnmarshalFixedUnprefixedText(typname string, input, out []byte) error {
  99. raw, err := checkText(input, false)
  100. if err != nil {
  101. return err
  102. }
  103. if len(raw)/2 != len(out) {
  104. return fmt.Errorf("hex string has length %d, want %d for %s", len(raw), len(out)*2, typname)
  105. }
  106. // Pre-verify syntax before modifying out.
  107. for _, b := range raw {
  108. if decodeNibble(b) == badNibble {
  109. return ErrSyntax
  110. }
  111. }
  112. hex.Decode(out, raw)
  113. return nil
  114. }
  115. // Big marshals/unmarshals as a JSON string with 0x prefix.
  116. // The zero value marshals as "0x0".
  117. //
  118. // Negative integers are not supported at this time. Attempting to marshal them will
  119. // return an error. Values larger than 256bits are rejected by Unmarshal but will be
  120. // marshaled without error.
  121. type Big big.Int
  122. // MarshalText implements encoding.TextMarshaler
  123. func (b Big) MarshalText() ([]byte, error) {
  124. return []byte(EncodeBig((*big.Int)(&b))), nil
  125. }
  126. // UnmarshalJSON implements json.Unmarshaler.
  127. func (b *Big) UnmarshalJSON(input []byte) error {
  128. if !isString(input) {
  129. return errNonString(bigT)
  130. }
  131. return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), bigT)
  132. }
  133. // UnmarshalText implements encoding.TextUnmarshaler
  134. func (b *Big) UnmarshalText(input []byte) error {
  135. raw, err := checkNumberText(input)
  136. if err != nil {
  137. return err
  138. }
  139. if len(raw) > 64 {
  140. return ErrBig256Range
  141. }
  142. words := make([]big.Word, len(raw)/bigWordNibbles+1)
  143. end := len(raw)
  144. for i := range words {
  145. start := end - bigWordNibbles
  146. if start < 0 {
  147. start = 0
  148. }
  149. for ri := start; ri < end; ri++ {
  150. nib := decodeNibble(raw[ri])
  151. if nib == badNibble {
  152. return ErrSyntax
  153. }
  154. words[i] *= 16
  155. words[i] += big.Word(nib)
  156. }
  157. end = start
  158. }
  159. var dec big.Int
  160. dec.SetBits(words)
  161. *b = (Big)(dec)
  162. return nil
  163. }
  164. // ToInt converts b to a big.Int.
  165. func (b *Big) ToInt() *big.Int {
  166. return (*big.Int)(b)
  167. }
  168. // String returns the hex encoding of b.
  169. func (b *Big) String() string {
  170. return EncodeBig(b.ToInt())
  171. }
  172. // Uint64 marshals/unmarshals as a JSON string with 0x prefix.
  173. // The zero value marshals as "0x0".
  174. type Uint64 uint64
  175. // MarshalText implements encoding.TextMarshaler.
  176. func (b Uint64) MarshalText() ([]byte, error) {
  177. buf := make([]byte, 2, 10)
  178. copy(buf, `0x`)
  179. buf = strconv.AppendUint(buf, uint64(b), 16)
  180. return buf, nil
  181. }
  182. // UnmarshalJSON implements json.Unmarshaler.
  183. func (b *Uint64) UnmarshalJSON(input []byte) error {
  184. if !isString(input) {
  185. return errNonString(uint64T)
  186. }
  187. return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), uint64T)
  188. }
  189. // UnmarshalText implements encoding.TextUnmarshaler
  190. func (b *Uint64) UnmarshalText(input []byte) error {
  191. raw, err := checkNumberText(input)
  192. if err != nil {
  193. return err
  194. }
  195. if len(raw) > 16 {
  196. return ErrUint64Range
  197. }
  198. var dec uint64
  199. for _, byte := range raw {
  200. nib := decodeNibble(byte)
  201. if nib == badNibble {
  202. return ErrSyntax
  203. }
  204. dec *= 16
  205. dec += nib
  206. }
  207. *b = Uint64(dec)
  208. return nil
  209. }
  210. // String returns the hex encoding of b.
  211. func (b Uint64) String() string {
  212. return EncodeUint64(uint64(b))
  213. }
  214. // Uint marshals/unmarshals as a JSON string with 0x prefix.
  215. // The zero value marshals as "0x0".
  216. type Uint uint
  217. // MarshalText implements encoding.TextMarshaler.
  218. func (b Uint) MarshalText() ([]byte, error) {
  219. return Uint64(b).MarshalText()
  220. }
  221. // UnmarshalJSON implements json.Unmarshaler.
  222. func (b *Uint) UnmarshalJSON(input []byte) error {
  223. if !isString(input) {
  224. return errNonString(uintT)
  225. }
  226. return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), uintT)
  227. }
  228. // UnmarshalText implements encoding.TextUnmarshaler.
  229. func (b *Uint) UnmarshalText(input []byte) error {
  230. var u64 Uint64
  231. err := u64.UnmarshalText(input)
  232. if u64 > Uint64(^uint(0)) || err == ErrUint64Range {
  233. return ErrUintRange
  234. } else if err != nil {
  235. return err
  236. }
  237. *b = Uint(u64)
  238. return nil
  239. }
  240. // String returns the hex encoding of b.
  241. func (b Uint) String() string {
  242. return EncodeUint64(uint64(b))
  243. }
  244. func isString(input []byte) bool {
  245. return len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"'
  246. }
  247. func bytesHave0xPrefix(input []byte) bool {
  248. return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X')
  249. }
  250. func checkText(input []byte, wantPrefix bool) ([]byte, error) {
  251. if len(input) == 0 {
  252. return nil, nil // empty strings are allowed
  253. }
  254. if bytesHave0xPrefix(input) {
  255. input = input[2:]
  256. } else if wantPrefix {
  257. return nil, ErrMissingPrefix
  258. }
  259. if len(input)%2 != 0 {
  260. return nil, ErrOddLength
  261. }
  262. return input, nil
  263. }
  264. func checkNumberText(input []byte) (raw []byte, err error) {
  265. if len(input) == 0 {
  266. return nil, nil // empty strings are allowed
  267. }
  268. if !bytesHave0xPrefix(input) {
  269. return nil, ErrMissingPrefix
  270. }
  271. input = input[2:]
  272. if len(input) == 0 {
  273. return nil, ErrEmptyNumber
  274. }
  275. if len(input) > 1 && input[0] == '0' {
  276. return nil, ErrLeadingZero
  277. }
  278. return input, nil
  279. }
  280. func wrapTypeError(err error, typ reflect.Type) error {
  281. if _, ok := err.(*decError); ok {
  282. return &json.UnmarshalTypeError{Value: err.Error(), Type: typ}
  283. }
  284. return err
  285. }
  286. func errNonString(typ reflect.Type) error {
  287. return &json.UnmarshalTypeError{Value: "non-string", Type: typ}
  288. }