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

     1  // Copyright 2020 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/klaytn/klaytn/common"
    23  	"github.com/klaytn/klaytn/common/math"
    24  	"github.com/klaytn/klaytn/kerrors"
    25  	"github.com/klaytn/klaytn/params"
    26  )
    27  
    28  func makeGasSStoreFunc(clearingRefund uint64) gasFunc {
    29  	return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
    30  		// If we fail the minimum gas availability invariant, fail (0)
    31  		if contract.Gas <= params.SstoreSentryGasEIP2200 {
    32  			return 0, errors.New("not enough gas for reentrancy sentry")
    33  		}
    34  		// Gas sentry honoured, do the actual gas calculation based on the stored value
    35  		var (
    36  			y, x    = stack.Back(1), stack.peek()
    37  			slot    = common.Hash(x.Bytes32())
    38  			current = evm.StateDB.GetState(contract.Address(), slot)
    39  			cost    = uint64(0)
    40  		)
    41  		// Check slot presence in the access list
    42  		if addrPresent, slotPresent := evm.StateDB.SlotInAccessList(contract.Address(), slot); !slotPresent {
    43  			cost = params.ColdSloadCostEIP2929
    44  			// If the caller cannot afford the cost, this change will be rolled back
    45  			evm.StateDB.AddSlotToAccessList(contract.Address(), slot)
    46  			if !addrPresent {
    47  				// Once we're done with YOLOv2 and schedule this for mainnet, might
    48  				// be good to remove this panic here, which is just really a
    49  				// canary to have during testing
    50  				panic("impossible case: address was not present in access list during sstore op")
    51  			}
    52  		}
    53  		value := common.Hash(y.Bytes32())
    54  
    55  		if current == value { // noop (1)
    56  			// EIP 2200 original clause:
    57  			//		return params.SloadGasEIP2200, nil
    58  			return cost + params.WarmStorageReadCostEIP2929, nil // SLOAD_GAS
    59  		}
    60  		original := evm.StateDB.GetCommittedState(contract.Address(), x.Bytes32())
    61  		if original == current {
    62  			if original == (common.Hash{}) { // create slot (2.1.1)
    63  				return cost + params.SstoreSetGasEIP2200, nil
    64  			}
    65  			if value == (common.Hash{}) { // delete slot (2.1.2b)
    66  				evm.StateDB.AddRefund(clearingRefund)
    67  			}
    68  			// EIP-2200 original clause:
    69  			//		return params.SstoreResetGasEIP2200, nil // write existing slot (2.1.2)
    70  			return cost + (params.SstoreResetGasEIP2200 - params.ColdSloadCostEIP2929), nil // write existing slot (2.1.2)
    71  		}
    72  		if original != (common.Hash{}) {
    73  			if current == (common.Hash{}) { // recreate slot (2.2.1.1)
    74  				evm.StateDB.SubRefund(clearingRefund)
    75  			} else if value == (common.Hash{}) { // delete slot (2.2.1.2)
    76  				evm.StateDB.AddRefund(clearingRefund)
    77  			}
    78  		}
    79  		if original == value {
    80  			if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
    81  				// EIP 2200 Original clause:
    82  				// evm.StateDB.AddRefund(params.SstoreSetGasEIP2200 - params.SloadGasEIP2200)
    83  				evm.StateDB.AddRefund(params.SstoreSetGasEIP2200 - params.WarmStorageReadCostEIP2929)
    84  			} else { // reset to original existing slot (2.2.2.2)
    85  				// EIP 2200 Original clause:
    86  				//	evm.StateDB.AddRefund(params.SstoreResetGasEIP2200 - params.SloadGasEIP2200)
    87  				// - SSTORE_RESET_GAS redefined as (5000 - COLD_SLOAD_COST)
    88  				// - SLOAD_GAS redefined as WARM_STORAGE_READ_COST
    89  				// Final: (5000 - COLD_SLOAD_COST) - WARM_STORAGE_READ_COST
    90  				evm.StateDB.AddRefund((params.SstoreResetGasEIP2200 - params.ColdSloadCostEIP2929) - params.WarmStorageReadCostEIP2929)
    91  			}
    92  		}
    93  		// EIP-2200 original clause:
    94  		// return params.SloadGasEIP2200, nil // dirty update (2.2)
    95  		return cost + params.WarmStorageReadCostEIP2929, nil // dirty update (2.2)
    96  	}
    97  }
    98  
    99  // gasSLoadEIP2929 calculates dynamic gas for SLOAD according to EIP-2929
   100  // For SLOAD, if the (address, storage_key) pair (where address is the address of the contract
   101  // whose storage is being read) is not yet in accessed_storage_keys,
   102  // charge 2100 gas and add the pair to accessed_storage_keys.
   103  // If the pair is already in accessed_storage_keys, charge 100 gas.
   104  func gasSLoadEIP2929(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   105  	loc := stack.peek()
   106  	slot := common.Hash(loc.Bytes32())
   107  	// Check slot presence in the access list
   108  	if _, slotPresent := evm.StateDB.SlotInAccessList(contract.Address(), slot); !slotPresent {
   109  		// If the caller cannot afford the cost, this change will be rolled back
   110  		// If he does afford it, we can skip checking the same thing later on, during execution
   111  		evm.StateDB.AddSlotToAccessList(contract.Address(), slot)
   112  		return params.ColdSloadCostEIP2929, nil
   113  	}
   114  	return params.WarmStorageReadCostEIP2929, nil
   115  }
   116  
   117  // gasExtCodeCopyEIP2929 implements extcodecopy according to EIP-2929
   118  // EIP spec:
   119  // > If the target is not in accessed_addresses,
   120  // > charge COLD_ACCOUNT_ACCESS_COST gas, and add the address to accessed_addresses.
   121  // > Otherwise, charge WARM_STORAGE_READ_COST gas.
   122  func gasExtCodeCopyEIP2929(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   123  	// memory expansion first (dynamic part of pre-2929 implementation)
   124  	gas, err := gasExtCodeCopy(evm, contract, stack, mem, memorySize)
   125  	if err != nil {
   126  		return 0, err
   127  	}
   128  	addr := common.Address(stack.peek().Bytes20())
   129  	// Check slot presence in the access list
   130  	if !evm.StateDB.AddressInAccessList(addr) {
   131  		evm.StateDB.AddAddressToAccessList(addr)
   132  		var overflow bool
   133  		// We charge (cold-warm), since 'warm' is already charged as constantGas
   134  		if gas, overflow = math.SafeAdd(gas, params.ColdAccountAccessCostEIP2929-params.WarmStorageReadCostEIP2929); overflow {
   135  			return 0, errGasUintOverflow
   136  		}
   137  		return gas, nil
   138  	}
   139  	return gas, nil
   140  }
   141  
   142  // gasEip2929AccountCheck checks whether the first stack item (as address) is present in the access list.
   143  // If it is, this method returns '0', otherwise 'cold-warm' gas, presuming that the opcode using it
   144  // is also using 'warm' as constant factor.
   145  // This method is used by:
   146  // - extcodehash,
   147  // - extcodesize,
   148  // - (ext) balance
   149  func gasEip2929AccountCheck(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   150  	addr := common.Address(stack.peek().Bytes20())
   151  	// Check slot presence in the access list
   152  	if !evm.StateDB.AddressInAccessList(addr) {
   153  		// If the caller cannot afford the cost, this change will be rolled back
   154  		evm.StateDB.AddAddressToAccessList(addr)
   155  		// The warm storage read cost is already charged as constantGas
   156  		return params.ColdAccountAccessCostEIP2929 - params.WarmStorageReadCostEIP2929, nil
   157  	}
   158  	return 0, nil
   159  }
   160  
   161  func makeCallVariantGasCallEIP2929(oldCalculator gasFunc) gasFunc {
   162  	return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   163  		addr := common.Address(stack.Back(1).Bytes20())
   164  		// Check slot presence in the access list
   165  		warmAccess := evm.StateDB.AddressInAccessList(addr)
   166  		// The WarmStorageReadCostEIP2929 (100) is already deducted in the form of a constant cost, so
   167  		// the cost to charge for cold access, if any, is Cold - Warm
   168  		coldCost := params.ColdAccountAccessCostEIP2929 - params.WarmStorageReadCostEIP2929
   169  		if !warmAccess {
   170  			evm.StateDB.AddAddressToAccessList(addr)
   171  			// Charge the remaining difference here already, to correctly calculate available
   172  			// gas for call
   173  			if !contract.UseGas(coldCost) {
   174  				return 0, kerrors.ErrOutOfGas
   175  			}
   176  		}
   177  		// Now call the old calculator, which takes into account
   178  		// - create new account
   179  		// - transfer value
   180  		// - memory expansion
   181  		// - 63/64ths rule
   182  		gas, err := oldCalculator(evm, contract, stack, mem, memorySize)
   183  		if warmAccess || err != nil {
   184  			return gas, err
   185  		}
   186  		// In case of a cold access, we temporarily add the cold charge back, and also
   187  		// add it to the returned gas. By adding it to the return, it will be charged
   188  		// outside of this function, as part of the dynamic gas, and that will make it
   189  		// also become correctly reported to tracers.
   190  		contract.Gas += coldCost
   191  		return gas + coldCost, nil
   192  	}
   193  }
   194  
   195  var (
   196  	gasCallEIP2929         = makeCallVariantGasCallEIP2929(gasCall)
   197  	gasDelegateCallEIP2929 = makeCallVariantGasCallEIP2929(gasDelegateCall)
   198  	gasStaticCallEIP2929   = makeCallVariantGasCallEIP2929(gasStaticCall)
   199  	gasCallCodeEIP2929     = makeCallVariantGasCallEIP2929(gasCallCode)
   200  	gasSelfdestructEIP2929 = makeSelfdestructGasFn(true)
   201  	// gasSelfdestructEIP3529 implements the changes in EIP-3529 (no refunds)
   202  	gasSelfdestructEIP3529 = makeSelfdestructGasFn(false)
   203  
   204  	// gasSStoreEIP2929 implements gas cost for SSTORE according to EIP-2929
   205  	//
   206  	// When calling SSTORE, check if the (address, storage_key) pair is in accessed_storage_keys.
   207  	// If it is not, charge an additional COLD_SLOAD_COST gas, and add the pair to accessed_storage_keys.
   208  	// Additionally, modify the parameters defined in EIP 2200 as follows:
   209  	//
   210  	// Parameter 	Old value 	New value
   211  	// SLOAD_GAS 	800 	= WARM_STORAGE_READ_COST
   212  	// SSTORE_RESET_GAS 	5000 	5000 - COLD_SLOAD_COST
   213  	//
   214  	//The other parameters defined in EIP 2200 are unchanged.
   215  	// see gasSStoreEIP2200(...) in core/vm/gas_table.go for more info about how EIP 2200 is specified
   216  	gasSStoreEIP2929 = makeGasSStoreFunc(params.SstoreClearsScheduleRefundEIP2200)
   217  
   218  	// gasSStoreEIP3529 implements gas cost for SSTORE according to EIP-3529
   219  	// Replace `SSTORE_CLEARS_SCHEDULE` with `SSTORE_RESET_GAS + ACCESS_LIST_STORAGE_KEY_COST` (4,800)
   220  	gasSStoreEIP3529 = makeGasSStoreFunc(params.SstoreClearsScheduleRefundEIP3529)
   221  )
   222  
   223  // makeSelfdestructGasFn can create the selfdestruct dynamic gas function for EIP-2929 and EIP-3529
   224  func makeSelfdestructGasFn(refundsEnabled bool) gasFunc {
   225  	gasFunc := func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
   226  		var (
   227  			gas     uint64
   228  			address = common.Address(stack.peek().Bytes20())
   229  		)
   230  		if !evm.StateDB.AddressInAccessList(address) {
   231  			// If the caller cannot afford the cost, this change will be rolled back
   232  			evm.StateDB.AddAddressToAccessList(address)
   233  			gas = params.ColdAccountAccessCostEIP2929
   234  		}
   235  		// if empty and transfers value
   236  		if evm.StateDB.Empty(address) && evm.StateDB.GetBalance(contract.Address()).Sign() != 0 {
   237  			gas += params.CreateBySelfdestructGas
   238  		}
   239  		if refundsEnabled && !evm.StateDB.HasSelfDestructed(contract.Address()) {
   240  			evm.StateDB.AddRefund(params.SelfdestructRefundGas)
   241  		}
   242  		return gas, nil
   243  	}
   244  	return gasFunc
   245  }