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