github.com/Debrief-BC/go-debrief@v0.0.0-20200420203408-0c26ca968123/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/Debrief-BC/go-debrief/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 byte, kind reflect.Kind, b []byte) interface{} {
    37  	switch kind {
    38  	case reflect.Uint8:
    39  		return b[len(b)-1]
    40  	case reflect.Uint16:
    41  		return binary.BigEndian.Uint16(b[len(b)-2:])
    42  	case reflect.Uint32:
    43  		return binary.BigEndian.Uint32(b[len(b)-4:])
    44  	case reflect.Uint64:
    45  		return binary.BigEndian.Uint64(b[len(b)-8:])
    46  	case reflect.Int8:
    47  		return int8(b[len(b)-1])
    48  	case reflect.Int16:
    49  		return int16(binary.BigEndian.Uint16(b[len(b)-2:]))
    50  	case reflect.Int32:
    51  		return int32(binary.BigEndian.Uint32(b[len(b)-4:]))
    52  	case reflect.Int64:
    53  		return int64(binary.BigEndian.Uint64(b[len(b)-8:]))
    54  	default:
    55  		// the only case left for integer is int256/uint256.
    56  		ret := new(big.Int).SetBytes(b)
    57  		if typ == UintTy {
    58  			return ret
    59  		}
    60  		// big.SetBytes can't tell if a number is negative or positive in itself.
    61  		// On EVM, if the returned number > max int256, it is negative.
    62  		// A number is > max int256 if the bit at position 255 is set.
    63  		if ret.Bit(255) == 1 {
    64  			ret.Add(MaxUint256, new(big.Int).Neg(ret))
    65  			ret.Add(ret, common.Big1)
    66  			ret.Neg(ret)
    67  		}
    68  		return ret
    69  	}
    70  }
    71  
    72  // reads a bool
    73  func readBool(word []byte) (bool, error) {
    74  	for _, b := range word[:31] {
    75  		if b != 0 {
    76  			return false, errBadBool
    77  		}
    78  	}
    79  	switch word[31] {
    80  	case 0:
    81  		return false, nil
    82  	case 1:
    83  		return true, nil
    84  	default:
    85  		return false, errBadBool
    86  	}
    87  }
    88  
    89  // A function type is simply the address with the function selection signature at the end.
    90  // This enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes)
    91  func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) {
    92  	if t.T != FunctionTy {
    93  		return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array")
    94  	}
    95  	if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 {
    96  		err = fmt.Errorf("abi: got improperly encoded function type, got %v", word)
    97  	} else {
    98  		copy(funcTy[:], word[0:24])
    99  	}
   100  	return
   101  }
   102  
   103  // ReadFixedBytes uses reflection to create a fixed array to be read from
   104  func ReadFixedBytes(t Type, word []byte) (interface{}, error) {
   105  	if t.T != FixedBytesTy {
   106  		return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array")
   107  	}
   108  	// convert
   109  	array := reflect.New(t.Type).Elem()
   110  
   111  	reflect.Copy(array, reflect.ValueOf(word[0:t.Size]))
   112  	return array.Interface(), nil
   113  
   114  }
   115  
   116  // iteratively unpack elements
   117  func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) {
   118  	if size < 0 {
   119  		return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size)
   120  	}
   121  	if start+32*size > len(output) {
   122  		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)
   123  	}
   124  
   125  	// this value will become our slice or our array, depending on the type
   126  	var refSlice reflect.Value
   127  
   128  	if t.T == SliceTy {
   129  		// declare our slice
   130  		refSlice = reflect.MakeSlice(t.Type, size, size)
   131  	} else if t.T == ArrayTy {
   132  		// declare our array
   133  		refSlice = reflect.New(t.Type).Elem()
   134  	} else {
   135  		return nil, fmt.Errorf("abi: invalid type in array/slice unpacking stage")
   136  	}
   137  
   138  	// Arrays have packed elements, resulting in longer unpack steps.
   139  	// Slices have just 32 bytes per element (pointing to the contents).
   140  	elemSize := getTypeSize(*t.Elem)
   141  
   142  	for i, j := start, 0; j < size; i, j = i+elemSize, j+1 {
   143  		inter, err := toGoType(i, *t.Elem, output)
   144  		if err != nil {
   145  			return nil, err
   146  		}
   147  
   148  		// append the item to our reflect slice
   149  		refSlice.Index(j).Set(reflect.ValueOf(inter))
   150  	}
   151  
   152  	// return the interface
   153  	return refSlice.Interface(), nil
   154  }
   155  
   156  func forTupleUnpack(t Type, output []byte) (interface{}, error) {
   157  	retval := reflect.New(t.Type).Elem()
   158  	virtualArgs := 0
   159  	for index, elem := range t.TupleElems {
   160  		marshalledValue, err := toGoType((index+virtualArgs)*32, *elem, output)
   161  		if elem.T == ArrayTy && !isDynamicType(*elem) {
   162  			// If we have a static array, like [3]uint256, these are coded as
   163  			// just like uint256,uint256,uint256.
   164  			// This means that we need to add two 'virtual' arguments when
   165  			// we count the index from now on.
   166  			//
   167  			// Array values nested multiple levels deep are also encoded inline:
   168  			// [2][3]uint256: uint256,uint256,uint256,uint256,uint256,uint256
   169  			//
   170  			// Calculate the full array size to get the correct offset for the next argument.
   171  			// Decrement it by 1, as the normal index increment is still applied.
   172  			virtualArgs += getTypeSize(*elem)/32 - 1
   173  		} else if elem.T == TupleTy && !isDynamicType(*elem) {
   174  			// If we have a static tuple, like (uint256, bool, uint256), these are
   175  			// coded as just like uint256,bool,uint256
   176  			virtualArgs += getTypeSize(*elem)/32 - 1
   177  		}
   178  		if err != nil {
   179  			return nil, err
   180  		}
   181  		retval.Field(index).Set(reflect.ValueOf(marshalledValue))
   182  	}
   183  	return retval.Interface(), nil
   184  }
   185  
   186  // toGoType parses the output bytes and recursively assigns the value of these bytes
   187  // into a go type with accordance with the ABI spec.
   188  func toGoType(index int, t Type, output []byte) (interface{}, error) {
   189  	if index+32 > len(output) {
   190  		return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), index+32)
   191  	}
   192  
   193  	var (
   194  		returnOutput  []byte
   195  		begin, length int
   196  		err           error
   197  	)
   198  
   199  	// if we require a length prefix, find the beginning word and size returned.
   200  	if t.requiresLengthPrefix() {
   201  		begin, length, err = lengthPrefixPointsTo(index, output)
   202  		if err != nil {
   203  			return nil, err
   204  		}
   205  	} else {
   206  		returnOutput = output[index : index+32]
   207  	}
   208  
   209  	switch t.T {
   210  	case TupleTy:
   211  		if isDynamicType(t) {
   212  			begin, err := tuplePointsTo(index, output)
   213  			if err != nil {
   214  				return nil, err
   215  			}
   216  			return forTupleUnpack(t, output[begin:])
   217  		} else {
   218  			return forTupleUnpack(t, output[index:])
   219  		}
   220  	case SliceTy:
   221  		return forEachUnpack(t, output[begin:], 0, length)
   222  	case ArrayTy:
   223  		if isDynamicType(*t.Elem) {
   224  			offset := int64(binary.BigEndian.Uint64(returnOutput[len(returnOutput)-8:]))
   225  			return forEachUnpack(t, output[offset:], 0, t.Size)
   226  		}
   227  		return forEachUnpack(t, output[index:], 0, t.Size)
   228  	case StringTy: // variable arrays are written at the end of the return bytes
   229  		return string(output[begin : begin+length]), nil
   230  	case IntTy, UintTy:
   231  		return ReadInteger(t.T, t.Kind, returnOutput), nil
   232  	case BoolTy:
   233  		return readBool(returnOutput)
   234  	case AddressTy:
   235  		return common.BytesToAddress(returnOutput), nil
   236  	case HashTy:
   237  		return common.BytesToHash(returnOutput), nil
   238  	case BytesTy:
   239  		return output[begin : begin+length], nil
   240  	case FixedBytesTy:
   241  		return ReadFixedBytes(t, returnOutput)
   242  	case FunctionTy:
   243  		return readFunctionType(t, returnOutput)
   244  	default:
   245  		return nil, fmt.Errorf("abi: unknown type %v", t.T)
   246  	}
   247  }
   248  
   249  // interprets a 32 byte slice as an offset and then determines which indice to look to decode the type.
   250  func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) {
   251  	bigOffsetEnd := big.NewInt(0).SetBytes(output[index : index+32])
   252  	bigOffsetEnd.Add(bigOffsetEnd, common.Big32)
   253  	outputLength := big.NewInt(int64(len(output)))
   254  
   255  	if bigOffsetEnd.Cmp(outputLength) > 0 {
   256  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", bigOffsetEnd, outputLength)
   257  	}
   258  
   259  	if bigOffsetEnd.BitLen() > 63 {
   260  		return 0, 0, fmt.Errorf("abi offset larger than int64: %v", bigOffsetEnd)
   261  	}
   262  
   263  	offsetEnd := int(bigOffsetEnd.Uint64())
   264  	lengthBig := big.NewInt(0).SetBytes(output[offsetEnd-32 : offsetEnd])
   265  
   266  	totalSize := big.NewInt(0)
   267  	totalSize.Add(totalSize, bigOffsetEnd)
   268  	totalSize.Add(totalSize, lengthBig)
   269  	if totalSize.BitLen() > 63 {
   270  		return 0, 0, fmt.Errorf("abi: length larger than int64: %v", totalSize)
   271  	}
   272  
   273  	if totalSize.Cmp(outputLength) > 0 {
   274  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %v require %v", outputLength, totalSize)
   275  	}
   276  	start = int(bigOffsetEnd.Uint64())
   277  	length = int(lengthBig.Uint64())
   278  	return
   279  }
   280  
   281  // tuplePointsTo resolves the location reference for dynamic tuple.
   282  func tuplePointsTo(index int, output []byte) (start int, err error) {
   283  	offset := big.NewInt(0).SetBytes(output[index : index+32])
   284  	outputLen := big.NewInt(int64(len(output)))
   285  
   286  	if offset.Cmp(big.NewInt(int64(len(output)))) > 0 {
   287  		return 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", offset, outputLen)
   288  	}
   289  	if offset.BitLen() > 63 {
   290  		return 0, fmt.Errorf("abi offset larger than int64: %v", offset)
   291  	}
   292  	return int(offset.Uint64()), nil
   293  }