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