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