runner.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. var (
  69. tracer vm.Tracer
  70. debugLogger *vm.StructLogger
  71. statedb *state.StateDB
  72. chainConfig *params.ChainConfig
  73. sender = common.StringToAddress("sender")
  74. )
  75. if ctx.GlobalBool(MachineFlag.Name) {
  76. tracer = NewJSONLogger(os.Stdout)
  77. } else if ctx.GlobalBool(DebugFlag.Name) {
  78. debugLogger = vm.NewStructLogger(nil)
  79. tracer = debugLogger
  80. } else {
  81. debugLogger = vm.NewStructLogger(nil)
  82. }
  83. if ctx.GlobalString(GenesisFlag.Name) != "" {
  84. gen := readGenesis(ctx.GlobalString(GenesisFlag.Name))
  85. _, statedb = gen.ToBlock()
  86. chainConfig = gen.Config
  87. } else {
  88. var db, _ = ethdb.NewMemDatabase()
  89. statedb, _ = state.New(common.Hash{}, db)
  90. }
  91. if ctx.GlobalString(SenderFlag.Name) != "" {
  92. sender = common.HexToAddress(ctx.GlobalString(SenderFlag.Name))
  93. }
  94. statedb.CreateAccount(sender)
  95. var (
  96. code []byte
  97. ret []byte
  98. err error
  99. )
  100. if fn := ctx.Args().First(); len(fn) > 0 {
  101. src, err := ioutil.ReadFile(fn)
  102. if err != nil {
  103. return err
  104. }
  105. bin, err := compiler.Compile(fn, src, false)
  106. if err != nil {
  107. return err
  108. }
  109. code = common.Hex2Bytes(bin)
  110. } else if ctx.GlobalString(CodeFlag.Name) != "" {
  111. code = common.Hex2Bytes(ctx.GlobalString(CodeFlag.Name))
  112. } else {
  113. var hexcode []byte
  114. if ctx.GlobalString(CodeFileFlag.Name) != "" {
  115. var err error
  116. hexcode, err = ioutil.ReadFile(ctx.GlobalString(CodeFileFlag.Name))
  117. if err != nil {
  118. fmt.Printf("Could not load code from file: %v\n", err)
  119. os.Exit(1)
  120. }
  121. } else {
  122. var err error
  123. hexcode, err = ioutil.ReadAll(os.Stdin)
  124. if err != nil {
  125. fmt.Printf("Could not load code from stdin: %v\n", err)
  126. os.Exit(1)
  127. }
  128. }
  129. code = common.Hex2Bytes(string(bytes.TrimRight(hexcode, "\n")))
  130. }
  131. initialGas := ctx.GlobalUint64(GasFlag.Name)
  132. runtimeConfig := runtime.Config{
  133. Origin: sender,
  134. State: statedb,
  135. GasLimit: initialGas,
  136. GasPrice: utils.GlobalBig(ctx, PriceFlag.Name),
  137. Value: utils.GlobalBig(ctx, ValueFlag.Name),
  138. EVMConfig: vm.Config{
  139. Tracer: tracer,
  140. Debug: ctx.GlobalBool(DebugFlag.Name) || ctx.GlobalBool(MachineFlag.Name),
  141. DisableGasMetering: ctx.GlobalBool(DisableGasMeteringFlag.Name),
  142. },
  143. }
  144. if cpuProfilePath := ctx.GlobalString(CPUProfileFlag.Name); cpuProfilePath != "" {
  145. f, err := os.Create(cpuProfilePath)
  146. if err != nil {
  147. fmt.Println("could not create CPU profile: ", err)
  148. os.Exit(1)
  149. }
  150. if err := pprof.StartCPUProfile(f); err != nil {
  151. fmt.Println("could not start CPU profile: ", err)
  152. os.Exit(1)
  153. }
  154. defer pprof.StopCPUProfile()
  155. }
  156. if chainConfig != nil {
  157. runtimeConfig.ChainConfig = chainConfig
  158. }
  159. tstart := time.Now()
  160. var leftOverGas uint64
  161. if ctx.GlobalBool(CreateFlag.Name) {
  162. input := append(code, common.Hex2Bytes(ctx.GlobalString(InputFlag.Name))...)
  163. ret, _, leftOverGas, err = runtime.Create(input, &runtimeConfig)
  164. } else {
  165. receiver := common.StringToAddress("receiver")
  166. statedb.SetCode(receiver, code)
  167. ret, leftOverGas, err = runtime.Call(receiver, common.Hex2Bytes(ctx.GlobalString(InputFlag.Name)), &runtimeConfig)
  168. }
  169. execTime := time.Since(tstart)
  170. if ctx.GlobalBool(DumpFlag.Name) {
  171. statedb.Commit(true)
  172. fmt.Println(string(statedb.Dump()))
  173. }
  174. if memProfilePath := ctx.GlobalString(MemProfileFlag.Name); memProfilePath != "" {
  175. f, err := os.Create(memProfilePath)
  176. if err != nil {
  177. fmt.Println("could not create memory profile: ", err)
  178. os.Exit(1)
  179. }
  180. if err := pprof.WriteHeapProfile(f); err != nil {
  181. fmt.Println("could not write memory profile: ", err)
  182. os.Exit(1)
  183. }
  184. f.Close()
  185. }
  186. if ctx.GlobalBool(DebugFlag.Name) {
  187. if debugLogger != nil {
  188. fmt.Fprintln(os.Stderr, "#### TRACE ####")
  189. vm.WriteTrace(os.Stderr, debugLogger.StructLogs())
  190. }
  191. fmt.Fprintln(os.Stderr, "#### LOGS ####")
  192. vm.WriteLogs(os.Stderr, statedb.Logs())
  193. }
  194. if ctx.GlobalBool(StatDumpFlag.Name) {
  195. var mem goruntime.MemStats
  196. goruntime.ReadMemStats(&mem)
  197. fmt.Fprintf(os.Stderr, `evm execution time: %v
  198. heap objects: %d
  199. allocations: %d
  200. total allocations: %d
  201. GC calls: %d
  202. Gas used: %d
  203. `, execTime, mem.HeapObjects, mem.Alloc, mem.TotalAlloc, mem.NumGC, initialGas-leftOverGas)
  204. }
  205. if tracer != nil {
  206. tracer.CaptureEnd(ret, initialGas-leftOverGas, execTime)
  207. } else {
  208. fmt.Printf("0x%x\n", ret)
  209. }
  210. if err != nil {
  211. fmt.Printf(" error: %v\n", err)
  212. }
  213. return nil
  214. }