main.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU 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. // go-ethereum 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 General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. // evm executes EVM code snippets.
  17. package main
  18. import (
  19. "fmt"
  20. "math/big"
  21. "os"
  22. "runtime"
  23. "time"
  24. "github.com/ethereum/go-ethereum/cmd/utils"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/core/state"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/core/vm"
  30. "github.com/ethereum/go-ethereum/crypto"
  31. "github.com/ethereum/go-ethereum/ethdb"
  32. "github.com/ethereum/go-ethereum/logger/glog"
  33. "github.com/ethereum/go-ethereum/params"
  34. "gopkg.in/urfave/cli.v1"
  35. )
  36. var gitCommit = "" // Git SHA1 commit hash of the release (set via linker flags)
  37. var (
  38. app = utils.NewApp(gitCommit, "the evm command line interface")
  39. DebugFlag = cli.BoolFlag{
  40. Name: "debug",
  41. Usage: "output full trace logs",
  42. }
  43. ForceJitFlag = cli.BoolFlag{
  44. Name: "forcejit",
  45. Usage: "forces jit compilation",
  46. }
  47. DisableJitFlag = cli.BoolFlag{
  48. Name: "nojit",
  49. Usage: "disabled jit compilation",
  50. }
  51. CodeFlag = cli.StringFlag{
  52. Name: "code",
  53. Usage: "EVM code",
  54. }
  55. GasFlag = cli.StringFlag{
  56. Name: "gas",
  57. Usage: "gas limit for the evm",
  58. Value: "10000000000",
  59. }
  60. PriceFlag = cli.StringFlag{
  61. Name: "price",
  62. Usage: "price set for the evm",
  63. Value: "0",
  64. }
  65. ValueFlag = cli.StringFlag{
  66. Name: "value",
  67. Usage: "value set for the evm",
  68. Value: "0",
  69. }
  70. DumpFlag = cli.BoolFlag{
  71. Name: "dump",
  72. Usage: "dumps the state after the run",
  73. }
  74. InputFlag = cli.StringFlag{
  75. Name: "input",
  76. Usage: "input for the EVM",
  77. }
  78. SysStatFlag = cli.BoolFlag{
  79. Name: "sysstat",
  80. Usage: "display system stats",
  81. }
  82. VerbosityFlag = cli.IntFlag{
  83. Name: "verbosity",
  84. Usage: "sets the verbosity level",
  85. }
  86. CreateFlag = cli.BoolFlag{
  87. Name: "create",
  88. Usage: "indicates the action should be create rather than call",
  89. }
  90. )
  91. func init() {
  92. app.Flags = []cli.Flag{
  93. CreateFlag,
  94. DebugFlag,
  95. VerbosityFlag,
  96. ForceJitFlag,
  97. DisableJitFlag,
  98. SysStatFlag,
  99. CodeFlag,
  100. GasFlag,
  101. PriceFlag,
  102. ValueFlag,
  103. DumpFlag,
  104. InputFlag,
  105. }
  106. app.Action = run
  107. }
  108. func run(ctx *cli.Context) error {
  109. glog.SetToStderr(true)
  110. glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
  111. db, _ := ethdb.NewMemDatabase()
  112. statedb, _ := state.New(common.Hash{}, db)
  113. sender := statedb.CreateAccount(common.StringToAddress("sender"))
  114. logger := vm.NewStructLogger(nil)
  115. vmenv := NewEnv(statedb, common.StringToAddress("evmuser"), common.Big(ctx.GlobalString(ValueFlag.Name)), vm.Config{
  116. Debug: ctx.GlobalBool(DebugFlag.Name),
  117. ForceJit: ctx.GlobalBool(ForceJitFlag.Name),
  118. EnableJit: !ctx.GlobalBool(DisableJitFlag.Name),
  119. Tracer: logger,
  120. })
  121. tstart := time.Now()
  122. var (
  123. ret []byte
  124. err error
  125. )
  126. if ctx.GlobalBool(CreateFlag.Name) {
  127. input := append(common.Hex2Bytes(ctx.GlobalString(CodeFlag.Name)), common.Hex2Bytes(ctx.GlobalString(InputFlag.Name))...)
  128. ret, _, err = vmenv.Create(
  129. sender,
  130. input,
  131. common.Big(ctx.GlobalString(GasFlag.Name)),
  132. common.Big(ctx.GlobalString(PriceFlag.Name)),
  133. common.Big(ctx.GlobalString(ValueFlag.Name)),
  134. )
  135. } else {
  136. receiver := statedb.CreateAccount(common.StringToAddress("receiver"))
  137. code := common.Hex2Bytes(ctx.GlobalString(CodeFlag.Name))
  138. receiver.SetCode(crypto.Keccak256Hash(code), code)
  139. ret, err = vmenv.Call(
  140. sender,
  141. receiver.Address(),
  142. common.Hex2Bytes(ctx.GlobalString(InputFlag.Name)),
  143. common.Big(ctx.GlobalString(GasFlag.Name)),
  144. common.Big(ctx.GlobalString(PriceFlag.Name)),
  145. common.Big(ctx.GlobalString(ValueFlag.Name)),
  146. )
  147. }
  148. vmdone := time.Since(tstart)
  149. if ctx.GlobalBool(DumpFlag.Name) {
  150. statedb.Commit()
  151. fmt.Println(string(statedb.Dump()))
  152. }
  153. vm.StdErrFormat(logger.StructLogs())
  154. if ctx.GlobalBool(SysStatFlag.Name) {
  155. var mem runtime.MemStats
  156. runtime.ReadMemStats(&mem)
  157. fmt.Printf("vm took %v\n", vmdone)
  158. fmt.Printf(`alloc: %d
  159. tot alloc: %d
  160. no. malloc: %d
  161. heap alloc: %d
  162. heap objs: %d
  163. num gc: %d
  164. `, mem.Alloc, mem.TotalAlloc, mem.Mallocs, mem.HeapAlloc, mem.HeapObjects, mem.NumGC)
  165. }
  166. fmt.Printf("OUT: 0x%x", ret)
  167. if err != nil {
  168. fmt.Printf(" error: %v", err)
  169. }
  170. fmt.Println()
  171. return nil
  172. }
  173. func main() {
  174. if err := app.Run(os.Args); err != nil {
  175. fmt.Fprintln(os.Stderr, err)
  176. os.Exit(1)
  177. }
  178. }
  179. type VMEnv struct {
  180. state *state.StateDB
  181. block *types.Block
  182. transactor *common.Address
  183. value *big.Int
  184. depth int
  185. Gas *big.Int
  186. time *big.Int
  187. logs []vm.StructLog
  188. evm *vm.EVM
  189. }
  190. func NewEnv(state *state.StateDB, transactor common.Address, value *big.Int, cfg vm.Config) *VMEnv {
  191. env := &VMEnv{
  192. state: state,
  193. transactor: &transactor,
  194. value: value,
  195. time: big.NewInt(time.Now().Unix()),
  196. }
  197. env.evm = vm.New(env, cfg)
  198. return env
  199. }
  200. // ruleSet implements vm.RuleSet and will always default to the homestead rule set.
  201. type ruleSet struct{}
  202. func (ruleSet) IsHomestead(*big.Int) bool { return true }
  203. func (ruleSet) GasTable(*big.Int) params.GasTable {
  204. return params.GasTableHomesteadGasRepriceFork
  205. }
  206. func (self *VMEnv) RuleSet() vm.RuleSet { return ruleSet{} }
  207. func (self *VMEnv) Vm() vm.Vm { return self.evm }
  208. func (self *VMEnv) Db() vm.Database { return self.state }
  209. func (self *VMEnv) SnapshotDatabase() int { return self.state.Snapshot() }
  210. func (self *VMEnv) RevertToSnapshot(snap int) { self.state.RevertToSnapshot(snap) }
  211. func (self *VMEnv) Origin() common.Address { return *self.transactor }
  212. func (self *VMEnv) BlockNumber() *big.Int { return common.Big0 }
  213. func (self *VMEnv) Coinbase() common.Address { return *self.transactor }
  214. func (self *VMEnv) Time() *big.Int { return self.time }
  215. func (self *VMEnv) Difficulty() *big.Int { return common.Big1 }
  216. func (self *VMEnv) BlockHash() []byte { return make([]byte, 32) }
  217. func (self *VMEnv) Value() *big.Int { return self.value }
  218. func (self *VMEnv) GasLimit() *big.Int { return big.NewInt(1000000000) }
  219. func (self *VMEnv) VmType() vm.Type { return vm.StdVmTy }
  220. func (self *VMEnv) Depth() int { return 0 }
  221. func (self *VMEnv) SetDepth(i int) { self.depth = i }
  222. func (self *VMEnv) GetHash(n uint64) common.Hash {
  223. if self.block.Number().Cmp(big.NewInt(int64(n))) == 0 {
  224. return self.block.Hash()
  225. }
  226. return common.Hash{}
  227. }
  228. func (self *VMEnv) AddLog(log *vm.Log) {
  229. self.state.AddLog(log)
  230. }
  231. func (self *VMEnv) CanTransfer(from common.Address, balance *big.Int) bool {
  232. return self.state.GetBalance(from).Cmp(balance) >= 0
  233. }
  234. func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) {
  235. core.Transfer(from, to, amount)
  236. }
  237. func (self *VMEnv) Call(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
  238. self.Gas = gas
  239. return core.Call(self, caller, addr, data, gas, price, value)
  240. }
  241. func (self *VMEnv) CallCode(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
  242. return core.CallCode(self, caller, addr, data, gas, price, value)
  243. }
  244. func (self *VMEnv) DelegateCall(caller vm.ContractRef, addr common.Address, data []byte, gas, price *big.Int) ([]byte, error) {
  245. return core.DelegateCall(self, caller, addr, data, gas, price)
  246. }
  247. func (self *VMEnv) Create(caller vm.ContractRef, data []byte, gas, price, value *big.Int) ([]byte, common.Address, error) {
  248. return core.Create(self, caller, data, gas, price, value)
  249. }