github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/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  	"fmt"
    22  
    23  	"github.com/ethereum/go-ethereum/common"
    24  	"github.com/ethereum/go-ethereum/common/math"
    25  	"github.com/ethereum/go-ethereum/params"
    26  )
    27  
    28  // memoryGasCost calculates the quadratic gas for memory expansion. It does so
    29  // only for the memory region that is expanded, not the total memory.
    30  func memoryGasCost(mem *Memory, newMemSize uint64) (uint64, error) {
    31  	if newMemSize == 0 {
    32  		return 0, nil
    33  	}
    34  	// The maximum that will fit in a uint64 is max_word_count - 1. Anything above
    35  	// that will result in an overflow. Additionally, a newMemSize which results in
    36  	// a newMemSizeWords larger than 0xFFFFFFFF will cause the square operation to
    37  	// overflow. The constant 0x1FFFFFFFE0 is the highest number that can be used
    38  	// without overflowing the gas calculation.
    39  	if newMemSize > 0x1FFFFFFFE0 {
    40  		return 0, ErrGasUintOverflow
    41  	}
    42  	newMemSizeWords := toWordSize(newMemSize)
    43  	newMemSize = newMemSizeWords * 32
    44  
    45  	if newMemSize > uint64(mem.Len()) {
    46  		square := newMemSizeWords * newMemSizeWords
    47  		linCoef := newMemSizeWords * params.MemoryGas
    48  		quadCoef := square / params.QuadCoeffDiv
    49  		newTotalFee := linCoef + quadCoef
    50  
    51  		fee := newTotalFee - mem.lastGasCost
    52  		mem.lastGasCost = newTotalFee
    53  
    54  		return fee, nil
    55  	}
    56  	return 0, nil
    57  }
    58  
    59  // memoryCopierGas creates the gas functions for the following opcodes, and takes
    60  // the stack position of the operand which determines the size of the data to copy
    61  // as argument:
    62  // CALLDATACOPY (stack position 2)
    63  // CODECOPY (stack position 2)
    64  // MCOPY (stack position 2)
    65  // EXTCODECOPY (stack position 3)
    66  // RETURNDATACOPY (stack position 2)
    67  func memoryCopierGas(stackpos int) gasFunc {
    68  	return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
    69  		// Gas for expanding the memory
    70  		gas, err := memoryGasCost(mem, memorySize)
    71  		if err != nil {
    72  			return 0, err
    73  		}
    74  		// And gas for copying data, charged per word at param.CopyGas
    75  		words, overflow := stack.Back(stackpos).Uint64WithOverflow()
    76  		if overflow {
    77  			return 0, ErrGasUintOverflow
    78  		}
    79  
    80  		if words, overflow = math.SafeMul(toWordSize(words), params.CopyGas); overflow {
    81  			return 0, ErrGasUintOverflow
    82  		}
    83  
    84  		if gas, overflow = math.SafeAdd(gas, words); overflow {
    85  			return 0, ErrGasUintOverflow
    86  		}
    87  		return gas, nil
    88  	}
    89  }
    90  
    91  var (
    92  	gasCallDataCopy   = memoryCopierGas(2)
    93  	gasCodeCopy       = memoryCopierGas(2)
    94  	gasMcopy          = memoryCopierGas(2)
    95  	gasExtCodeCopy    = memoryCopierGas(3)
    96  	gasReturnDataCopy = memoryCopierGas(2)
    97  )
    98  
    99  func gasSStore(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   100  	var (
   101  		y, x    = stack.Back(1), stack.Back(0)
   102  		current = evm.StateDB.GetState(contract.Address(), x.Bytes32())
   103  	)
   104  	// The legacy gas metering only takes into consideration the current state
   105  	// Legacy rules should be applied if we are in Petersburg (removal of EIP-1283)
   106  	// OR Constantinople is not active
   107  	if evm.chainRules.IsPetersburg || !evm.chainRules.IsConstantinople {
   108  		// This checks for 3 scenarios and calculates gas accordingly:
   109  		//
   110  		// 1. From a zero-value address to a non-zero value         (NEW VALUE)
   111  		// 2. From a non-zero value address to a zero-value address (DELETE)
   112  		// 3. From a non-zero to a non-zero                         (CHANGE)
   113  		switch {
   114  		case current == (common.Hash{}) && y.Sign() != 0: // 0 => non 0
   115  			return params.SstoreSetGas, nil
   116  		case current != (common.Hash{}) && y.Sign() == 0: // non 0 => 0
   117  			evm.StateDB.AddRefund(params.SstoreRefundGas)
   118  			return params.SstoreClearGas, nil
   119  		default: // non 0 => non 0 (or 0 => 0)
   120  			return params.SstoreResetGas, nil
   121  		}
   122  	}
   123  
   124  	// The new gas metering is based on net gas costs (EIP-1283):
   125  	//
   126  	// (1.) If current value equals new value (this is a no-op), 200 gas is deducted.
   127  	// (2.) If current value does not equal new value
   128  	//	(2.1.) If original value equals current value (this storage slot has not been changed by the current execution context)
   129  	//		(2.1.1.) If original value is 0, 20000 gas is deducted.
   130  	//		(2.1.2.) Otherwise, 5000 gas is deducted. If new value is 0, add 15000 gas to refund counter.
   131  	//	(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.
   132  	//		(2.2.1.) If original value is not 0
   133  	//			(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.
   134  	//			(2.2.1.2.) If new value is 0 (also means that current value is not 0), add 15000 gas to refund counter.
   135  	//		(2.2.2.) If original value equals new value (this storage slot is reset)
   136  	//			(2.2.2.1.) If original value is 0, add 19800 gas to refund counter.
   137  	//			(2.2.2.2.) Otherwise, add 4800 gas to refund counter.
   138  	value := common.Hash(y.Bytes32())
   139  	if current == value { // noop (1)
   140  		return params.NetSstoreNoopGas, nil
   141  	}
   142  	original := evm.StateDB.GetCommittedState(contract.Address(), x.Bytes32())
   143  	if original == current {
   144  		if original == (common.Hash{}) { // create slot (2.1.1)
   145  			return params.NetSstoreInitGas, nil
   146  		}
   147  		if value == (common.Hash{}) { // delete slot (2.1.2b)
   148  			evm.StateDB.AddRefund(params.NetSstoreClearRefund)
   149  		}
   150  		return params.NetSstoreCleanGas, nil // write existing slot (2.1.2)
   151  	}
   152  	if original != (common.Hash{}) {
   153  		if current == (common.Hash{}) { // recreate slot (2.2.1.1)
   154  			evm.StateDB.SubRefund(params.NetSstoreClearRefund)
   155  		} else if value == (common.Hash{}) { // delete slot (2.2.1.2)
   156  			evm.StateDB.AddRefund(params.NetSstoreClearRefund)
   157  		}
   158  	}
   159  	if original == value {
   160  		if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
   161  			evm.StateDB.AddRefund(params.NetSstoreResetClearRefund)
   162  		} else { // reset to original existing slot (2.2.2.2)
   163  			evm.StateDB.AddRefund(params.NetSstoreResetRefund)
   164  		}
   165  	}
   166  	return params.NetSstoreDirtyGas, nil
   167  }
   168  
   169  // Here come the EIP2200 rules:
   170  //
   171  //	(0.) If *gasleft* is less than or equal to 2300, fail the current call.
   172  //	(1.) If current value equals new value (this is a no-op), SLOAD_GAS is deducted.
   173  //	(2.) If current value does not equal new value:
   174  //		(2.1.) If original value equals current value (this storage slot has not been changed by the current execution context):
   175  //			(2.1.1.) If original value is 0, SSTORE_SET_GAS (20K) gas is deducted.
   176  //			(2.1.2.) Otherwise, SSTORE_RESET_GAS gas is deducted. If new value is 0, add SSTORE_CLEARS_SCHEDULE to refund counter.
   177  //		(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:
   178  //			(2.2.1.) If original value is not 0:
   179  //				(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.
   180  //				(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.
   181  //			(2.2.2.) If original value equals new value (this storage slot is reset):
   182  //				(2.2.2.1.) If original value is 0, add SSTORE_SET_GAS - SLOAD_GAS to refund counter.
   183  //				(2.2.2.2.) Otherwise, add SSTORE_RESET_GAS - SLOAD_GAS gas to refund counter.
   184  func gasSStoreEIP2200(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   185  	// If we fail the minimum gas availability invariant, fail (0)
   186  	if contract.Gas <= params.SstoreSentryGasEIP2200 {
   187  		return 0, errors.New("not enough gas for reentrancy sentry")
   188  	}
   189  	// Gas sentry honoured, do the actual gas calculation based on the stored value
   190  	var (
   191  		y, x    = stack.Back(1), stack.Back(0)
   192  		current = evm.StateDB.GetState(contract.Address(), x.Bytes32())
   193  	)
   194  	value := common.Hash(y.Bytes32())
   195  
   196  	if current == value { // noop (1)
   197  		return params.SloadGasEIP2200, nil
   198  	}
   199  	original := evm.StateDB.GetCommittedState(contract.Address(), x.Bytes32())
   200  	if original == current {
   201  		if original == (common.Hash{}) { // create slot (2.1.1)
   202  			return params.SstoreSetGasEIP2200, nil
   203  		}
   204  		if value == (common.Hash{}) { // delete slot (2.1.2b)
   205  			evm.StateDB.AddRefund(params.SstoreClearsScheduleRefundEIP2200)
   206  		}
   207  		return params.SstoreResetGasEIP2200, nil // write existing slot (2.1.2)
   208  	}
   209  	if original != (common.Hash{}) {
   210  		if current == (common.Hash{}) { // recreate slot (2.2.1.1)
   211  			evm.StateDB.SubRefund(params.SstoreClearsScheduleRefundEIP2200)
   212  		} else if value == (common.Hash{}) { // delete slot (2.2.1.2)
   213  			evm.StateDB.AddRefund(params.SstoreClearsScheduleRefundEIP2200)
   214  		}
   215  	}
   216  	if original == value {
   217  		if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
   218  			evm.StateDB.AddRefund(params.SstoreSetGasEIP2200 - params.SloadGasEIP2200)
   219  		} else { // reset to original existing slot (2.2.2.2)
   220  			evm.StateDB.AddRefund(params.SstoreResetGasEIP2200 - params.SloadGasEIP2200)
   221  		}
   222  	}
   223  	return params.SloadGasEIP2200, nil // dirty update (2.2)
   224  }
   225  
   226  func makeGasLog(n uint64) gasFunc {
   227  	return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   228  		requestedSize, overflow := stack.Back(1).Uint64WithOverflow()
   229  		if overflow {
   230  			return 0, ErrGasUintOverflow
   231  		}
   232  
   233  		gas, err := memoryGasCost(mem, memorySize)
   234  		if err != nil {
   235  			return 0, err
   236  		}
   237  
   238  		if gas, overflow = math.SafeAdd(gas, params.LogGas); overflow {
   239  			return 0, ErrGasUintOverflow
   240  		}
   241  		if gas, overflow = math.SafeAdd(gas, n*params.LogTopicGas); overflow {
   242  			return 0, ErrGasUintOverflow
   243  		}
   244  
   245  		var memorySizeGas uint64
   246  		if memorySizeGas, overflow = math.SafeMul(requestedSize, params.LogDataGas); overflow {
   247  			return 0, ErrGasUintOverflow
   248  		}
   249  		if gas, overflow = math.SafeAdd(gas, memorySizeGas); overflow {
   250  			return 0, ErrGasUintOverflow
   251  		}
   252  		return gas, nil
   253  	}
   254  }
   255  
   256  func gasKeccak256(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   257  	gas, err := memoryGasCost(mem, memorySize)
   258  	if err != nil {
   259  		return 0, err
   260  	}
   261  	wordGas, overflow := stack.Back(1).Uint64WithOverflow()
   262  	if overflow {
   263  		return 0, ErrGasUintOverflow
   264  	}
   265  	if wordGas, overflow = math.SafeMul(toWordSize(wordGas), params.Keccak256WordGas); overflow {
   266  		return 0, ErrGasUintOverflow
   267  	}
   268  	if gas, overflow = math.SafeAdd(gas, wordGas); overflow {
   269  		return 0, ErrGasUintOverflow
   270  	}
   271  	return gas, nil
   272  }
   273  
   274  // pureMemoryGascost is used by several operations, which aside from their
   275  // static cost have a dynamic cost which is solely based on the memory
   276  // expansion
   277  func pureMemoryGascost(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   278  	return memoryGasCost(mem, memorySize)
   279  }
   280  
   281  var (
   282  	gasReturn  = pureMemoryGascost
   283  	gasRevert  = pureMemoryGascost
   284  	gasMLoad   = pureMemoryGascost
   285  	gasMStore8 = pureMemoryGascost
   286  	gasMStore  = pureMemoryGascost
   287  	gasCreate  = pureMemoryGascost
   288  )
   289  
   290  func gasCreate2(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   291  	gas, err := memoryGasCost(mem, memorySize)
   292  	if err != nil {
   293  		return 0, err
   294  	}
   295  	wordGas, overflow := stack.Back(2).Uint64WithOverflow()
   296  	if overflow {
   297  		return 0, ErrGasUintOverflow
   298  	}
   299  	if wordGas, overflow = math.SafeMul(toWordSize(wordGas), params.Keccak256WordGas); overflow {
   300  		return 0, ErrGasUintOverflow
   301  	}
   302  	if gas, overflow = math.SafeAdd(gas, wordGas); overflow {
   303  		return 0, ErrGasUintOverflow
   304  	}
   305  	return gas, nil
   306  }
   307  
   308  func gasCreateEip3860(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  	size, overflow := stack.Back(2).Uint64WithOverflow()
   314  	if overflow {
   315  		return 0, ErrGasUintOverflow
   316  	}
   317  	if size > params.MaxInitCodeSize {
   318  		return 0, fmt.Errorf("%w: size %d", ErrMaxInitCodeSizeExceeded, size)
   319  	}
   320  	// Since size <= params.MaxInitCodeSize, these multiplication cannot overflow
   321  	moreGas := params.InitCodeWordGas * ((size + 31) / 32)
   322  	if gas, overflow = math.SafeAdd(gas, moreGas); overflow {
   323  		return 0, ErrGasUintOverflow
   324  	}
   325  	return gas, nil
   326  }
   327  func gasCreate2Eip3860(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   328  	gas, err := memoryGasCost(mem, memorySize)
   329  	if err != nil {
   330  		return 0, err
   331  	}
   332  	size, overflow := stack.Back(2).Uint64WithOverflow()
   333  	if overflow {
   334  		return 0, ErrGasUintOverflow
   335  	}
   336  	if size > params.MaxInitCodeSize {
   337  		return 0, fmt.Errorf("%w: size %d", ErrMaxInitCodeSizeExceeded, size)
   338  	}
   339  	// Since size <= params.MaxInitCodeSize, these multiplication cannot overflow
   340  	moreGas := (params.InitCodeWordGas + params.Keccak256WordGas) * ((size + 31) / 32)
   341  	if gas, overflow = math.SafeAdd(gas, moreGas); overflow {
   342  		return 0, ErrGasUintOverflow
   343  	}
   344  	return gas, nil
   345  }
   346  
   347  func gasExpFrontier(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   348  	expByteLen := uint64((stack.data[stack.len()-2].BitLen() + 7) / 8)
   349  
   350  	var (
   351  		gas      = expByteLen * params.ExpByteFrontier // no overflow check required. Max is 256 * ExpByte gas
   352  		overflow bool
   353  	)
   354  	if gas, overflow = math.SafeAdd(gas, params.ExpGas); overflow {
   355  		return 0, ErrGasUintOverflow
   356  	}
   357  	return gas, nil
   358  }
   359  
   360  func gasExpEIP158(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   361  	expByteLen := uint64((stack.data[stack.len()-2].BitLen() + 7) / 8)
   362  
   363  	var (
   364  		gas      = expByteLen * params.ExpByteEIP158 // no overflow check required. Max is 256 * ExpByte gas
   365  		overflow bool
   366  	)
   367  	if gas, overflow = math.SafeAdd(gas, params.ExpGas); overflow {
   368  		return 0, ErrGasUintOverflow
   369  	}
   370  	return gas, nil
   371  }
   372  
   373  func gasCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   374  	var (
   375  		gas            uint64
   376  		transfersValue = !stack.Back(2).IsZero()
   377  		address        = common.Address(stack.Back(1).Bytes20())
   378  	)
   379  	if evm.chainRules.IsEIP158 {
   380  		if transfersValue && evm.StateDB.Empty(address) {
   381  			gas += params.CallNewAccountGas
   382  		}
   383  	} else if !evm.StateDB.Exist(address) {
   384  		gas += params.CallNewAccountGas
   385  	}
   386  	if transfersValue {
   387  		gas += params.CallValueTransferGas
   388  	}
   389  	memoryGas, err := memoryGasCost(mem, memorySize)
   390  	if err != nil {
   391  		return 0, err
   392  	}
   393  	var overflow bool
   394  	if gas, overflow = math.SafeAdd(gas, memoryGas); overflow {
   395  		return 0, ErrGasUintOverflow
   396  	}
   397  
   398  	evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))
   399  	if err != nil {
   400  		return 0, err
   401  	}
   402  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   403  		return 0, ErrGasUintOverflow
   404  	}
   405  	return gas, nil
   406  }
   407  
   408  func gasCallCode(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   409  	memoryGas, err := memoryGasCost(mem, memorySize)
   410  	if err != nil {
   411  		return 0, err
   412  	}
   413  	var (
   414  		gas      uint64
   415  		overflow bool
   416  	)
   417  	if stack.Back(2).Sign() != 0 {
   418  		gas += params.CallValueTransferGas
   419  	}
   420  	if gas, overflow = math.SafeAdd(gas, memoryGas); overflow {
   421  		return 0, ErrGasUintOverflow
   422  	}
   423  	evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))
   424  	if err != nil {
   425  		return 0, err
   426  	}
   427  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   428  		return 0, ErrGasUintOverflow
   429  	}
   430  	return gas, nil
   431  }
   432  
   433  func gasDelegateCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   434  	gas, err := memoryGasCost(mem, memorySize)
   435  	if err != nil {
   436  		return 0, err
   437  	}
   438  	evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))
   439  	if err != nil {
   440  		return 0, err
   441  	}
   442  	var overflow bool
   443  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   444  		return 0, ErrGasUintOverflow
   445  	}
   446  	return gas, nil
   447  }
   448  
   449  func gasStaticCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   450  	gas, err := memoryGasCost(mem, memorySize)
   451  	if err != nil {
   452  		return 0, err
   453  	}
   454  	evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))
   455  	if err != nil {
   456  		return 0, err
   457  	}
   458  	var overflow bool
   459  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   460  		return 0, ErrGasUintOverflow
   461  	}
   462  	return gas, nil
   463  }
   464  
   465  func gasSelfdestruct(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   466  	var gas uint64
   467  	// EIP150 homestead gas reprice fork:
   468  	if evm.chainRules.IsEIP150 {
   469  		gas = params.SelfdestructGasEIP150
   470  		var address = common.Address(stack.Back(0).Bytes20())
   471  
   472  		if evm.chainRules.IsEIP158 {
   473  			// if empty and transfers value
   474  			if evm.StateDB.Empty(address) && evm.StateDB.GetBalance(contract.Address()).Sign() != 0 {
   475  				gas += params.CreateBySelfdestructGas
   476  			}
   477  		} else if !evm.StateDB.Exist(address) {
   478  			gas += params.CreateBySelfdestructGas
   479  		}
   480  	}
   481  
   482  	if !evm.StateDB.HasSelfDestructed(contract.Address()) {
   483  		evm.StateDB.AddRefund(params.SelfdestructRefundGas)
   484  	}
   485  	return gas, nil
   486  }