github.com/intfoundation/intchain@v0.0.0-20220727031208-4316ad31ca73/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/intfoundation/intchain/common"
    26  )
    27  
    28  var (
    29  	// MaxUint256 is the maximum value that can be represented by a uint256
    30  	MaxUint256 = big.NewInt(0).Add(
    31  		big.NewInt(0).Exp(big.NewInt(2), big.NewInt(256), nil),
    32  		big.NewInt(-1))
    33  	// MaxInt256 is the maximum value that can be represented by a int256
    34  	MaxInt256 = big.NewInt(0).Add(
    35  		big.NewInt(0).Exp(big.NewInt(2), big.NewInt(255), nil),
    36  		big.NewInt(-1))
    37  )
    38  
    39  // ReadInteger reads the integer based on its kind and returns the appropriate value
    40  func ReadInteger(typ byte, kind reflect.Kind, b []byte) interface{} {
    41  	switch kind {
    42  	case reflect.Uint8:
    43  		return b[len(b)-1]
    44  	case reflect.Uint16:
    45  		return binary.BigEndian.Uint16(b[len(b)-2:])
    46  	case reflect.Uint32:
    47  		return binary.BigEndian.Uint32(b[len(b)-4:])
    48  	case reflect.Uint64:
    49  		return binary.BigEndian.Uint64(b[len(b)-8:])
    50  	case reflect.Int8:
    51  		return int8(b[len(b)-1])
    52  	case reflect.Int16:
    53  		return int16(binary.BigEndian.Uint16(b[len(b)-2:]))
    54  	case reflect.Int32:
    55  		return int32(binary.BigEndian.Uint32(b[len(b)-4:]))
    56  	case reflect.Int64:
    57  		return int64(binary.BigEndian.Uint64(b[len(b)-8:]))
    58  	default:
    59  		// the only case lefts for integer is int256/uint256.
    60  		// big.SetBytes can't tell if a number is negative, positive on itself.
    61  		// On EVM, if the returned number > max int256, it is negative.
    62  		ret := new(big.Int).SetBytes(b)
    63  		if typ == UintTy {
    64  			return ret
    65  		}
    66  
    67  		if ret.Cmp(MaxInt256) > 0 {
    68  			ret.Add(MaxUint256, big.NewInt(0).Neg(ret))
    69  			ret.Add(ret, big.NewInt(1))
    70  			ret.Neg(ret)
    71  		}
    72  		return ret
    73  	}
    74  }
    75  
    76  // 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  // This enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes)
    95  func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) {
    96  	if t.T != FunctionTy {
    97  		return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array")
    98  	}
    99  	if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 {
   100  		err = fmt.Errorf("abi: got improperly encoded function type, got %v", word)
   101  	} else {
   102  		copy(funcTy[:], word[0:24])
   103  	}
   104  	return
   105  }
   106  
   107  // ReadFixedBytes uses reflection to create a fixed array to be read from
   108  func ReadFixedBytes(t Type, word []byte) (interface{}, error) {
   109  	if t.T != FixedBytesTy {
   110  		return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array")
   111  	}
   112  	// convert
   113  	array := reflect.New(t.Type).Elem()
   114  
   115  	reflect.Copy(array, reflect.ValueOf(word[0:t.Size]))
   116  	return array.Interface(), nil
   117  
   118  }
   119  
   120  // 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.Type, size, size)
   135  	} else if t.T == ArrayTy {
   136  		// declare our array
   137  		refSlice = reflect.New(t.Type).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.Type).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  		} else {
   222  			return forTupleUnpack(t, output[index:])
   223  		}
   224  	case SliceTy:
   225  		return forEachUnpack(t, output[begin:], 0, length)
   226  	case ArrayTy:
   227  		if isDynamicType(*t.Elem) {
   228  			offset := int64(binary.BigEndian.Uint64(returnOutput[len(returnOutput)-8:]))
   229  			return forEachUnpack(t, output[offset:], 0, t.Size)
   230  		}
   231  		return forEachUnpack(t, output[index:], 0, t.Size)
   232  	case StringTy: // variable arrays are written at the end of the return bytes
   233  		return string(output[begin : begin+length]), nil
   234  	case IntTy, UintTy:
   235  		return ReadInteger(t.T, t.Kind, returnOutput), nil
   236  	case BoolTy:
   237  		return readBool(returnOutput)
   238  	case AddressTy:
   239  		return common.BytesToAddress(returnOutput), nil
   240  	case HashTy:
   241  		return common.BytesToHash(returnOutput), nil
   242  	case BytesTy:
   243  		return output[begin : begin+length], nil
   244  	case FixedBytesTy:
   245  		return ReadFixedBytes(t, returnOutput)
   246  	case FunctionTy:
   247  		return readFunctionType(t, returnOutput)
   248  	default:
   249  		return nil, fmt.Errorf("abi: unknown type %v", t.T)
   250  	}
   251  }
   252  
   253  // interprets a 32 byte slice as an offset and then determines which indice to look to decode the type.
   254  func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) {
   255  	bigOffsetEnd := big.NewInt(0).SetBytes(output[index : index+32])
   256  	bigOffsetEnd.Add(bigOffsetEnd, common.Big32)
   257  	outputLength := big.NewInt(int64(len(output)))
   258  
   259  	if bigOffsetEnd.Cmp(outputLength) > 0 {
   260  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", bigOffsetEnd, outputLength)
   261  	}
   262  
   263  	if bigOffsetEnd.BitLen() > 63 {
   264  		return 0, 0, fmt.Errorf("abi offset larger than int64: %v", bigOffsetEnd)
   265  	}
   266  
   267  	offsetEnd := int(bigOffsetEnd.Uint64())
   268  	lengthBig := big.NewInt(0).SetBytes(output[offsetEnd-32 : offsetEnd])
   269  
   270  	totalSize := big.NewInt(0)
   271  	totalSize.Add(totalSize, bigOffsetEnd)
   272  	totalSize.Add(totalSize, 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 := big.NewInt(0).SetBytes(output[index : index+32])
   288  	outputLen := big.NewInt(int64(len(output)))
   289  
   290  	if offset.Cmp(big.NewInt(int64(len(output)))) > 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  }