github.com/fff-chain/go-fff@v0.0.0-20220726032732-1c84420b8a99/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/fff-chain/go-fff/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  
   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  }