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