github.com/core-coin/go-core/v2@v2.1.9/accounts/abi/unpack.go (about)

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