github.com/ava-labs/subnet-evm@v0.6.4/accounts/abi/unpack.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2017 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package abi
    28  
    29  import (
    30  	"encoding/binary"
    31  	"errors"
    32  	"fmt"
    33  	"math"
    34  	"math/big"
    35  	"reflect"
    36  
    37  	"github.com/ethereum/go-ethereum/common"
    38  )
    39  
    40  var (
    41  	// MaxUint256 is the maximum value that can be represented by a uint256.
    42  	MaxUint256 = new(big.Int).Sub(new(big.Int).Lsh(common.Big1, 256), common.Big1)
    43  	// MaxInt256 is the maximum value that can be represented by a int256.
    44  	MaxInt256 = new(big.Int).Sub(new(big.Int).Lsh(common.Big1, 255), common.Big1)
    45  )
    46  
    47  // ReadInteger reads the integer based on its kind and returns the appropriate value.
    48  func ReadInteger(typ Type, b []byte) (interface{}, error) {
    49  	ret := new(big.Int).SetBytes(b)
    50  
    51  	if typ.T == UintTy {
    52  		u64, isu64 := ret.Uint64(), ret.IsUint64()
    53  		switch typ.Size {
    54  		case 8:
    55  			if !isu64 || u64 > math.MaxUint8 {
    56  				return nil, errBadUint8
    57  			}
    58  			return byte(u64), nil
    59  		case 16:
    60  			if !isu64 || u64 > math.MaxUint16 {
    61  				return nil, errBadUint16
    62  			}
    63  			return uint16(u64), nil
    64  		case 32:
    65  			if !isu64 || u64 > math.MaxUint32 {
    66  				return nil, errBadUint32
    67  			}
    68  			return uint32(u64), nil
    69  		case 64:
    70  			if !isu64 {
    71  				return nil, errBadUint64
    72  			}
    73  			return u64, nil
    74  		default:
    75  			// the only case left for unsigned integer is uint256.
    76  			return ret, nil
    77  		}
    78  	}
    79  
    80  	// big.SetBytes can't tell if a number is negative or positive in itself.
    81  	// On EVM, if the returned number > max int256, it is negative.
    82  	// A number is > max int256 if the bit at position 255 is set.
    83  	if ret.Bit(255) == 1 {
    84  		ret.Add(MaxUint256, new(big.Int).Neg(ret))
    85  		ret.Add(ret, common.Big1)
    86  		ret.Neg(ret)
    87  	}
    88  	i64, isi64 := ret.Int64(), ret.IsInt64()
    89  	switch typ.Size {
    90  	case 8:
    91  		if !isi64 || i64 < math.MinInt8 || i64 > math.MaxInt8 {
    92  			return nil, errBadInt8
    93  		}
    94  		return int8(i64), nil
    95  	case 16:
    96  		if !isi64 || i64 < math.MinInt16 || i64 > math.MaxInt16 {
    97  			return nil, errBadInt16
    98  		}
    99  		return int16(i64), nil
   100  	case 32:
   101  		if !isi64 || i64 < math.MinInt32 || i64 > math.MaxInt32 {
   102  			return nil, errBadInt32
   103  		}
   104  		return int32(i64), nil
   105  	case 64:
   106  		if !isi64 {
   107  			return nil, errBadInt64
   108  		}
   109  		return i64, nil
   110  	default:
   111  		// the only case left for integer is int256
   112  
   113  		return ret, nil
   114  	}
   115  }
   116  
   117  // readBool reads a bool.
   118  func readBool(word []byte) (bool, error) {
   119  	for _, b := range word[:31] {
   120  		if b != 0 {
   121  			return false, errBadBool
   122  		}
   123  	}
   124  	switch word[31] {
   125  	case 0:
   126  		return false, nil
   127  	case 1:
   128  		return true, nil
   129  	default:
   130  		return false, errBadBool
   131  	}
   132  }
   133  
   134  // A function type is simply the address with the function selection signature at the end.
   135  //
   136  // readFunctionType enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes)
   137  func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) {
   138  	if t.T != FunctionTy {
   139  		return [24]byte{}, errors.New("abi: invalid type in call to make function type byte array")
   140  	}
   141  	if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 {
   142  		err = fmt.Errorf("abi: got improperly encoded function type, got %v", word)
   143  	} else {
   144  		copy(funcTy[:], word[0:24])
   145  	}
   146  	return
   147  }
   148  
   149  // ReadFixedBytes uses reflection to create a fixed array to be read from.
   150  func ReadFixedBytes(t Type, word []byte) (interface{}, error) {
   151  	if t.T != FixedBytesTy {
   152  		return nil, errors.New("abi: invalid type in call to make fixed byte array")
   153  	}
   154  	// convert
   155  	array := reflect.New(t.GetType()).Elem()
   156  
   157  	reflect.Copy(array, reflect.ValueOf(word[0:t.Size]))
   158  	return array.Interface(), nil
   159  }
   160  
   161  // forEachUnpack iteratively unpack elements.
   162  func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) {
   163  	if size < 0 {
   164  		return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size)
   165  	}
   166  	if start+32*size > len(output) {
   167  		return nil, fmt.Errorf("abi: cannot marshal into go array: offset %d would go over slice boundary (len=%d)", len(output), start+32*size)
   168  	}
   169  
   170  	// this value will become our slice or our array, depending on the type
   171  	var refSlice reflect.Value
   172  
   173  	switch t.T {
   174  	case SliceTy:
   175  		// declare our slice
   176  		refSlice = reflect.MakeSlice(t.GetType(), size, size)
   177  	case ArrayTy:
   178  		// declare our array
   179  		refSlice = reflect.New(t.GetType()).Elem()
   180  	default:
   181  		return nil, errors.New("abi: invalid type in array/slice unpacking stage")
   182  	}
   183  
   184  	// Arrays have packed elements, resulting in longer unpack steps.
   185  	// Slices have just 32 bytes per element (pointing to the contents).
   186  	elemSize := getTypeSize(*t.Elem)
   187  
   188  	for i, j := start, 0; j < size; i, j = i+elemSize, j+1 {
   189  		inter, err := toGoType(i, *t.Elem, output)
   190  		if err != nil {
   191  			return nil, err
   192  		}
   193  
   194  		// append the item to our reflect slice
   195  		refSlice.Index(j).Set(reflect.ValueOf(inter))
   196  	}
   197  
   198  	// return the interface
   199  	return refSlice.Interface(), nil
   200  }
   201  
   202  func forTupleUnpack(t Type, output []byte) (interface{}, error) {
   203  	retval := reflect.New(t.GetType()).Elem()
   204  	virtualArgs := 0
   205  	for index, elem := range t.TupleElems {
   206  		marshalledValue, err := toGoType((index+virtualArgs)*32, *elem, output)
   207  		if err != nil {
   208  			return nil, err
   209  		}
   210  		if elem.T == ArrayTy && !isDynamicType(*elem) {
   211  			// If we have a static array, like [3]uint256, these are coded as
   212  			// just like uint256,uint256,uint256.
   213  			// This means that we need to add two 'virtual' arguments when
   214  			// we count the index from now on.
   215  			//
   216  			// Array values nested multiple levels deep are also encoded inline:
   217  			// [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256
   218  			//
   219  			// Calculate the full array size to get the correct offset for the next argument.
   220  			// Decrement it by 1, as the normal index increment is still applied.
   221  			virtualArgs += getTypeSize(*elem)/32 - 1
   222  		} else if elem.T == TupleTy && !isDynamicType(*elem) {
   223  			// If we have a static tuple, like (uint256, bool, uint256), these are
   224  			// coded as just like uint256,bool,uint256
   225  			virtualArgs += getTypeSize(*elem)/32 - 1
   226  		}
   227  		retval.Field(index).Set(reflect.ValueOf(marshalledValue))
   228  	}
   229  	return retval.Interface(), nil
   230  }
   231  
   232  // toGoType parses the output bytes and recursively assigns the value of these bytes
   233  // into a go type with accordance with the ABI spec.
   234  func toGoType(index int, t Type, output []byte) (interface{}, error) {
   235  	if index+32 > len(output) {
   236  		return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), index+32)
   237  	}
   238  
   239  	var (
   240  		returnOutput  []byte
   241  		begin, length int
   242  		err           error
   243  	)
   244  
   245  	// if we require a length prefix, find the beginning word and size returned.
   246  	if t.requiresLengthPrefix() {
   247  		begin, length, err = lengthPrefixPointsTo(index, output)
   248  		if err != nil {
   249  			return nil, err
   250  		}
   251  	} else {
   252  		returnOutput = output[index : index+32]
   253  	}
   254  
   255  	switch t.T {
   256  	case TupleTy:
   257  		if isDynamicType(t) {
   258  			begin, err := tuplePointsTo(index, output)
   259  			if err != nil {
   260  				return nil, err
   261  			}
   262  			return forTupleUnpack(t, output[begin:])
   263  		}
   264  		return forTupleUnpack(t, output[index:])
   265  	case SliceTy:
   266  		return forEachUnpack(t, output[begin:], 0, length)
   267  	case ArrayTy:
   268  		if isDynamicType(*t.Elem) {
   269  			offset := binary.BigEndian.Uint64(returnOutput[len(returnOutput)-8:])
   270  			if offset > uint64(len(output)) {
   271  				return nil, fmt.Errorf("abi: toGoType offset greater than output length: offset: %d, len(output): %d", offset, len(output))
   272  			}
   273  			return forEachUnpack(t, output[offset:], 0, t.Size)
   274  		}
   275  		return forEachUnpack(t, output[index:], 0, t.Size)
   276  	case StringTy: // variable arrays are written at the end of the return bytes
   277  		return string(output[begin : begin+length]), nil
   278  	case IntTy, UintTy:
   279  		return ReadInteger(t, returnOutput)
   280  	case BoolTy:
   281  		return readBool(returnOutput)
   282  	case AddressTy:
   283  		return common.BytesToAddress(returnOutput), nil
   284  	case HashTy:
   285  		return common.BytesToHash(returnOutput), nil
   286  	case BytesTy:
   287  		return output[begin : begin+length], nil
   288  	case FixedBytesTy:
   289  		return ReadFixedBytes(t, returnOutput)
   290  	case FunctionTy:
   291  		return readFunctionType(t, returnOutput)
   292  	default:
   293  		return nil, fmt.Errorf("abi: unknown type %v", t.T)
   294  	}
   295  }
   296  
   297  // lengthPrefixPointsTo interprets a 32 byte slice as an offset and then determines which indices to look to decode the type.
   298  func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) {
   299  	bigOffsetEnd := new(big.Int).SetBytes(output[index : index+32])
   300  	bigOffsetEnd.Add(bigOffsetEnd, common.Big32)
   301  	outputLength := big.NewInt(int64(len(output)))
   302  
   303  	if bigOffsetEnd.Cmp(outputLength) > 0 {
   304  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", bigOffsetEnd, outputLength)
   305  	}
   306  
   307  	if bigOffsetEnd.BitLen() > 63 {
   308  		return 0, 0, fmt.Errorf("abi offset larger than int64: %v", bigOffsetEnd)
   309  	}
   310  
   311  	offsetEnd := int(bigOffsetEnd.Uint64())
   312  	lengthBig := new(big.Int).SetBytes(output[offsetEnd-32 : offsetEnd])
   313  
   314  	totalSize := new(big.Int).Add(bigOffsetEnd, lengthBig)
   315  	if totalSize.BitLen() > 63 {
   316  		return 0, 0, fmt.Errorf("abi: length larger than int64: %v", totalSize)
   317  	}
   318  
   319  	if totalSize.Cmp(outputLength) > 0 {
   320  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %v require %v", outputLength, totalSize)
   321  	}
   322  	start = int(bigOffsetEnd.Uint64())
   323  	length = int(lengthBig.Uint64())
   324  	return
   325  }
   326  
   327  // tuplePointsTo resolves the location reference for dynamic tuple.
   328  func tuplePointsTo(index int, output []byte) (start int, err error) {
   329  	offset := new(big.Int).SetBytes(output[index : index+32])
   330  	outputLen := big.NewInt(int64(len(output)))
   331  
   332  	if offset.Cmp(outputLen) > 0 {
   333  		return 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", offset, outputLen)
   334  	}
   335  	if offset.BitLen() > 63 {
   336  		return 0, fmt.Errorf("abi offset larger than int64: %v", offset)
   337  	}
   338  	return int(offset.Uint64()), nil
   339  }