github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/core/vm/gas_table.go (about)

     1  // Copyright 2017 The go-simplechain Authors
     2  // This file is part of the go-simplechain library.
     3  //
     4  // The go-simplechain 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-simplechain 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-simplechain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package vm
    18  
    19  import (
    20  	"errors"
    21  
    22  	"github.com/bigzoro/my_simplechain/common"
    23  	"github.com/bigzoro/my_simplechain/common/math"
    24  	"github.com/bigzoro/my_simplechain/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 := bigUint64(stack.Back(stackpos))
    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(), common.BigToHash(x))
   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  	// The new gas metering is based on net gas costs (EIP-1283):
   121  	//
   122  	// 1. If current value equals new value (this is a no-op), 200 gas is deducted.
   123  	// 2. If current value does not equal new value
   124  	//   2.1. If original value equals current value (this storage slot has not been changed by the current execution context)
   125  	//     2.1.1. If original value is 0, 20000 gas is deducted.
   126  	// 	   2.1.2. Otherwise, 5000 gas is deducted. If new value is 0, add 15000 gas to refund counter.
   127  	// 	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.
   128  	// 	  2.2.1. If original value is not 0
   129  	//       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.
   130  	//       2.2.1.2. If new value is 0 (also means that current value is not 0), add 15000 gas to refund counter.
   131  	// 	  2.2.2. If original value equals new value (this storage slot is reset)
   132  	//       2.2.2.1. If original value is 0, add 19800 gas to refund counter.
   133  	// 	     2.2.2.2. Otherwise, add 4800 gas to refund counter.
   134  	//value := common.BigToHash(y)
   135  	//if current == value { // noop (1)
   136  	//	return params.NetSstoreNoopGas, nil
   137  	//}
   138  	//original := evm.StateDB.GetCommittedState(contract.Address(), common.BigToHash(x))
   139  	//if original == current {
   140  	//	if original == (common.Hash{}) { // create slot (2.1.1)
   141  	//		return params.NetSstoreInitGas, nil
   142  	//	}
   143  	//	if value == (common.Hash{}) { // delete slot (2.1.2b)
   144  	//		evm.StateDB.AddRefund(params.NetSstoreClearRefund)
   145  	//	}
   146  	//	return params.NetSstoreCleanGas, nil // write existing slot (2.1.2)
   147  	//}
   148  	//if original != (common.Hash{}) {
   149  	//	if current == (common.Hash{}) { // recreate slot (2.2.1.1)
   150  	//		evm.StateDB.SubRefund(params.NetSstoreClearRefund)
   151  	//	} else if value == (common.Hash{}) { // delete slot (2.2.1.2)
   152  	//		evm.StateDB.AddRefund(params.NetSstoreClearRefund)
   153  	//	}
   154  	//}
   155  	//if original == value {
   156  	//	if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
   157  	//		evm.StateDB.AddRefund(params.NetSstoreResetClearRefund)
   158  	//	} else { // reset to original existing slot (2.2.2.2)
   159  	//		evm.StateDB.AddRefund(params.NetSstoreResetRefund)
   160  	//	}
   161  	//}
   162  	//return params.NetSstoreDirtyGas, nil
   163  }
   164  
   165  //  0. If *gasleft* is less than or equal to 2300, fail the current call.
   166  //  1. If current value equals new value (this is a no-op), SSTORE_NOOP_GAS gas is deducted.
   167  //  2. If current value does not equal new value:
   168  //     2.1. If original value equals current value (this storage slot has not been changed by the current execution context):
   169  //     2.1.1. If original value is 0, SSTORE_INIT_GAS gas is deducted.
   170  //     2.1.2. Otherwise, SSTORE_CLEAN_GAS gas is deducted. If new value is 0, add SSTORE_CLEAR_REFUND to refund counter.
   171  //     2.2. If original value does not equal current value (this storage slot is dirty), SSTORE_DIRTY_GAS gas is deducted. Apply both of the following clauses:
   172  //     2.2.1. If original value is not 0:
   173  //     2.2.1.1. If current value is 0 (also means that new value is not 0), subtract SSTORE_CLEAR_REFUND gas from refund counter. We can prove that refund counter will never go below 0.
   174  //     2.2.1.2. If new value is 0 (also means that current value is not 0), add SSTORE_CLEAR_REFUND gas to refund counter.
   175  //     2.2.2. If original value equals new value (this storage slot is reset):
   176  //     2.2.2.1. If original value is 0, add SSTORE_INIT_REFUND to refund counter.
   177  //     2.2.2.2. Otherwise, add SSTORE_CLEAN_REFUND gas to refund counter.
   178  func gasSStoreEIP2200(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   179  	// If we fail the minimum gas availability invariant, fail (0)
   180  	if contract.Gas <= params.SstoreSentryGasEIP2200 {
   181  		return 0, errors.New("not enough gas for reentrancy sentry")
   182  	}
   183  	// Gas sentry honoured, do the actual gas calculation based on the stored value
   184  	var (
   185  		y, x    = stack.Back(1), stack.Back(0)
   186  		current = evm.StateDB.GetState(contract.Address(), common.BigToHash(x))
   187  	)
   188  	value := common.BigToHash(y)
   189  
   190  	if current == value { // noop (1)
   191  		return params.SstoreNoopGasEIP2200, nil
   192  	}
   193  	original := evm.StateDB.GetCommittedState(contract.Address(), common.BigToHash(x))
   194  	if original == current {
   195  		if original == (common.Hash{}) { // create slot (2.1.1)
   196  			return params.SstoreInitGasEIP2200, nil
   197  		}
   198  		if value == (common.Hash{}) { // delete slot (2.1.2b)
   199  			evm.StateDB.AddRefund(params.SstoreClearRefundEIP2200)
   200  		}
   201  		return params.SstoreCleanGasEIP2200, nil // write existing slot (2.1.2)
   202  	}
   203  	if original != (common.Hash{}) {
   204  		if current == (common.Hash{}) { // recreate slot (2.2.1.1)
   205  			evm.StateDB.SubRefund(params.SstoreClearRefundEIP2200)
   206  		} else if value == (common.Hash{}) { // delete slot (2.2.1.2)
   207  			evm.StateDB.AddRefund(params.SstoreClearRefundEIP2200)
   208  		}
   209  	}
   210  	if original == value {
   211  		if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
   212  			evm.StateDB.AddRefund(params.SstoreInitRefundEIP2200)
   213  		} else { // reset to original existing slot (2.2.2.2)
   214  			evm.StateDB.AddRefund(params.SstoreCleanRefundEIP2200)
   215  		}
   216  	}
   217  	return params.SstoreDirtyGasEIP2200, nil // dirty update (2.2)
   218  }
   219  
   220  func makeGasLog(n uint64) gasFunc {
   221  	return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   222  		requestedSize, overflow := bigUint64(stack.Back(1))
   223  		if overflow {
   224  			return 0, errGasUintOverflow
   225  		}
   226  
   227  		gas, err := memoryGasCost(mem, memorySize)
   228  		if err != nil {
   229  			return 0, err
   230  		}
   231  
   232  		if gas, overflow = math.SafeAdd(gas, params.LogGas); overflow {
   233  			return 0, errGasUintOverflow
   234  		}
   235  		if gas, overflow = math.SafeAdd(gas, n*params.LogTopicGas); overflow {
   236  			return 0, errGasUintOverflow
   237  		}
   238  
   239  		var memorySizeGas uint64
   240  		if memorySizeGas, overflow = math.SafeMul(requestedSize, params.LogDataGas); overflow {
   241  			return 0, errGasUintOverflow
   242  		}
   243  		if gas, overflow = math.SafeAdd(gas, memorySizeGas); overflow {
   244  			return 0, errGasUintOverflow
   245  		}
   246  		return gas, nil
   247  	}
   248  }
   249  
   250  func gasSha3(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   251  	gas, err := memoryGasCost(mem, memorySize)
   252  	if err != nil {
   253  		return 0, err
   254  	}
   255  	wordGas, overflow := bigUint64(stack.Back(1))
   256  	if overflow {
   257  		return 0, errGasUintOverflow
   258  	}
   259  	if wordGas, overflow = math.SafeMul(toWordSize(wordGas), params.Sha3WordGas); overflow {
   260  		return 0, errGasUintOverflow
   261  	}
   262  	if gas, overflow = math.SafeAdd(gas, wordGas); overflow {
   263  		return 0, errGasUintOverflow
   264  	}
   265  	return gas, nil
   266  }
   267  
   268  // pureMemoryGascost is used by several operations, which aside from their
   269  // static cost have a dynamic cost which is solely based on the memory
   270  // expansion
   271  func pureMemoryGascost(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   272  	return memoryGasCost(mem, memorySize)
   273  }
   274  
   275  var (
   276  	gasReturn  = pureMemoryGascost
   277  	gasRevert  = pureMemoryGascost
   278  	gasMLoad   = pureMemoryGascost
   279  	gasMStore8 = pureMemoryGascost
   280  	gasMStore  = pureMemoryGascost
   281  	gasCreate  = pureMemoryGascost
   282  )
   283  
   284  func gasCreate2(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   285  	gas, err := memoryGasCost(mem, memorySize)
   286  	if err != nil {
   287  		return 0, err
   288  	}
   289  	wordGas, overflow := bigUint64(stack.Back(2))
   290  	if overflow {
   291  		return 0, errGasUintOverflow
   292  	}
   293  	if wordGas, overflow = math.SafeMul(toWordSize(wordGas), params.Sha3WordGas); overflow {
   294  		return 0, errGasUintOverflow
   295  	}
   296  	if gas, overflow = math.SafeAdd(gas, wordGas); overflow {
   297  		return 0, errGasUintOverflow
   298  	}
   299  	return gas, nil
   300  }
   301  
   302  func gasExpFrontier(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   303  	expByteLen := uint64((stack.data[stack.len()-2].BitLen() + 7) / 8)
   304  
   305  	var (
   306  		gas      = expByteLen * params.ExpByteFrontier // no overflow check required. Max is 256 * ExpByte gas
   307  		overflow bool
   308  	)
   309  	if gas, overflow = math.SafeAdd(gas, params.ExpGas); overflow {
   310  		return 0, errGasUintOverflow
   311  	}
   312  	return gas, nil
   313  }
   314  
   315  func gasExpEIP158(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   316  	expByteLen := uint64((stack.data[stack.len()-2].BitLen() + 7) / 8)
   317  
   318  	var (
   319  		gas      = expByteLen * params.ExpByteEIP158 // no overflow check required. Max is 256 * ExpByte gas
   320  		overflow bool
   321  	)
   322  	if gas, overflow = math.SafeAdd(gas, params.ExpGas); overflow {
   323  		return 0, errGasUintOverflow
   324  	}
   325  	return gas, nil
   326  }
   327  
   328  func gasCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   329  	var (
   330  		gas            uint64
   331  		transfersValue = stack.Back(2).Sign() != 0
   332  		address        = common.BigToAddress(stack.Back(1))
   333  	)
   334  
   335  	if transfersValue && evm.StateDB.Empty(address) {
   336  		gas += params.CallNewAccountGas
   337  	}
   338  	if transfersValue {
   339  		gas += params.CallValueTransferGas
   340  	}
   341  	memoryGas, err := memoryGasCost(mem, memorySize)
   342  	if err != nil {
   343  		return 0, err
   344  	}
   345  	var overflow bool
   346  	if gas, overflow = math.SafeAdd(gas, memoryGas); overflow {
   347  		return 0, errGasUintOverflow
   348  	}
   349  
   350  	evm.callGasTemp, err = callGas(contract.Gas, gas, stack.Back(0))
   351  	if err != nil {
   352  		return 0, err
   353  	}
   354  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   355  		return 0, errGasUintOverflow
   356  	}
   357  	return gas, nil
   358  }
   359  
   360  func gasCallCode(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   361  	memoryGas, err := memoryGasCost(mem, memorySize)
   362  	if err != nil {
   363  		return 0, err
   364  	}
   365  	var (
   366  		gas      uint64
   367  		overflow bool
   368  	)
   369  	if stack.Back(2).Sign() != 0 {
   370  		gas += params.CallValueTransferGas
   371  	}
   372  	if gas, overflow = math.SafeAdd(gas, memoryGas); overflow {
   373  		return 0, errGasUintOverflow
   374  	}
   375  	evm.callGasTemp, err = callGas(contract.Gas, gas, stack.Back(0))
   376  	if err != nil {
   377  		return 0, err
   378  	}
   379  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   380  		return 0, errGasUintOverflow
   381  	}
   382  	return gas, nil
   383  }
   384  
   385  func gasDelegateCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   386  	gas, err := memoryGasCost(mem, memorySize)
   387  	if err != nil {
   388  		return 0, err
   389  	}
   390  	evm.callGasTemp, err = callGas(contract.Gas, gas, stack.Back(0))
   391  	if err != nil {
   392  		return 0, err
   393  	}
   394  	var overflow bool
   395  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   396  		return 0, errGasUintOverflow
   397  	}
   398  	return gas, nil
   399  }
   400  
   401  func gasStaticCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   402  	gas, err := memoryGasCost(mem, memorySize)
   403  	if err != nil {
   404  		return 0, err
   405  	}
   406  	evm.callGasTemp, err = callGas(contract.Gas, gas, stack.Back(0))
   407  	if err != nil {
   408  		return 0, err
   409  	}
   410  	var overflow bool
   411  	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
   412  		return 0, errGasUintOverflow
   413  	}
   414  	return gas, nil
   415  }
   416  
   417  func gasSelfdestruct(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   418  	var gas uint64
   419  
   420  	gas = params.SelfdestructGasEIP150
   421  	var address = common.BigToAddress(stack.Back(0))
   422  
   423  	// if empty and transfers value
   424  	if evm.StateDB.Empty(address) && evm.StateDB.GetBalance(contract.Address()).Sign() != 0 {
   425  		gas += params.CreateBySelfdestructGas
   426  	}
   427  
   428  	if !evm.StateDB.HasSuicided(contract.Address()) {
   429  		evm.StateDB.AddRefund(params.SelfdestructRefundGas)
   430  	}
   431  	return gas, nil
   432  }