github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/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/ethereum/go-ethereum/common"
    23  	"github.com/ethereum/go-ethereum/common/math"
    24  	"github.com/ethereum/go-ethereum/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 position 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  	gasExtCodeCopy    = memoryCopierGas(3)
    93  	gasReturnDataCopy = memoryCopierGas(2)
    94  )
    95  
    96  func gasSStore(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
    97  	var (
    98  		y, x    = stack.Back(1), stack.Back(0)
    99  		current = evm.StateDB.GetState(contract.Address(), x.Bytes32())
   100  	)
   101  	// The legacy gas metering only takes into consideration the current state
   102  	// Legacy rules should be applied if we are in Petersburg (removal of EIP-1283)
   103  	// OR Constantinople is not active
   104  	if evm.chainRules.IsPetersburg || !evm.chainRules.IsConstantinople {
   105  		// This checks for 3 scenario's and calculates gas accordingly:
   106  		//
   107  		// 1. From a zero-value address to a non-zero value         (NEW VALUE)
   108  		// 2. From a non-zero value address to a zero-value address (DELETE)
   109  		// 3. From a non-zero to a non-zero                         (CHANGE)
   110  		switch {
   111  		case current == (common.Hash{}) && y.Sign() != 0: // 0 => non 0
   112  			return params.SstoreSetGas, nil
   113  		case current != (common.Hash{}) && y.Sign() == 0: // non 0 => 0
   114  			evm.StateDB.AddRefund(params.SstoreRefundGas)
   115  			return params.SstoreClearGas, nil
   116  		default: // non 0 => non 0 (or 0 => 0)
   117  			return params.SstoreResetGas, nil
   118  		}
   119  	}
   120  
   121  	// The new gas metering is based on net gas costs (EIP-1283):
   122  	//
   123  	// (1.) If current value equals new value (this is a no-op), 200 gas is deducted.
   124  	// (2.) If current value does not equal new value
   125  	//	(2.1.) If original value equals current value (this storage slot has not been changed by the current execution context)
   126  	//		(2.1.1.) If original value is 0, 20000 gas is deducted.
   127  	//		(2.1.2.) Otherwise, 5000 gas is deducted. If new value is 0, add 15000 gas to refund counter.
   128  	//	(2.2.) If original value does not equal current value (this storage slot is dirty), 200 gas is deducted. Apply both of the following clauses.
   129  	//		(2.2.1.) If original value is not 0
   130  	//			(2.2.1.1.) If current value is 0 (also means that new value is not 0), remove 15000 gas from refund counter. We can prove that refund counter will never go below 0.
   131  	//			(2.2.1.2.) If new value is 0 (also means that current value is not 0), add 15000 gas to refund counter.
   132  	//		(2.2.2.) If original value equals new value (this storage slot is reset)
   133  	//			(2.2.2.1.) If original value is 0, add 19800 gas to refund counter.
   134  	//			(2.2.2.2.) Otherwise, add 4800 gas to refund counter.
   135  	value := common.Hash(y.Bytes32())
   136  	if current == value { // noop (1)
   137  		return params.NetSstoreNoopGas, nil
   138  	}
   139  	original := evm.StateDB.GetCommittedState(contract.Address(), x.Bytes32())
   140  	if original == current {
   141  		if original == (common.Hash{}) { // create slot (2.1.1)
   142  			return params.NetSstoreInitGas, nil
   143  		}
   144  		if value == (common.Hash{}) { // delete slot (2.1.2b)
   145  			evm.StateDB.AddRefund(params.NetSstoreClearRefund)
   146  		}
   147  		return params.NetSstoreCleanGas, nil // write existing slot (2.1.2)
   148  	}
   149  	if original != (common.Hash{}) {
   150  		if current == (common.Hash{}) { // recreate slot (2.2.1.1)
   151  			evm.StateDB.SubRefund(params.NetSstoreClearRefund)
   152  		} else if value == (common.Hash{}) { // delete slot (2.2.1.2)
   153  			evm.StateDB.AddRefund(params.NetSstoreClearRefund)
   154  		}
   155  	}
   156  	if original == value {
   157  		if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
   158  			evm.StateDB.AddRefund(params.NetSstoreResetClearRefund)
   159  		} else { // reset to original existing slot (2.2.2.2)
   160  			evm.StateDB.AddRefund(params.NetSstoreResetRefund)
   161  		}
   162  	}
   163  	return params.NetSstoreDirtyGas, nil
   164  }
   165  
   166  // Here come the EIP220 rules:
   167  //
   168  //	(0.) If *gasleft* is less than or equal to 2300, fail the current call.
   169  //	(1.) If current value equals new value (this is a no-op), SLOAD_GAS is deducted.
   170  //	(2.) If current value does not equal new value:
   171  //		(2.1.) If original value equals current value (this storage slot has not been changed by the current execution context):
   172  //			(2.1.1.) If original value is 0, SSTORE_SET_GAS (20K) gas is deducted.
   173  //			(2.1.2.) Otherwise, SSTORE_RESET_GAS gas is deducted. If new value is 0, add SSTORE_CLEARS_SCHEDULE to refund counter.
   174  //		(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:
   175  //			(2.2.1.) If original value is not 0:
   176  //				(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.
   177  //				(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.
   178  //			(2.2.2.) If original value equals new value (this storage slot is reset):
   179  //				(2.2.2.1.) If original value is 0, add SSTORE_SET_GAS - SLOAD_GAS to refund counter.
   180  //				(2.2.2.2.) Otherwise, add SSTORE_RESET_GAS - SLOAD_GAS gas to refund counter.
   181  func gasSStoreEIP2200(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   182  	// If we fail the minimum gas availability invariant, fail (0)
   183  	if contract.Gas <= params.SstoreSentryGasEIP2200 {
   184  		return 0, errors.New("not enough gas for reentrancy sentry")
   185  	}
   186  	// Gas sentry honoured, do the actual gas calculation based on the stored value
   187  	var (
   188  		y, x    = stack.Back(1), stack.Back(0)
   189  		current = evm.StateDB.GetState(contract.Address(), x.Bytes32())
   190  	)
   191  	value := common.Hash(y.Bytes32())
   192  
   193  	if current == value { // noop (1)
   194  		return params.SloadGasEIP2200, nil
   195  	}
   196  	original := evm.StateDB.GetCommittedState(contract.Address(), x.Bytes32())
   197  	if original == current {
   198  		if original == (common.Hash{}) { // create slot (2.1.1)
   199  			return params.SstoreSetGasEIP2200, nil
   200  		}
   201  		if value == (common.Hash{}) { // delete slot (2.1.2b)
   202  			evm.StateDB.AddRefund(params.SstoreClearsScheduleRefundEIP2200)
   203  		}
   204  		return params.SstoreResetGasEIP2200, nil // write existing slot (2.1.2)
   205  	}
   206  	if original != (common.Hash{}) {
   207  		if current == (common.Hash{}) { // recreate slot (2.2.1.1)
   208  			evm.StateDB.SubRefund(params.SstoreClearsScheduleRefundEIP2200)
   209  		} else if value == (common.Hash{}) { // delete slot (2.2.1.2)
   210  			evm.StateDB.AddRefund(params.SstoreClearsScheduleRefundEIP2200)
   211  		}
   212  	}
   213  	if original == value {
   214  		if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
   215  			evm.StateDB.AddRefund(params.SstoreSetGasEIP2200 - params.SloadGasEIP2200)
   216  		} else { // reset to original existing slot (2.2.2.2)
   217  			evm.StateDB.AddRefund(params.SstoreResetGasEIP2200 - params.SloadGasEIP2200)
   218  		}
   219  	}
   220  	return params.SloadGasEIP2200, nil // dirty update (2.2)
   221  }
   222  
   223  func makeGasLog(n uint64) gasFunc {
   224  	return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   225  		requestedSize, overflow := stack.Back(1).Uint64WithOverflow()
   226  		if overflow {
   227  			return 0, ErrGasUintOverflow
   228  		}
   229  
   230  		gas, err := memoryGasCost(mem, memorySize)
   231  		if err != nil {
   232  			return 0, err
   233  		}
   234  
   235  		if gas, overflow = math.SafeAdd(gas, params.LogGas); overflow {
   236  			return 0, ErrGasUintOverflow
   237  		}
   238  		if gas, overflow = math.SafeAdd(gas, n*params.LogTopicGas); overflow {
   239  			return 0, ErrGasUintOverflow
   240  		}
   241  
   242  		var memorySizeGas uint64
   243  		if memorySizeGas, overflow = math.SafeMul(requestedSize, params.LogDataGas); overflow {
   244  			return 0, ErrGasUintOverflow
   245  		}
   246  		if gas, overflow = math.SafeAdd(gas, memorySizeGas); overflow {
   247  			return 0, ErrGasUintOverflow
   248  		}
   249  		return gas, nil
   250  	}
   251  }
   252  
   253  func gasKeccak256(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   254  	gas, err := memoryGasCost(mem, memorySize)
   255  	if err != nil {
   256  		return 0, err
   257  	}
   258  	wordGas, overflow := stack.Back(1).Uint64WithOverflow()
   259  	if overflow {
   260  		return 0, ErrGasUintOverflow
   261  	}
   262  	if wordGas, overflow = math.SafeMul(toWordSize(wordGas), params.Keccak256WordGas); overflow {
   263  		return 0, ErrGasUintOverflow
   264  	}
   265  	if gas, overflow = math.SafeAdd(gas, wordGas); overflow {
   266  		return 0, ErrGasUintOverflow
   267  	}
   268  	return gas, nil
   269  }
   270  
   271  // pureMemoryGascost is used by several operations, which aside from their
   272  // static cost have a dynamic cost which is solely based on the memory
   273  // expansion
   274  func pureMemoryGascost(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   275  	return memoryGasCost(mem, memorySize)
   276  }
   277  
   278  var (
   279  	gasReturn  = pureMemoryGascost
   280  	gasRevert  = pureMemoryGascost
   281  	gasMLoad   = pureMemoryGascost
   282  	gasMStore8 = pureMemoryGascost
   283  	gasMStore  = pureMemoryGascost
   284  	gasCreate  = pureMemoryGascost
   285  )
   286  
   287  func gasCreate2(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   288  	gas, err := memoryGasCost(mem, memorySize)
   289  	if err != nil {
   290  		return 0, err
   291  	}
   292  	wordGas, overflow := stack.Back(2).Uint64WithOverflow()
   293  	if overflow {
   294  		return 0, ErrGasUintOverflow
   295  	}
   296  	if wordGas, overflow = math.SafeMul(toWordSize(wordGas), params.Keccak256WordGas); overflow {
   297  		return 0, ErrGasUintOverflow
   298  	}
   299  	if gas, overflow = math.SafeAdd(gas, wordGas); overflow {
   300  		return 0, ErrGasUintOverflow
   301  	}
   302  	return gas, nil
   303  }
   304  
   305  func gasExpFrontier(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   306  	expByteLen := uint64((stack.data[stack.len()-2].BitLen() + 7) / 8)
   307  
   308  	var (
   309  		gas      = expByteLen * params.ExpByteFrontier // no overflow check required. Max is 256 * ExpByte gas
   310  		overflow bool
   311  	)
   312  	if gas, overflow = math.SafeAdd(gas, params.ExpGas); overflow {
   313  		return 0, ErrGasUintOverflow
   314  	}
   315  	return gas, nil
   316  }
   317  
   318  func gasExpEIP158(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   319  	expByteLen := uint64((stack.data[stack.len()-2].BitLen() + 7) / 8)
   320  
   321  	var (
   322  		gas      = expByteLen * params.ExpByteEIP158 // no overflow check required. Max is 256 * ExpByte gas
   323  		overflow bool
   324  	)
   325  	if gas, overflow = math.SafeAdd(gas, params.ExpGas); overflow {
   326  		return 0, ErrGasUintOverflow
   327  	}
   328  	return gas, nil
   329  }
   330  
   331  func gasCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   332  	var (
   333  		gas            uint64
   334  		transfersValue = !stack.Back(2).IsZero()
   335  		address        = common.Address(stack.Back(1).Bytes20())
   336  	)
   337  	if evm.chainRules.IsEIP158 {
   338  		if transfersValue && evm.StateDB.Empty(address) {
   339  			gas += params.CallNewAccountGas
   340  		}
   341  	} else if !evm.StateDB.Exist(address) {
   342  		gas += params.CallNewAccountGas
   343  	}
   344  	if transfersValue {
   345  		gas += params.CallValueTransferGas
   346  	}
   347  	memoryGas, err := memoryGasCost(mem, memorySize)
   348  	if err != nil {
   349  		return 0, err
   350  	}
   351  	var overflow bool
   352  	if gas, overflow = math.SafeAdd(gas, memoryGas); overflow {
   353  		return 0, ErrGasUintOverflow
   354  	}
   355  
   356  	evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))
   357  	if err != nil {
   358  		return 0, err
   359  	}
   360  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   361  		return 0, ErrGasUintOverflow
   362  	}
   363  	return gas, nil
   364  }
   365  
   366  func gasCallCode(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   367  	memoryGas, err := memoryGasCost(mem, memorySize)
   368  	if err != nil {
   369  		return 0, err
   370  	}
   371  	var (
   372  		gas      uint64
   373  		overflow bool
   374  	)
   375  	if stack.Back(2).Sign() != 0 {
   376  		gas += params.CallValueTransferGas
   377  	}
   378  	if gas, overflow = math.SafeAdd(gas, memoryGas); overflow {
   379  		return 0, ErrGasUintOverflow
   380  	}
   381  	evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))
   382  	if err != nil {
   383  		return 0, err
   384  	}
   385  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   386  		return 0, ErrGasUintOverflow
   387  	}
   388  	return gas, nil
   389  }
   390  
   391  func gasDelegateCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   392  	gas, err := memoryGasCost(mem, memorySize)
   393  	if err != nil {
   394  		return 0, err
   395  	}
   396  	evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))
   397  	if err != nil {
   398  		return 0, err
   399  	}
   400  	var overflow bool
   401  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   402  		return 0, ErrGasUintOverflow
   403  	}
   404  	return gas, nil
   405  }
   406  
   407  func gasStaticCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   408  	gas, err := memoryGasCost(mem, memorySize)
   409  	if err != nil {
   410  		return 0, err
   411  	}
   412  	evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))
   413  	if err != nil {
   414  		return 0, err
   415  	}
   416  	var overflow bool
   417  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   418  		return 0, ErrGasUintOverflow
   419  	}
   420  	return gas, nil
   421  }
   422  
   423  func gasSelfdestruct(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   424  	var gas uint64
   425  	// EIP150 homestead gas reprice fork:
   426  	if evm.chainRules.IsEIP150 {
   427  		gas = params.SelfdestructGasEIP150
   428  		var address = common.Address(stack.Back(0).Bytes20())
   429  
   430  		if evm.chainRules.IsEIP158 {
   431  			// if empty and transfers value
   432  			if evm.StateDB.Empty(address) && evm.StateDB.GetBalance(contract.Address()).Sign() != 0 {
   433  				gas += params.CreateBySelfdestructGas
   434  			}
   435  		} else if !evm.StateDB.Exist(address) {
   436  			gas += params.CreateBySelfdestructGas
   437  		}
   438  	}
   439  
   440  	if !evm.StateDB.HasSuicided(contract.Address()) {
   441  		evm.StateDB.AddRefund(params.SelfdestructRefundGas)
   442  	}
   443  	return gas, nil
   444  }