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