github.com/klaytn/klaytn@v1.12.1/blockchain/vm/gas_table.go (about)

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