github.com/devfans/go-ethereum@v1.5.10-0.20170326212234-7419d0c38291/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/ethereum/go-ethereum/common" 24 "github.com/ethereum/go-ethereum/crypto" 25 "github.com/ethereum/go-ethereum/params" 26 ) 27 28 type ( 29 CanTransferFunc func(StateDB, common.Address, *big.Int) bool 30 TransferFunc func(StateDB, common.Address, common.Address, *big.Int) 31 // GetHashFunc returns the nth block hash in the blockchain 32 // and is used by the BLOCKHASH EVM op code. 33 GetHashFunc func(uint64) common.Hash 34 ) 35 36 // Context provides the EVM with auxiliary information. Once provided it shouldn't be modified. 37 type Context struct { 38 // CanTransfer returns whether the account contains 39 // sufficient ether to transfer the value 40 CanTransfer CanTransferFunc 41 // Transfer transfers ether from one account to the other 42 Transfer TransferFunc 43 // GetHash returns the hash corresponding to n 44 GetHash GetHashFunc 45 46 // Message information 47 Origin common.Address // Provides information for ORIGIN 48 GasPrice *big.Int // Provides information for GASPRICE 49 50 // Block information 51 Coinbase common.Address // Provides information for COINBASE 52 GasLimit *big.Int // Provides information for GASLIMIT 53 BlockNumber *big.Int // Provides information for NUMBER 54 Time *big.Int // Provides information for TIME 55 Difficulty *big.Int // Provides information for DIFFICULTY 56 } 57 58 // EVM provides information about external sources for the EVM 59 // 60 // The EVM should never be reused and is not thread safe. 61 type EVM struct { 62 // Context provides auxiliary blockchain related information 63 Context 64 // StateDB gives access to the underlying state 65 StateDB StateDB 66 // Depth is the current call stack 67 depth int 68 69 // chainConfig contains information about the current chain 70 chainConfig *params.ChainConfig 71 // virtual machine configuration options used to initialise the 72 // evm. 73 vmConfig Config 74 // global (to this context) ethereum virtual machine 75 // used throughout the execution of the tx. 76 interpreter *Interpreter 77 // abort is used to abort the EVM calling operations 78 // NOTE: must be set atomically 79 abort int32 80 } 81 82 // NewEVM retutrns a new EVM evmironment. 83 func NewEVM(ctx Context, statedb StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM { 84 evm := &EVM{ 85 Context: ctx, 86 StateDB: statedb, 87 vmConfig: vmConfig, 88 chainConfig: chainConfig, 89 } 90 91 evm.interpreter = NewInterpreter(evm, vmConfig) 92 return evm 93 } 94 95 // Cancel cancels any running EVM operation. This may be called concurrently and it's safe to be 96 // called multiple times. 97 func (evm *EVM) Cancel() { 98 atomic.StoreInt32(&evm.abort, 1) 99 } 100 101 // Call executes the contract associated with the addr with the given input as parameters. It also handles any 102 // necessary value transfer required and takes the necessary steps to create accounts and reverses the state in 103 // case of an execution error or failed value transfer. 104 func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { 105 if evm.vmConfig.NoRecursion && evm.depth > 0 { 106 return nil, gas, nil 107 } 108 109 // Depth check execution. Fail if we're trying to execute above the 110 // limit. 111 if evm.depth > int(params.CallCreateDepth) { 112 return nil, gas, ErrDepth 113 } 114 if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { 115 return nil, gas, ErrInsufficientBalance 116 } 117 118 var ( 119 to = AccountRef(addr) 120 snapshot = evm.StateDB.Snapshot() 121 ) 122 if !evm.StateDB.Exist(addr) { 123 if PrecompiledContracts[addr] == nil && evm.ChainConfig().IsEIP158(evm.BlockNumber) && value.Sign() == 0 { 124 return nil, gas, nil 125 } 126 127 evm.StateDB.CreateAccount(addr) 128 } 129 evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value) 130 131 // initialise a new contract and set the code that is to be used by the 132 // E The contract is a scoped evmironment for this execution context 133 // only. 134 contract := NewContract(caller, to, value, gas) 135 contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr)) 136 137 ret, err = evm.interpreter.Run(contract, input) 138 // When an error was returned by the EVM or when setting the creation code 139 // above we revert to the snapshot and consume any gas remaining. Additionally 140 // when we're in homestead this also counts for code storage gas errors. 141 if err != nil { 142 contract.UseGas(contract.Gas) 143 144 evm.StateDB.RevertToSnapshot(snapshot) 145 } 146 return ret, contract.Gas, err 147 } 148 149 // CallCode executes the contract associated with the addr with the given input as parameters. It also handles any 150 // necessary value transfer required and takes the necessary steps to create accounts and reverses the state in 151 // case of an execution error or failed value transfer. 152 // 153 // CallCode differs from Call in the sense that it executes the given address' code with the caller as context. 154 func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { 155 if evm.vmConfig.NoRecursion && evm.depth > 0 { 156 return nil, gas, nil 157 } 158 159 // Depth check execution. Fail if we're trying to execute above the 160 // limit. 161 if evm.depth > int(params.CallCreateDepth) { 162 return nil, gas, ErrDepth 163 } 164 if !evm.CanTransfer(evm.StateDB, caller.Address(), value) { 165 return nil, gas, ErrInsufficientBalance 166 } 167 168 var ( 169 snapshot = evm.StateDB.Snapshot() 170 to = AccountRef(caller.Address()) 171 ) 172 // initialise a new contract and set the code that is to be used by the 173 // E The contract is a scoped evmironment for this execution context 174 // only. 175 contract := NewContract(caller, to, value, gas) 176 contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr)) 177 178 ret, err = evm.interpreter.Run(contract, input) 179 if err != nil { 180 contract.UseGas(contract.Gas) 181 182 evm.StateDB.RevertToSnapshot(snapshot) 183 } 184 185 return ret, contract.Gas, err 186 } 187 188 // DelegateCall executes the contract associated with the addr with the given input as parameters. 189 // It reverses the state in case of an execution error. 190 // 191 // DelegateCall differs from CallCode in the sense that it executes the given address' code with the caller as context 192 // and the caller is set to the caller of the caller. 193 func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) { 194 if evm.vmConfig.NoRecursion && evm.depth > 0 { 195 return nil, gas, nil 196 } 197 198 // Depth check execution. Fail if we're trying to execute above the 199 // limit. 200 if evm.depth > int(params.CallCreateDepth) { 201 return nil, gas, ErrDepth 202 } 203 204 var ( 205 snapshot = evm.StateDB.Snapshot() 206 to = AccountRef(caller.Address()) 207 ) 208 209 // Iinitialise a new contract and make initialise the delegate values 210 contract := NewContract(caller, to, nil, gas).AsDelegate() 211 contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr)) 212 213 ret, err = evm.interpreter.Run(contract, input) 214 if err != nil { 215 contract.UseGas(contract.Gas) 216 217 evm.StateDB.RevertToSnapshot(snapshot) 218 } 219 220 return ret, contract.Gas, err 221 } 222 223 // Create creates a new contract using code as deployment code. 224 func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) { 225 if evm.vmConfig.NoRecursion && evm.depth > 0 { 226 return nil, common.Address{}, gas, nil 227 } 228 229 // Depth check execution. Fail if we're trying to execute above the 230 // limit. 231 if evm.depth > int(params.CallCreateDepth) { 232 return nil, common.Address{}, gas, ErrDepth 233 } 234 if !evm.CanTransfer(evm.StateDB, caller.Address(), value) { 235 return nil, common.Address{}, gas, ErrInsufficientBalance 236 } 237 238 // Create a new account on the state 239 nonce := evm.StateDB.GetNonce(caller.Address()) 240 evm.StateDB.SetNonce(caller.Address(), nonce+1) 241 242 snapshot := evm.StateDB.Snapshot() 243 contractAddr = crypto.CreateAddress(caller.Address(), nonce) 244 evm.StateDB.CreateAccount(contractAddr) 245 if evm.ChainConfig().IsEIP158(evm.BlockNumber) { 246 evm.StateDB.SetNonce(contractAddr, 1) 247 } 248 evm.Transfer(evm.StateDB, caller.Address(), contractAddr, value) 249 250 // initialise a new contract and set the code that is to be used by the 251 // E The contract is a scoped evmironment for this execution context 252 // only. 253 contract := NewContract(caller, AccountRef(contractAddr), value, gas) 254 contract.SetCallCode(&contractAddr, crypto.Keccak256Hash(code), code) 255 256 ret, err = evm.interpreter.Run(contract, nil) 257 258 // check whether the max code size has been exceeded 259 maxCodeSizeExceeded := len(ret) > params.MaxCodeSize 260 // if the contract creation ran successfully and no errors were returned 261 // calculate the gas required to store the code. If the code could not 262 // be stored due to not enough gas set an error and let it be handled 263 // by the error checking condition below. 264 if err == nil && !maxCodeSizeExceeded { 265 createDataGas := uint64(len(ret)) * params.CreateDataGas 266 if contract.UseGas(createDataGas) { 267 evm.StateDB.SetCode(contractAddr, ret) 268 } else { 269 err = ErrCodeStoreOutOfGas 270 } 271 } 272 273 // When an error was returned by the EVM or when setting the creation code 274 // above we revert to the snapshot and consume any gas remaining. Additionally 275 // when we're in homestead this also counts for code storage gas errors. 276 if maxCodeSizeExceeded || 277 (err != nil && (evm.ChainConfig().IsHomestead(evm.BlockNumber) || err != ErrCodeStoreOutOfGas)) { 278 evm.StateDB.RevertToSnapshot(snapshot) 279 280 // Nothing should be returned when an error is thrown. 281 return nil, contractAddr, 0, err 282 } 283 // If the vm returned with an error the return value should be set to nil. 284 // This isn't consensus critical but merely to for behaviour reasons such as 285 // tests, RPC calls, etc. 286 if err != nil { 287 ret = nil 288 } 289 290 return ret, contractAddr, contract.Gas, err 291 } 292 293 // ChainConfig returns the evmironment's chain configuration 294 func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig } 295 296 // Interpreter returns the EVM interpreter 297 func (evm *EVM) Interpreter() *Interpreter { return evm.interpreter }