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