github.com/ethereum/go-ethereum@v1.14.3/accounts/abi/unpack.go (about)

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