github.com/ontio/ontology@v1.14.4/vm/evm/gas_table.go (about)

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