environment.go 11 KB

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