github.com/aerth/aquachain@v1.4.1/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  	"github.com/aquanetwork/aquachain/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  // iteratively unpack elements
    97  func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) {
    98  	if size < 0 {
    99  		return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size)
   100  	}
   101  	if start+32*size > len(output) {
   102  		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)
   103  	}
   104  
   105  	// this value will become our slice or our array, depending on the type
   106  	var refSlice reflect.Value
   107  	slice := output[start : start+size*32]
   108  
   109  	if t.T == SliceTy {
   110  		// declare our slice
   111  		refSlice = reflect.MakeSlice(t.Type, size, size)
   112  	} else if t.T == ArrayTy {
   113  		// declare our array
   114  		refSlice = reflect.New(t.Type).Elem()
   115  	} else {
   116  		return nil, fmt.Errorf("abi: invalid type in array/slice unpacking stage")
   117  	}
   118  
   119  	for i, j := start, 0; j*32 < len(slice); i, j = i+32, j+1 {
   120  		// this corrects the arrangement so that we get all the underlying array values
   121  		if t.Elem.T == ArrayTy && j != 0 {
   122  			i = start + t.Elem.Size*32*j
   123  		}
   124  		inter, err := toGoType(i, *t.Elem, output)
   125  		if err != nil {
   126  			return nil, err
   127  		}
   128  		// append the item to our reflect slice
   129  		refSlice.Index(j).Set(reflect.ValueOf(inter))
   130  	}
   131  
   132  	// return the interface
   133  	return refSlice.Interface(), nil
   134  }
   135  
   136  // toGoType parses the output bytes and recursively assigns the value of these bytes
   137  // into a go type with accordance with the ABI spec.
   138  func toGoType(index int, t Type, output []byte) (interface{}, error) {
   139  	if index+32 > len(output) {
   140  		return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), index+32)
   141  	}
   142  
   143  	var (
   144  		returnOutput []byte
   145  		begin, end   int
   146  		err          error
   147  	)
   148  
   149  	// if we require a length prefix, find the beginning word and size returned.
   150  	if t.requiresLengthPrefix() {
   151  		begin, end, err = lengthPrefixPointsTo(index, output)
   152  		if err != nil {
   153  			return nil, err
   154  		}
   155  	} else {
   156  		returnOutput = output[index : index+32]
   157  	}
   158  
   159  	switch t.T {
   160  	case SliceTy:
   161  		return forEachUnpack(t, output, begin, end)
   162  	case ArrayTy:
   163  		return forEachUnpack(t, output, index, t.Size)
   164  	case StringTy: // variable arrays are written at the end of the return bytes
   165  		return string(output[begin : begin+end]), nil
   166  	case IntTy, UintTy:
   167  		return readInteger(t.Kind, returnOutput), nil
   168  	case BoolTy:
   169  		return readBool(returnOutput)
   170  	case AddressTy:
   171  		return common.BytesToAddress(returnOutput), nil
   172  	case HashTy:
   173  		return common.BytesToHash(returnOutput), nil
   174  	case BytesTy:
   175  		return output[begin : begin+end], nil
   176  	case FixedBytesTy:
   177  		return readFixedBytes(t, returnOutput)
   178  	case FunctionTy:
   179  		return readFunctionType(t, returnOutput)
   180  	default:
   181  		return nil, fmt.Errorf("abi: unknown type %v", t.T)
   182  	}
   183  }
   184  
   185  // interprets a 32 byte slice as an offset and then determines which indice to look to decode the type.
   186  func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) {
   187  	bigOffsetEnd := big.NewInt(0).SetBytes(output[index : index+32])
   188  	bigOffsetEnd.Add(bigOffsetEnd, common.Big32)
   189  	outputLength := big.NewInt(int64(len(output)))
   190  
   191  	if bigOffsetEnd.Cmp(outputLength) > 0 {
   192  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", bigOffsetEnd, outputLength)
   193  	}
   194  
   195  	if bigOffsetEnd.BitLen() > 63 {
   196  		return 0, 0, fmt.Errorf("abi offset larger than int64: %v", bigOffsetEnd)
   197  	}
   198  
   199  	offsetEnd := int(bigOffsetEnd.Uint64())
   200  	lengthBig := big.NewInt(0).SetBytes(output[offsetEnd-32 : offsetEnd])
   201  
   202  	totalSize := big.NewInt(0)
   203  	totalSize.Add(totalSize, bigOffsetEnd)
   204  	totalSize.Add(totalSize, lengthBig)
   205  	if totalSize.BitLen() > 63 {
   206  		return 0, 0, fmt.Errorf("abi length larger than int64: %v", totalSize)
   207  	}
   208  
   209  	if totalSize.Cmp(outputLength) > 0 {
   210  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %v require %v", outputLength, totalSize)
   211  	}
   212  	start = int(bigOffsetEnd.Uint64())
   213  	length = int(lengthBig.Uint64())
   214  	return
   215  }