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