github.com/oskarth/go-ethereum@v1.6.8-0.20191013093314-dac24a9d3494/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  func getFullElemSize(elem *Type) int {
   119  	//all other should be counted as 32 (slices have pointers to respective elements)
   120  	size := 32
   121  	//arrays wrap it, each element being the same size
   122  	for elem.T == ArrayTy {
   123  		size *= elem.Size
   124  		elem = elem.Elem
   125  	}
   126  	return size
   127  }
   128  
   129  // iteratively unpack elements
   130  func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) {
   131  	if size < 0 {
   132  		return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size)
   133  	}
   134  	if start+32*size > len(output) {
   135  		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)
   136  	}
   137  
   138  	// this value will become our slice or our array, depending on the type
   139  	var refSlice reflect.Value
   140  
   141  	if t.T == SliceTy {
   142  		// declare our slice
   143  		refSlice = reflect.MakeSlice(t.Type, size, size)
   144  	} else if t.T == ArrayTy {
   145  		// declare our array
   146  		refSlice = reflect.New(t.Type).Elem()
   147  	} else {
   148  		return nil, fmt.Errorf("abi: invalid type in array/slice unpacking stage")
   149  	}
   150  
   151  	// Arrays have packed elements, resulting in longer unpack steps.
   152  	// Slices have just 32 bytes per element (pointing to the contents).
   153  	elemSize := 32
   154  	if t.T == ArrayTy {
   155  		elemSize = getFullElemSize(t.Elem)
   156  	}
   157  
   158  	for i, j := start, 0; j < size; i, j = i+elemSize, j+1 {
   159  
   160  		inter, err := toGoType(i, *t.Elem, output)
   161  		if err != nil {
   162  			return nil, err
   163  		}
   164  
   165  		// append the item to our reflect slice
   166  		refSlice.Index(j).Set(reflect.ValueOf(inter))
   167  	}
   168  
   169  	// return the interface
   170  	return refSlice.Interface(), nil
   171  }
   172  
   173  // toGoType parses the output bytes and recursively assigns the value of these bytes
   174  // into a go type with accordance with the ABI spec.
   175  func toGoType(index int, t Type, output []byte) (interface{}, error) {
   176  	if index+32 > len(output) {
   177  		return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), index+32)
   178  	}
   179  
   180  	var (
   181  		returnOutput []byte
   182  		begin, end   int
   183  		err          error
   184  	)
   185  
   186  	// if we require a length prefix, find the beginning word and size returned.
   187  	if t.requiresLengthPrefix() {
   188  		begin, end, err = lengthPrefixPointsTo(index, output)
   189  		if err != nil {
   190  			return nil, err
   191  		}
   192  	} else {
   193  		returnOutput = output[index : index+32]
   194  	}
   195  
   196  	switch t.T {
   197  	case SliceTy:
   198  		return forEachUnpack(t, output, begin, end)
   199  	case ArrayTy:
   200  		return forEachUnpack(t, output, index, t.Size)
   201  	case StringTy: // variable arrays are written at the end of the return bytes
   202  		return string(output[begin : begin+end]), nil
   203  	case IntTy, UintTy:
   204  		return readInteger(t.T, t.Kind, returnOutput), nil
   205  	case BoolTy:
   206  		return readBool(returnOutput)
   207  	case AddressTy:
   208  		return common.BytesToAddress(returnOutput), nil
   209  	case HashTy:
   210  		return common.BytesToHash(returnOutput), nil
   211  	case BytesTy:
   212  		return output[begin : begin+end], nil
   213  	case FixedBytesTy:
   214  		return readFixedBytes(t, returnOutput)
   215  	case FunctionTy:
   216  		return readFunctionType(t, returnOutput)
   217  	default:
   218  		return nil, fmt.Errorf("abi: unknown type %v", t.T)
   219  	}
   220  }
   221  
   222  // interprets a 32 byte slice as an offset and then determines which indice to look to decode the type.
   223  func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) {
   224  	bigOffsetEnd := big.NewInt(0).SetBytes(output[index : index+32])
   225  	bigOffsetEnd.Add(bigOffsetEnd, common.Big32)
   226  	outputLength := big.NewInt(int64(len(output)))
   227  
   228  	if bigOffsetEnd.Cmp(outputLength) > 0 {
   229  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", bigOffsetEnd, outputLength)
   230  	}
   231  
   232  	if bigOffsetEnd.BitLen() > 63 {
   233  		return 0, 0, fmt.Errorf("abi offset larger than int64: %v", bigOffsetEnd)
   234  	}
   235  
   236  	offsetEnd := int(bigOffsetEnd.Uint64())
   237  	lengthBig := big.NewInt(0).SetBytes(output[offsetEnd-32 : offsetEnd])
   238  
   239  	totalSize := big.NewInt(0)
   240  	totalSize.Add(totalSize, bigOffsetEnd)
   241  	totalSize.Add(totalSize, lengthBig)
   242  	if totalSize.BitLen() > 63 {
   243  		return 0, 0, fmt.Errorf("abi length larger than int64: %v", totalSize)
   244  	}
   245  
   246  	if totalSize.Cmp(outputLength) > 0 {
   247  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %v require %v", outputLength, totalSize)
   248  	}
   249  	start = int(bigOffsetEnd.Uint64())
   250  	length = int(lengthBig.Uint64())
   251  	return
   252  }