environment.go 11 KB

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