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