evm.go 12 KB

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