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