json.go 7.4 KB

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