runner.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. // Copyright 2017 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. package main
  17. import (
  18. "bytes"
  19. "encoding/json"
  20. "fmt"
  21. "io/ioutil"
  22. "os"
  23. "runtime/pprof"
  24. "time"
  25. goruntime "runtime"
  26. "github.com/ethereum/go-ethereum/cmd/evm/internal/compiler"
  27. "github.com/ethereum/go-ethereum/cmd/utils"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/core"
  30. "github.com/ethereum/go-ethereum/core/state"
  31. "github.com/ethereum/go-ethereum/core/vm"
  32. "github.com/ethereum/go-ethereum/core/vm/runtime"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/log"
  35. "github.com/ethereum/go-ethereum/params"
  36. cli "gopkg.in/urfave/cli.v1"
  37. )
  38. var runCommand = cli.Command{
  39. Action: runCmd,
  40. Name: "run",
  41. Usage: "run arbitrary evm binary",
  42. ArgsUsage: "<code>",
  43. Description: `The run command runs arbitrary EVM code.`,
  44. }
  45. // readGenesis will read the given JSON format genesis file and return
  46. // the initialized Genesis structure
  47. func readGenesis(genesisPath string) *core.Genesis {
  48. // Make sure we have a valid genesis JSON
  49. //genesisPath := ctx.Args().First()
  50. if len(genesisPath) == 0 {
  51. utils.Fatalf("Must supply path to genesis JSON file")
  52. }
  53. file, err := os.Open(genesisPath)
  54. if err != nil {
  55. utils.Fatalf("Failed to read genesis file: %v", err)
  56. }
  57. defer file.Close()
  58. genesis := new(core.Genesis)
  59. if err := json.NewDecoder(file).Decode(genesis); err != nil {
  60. utils.Fatalf("invalid genesis file: %v", err)
  61. }
  62. return genesis
  63. }
  64. func runCmd(ctx *cli.Context) error {
  65. glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
  66. glogger.Verbosity(log.Lvl(ctx.GlobalInt(VerbosityFlag.Name)))
  67. log.Root().SetHandler(glogger)
  68. logconfig := &vm.LogConfig{
  69. DisableMemory: ctx.GlobalBool(DisableMemoryFlag.Name),
  70. DisableStack: ctx.GlobalBool(DisableStackFlag.Name),
  71. Debug: ctx.GlobalBool(DebugFlag.Name),
  72. }
  73. var (
  74. tracer vm.Tracer
  75. debugLogger *vm.StructLogger
  76. statedb *state.StateDB
  77. chainConfig *params.ChainConfig
  78. sender = common.StringToAddress("sender")
  79. receiver = common.StringToAddress("receiver")
  80. )
  81. if ctx.GlobalBool(MachineFlag.Name) {
  82. tracer = NewJSONLogger(logconfig, os.Stdout)
  83. } else if ctx.GlobalBool(DebugFlag.Name) {
  84. debugLogger = vm.NewStructLogger(logconfig)
  85. tracer = debugLogger
  86. } else {
  87. debugLogger = vm.NewStructLogger(logconfig)
  88. }
  89. if ctx.GlobalString(GenesisFlag.Name) != "" {
  90. gen := readGenesis(ctx.GlobalString(GenesisFlag.Name))
  91. db, _ := ethdb.NewMemDatabase()
  92. genesis := gen.ToBlock(db)
  93. statedb, _ = state.New(genesis.Root(), state.NewDatabase(db))
  94. chainConfig = gen.Config
  95. } else {
  96. db, _ := ethdb.NewMemDatabase()
  97. statedb, _ = state.New(common.Hash{}, state.NewDatabase(db))
  98. }
  99. if ctx.GlobalString(SenderFlag.Name) != "" {
  100. sender = common.HexToAddress(ctx.GlobalString(SenderFlag.Name))
  101. }
  102. statedb.CreateAccount(sender)
  103. if ctx.GlobalString(ReceiverFlag.Name) != "" {
  104. receiver = common.HexToAddress(ctx.GlobalString(ReceiverFlag.Name))
  105. }
  106. var (
  107. code []byte
  108. ret []byte
  109. err error
  110. )
  111. // The '--code' or '--codefile' flag overrides code in state
  112. if ctx.GlobalString(CodeFileFlag.Name) != "" {
  113. var hexcode []byte
  114. var err error
  115. // If - is specified, it means that code comes from stdin
  116. if ctx.GlobalString(CodeFileFlag.Name) == "-" {
  117. //Try reading from stdin
  118. if hexcode, err = ioutil.ReadAll(os.Stdin); err != nil {
  119. fmt.Printf("Could not load code from stdin: %v\n", err)
  120. os.Exit(1)
  121. }
  122. } else {
  123. // Codefile with hex assembly
  124. if hexcode, err = ioutil.ReadFile(ctx.GlobalString(CodeFileFlag.Name)); err != nil {
  125. fmt.Printf("Could not load code from file: %v\n", err)
  126. os.Exit(1)
  127. }
  128. }
  129. code = common.Hex2Bytes(string(bytes.TrimRight(hexcode, "\n")))
  130. } else if ctx.GlobalString(CodeFlag.Name) != "" {
  131. code = common.Hex2Bytes(ctx.GlobalString(CodeFlag.Name))
  132. } else if fn := ctx.Args().First(); len(fn) > 0 {
  133. // EASM-file to compile
  134. src, err := ioutil.ReadFile(fn)
  135. if err != nil {
  136. return err
  137. }
  138. bin, err := compiler.Compile(fn, src, false)
  139. if err != nil {
  140. return err
  141. }
  142. code = common.Hex2Bytes(bin)
  143. }
  144. initialGas := ctx.GlobalUint64(GasFlag.Name)
  145. runtimeConfig := runtime.Config{
  146. Origin: sender,
  147. State: statedb,
  148. GasLimit: initialGas,
  149. GasPrice: utils.GlobalBig(ctx, PriceFlag.Name),
  150. Value: utils.GlobalBig(ctx, ValueFlag.Name),
  151. EVMConfig: vm.Config{
  152. Tracer: tracer,
  153. Debug: ctx.GlobalBool(DebugFlag.Name) || ctx.GlobalBool(MachineFlag.Name),
  154. },
  155. }
  156. if cpuProfilePath := ctx.GlobalString(CPUProfileFlag.Name); cpuProfilePath != "" {
  157. f, err := os.Create(cpuProfilePath)
  158. if err != nil {
  159. fmt.Println("could not create CPU profile: ", err)
  160. os.Exit(1)
  161. }
  162. if err := pprof.StartCPUProfile(f); err != nil {
  163. fmt.Println("could not start CPU profile: ", err)
  164. os.Exit(1)
  165. }
  166. defer pprof.StopCPUProfile()
  167. }
  168. if chainConfig != nil {
  169. runtimeConfig.ChainConfig = chainConfig
  170. }
  171. tstart := time.Now()
  172. var leftOverGas uint64
  173. if ctx.GlobalBool(CreateFlag.Name) {
  174. input := append(code, common.Hex2Bytes(ctx.GlobalString(InputFlag.Name))...)
  175. ret, _, leftOverGas, err = runtime.Create(input, &runtimeConfig)
  176. } else {
  177. if len(code) > 0 {
  178. statedb.SetCode(receiver, code)
  179. }
  180. ret, leftOverGas, err = runtime.Call(receiver, common.Hex2Bytes(ctx.GlobalString(InputFlag.Name)), &runtimeConfig)
  181. }
  182. execTime := time.Since(tstart)
  183. if ctx.GlobalBool(DumpFlag.Name) {
  184. statedb.IntermediateRoot(true)
  185. fmt.Println(string(statedb.Dump()))
  186. }
  187. if memProfilePath := ctx.GlobalString(MemProfileFlag.Name); memProfilePath != "" {
  188. f, err := os.Create(memProfilePath)
  189. if err != nil {
  190. fmt.Println("could not create memory profile: ", err)
  191. os.Exit(1)
  192. }
  193. if err := pprof.WriteHeapProfile(f); err != nil {
  194. fmt.Println("could not write memory profile: ", err)
  195. os.Exit(1)
  196. }
  197. f.Close()
  198. }
  199. if ctx.GlobalBool(DebugFlag.Name) {
  200. if debugLogger != nil {
  201. fmt.Fprintln(os.Stderr, "#### TRACE ####")
  202. vm.WriteTrace(os.Stderr, debugLogger.StructLogs())
  203. }
  204. fmt.Fprintln(os.Stderr, "#### LOGS ####")
  205. vm.WriteLogs(os.Stderr, statedb.Logs())
  206. }
  207. if ctx.GlobalBool(StatDumpFlag.Name) {
  208. var mem goruntime.MemStats
  209. goruntime.ReadMemStats(&mem)
  210. fmt.Fprintf(os.Stderr, `evm execution time: %v
  211. heap objects: %d
  212. allocations: %d
  213. total allocations: %d
  214. GC calls: %d
  215. Gas used: %d
  216. `, execTime, mem.HeapObjects, mem.Alloc, mem.TotalAlloc, mem.NumGC, initialGas-leftOverGas)
  217. }
  218. if tracer == nil {
  219. fmt.Printf("0x%x\n", ret)
  220. if err != nil {
  221. fmt.Printf(" error: %v\n", err)
  222. }
  223. }
  224. return nil
  225. }