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