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