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