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