github.com/CommerciumBlockchain/go-commercium@v0.0.0-20220709212705-b46438a77516/core/vm/evm.go (about) 1 // Copyright 2014 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 "math/big" 22 "sync/atomic" 23 "time" 24 25 "github.com/CommerciumBlockchain/go-commercium/common" 26 "github.com/CommerciumBlockchain/go-commercium/crypto" 27 "github.com/CommerciumBlockchain/go-commercium/params" 28 "github.com/holiman/uint256" 29 ) 30 31 // emptyCodeHash is used by create to ensure deployment is disallowed to already 32 // deployed contract addresses (relevant after the account abstraction). 33 var emptyCodeHash = crypto.Keccak256Hash(nil) 34 35 type ( 36 // CanTransferFunc is the signature of a transfer guard function 37 CanTransferFunc func(StateDB, common.Address, *big.Int) bool 38 // TransferFunc is the signature of a transfer function 39 TransferFunc func(StateDB, common.Address, common.Address, *big.Int) 40 // GetHashFunc returns the n'th block hash in the blockchain 41 // and is used by the BLOCKHASH EVM op code. 42 GetHashFunc func(uint64) common.Hash 43 ) 44 45 // ActivePrecompiles returns the addresses of the precompiles enabled with the current 46 // configuration 47 func (evm *EVM) ActivePrecompiles() []common.Address { 48 switch { 49 case evm.chainRules.IsYoloV2: 50 return PrecompiledAddressesYoloV2 51 case evm.chainRules.IsIstanbul: 52 return PrecompiledAddressesIstanbul 53 case evm.chainRules.IsByzantium: 54 return PrecompiledAddressesByzantium 55 default: 56 return PrecompiledAddressesHomestead 57 } 58 } 59 60 func (evm *EVM) precompile(addr common.Address) (PrecompiledContract, bool) { 61 var precompiles map[common.Address]PrecompiledContract 62 switch { 63 case evm.chainRules.IsYoloV2: 64 precompiles = PrecompiledContractsYoloV2 65 case evm.chainRules.IsIstanbul: 66 precompiles = PrecompiledContractsIstanbul 67 case evm.chainRules.IsByzantium: 68 precompiles = PrecompiledContractsByzantium 69 default: 70 precompiles = PrecompiledContractsHomestead 71 } 72 p, ok := precompiles[addr] 73 return p, ok 74 } 75 76 // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter. 77 func run(evm *EVM, contract *Contract, input []byte, readOnly bool) ([]byte, error) { 78 for _, interpreter := range evm.interpreters { 79 if interpreter.CanRun(contract.Code) { 80 if evm.interpreter != interpreter { 81 // Ensure that the interpreter pointer is set back 82 // to its current value upon return. 83 defer func(i Interpreter) { 84 evm.interpreter = i 85 }(evm.interpreter) 86 evm.interpreter = interpreter 87 } 88 return interpreter.Run(contract, input, readOnly) 89 } 90 } 91 return nil, errors.New("no compatible interpreter") 92 } 93 94 // BlockContext provides the EVM with auxiliary information. Once provided 95 // it shouldn't be modified. 96 type BlockContext struct { 97 // CanTransfer returns whether the account contains 98 // sufficient ether to transfer the value 99 CanTransfer CanTransferFunc 100 // Transfer transfers ether from one account to the other 101 Transfer TransferFunc 102 // GetHash returns the hash corresponding to n 103 GetHash GetHashFunc 104 105 // Block information 106 Coinbase common.Address // Provides information for COINBASE 107 GasLimit uint64 // Provides information for GASLIMIT 108 BlockNumber *big.Int // Provides information for NUMBER 109 Time *big.Int // Provides information for TIME 110 Difficulty *big.Int // Provides information for DIFFICULTY 111 } 112 113 // TxContext provides the EVM with information about a transaction. 114 // All fields can change between transactions. 115 type TxContext struct { 116 // Message information 117 Origin common.Address // Provides information for ORIGIN 118 GasPrice *big.Int // Provides information for GASPRICE 119 } 120 121 // EVM is the Ethereum Virtual Machine base object and provides 122 // the necessary tools to run a contract on the given state with 123 // the provided context. It should be noted that any error 124 // generated through any of the calls should be considered a 125 // revert-state-and-consume-all-gas operation, no checks on 126 // specific errors should ever be performed. The interpreter makes 127 // sure that any errors generated are to be considered faulty code. 128 // 129 // The EVM should never be reused and is not thread safe. 130 type EVM struct { 131 // Context provides auxiliary blockchain related information 132 Context BlockContext 133 TxContext 134 // StateDB gives access to the underlying state 135 StateDB StateDB 136 // Depth is the current call stack 137 depth int 138 139 // chainConfig contains information about the current chain 140 chainConfig *params.ChainConfig 141 // chain rules contains the chain rules for the current epoch 142 chainRules params.Rules 143 // virtual machine configuration options used to initialise the 144 // evm. 145 vmConfig Config 146 // global (to this context) ethereum virtual machine 147 // used throughout the execution of the tx. 148 interpreters []Interpreter 149 interpreter Interpreter 150 // abort is used to abort the EVM calling operations 151 // NOTE: must be set atomically 152 abort int32 153 // callGasTemp holds the gas available for the current call. This is needed because the 154 // available gas is calculated in gasCall* according to the 63/64 rule and later 155 // applied in opCall*. 156 callGasTemp uint64 157 } 158 159 // NewEVM returns a new EVM. The returned EVM is not thread safe and should 160 // only ever be used *once*. 161 func NewEVM(blockCtx BlockContext, txCtx TxContext, statedb StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM { 162 evm := &EVM{ 163 Context: blockCtx, 164 TxContext: txCtx, 165 StateDB: statedb, 166 vmConfig: vmConfig, 167 chainConfig: chainConfig, 168 chainRules: chainConfig.Rules(blockCtx.BlockNumber), 169 interpreters: make([]Interpreter, 0, 1), 170 } 171 172 if chainConfig.IsEWASM(blockCtx.BlockNumber) { 173 // to be implemented by EVM-C and Wagon PRs. 174 // if vmConfig.EWASMInterpreter != "" { 175 // extIntOpts := strings.Split(vmConfig.EWASMInterpreter, ":") 176 // path := extIntOpts[0] 177 // options := []string{} 178 // if len(extIntOpts) > 1 { 179 // options = extIntOpts[1..] 180 // } 181 // evm.interpreters = append(evm.interpreters, NewEVMVCInterpreter(evm, vmConfig, options)) 182 // } else { 183 // evm.interpreters = append(evm.interpreters, NewEWASMInterpreter(evm, vmConfig)) 184 // } 185 panic("No supported ewasm interpreter yet.") 186 } 187 188 // vmConfig.EVMInterpreter will be used by EVM-C, it won't be checked here 189 // as we always want to have the built-in EVM as the failover option. 190 evm.interpreters = append(evm.interpreters, NewEVMInterpreter(evm, vmConfig)) 191 evm.interpreter = evm.interpreters[0] 192 193 return evm 194 } 195 196 // Reset resets the EVM with a new transaction context.Reset 197 // This is not threadsafe and should only be done very cautiously. 198 func (evm *EVM) Reset(txCtx TxContext, statedb StateDB) { 199 evm.TxContext = txCtx 200 evm.StateDB = statedb 201 } 202 203 // Cancel cancels any running EVM operation. This may be called concurrently and 204 // it's safe to be called multiple times. 205 func (evm *EVM) Cancel() { 206 atomic.StoreInt32(&evm.abort, 1) 207 } 208 209 // Cancelled returns true if Cancel has been called 210 func (evm *EVM) Cancelled() bool { 211 return atomic.LoadInt32(&evm.abort) == 1 212 } 213 214 // Interpreter returns the current interpreter 215 func (evm *EVM) Interpreter() Interpreter { 216 return evm.interpreter 217 } 218 219 // Call executes the contract associated with the addr with the given input as 220 // parameters. It also handles any necessary value transfer required and takes 221 // the necessary steps to create accounts and reverses the state in case of an 222 // execution error or failed value transfer. 223 func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { 224 if evm.vmConfig.NoRecursion && evm.depth > 0 { 225 return nil, gas, nil 226 } 227 // Fail if we're trying to execute above the call depth limit 228 if evm.depth > int(params.CallCreateDepth) { 229 return nil, gas, ErrDepth 230 } 231 // Fail if we're trying to transfer more than the available balance 232 if value.Sign() != 0 && !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { 233 return nil, gas, ErrInsufficientBalance 234 } 235 snapshot := evm.StateDB.Snapshot() 236 p, isPrecompile := evm.precompile(addr) 237 238 if !evm.StateDB.Exist(addr) { 239 if !isPrecompile && evm.chainRules.IsEIP158 && value.Sign() == 0 { 240 // Calling a non existing account, don't do anything, but ping the tracer 241 if evm.vmConfig.Debug && evm.depth == 0 { 242 evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value) 243 evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil) 244 } 245 return nil, gas, nil 246 } 247 evm.StateDB.CreateAccount(addr) 248 } 249 evm.Context.Transfer(evm.StateDB, caller.Address(), addr, value) 250 251 // Capture the tracer start/end events in debug mode 252 if evm.vmConfig.Debug && evm.depth == 0 { 253 evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value) 254 defer func(startGas uint64, startTime time.Time) { // Lazy evaluation of the parameters 255 evm.vmConfig.Tracer.CaptureEnd(ret, startGas-gas, time.Since(startTime), err) 256 }(gas, time.Now()) 257 } 258 259 if isPrecompile { 260 ret, gas, err = RunPrecompiledContract(p, input, gas) 261 } else { 262 // Initialise a new contract and set the code that is to be used by the EVM. 263 // The contract is a scoped environment for this execution context only. 264 code := evm.StateDB.GetCode(addr) 265 if len(code) == 0 { 266 ret, err = nil, nil // gas is unchanged 267 } else { 268 addrCopy := addr 269 // If the account has no code, we can abort here 270 // The depth-check is already done, and precompiles handled above 271 contract := NewContract(caller, AccountRef(addrCopy), value, gas) 272 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), code) 273 ret, err = run(evm, contract, input, false) 274 gas = contract.Gas 275 } 276 } 277 // When an error was returned by the EVM or when setting the creation code 278 // above we revert to the snapshot and consume any gas remaining. Additionally 279 // when we're in homestead this also counts for code storage gas errors. 280 if err != nil { 281 evm.StateDB.RevertToSnapshot(snapshot) 282 if err != ErrExecutionReverted { 283 gas = 0 284 } 285 // TODO: consider clearing up unused snapshots: 286 //} else { 287 // evm.StateDB.DiscardSnapshot(snapshot) 288 } 289 return ret, gas, err 290 } 291 292 // CallCode executes the contract associated with the addr with the given input 293 // as parameters. It also handles any necessary value transfer required and takes 294 // the necessary steps to create accounts and reverses the state in case of an 295 // execution error or failed value transfer. 296 // 297 // CallCode differs from Call in the sense that it executes the given address' 298 // code with the caller as context. 299 func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { 300 if evm.vmConfig.NoRecursion && evm.depth > 0 { 301 return nil, gas, nil 302 } 303 // Fail if we're trying to execute above the call depth limit 304 if evm.depth > int(params.CallCreateDepth) { 305 return nil, gas, ErrDepth 306 } 307 // Fail if we're trying to transfer more than the available balance 308 // Note although it's noop to transfer X ether to caller itself. But 309 // if caller doesn't have enough balance, it would be an error to allow 310 // over-charging itself. So the check here is necessary. 311 if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { 312 return nil, gas, ErrInsufficientBalance 313 } 314 var snapshot = evm.StateDB.Snapshot() 315 316 // It is allowed to call precompiles, even via delegatecall 317 if p, isPrecompile := evm.precompile(addr); isPrecompile { 318 ret, gas, err = RunPrecompiledContract(p, input, gas) 319 } else { 320 addrCopy := addr 321 // Initialise a new contract and set the code that is to be used by the EVM. 322 // The contract is a scoped environment for this execution context only. 323 contract := NewContract(caller, AccountRef(caller.Address()), value, gas) 324 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy)) 325 ret, err = run(evm, contract, input, false) 326 gas = contract.Gas 327 } 328 if err != nil { 329 evm.StateDB.RevertToSnapshot(snapshot) 330 if err != ErrExecutionReverted { 331 gas = 0 332 } 333 } 334 return ret, gas, err 335 } 336 337 // DelegateCall executes the contract associated with the addr with the given input 338 // as parameters. It reverses the state in case of an execution error. 339 // 340 // DelegateCall differs from CallCode in the sense that it executes the given address' 341 // code with the caller as context and the caller is set to the caller of the caller. 342 func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) { 343 if evm.vmConfig.NoRecursion && evm.depth > 0 { 344 return nil, gas, nil 345 } 346 // Fail if we're trying to execute above the call depth limit 347 if evm.depth > int(params.CallCreateDepth) { 348 return nil, gas, ErrDepth 349 } 350 var snapshot = evm.StateDB.Snapshot() 351 352 // It is allowed to call precompiles, even via delegatecall 353 if p, isPrecompile := evm.precompile(addr); isPrecompile { 354 ret, gas, err = RunPrecompiledContract(p, input, gas) 355 } else { 356 addrCopy := addr 357 // Initialise a new contract and make initialise the delegate values 358 contract := NewContract(caller, AccountRef(caller.Address()), nil, gas).AsDelegate() 359 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy)) 360 ret, err = run(evm, contract, input, false) 361 gas = contract.Gas 362 } 363 if err != nil { 364 evm.StateDB.RevertToSnapshot(snapshot) 365 if err != ErrExecutionReverted { 366 gas = 0 367 } 368 } 369 return ret, gas, err 370 } 371 372 // StaticCall executes the contract associated with the addr with the given input 373 // as parameters while disallowing any modifications to the state during the call. 374 // Opcodes that attempt to perform such modifications will result in exceptions 375 // instead of performing the modifications. 376 func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) { 377 if evm.vmConfig.NoRecursion && evm.depth > 0 { 378 return nil, gas, nil 379 } 380 // Fail if we're trying to execute above the call depth limit 381 if evm.depth > int(params.CallCreateDepth) { 382 return nil, gas, ErrDepth 383 } 384 // We take a snapshot here. This is a bit counter-intuitive, and could probably be skipped. 385 // However, even a staticcall is considered a 'touch'. On mainnet, static calls were introduced 386 // after all empty accounts were deleted, so this is not required. However, if we omit this, 387 // then certain tests start failing; stRevertTest/RevertPrecompiledTouchExactOOG.json. 388 // We could change this, but for now it's left for legacy reasons 389 var snapshot = evm.StateDB.Snapshot() 390 391 // We do an AddBalance of zero here, just in order to trigger a touch. 392 // This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium, 393 // but is the correct thing to do and matters on other networks, in tests, and potential 394 // future scenarios 395 evm.StateDB.AddBalance(addr, big0) 396 397 if p, isPrecompile := evm.precompile(addr); isPrecompile { 398 ret, gas, err = RunPrecompiledContract(p, input, gas) 399 } else { 400 // At this point, we use a copy of address. If we don't, the go compiler will 401 // leak the 'contract' to the outer scope, and make allocation for 'contract' 402 // even if the actual execution ends on RunPrecompiled above. 403 addrCopy := addr 404 // Initialise a new contract and set the code that is to be used by the EVM. 405 // The contract is a scoped environment for this execution context only. 406 contract := NewContract(caller, AccountRef(addrCopy), new(big.Int), gas) 407 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy)) 408 // When an error was returned by the EVM or when setting the creation code 409 // above we revert to the snapshot and consume any gas remaining. Additionally 410 // when we're in Homestead this also counts for code storage gas errors. 411 ret, err = run(evm, contract, input, true) 412 gas = contract.Gas 413 } 414 if err != nil { 415 evm.StateDB.RevertToSnapshot(snapshot) 416 if err != ErrExecutionReverted { 417 gas = 0 418 } 419 } 420 return ret, gas, err 421 } 422 423 type codeAndHash struct { 424 code []byte 425 hash common.Hash 426 } 427 428 func (c *codeAndHash) Hash() common.Hash { 429 if c.hash == (common.Hash{}) { 430 c.hash = crypto.Keccak256Hash(c.code) 431 } 432 return c.hash 433 } 434 435 // create creates a new contract using code as deployment code. 436 func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) { 437 // Depth check execution. Fail if we're trying to execute above the 438 // limit. 439 if evm.depth > int(params.CallCreateDepth) { 440 return nil, common.Address{}, gas, ErrDepth 441 } 442 if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { 443 return nil, common.Address{}, gas, ErrInsufficientBalance 444 } 445 nonce := evm.StateDB.GetNonce(caller.Address()) 446 evm.StateDB.SetNonce(caller.Address(), nonce+1) 447 // We add this to the access list _before_ taking a snapshot. Even if the creation fails, 448 // the access-list change should not be rolled back 449 if evm.chainRules.IsYoloV2 { 450 evm.StateDB.AddAddressToAccessList(address) 451 } 452 // Ensure there's no existing contract already at the designated address 453 contractHash := evm.StateDB.GetCodeHash(address) 454 if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) { 455 return nil, common.Address{}, 0, ErrContractAddressCollision 456 } 457 // Create a new account on the state 458 snapshot := evm.StateDB.Snapshot() 459 evm.StateDB.CreateAccount(address) 460 if evm.chainRules.IsEIP158 { 461 evm.StateDB.SetNonce(address, 1) 462 } 463 evm.Context.Transfer(evm.StateDB, caller.Address(), address, value) 464 465 // Initialise a new contract and set the code that is to be used by the EVM. 466 // The contract is a scoped environment for this execution context only. 467 contract := NewContract(caller, AccountRef(address), value, gas) 468 contract.SetCodeOptionalHash(&address, codeAndHash) 469 470 if evm.vmConfig.NoRecursion && evm.depth > 0 { 471 return nil, address, gas, nil 472 } 473 474 if evm.vmConfig.Debug && evm.depth == 0 { 475 evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, codeAndHash.code, gas, value) 476 } 477 start := time.Now() 478 479 ret, err := run(evm, contract, nil, false) 480 481 // check whether the max code size has been exceeded 482 maxCodeSizeExceeded := evm.chainRules.IsEIP158 && len(ret) > params.MaxCodeSize 483 // if the contract creation ran successfully and no errors were returned 484 // calculate the gas required to store the code. If the code could not 485 // be stored due to not enough gas set an error and let it be handled 486 // by the error checking condition below. 487 if err == nil && !maxCodeSizeExceeded { 488 createDataGas := uint64(len(ret)) * params.CreateDataGas 489 if contract.UseGas(createDataGas) { 490 evm.StateDB.SetCode(address, ret) 491 } else { 492 err = ErrCodeStoreOutOfGas 493 } 494 } 495 496 // When an error was returned by the EVM or when setting the creation code 497 // above we revert to the snapshot and consume any gas remaining. Additionally 498 // when we're in homestead this also counts for code storage gas errors. 499 if maxCodeSizeExceeded || (err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas)) { 500 evm.StateDB.RevertToSnapshot(snapshot) 501 if err != ErrExecutionReverted { 502 contract.UseGas(contract.Gas) 503 } 504 } 505 // Assign err if contract code size exceeds the max while the err is still empty. 506 if maxCodeSizeExceeded && err == nil { 507 err = ErrMaxCodeSizeExceeded 508 } 509 if evm.vmConfig.Debug && evm.depth == 0 { 510 evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err) 511 } 512 return ret, address, contract.Gas, err 513 514 } 515 516 // Create creates a new contract using code as deployment code. 517 func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) { 518 contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address())) 519 return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr) 520 } 521 522 // Create2 creates a new contract using code as deployment code. 523 // 524 // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:] 525 // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at. 526 func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) { 527 codeAndHash := &codeAndHash{code: code} 528 contractAddr = crypto.CreateAddress2(caller.Address(), salt.Bytes32(), codeAndHash.Hash().Bytes()) 529 return evm.create(caller, codeAndHash, gas, endowment, contractAddr) 530 } 531 532 // ChainConfig returns the environment's chain configuration 533 func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }