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