github.com/aquanetwork/aquachain@v1.7.8/aqua/accounts/abi/unpack.go (about)

     1  // Copyright 2017 The aquachain Authors
     2  // This file is part of the aquachain library.
     3  //
     4  // The aquachain 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 aquachain 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 aquachain 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  	"gitlab.com/aquachain/aquachain/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  	slice := output[start : start+size*32]
   130  
   131  	if t.T == SliceTy {
   132  		// declare our slice
   133  		refSlice = reflect.MakeSlice(t.Type, size, size)
   134  	} else if t.T == ArrayTy {
   135  		// declare our array
   136  		refSlice = reflect.New(t.Type).Elem()
   137  	} else {
   138  		return nil, fmt.Errorf("abi: invalid type in array/slice unpacking stage")
   139  	}
   140  
   141  	for i, j := start, 0; j*32 < len(slice); i, j = i+32, j+1 {
   142  		// this corrects the arrangement so that we get all the underlying array values
   143  		if t.Elem.T == ArrayTy && j != 0 {
   144  			i = start + t.Elem.Size*32*j
   145  		}
   146  		inter, err := toGoType(i, *t.Elem, output)
   147  		if err != nil {
   148  			return nil, err
   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  // toGoType parses the output bytes and recursively assigns the value of these bytes
   159  // into a go type with accordance with the ABI spec.
   160  func toGoType(index int, t Type, output []byte) (interface{}, error) {
   161  	if index+32 > len(output) {
   162  		return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), index+32)
   163  	}
   164  
   165  	var (
   166  		returnOutput []byte
   167  		begin, end   int
   168  		err          error
   169  	)
   170  
   171  	// if we require a length prefix, find the beginning word and size returned.
   172  	if t.requiresLengthPrefix() {
   173  		begin, end, err = lengthPrefixPointsTo(index, output)
   174  		if err != nil {
   175  			return nil, err
   176  		}
   177  	} else {
   178  		returnOutput = output[index : index+32]
   179  	}
   180  
   181  	switch t.T {
   182  	case SliceTy:
   183  		return forEachUnpack(t, output, begin, end)
   184  	case ArrayTy:
   185  		return forEachUnpack(t, output, index, t.Size)
   186  	case StringTy: // variable arrays are written at the end of the return bytes
   187  		return string(output[begin : begin+end]), nil
   188  	case IntTy, UintTy:
   189  		return readInteger(t.T, t.Kind, returnOutput), nil
   190  	case BoolTy:
   191  		return readBool(returnOutput)
   192  	case AddressTy:
   193  		return common.BytesToAddress(returnOutput), nil
   194  	case HashTy:
   195  		return common.BytesToHash(returnOutput), nil
   196  	case BytesTy:
   197  		return output[begin : begin+end], nil
   198  	case FixedBytesTy:
   199  		return readFixedBytes(t, returnOutput)
   200  	case FunctionTy:
   201  		return readFunctionType(t, returnOutput)
   202  	default:
   203  		return nil, fmt.Errorf("abi: unknown type %v", t.T)
   204  	}
   205  }
   206  
   207  // interprets a 32 byte slice as an offset and then determines which indice to look to decode the type.
   208  func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) {
   209  	bigOffsetEnd := big.NewInt(0).SetBytes(output[index : index+32])
   210  	bigOffsetEnd.Add(bigOffsetEnd, common.Big32)
   211  	outputLength := big.NewInt(int64(len(output)))
   212  
   213  	if bigOffsetEnd.Cmp(outputLength) > 0 {
   214  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", bigOffsetEnd, outputLength)
   215  	}
   216  
   217  	if bigOffsetEnd.BitLen() > 63 {
   218  		return 0, 0, fmt.Errorf("abi offset larger than int64: %v", bigOffsetEnd)
   219  	}
   220  
   221  	offsetEnd := int(bigOffsetEnd.Uint64())
   222  	lengthBig := big.NewInt(0).SetBytes(output[offsetEnd-32 : offsetEnd])
   223  
   224  	totalSize := big.NewInt(0)
   225  	totalSize.Add(totalSize, bigOffsetEnd)
   226  	totalSize.Add(totalSize, lengthBig)
   227  	if totalSize.BitLen() > 63 {
   228  		return 0, 0, fmt.Errorf("abi length larger than int64: %v", totalSize)
   229  	}
   230  
   231  	if totalSize.Cmp(outputLength) > 0 {
   232  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %v require %v", outputLength, totalSize)
   233  	}
   234  	start = int(bigOffsetEnd.Uint64())
   235  	length = int(lengthBig.Uint64())
   236  	return
   237  }