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