github.com/quinndk/ethereum_read@v0.0.0-20181211143958-29c55eec3237/go-ethereum-master_read/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  // reads the integer based on its kind
    29  func readInteger(kind reflect.Kind, b []byte) interface{} {
    30  	switch kind {
    31  	case reflect.Uint8:
    32  		return b[len(b)-1]
    33  	case reflect.Uint16:
    34  		return binary.BigEndian.Uint16(b[len(b)-2:])
    35  	case reflect.Uint32:
    36  		return binary.BigEndian.Uint32(b[len(b)-4:])
    37  	case reflect.Uint64:
    38  		return binary.BigEndian.Uint64(b[len(b)-8:])
    39  	case reflect.Int8:
    40  		return int8(b[len(b)-1])
    41  	case reflect.Int16:
    42  		return int16(binary.BigEndian.Uint16(b[len(b)-2:]))
    43  	case reflect.Int32:
    44  		return int32(binary.BigEndian.Uint32(b[len(b)-4:]))
    45  	case reflect.Int64:
    46  		return int64(binary.BigEndian.Uint64(b[len(b)-8:]))
    47  	default:
    48  		return new(big.Int).SetBytes(b)
    49  	}
    50  }
    51  
    52  // reads a bool
    53  func readBool(word []byte) (bool, error) {
    54  	for _, b := range word[:31] {
    55  		if b != 0 {
    56  			return false, errBadBool
    57  		}
    58  	}
    59  	switch word[31] {
    60  	case 0:
    61  		return false, nil
    62  	case 1:
    63  		return true, nil
    64  	default:
    65  		return false, errBadBool
    66  	}
    67  }
    68  
    69  // A function type is simply the address with the function selection signature at the end.
    70  // This enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes)
    71  func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) {
    72  	if t.T != FunctionTy {
    73  		return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array")
    74  	}
    75  	if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 {
    76  		err = fmt.Errorf("abi: got improperly encoded function type, got %v", word)
    77  	} else {
    78  		copy(funcTy[:], word[0:24])
    79  	}
    80  	return
    81  }
    82  
    83  // through reflection, creates a fixed array to be read from
    84  func readFixedBytes(t Type, word []byte) (interface{}, error) {
    85  	if t.T != FixedBytesTy {
    86  		return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array")
    87  	}
    88  	// convert
    89  	array := reflect.New(t.Type).Elem()
    90  
    91  	reflect.Copy(array, reflect.ValueOf(word[0:t.Size]))
    92  	return array.Interface(), nil
    93  
    94  }
    95  
    96  func getFullElemSize(elem *Type) int {
    97  	//all other should be counted as 32 (slices have pointers to respective elements)
    98  	size := 32
    99  	//arrays wrap it, each element being the same size
   100  	for elem.T == ArrayTy {
   101  		size *= elem.Size
   102  		elem = elem.Elem
   103  	}
   104  	return size
   105  }
   106  
   107  // iteratively unpack elements
   108  func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) {
   109  	if size < 0 {
   110  		return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size)
   111  	}
   112  	if start+32*size > len(output) {
   113  		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)
   114  	}
   115  
   116  	// this value will become our slice or our array, depending on the type
   117  	var refSlice reflect.Value
   118  
   119  	if t.T == SliceTy {
   120  		// declare our slice
   121  		refSlice = reflect.MakeSlice(t.Type, size, size)
   122  	} else if t.T == ArrayTy {
   123  		// declare our array
   124  		refSlice = reflect.New(t.Type).Elem()
   125  	} else {
   126  		return nil, fmt.Errorf("abi: invalid type in array/slice unpacking stage")
   127  	}
   128  
   129  	// Arrays have packed elements, resulting in longer unpack steps.
   130  	// Slices have just 32 bytes per element (pointing to the contents).
   131  	elemSize := 32
   132  	if t.T == ArrayTy {
   133  		elemSize = getFullElemSize(t.Elem)
   134  	}
   135  
   136  	for i, j := start, 0; j < size; i, j = i+elemSize, j+1 {
   137  
   138  		inter, err := toGoType(i, *t.Elem, output)
   139  		if err != nil {
   140  			return nil, err
   141  		}
   142  
   143  		// append the item to our reflect slice
   144  		refSlice.Index(j).Set(reflect.ValueOf(inter))
   145  	}
   146  
   147  	// return the interface
   148  	return refSlice.Interface(), nil
   149  }
   150  
   151  // toGoType parses the output bytes and recursively assigns the value of these bytes
   152  // into a go type with accordance with the ABI spec.
   153  func toGoType(index int, t Type, output []byte) (interface{}, error) {
   154  	if index+32 > len(output) {
   155  		return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), index+32)
   156  	}
   157  
   158  	var (
   159  		returnOutput []byte
   160  		begin, end   int
   161  		err          error
   162  	)
   163  
   164  	// if we require a length prefix, find the beginning word and size returned.
   165  	if t.requiresLengthPrefix() {
   166  		begin, end, err = lengthPrefixPointsTo(index, output)
   167  		if err != nil {
   168  			return nil, err
   169  		}
   170  	} else {
   171  		returnOutput = output[index : index+32]
   172  	}
   173  
   174  	switch t.T {
   175  	case SliceTy:
   176  		return forEachUnpack(t, output, begin, end)
   177  	case ArrayTy:
   178  		return forEachUnpack(t, output, index, t.Size)
   179  	case StringTy: // variable arrays are written at the end of the return bytes
   180  		return string(output[begin : begin+end]), nil
   181  	case IntTy, UintTy:
   182  		return readInteger(t.Kind, returnOutput), nil
   183  	case BoolTy:
   184  		return readBool(returnOutput)
   185  	case AddressTy:
   186  		return common.BytesToAddress(returnOutput), nil
   187  	case HashTy:
   188  		return common.BytesToHash(returnOutput), nil
   189  	case BytesTy:
   190  		return output[begin : begin+end], nil
   191  	case FixedBytesTy:
   192  		return readFixedBytes(t, returnOutput)
   193  	case FunctionTy:
   194  		return readFunctionType(t, returnOutput)
   195  	default:
   196  		return nil, fmt.Errorf("abi: unknown type %v", t.T)
   197  	}
   198  }
   199  
   200  // interprets a 32 byte slice as an offset and then determines which indice to look to decode the type.
   201  func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) {
   202  	bigOffsetEnd := big.NewInt(0).SetBytes(output[index : index+32])
   203  	bigOffsetEnd.Add(bigOffsetEnd, common.Big32)
   204  	outputLength := big.NewInt(int64(len(output)))
   205  
   206  	if bigOffsetEnd.Cmp(outputLength) > 0 {
   207  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", bigOffsetEnd, outputLength)
   208  	}
   209  
   210  	if bigOffsetEnd.BitLen() > 63 {
   211  		return 0, 0, fmt.Errorf("abi offset larger than int64: %v", bigOffsetEnd)
   212  	}
   213  
   214  	offsetEnd := int(bigOffsetEnd.Uint64())
   215  	lengthBig := big.NewInt(0).SetBytes(output[offsetEnd-32 : offsetEnd])
   216  
   217  	totalSize := big.NewInt(0)
   218  	totalSize.Add(totalSize, bigOffsetEnd)
   219  	totalSize.Add(totalSize, lengthBig)
   220  	if totalSize.BitLen() > 63 {
   221  		return 0, 0, fmt.Errorf("abi length larger than int64: %v", totalSize)
   222  	}
   223  
   224  	if totalSize.Cmp(outputLength) > 0 {
   225  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %v require %v", outputLength, totalSize)
   226  	}
   227  	start = int(bigOffsetEnd.Uint64())
   228  	length = int(lengthBig.Uint64())
   229  	return
   230  }