github.com/bamzi/go-ethereum@v1.6.7-0.20170704111104-138f26c93af1/common/hexutil/json.go (about)

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