github.com/dominant-strategies/go-quai@v0.28.2/core/vm/gas_table.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 vm
    18  
    19  import (
    20  	"errors"
    21  
    22  	"github.com/dominant-strategies/go-quai/common"
    23  	"github.com/dominant-strategies/go-quai/common/math"
    24  	"github.com/dominant-strategies/go-quai/params"
    25  )
    26  
    27  // memoryGasCost calculates the quadratic gas for memory expansion. It does so
    28  // only for the memory region that is expanded, not the total memory.
    29  func memoryGasCost(mem *Memory, newMemSize uint64) (uint64, error) {
    30  	if newMemSize == 0 {
    31  		return 0, nil
    32  	}
    33  	// The maximum that will fit in a uint64 is max_word_count - 1. Anything above
    34  	// that will result in an overflow. Additionally, a newMemSize which results in
    35  	// a newMemSizeWords larger than 0xFFFFFFFF will cause the square operation to
    36  	// overflow. The constant 0x1FFFFFFFE0 is the highest number that can be used
    37  	// without overflowing the gas calculation.
    38  	if newMemSize > 0x1FFFFFFFE0 {
    39  		return 0, ErrGasUintOverflow
    40  	}
    41  	newMemSizeWords := toWordSize(newMemSize)
    42  	newMemSize = newMemSizeWords * 32
    43  
    44  	if newMemSize > uint64(mem.Len()) {
    45  		square := newMemSizeWords * newMemSizeWords
    46  		linCoef := newMemSizeWords * params.MemoryGas
    47  		quadCoef := square / params.QuadCoeffDiv
    48  		newTotalFee := linCoef + quadCoef
    49  
    50  		fee := newTotalFee - mem.lastGasCost
    51  		mem.lastGasCost = newTotalFee
    52  
    53  		return fee, nil
    54  	}
    55  	return 0, nil
    56  }
    57  
    58  // memoryCopierGas creates the gas functions for the following opcodes, and takes
    59  // the stack position of the operand which determines the size of the data to copy
    60  // as argument:
    61  // CALLDATACOPY (stack position 2)
    62  // CODECOPY (stack position 2)
    63  // EXTCODECOPY (stack poition 3)
    64  // RETURNDATACOPY (stack position 2)
    65  func memoryCopierGas(stackpos int) gasFunc {
    66  	return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
    67  		// Gas for expanding the memory
    68  		gas, err := memoryGasCost(mem, memorySize)
    69  		if err != nil {
    70  			return 0, err
    71  		}
    72  		// And gas for copying data, charged per word at param.CopyGas
    73  		words, overflow := stack.Back(stackpos).Uint64WithOverflow()
    74  		if overflow {
    75  			return 0, ErrGasUintOverflow
    76  		}
    77  
    78  		if words, overflow = math.SafeMul(toWordSize(words), params.CopyGas); overflow {
    79  			return 0, ErrGasUintOverflow
    80  		}
    81  
    82  		if gas, overflow = math.SafeAdd(gas, words); overflow {
    83  			return 0, ErrGasUintOverflow
    84  		}
    85  		return gas, nil
    86  	}
    87  }
    88  
    89  var (
    90  	gasCallDataCopy   = memoryCopierGas(2)
    91  	gasCodeCopy       = memoryCopierGas(2)
    92  	gasReturnDataCopy = memoryCopierGas(2)
    93  )
    94  
    95  //  0. If *gasleft* is less than or equal to 2300, fail the current call.
    96  //  1. If current value equals new value (this is a no-op), SLOAD_GAS is deducted.
    97  //  2. If current value does not equal new value:
    98  //     2.1. If original value equals current value (this storage slot has not been changed by the current execution context):
    99  //     2.1.1. If original value is 0, SSTORE_SET_GAS (20K) gas is deducted.
   100  //     2.1.2. Otherwise, SSTORE_RESET_GAS gas is deducted. If new value is 0, add SSTORE_CLEARS_SCHEDULE to refund counter.
   101  //     2.2. If original value does not equal current value (this storage slot is dirty), SLOAD_GAS gas is deducted. Apply both of the following clauses:
   102  //     2.2.1. If original value is not 0:
   103  //     2.2.1.1. If current value is 0 (also means that new value is not 0), subtract SSTORE_CLEARS_SCHEDULE gas from refund counter.
   104  //     2.2.1.2. If new value is 0 (also means that current value is not 0), add SSTORE_CLEARS_SCHEDULE gas to refund counter.
   105  //     2.2.2. If original value equals new value (this storage slot is reset):
   106  //     2.2.2.1. If original value is 0, add SSTORE_SET_GAS - SLOAD_GAS to refund counter.
   107  //     2.2.2.2. Otherwise, add SSTORE_RESET_GAS - SLOAD_GAS gas to refund counter.
   108  func gasSStore(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   109  	// If we fail the minimum gas availability invariant, fail (0)
   110  	if contract.Gas <= params.SstoreSentryGas {
   111  		return 0, errors.New("not enough gas for reentrancy sentry")
   112  	}
   113  	// Gas sentry honoured, do the actual gas calculation based on the stored value
   114  	var (
   115  		y, x                      = stack.Back(1), stack.Back(0)
   116  		internalContractAddr, err = contract.Address().InternalAddress()
   117  	)
   118  	if err != nil {
   119  		return 0, err
   120  	}
   121  	current := evm.StateDB.GetState(internalContractAddr, x.Bytes32())
   122  	value := common.Hash(y.Bytes32())
   123  
   124  	if current == value { // noop (1)
   125  		return params.SloadGas, nil
   126  	}
   127  	original := evm.StateDB.GetCommittedState(internalContractAddr, x.Bytes32())
   128  	if original == current {
   129  		if original == (common.Hash{}) { // create slot (2.1.1)
   130  			return params.SstoreSetGas, nil
   131  		}
   132  		if value == (common.Hash{}) { // delete slot (2.1.2b)
   133  			evm.StateDB.AddRefund(params.SstoreClearsScheduleRefund)
   134  		}
   135  		return params.SstoreResetGas, nil // write existing slot (2.1.2)
   136  	}
   137  	if original != (common.Hash{}) {
   138  		if current == (common.Hash{}) { // recreate slot (2.2.1.1)
   139  			evm.StateDB.SubRefund(params.SstoreClearsScheduleRefund)
   140  		} else if value == (common.Hash{}) { // delete slot (2.2.1.2)
   141  			evm.StateDB.AddRefund(params.SstoreClearsScheduleRefund)
   142  		}
   143  	}
   144  	if original == value {
   145  		if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
   146  			evm.StateDB.AddRefund(params.SstoreSetGas - params.SloadGas)
   147  		} else { // reset to original existing slot (2.2.2.2)
   148  			evm.StateDB.AddRefund(params.SstoreResetGas - params.SloadGas)
   149  		}
   150  	}
   151  	return params.SloadGas, nil // dirty update (2.2)
   152  }
   153  
   154  func makeGasLog(n uint64) gasFunc {
   155  	return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   156  		requestedSize, overflow := stack.Back(1).Uint64WithOverflow()
   157  		if overflow {
   158  			return 0, ErrGasUintOverflow
   159  		}
   160  
   161  		gas, err := memoryGasCost(mem, memorySize)
   162  		if err != nil {
   163  			return 0, err
   164  		}
   165  
   166  		if gas, overflow = math.SafeAdd(gas, params.LogGas); overflow {
   167  			return 0, ErrGasUintOverflow
   168  		}
   169  		if gas, overflow = math.SafeAdd(gas, n*params.LogTopicGas); overflow {
   170  			return 0, ErrGasUintOverflow
   171  		}
   172  
   173  		var memorySizeGas uint64
   174  		if memorySizeGas, overflow = math.SafeMul(requestedSize, params.LogDataGas); overflow {
   175  			return 0, ErrGasUintOverflow
   176  		}
   177  		if gas, overflow = math.SafeAdd(gas, memorySizeGas); overflow {
   178  			return 0, ErrGasUintOverflow
   179  		}
   180  		return gas, nil
   181  	}
   182  }
   183  
   184  func gasSha3(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   185  	gas, err := memoryGasCost(mem, memorySize)
   186  	if err != nil {
   187  		return 0, err
   188  	}
   189  	wordGas, overflow := stack.Back(1).Uint64WithOverflow()
   190  	if overflow {
   191  		return 0, ErrGasUintOverflow
   192  	}
   193  	if wordGas, overflow = math.SafeMul(toWordSize(wordGas), params.Sha3WordGas); overflow {
   194  		return 0, ErrGasUintOverflow
   195  	}
   196  	if gas, overflow = math.SafeAdd(gas, wordGas); overflow {
   197  		return 0, ErrGasUintOverflow
   198  	}
   199  	return gas, nil
   200  }
   201  
   202  // pureMemoryGascost is used by several operations, which aside from their
   203  // static cost have a dynamic cost which is solely based on the memory
   204  // expansion
   205  func pureMemoryGascost(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   206  	return memoryGasCost(mem, memorySize)
   207  }
   208  
   209  var (
   210  	gasReturn  = pureMemoryGascost
   211  	gasRevert  = pureMemoryGascost
   212  	gasMLoad   = pureMemoryGascost
   213  	gasMStore8 = pureMemoryGascost
   214  	gasMStore  = pureMemoryGascost
   215  	gasCreate  = pureMemoryGascost
   216  )
   217  
   218  func gasCreate2(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   219  	gas, err := memoryGasCost(mem, memorySize)
   220  	if err != nil {
   221  		return 0, err
   222  	}
   223  	wordGas, overflow := stack.Back(2).Uint64WithOverflow()
   224  	if overflow {
   225  		return 0, ErrGasUintOverflow
   226  	}
   227  	if wordGas, overflow = math.SafeMul(toWordSize(wordGas), params.Sha3WordGas); overflow {
   228  		return 0, ErrGasUintOverflow
   229  	}
   230  	if gas, overflow = math.SafeAdd(gas, wordGas); overflow {
   231  		return 0, ErrGasUintOverflow
   232  	}
   233  	return gas, nil
   234  }
   235  
   236  func gasExp(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   237  	expByteLen := uint64((stack.data[stack.len()-2].BitLen() + 7) / 8)
   238  
   239  	var (
   240  		gas      = expByteLen * params.ExpByte // no overflow check required. Max is 256 * ExpByte gas
   241  		overflow bool
   242  	)
   243  	if gas, overflow = math.SafeAdd(gas, params.ExpGas); overflow {
   244  		return 0, ErrGasUintOverflow
   245  	}
   246  	return gas, nil
   247  }
   248  
   249  func gasCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   250  	var (
   251  		gas            uint64
   252  		transfersValue = !stack.Back(2).IsZero()
   253  		address, err   = common.Bytes20ToAddress(stack.Back(1).Bytes20()).InternalAddress()
   254  	)
   255  	if err != nil {
   256  		return 0, err
   257  	}
   258  	if transfersValue && evm.StateDB.Empty(address) {
   259  		gas += params.CallNewAccountGas
   260  	}
   261  	if transfersValue {
   262  		gas += params.CallValueTransferGas
   263  	}
   264  	memoryGas, err := memoryGasCost(mem, memorySize)
   265  	if err != nil {
   266  		return 0, err
   267  	}
   268  	var overflow bool
   269  	if gas, overflow = math.SafeAdd(gas, memoryGas); overflow {
   270  		return 0, ErrGasUintOverflow
   271  	}
   272  
   273  	evm.callGasTemp, err = callGas(contract.Gas, gas, stack.Back(0))
   274  	if err != nil {
   275  		return 0, err
   276  	}
   277  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   278  		return 0, ErrGasUintOverflow
   279  	}
   280  	return gas, nil
   281  }
   282  
   283  func gasCallCode(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   284  	memoryGas, err := memoryGasCost(mem, memorySize)
   285  	if err != nil {
   286  		return 0, err
   287  	}
   288  	var (
   289  		gas      uint64
   290  		overflow bool
   291  	)
   292  	if stack.Back(2).Sign() != 0 {
   293  		gas += params.CallValueTransferGas
   294  	}
   295  	if gas, overflow = math.SafeAdd(gas, memoryGas); overflow {
   296  		return 0, ErrGasUintOverflow
   297  	}
   298  	evm.callGasTemp, err = callGas(contract.Gas, gas, stack.Back(0))
   299  	if err != nil {
   300  		return 0, err
   301  	}
   302  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   303  		return 0, ErrGasUintOverflow
   304  	}
   305  	return gas, nil
   306  }
   307  
   308  func gasDelegateCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   309  	gas, err := memoryGasCost(mem, memorySize)
   310  	if err != nil {
   311  		return 0, err
   312  	}
   313  	evm.callGasTemp, err = callGas(contract.Gas, gas, stack.Back(0))
   314  	if err != nil {
   315  		return 0, err
   316  	}
   317  	var overflow bool
   318  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   319  		return 0, ErrGasUintOverflow
   320  	}
   321  	return gas, nil
   322  }
   323  
   324  func gasStaticCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   325  	gas, err := memoryGasCost(mem, memorySize)
   326  	if err != nil {
   327  		return 0, err
   328  	}
   329  	evm.callGasTemp, err = callGas(contract.Gas, gas, stack.Back(0))
   330  	if err != nil {
   331  		return 0, err
   332  	}
   333  	var overflow bool
   334  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   335  		return 0, ErrGasUintOverflow
   336  	}
   337  	return gas, nil
   338  }
   339  
   340  func gasSelfdestruct(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   341  	var gas uint64
   342  	contractAddr, err := contract.Address().InternalAddress()
   343  	if err != nil {
   344  		return 0, err
   345  	}
   346  	gas = params.SelfdestructGas
   347  	address, err := common.Bytes20ToAddress(stack.Back(0).Bytes20()).InternalAddress()
   348  	if err != nil {
   349  		return 0, err
   350  	}
   351  	// if empty and transfers value
   352  	if evm.StateDB.Empty(address) && evm.StateDB.GetBalance(contractAddr).Sign() != 0 {
   353  		gas += params.CreateBySelfdestructGas
   354  	}
   355  
   356  	if !evm.StateDB.HasSuicided(contractAddr) {
   357  		evm.StateDB.AddRefund(params.SelfdestructRefundGas)
   358  	}
   359  	return gas, nil
   360  }