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