runner.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. "math/big"
  23. "os"
  24. goruntime "runtime"
  25. "runtime/pprof"
  26. "testing"
  27. "time"
  28. "github.com/ethereum/go-ethereum/cmd/evm/internal/compiler"
  29. "github.com/ethereum/go-ethereum/cmd/utils"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/core"
  32. "github.com/ethereum/go-ethereum/core/rawdb"
  33. "github.com/ethereum/go-ethereum/core/state"
  34. "github.com/ethereum/go-ethereum/core/vm"
  35. "github.com/ethereum/go-ethereum/core/vm/runtime"
  36. "github.com/ethereum/go-ethereum/log"
  37. "github.com/ethereum/go-ethereum/params"
  38. cli "gopkg.in/urfave/cli.v1"
  39. )
  40. var runCommand = cli.Command{
  41. Action: runCmd,
  42. Name: "run",
  43. Usage: "run arbitrary evm binary",
  44. ArgsUsage: "<code>",
  45. Description: `The run command runs arbitrary EVM code.`,
  46. }
  47. // readGenesis will read the given JSON format genesis file and return
  48. // the initialized Genesis structure
  49. func readGenesis(genesisPath string) *core.Genesis {
  50. // Make sure we have a valid genesis JSON
  51. //genesisPath := ctx.Args().First()
  52. if len(genesisPath) == 0 {
  53. utils.Fatalf("Must supply path to genesis JSON file")
  54. }
  55. file, err := os.Open(genesisPath)
  56. if err != nil {
  57. utils.Fatalf("Failed to read genesis file: %v", err)
  58. }
  59. defer file.Close()
  60. genesis := new(core.Genesis)
  61. if err := json.NewDecoder(file).Decode(genesis); err != nil {
  62. utils.Fatalf("invalid genesis file: %v", err)
  63. }
  64. return genesis
  65. }
  66. func timedExec(bench bool, execFunc func() ([]byte, uint64, error)) ([]byte, uint64, time.Duration, error) {
  67. var (
  68. output []byte
  69. gasLeft uint64
  70. execTime time.Duration
  71. err error
  72. )
  73. if bench {
  74. result := testing.Benchmark(func(b *testing.B) {
  75. for i := 0; i < b.N; i++ {
  76. output, gasLeft, err = execFunc()
  77. }
  78. })
  79. // Get the average execution time from the benchmarking result.
  80. // There are other useful stats here that could be reported.
  81. execTime = time.Duration(result.NsPerOp())
  82. } else {
  83. startTime := time.Now()
  84. output, gasLeft, err = execFunc()
  85. execTime = time.Since(startTime)
  86. }
  87. return output, gasLeft, execTime, err
  88. }
  89. func runCmd(ctx *cli.Context) error {
  90. glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
  91. glogger.Verbosity(log.Lvl(ctx.GlobalInt(VerbosityFlag.Name)))
  92. log.Root().SetHandler(glogger)
  93. logconfig := &vm.LogConfig{
  94. DisableMemory: ctx.GlobalBool(DisableMemoryFlag.Name),
  95. DisableStack: ctx.GlobalBool(DisableStackFlag.Name),
  96. Debug: ctx.GlobalBool(DebugFlag.Name),
  97. }
  98. var (
  99. tracer vm.Tracer
  100. debugLogger *vm.StructLogger
  101. statedb *state.StateDB
  102. chainConfig *params.ChainConfig
  103. sender = common.BytesToAddress([]byte("sender"))
  104. receiver = common.BytesToAddress([]byte("receiver"))
  105. genesisConfig *core.Genesis
  106. )
  107. if ctx.GlobalBool(MachineFlag.Name) {
  108. tracer = vm.NewJSONLogger(logconfig, os.Stdout)
  109. } else if ctx.GlobalBool(DebugFlag.Name) {
  110. debugLogger = vm.NewStructLogger(logconfig)
  111. tracer = debugLogger
  112. } else {
  113. debugLogger = vm.NewStructLogger(logconfig)
  114. }
  115. if ctx.GlobalString(GenesisFlag.Name) != "" {
  116. gen := readGenesis(ctx.GlobalString(GenesisFlag.Name))
  117. genesisConfig = gen
  118. db := rawdb.NewMemoryDatabase()
  119. genesis := gen.ToBlock(db)
  120. statedb, _ = state.New(genesis.Root(), state.NewDatabase(db), nil)
  121. chainConfig = gen.Config
  122. } else {
  123. statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  124. genesisConfig = new(core.Genesis)
  125. }
  126. if ctx.GlobalString(SenderFlag.Name) != "" {
  127. sender = common.HexToAddress(ctx.GlobalString(SenderFlag.Name))
  128. }
  129. statedb.CreateAccount(sender)
  130. if ctx.GlobalString(ReceiverFlag.Name) != "" {
  131. receiver = common.HexToAddress(ctx.GlobalString(ReceiverFlag.Name))
  132. }
  133. var code []byte
  134. codeFileFlag := ctx.GlobalString(CodeFileFlag.Name)
  135. codeFlag := ctx.GlobalString(CodeFlag.Name)
  136. // The '--code' or '--codefile' flag overrides code in state
  137. if codeFileFlag != "" || codeFlag != "" {
  138. var hexcode []byte
  139. if codeFileFlag != "" {
  140. var err error
  141. // If - is specified, it means that code comes from stdin
  142. if codeFileFlag == "-" {
  143. //Try reading from stdin
  144. if hexcode, err = ioutil.ReadAll(os.Stdin); err != nil {
  145. fmt.Printf("Could not load code from stdin: %v\n", err)
  146. os.Exit(1)
  147. }
  148. } else {
  149. // Codefile with hex assembly
  150. if hexcode, err = ioutil.ReadFile(codeFileFlag); err != nil {
  151. fmt.Printf("Could not load code from file: %v\n", err)
  152. os.Exit(1)
  153. }
  154. }
  155. } else {
  156. hexcode = []byte(codeFlag)
  157. }
  158. hexcode = bytes.TrimSpace(hexcode)
  159. if len(hexcode)%2 != 0 {
  160. fmt.Printf("Invalid input length for hex data (%d)\n", len(hexcode))
  161. os.Exit(1)
  162. }
  163. code = common.FromHex(string(hexcode))
  164. } else if fn := ctx.Args().First(); len(fn) > 0 {
  165. // EASM-file to compile
  166. src, err := ioutil.ReadFile(fn)
  167. if err != nil {
  168. return err
  169. }
  170. bin, err := compiler.Compile(fn, src, false)
  171. if err != nil {
  172. return err
  173. }
  174. code = common.Hex2Bytes(bin)
  175. }
  176. initialGas := ctx.GlobalUint64(GasFlag.Name)
  177. if genesisConfig.GasLimit != 0 {
  178. initialGas = genesisConfig.GasLimit
  179. }
  180. runtimeConfig := runtime.Config{
  181. Origin: sender,
  182. State: statedb,
  183. GasLimit: initialGas,
  184. GasPrice: utils.GlobalBig(ctx, PriceFlag.Name),
  185. Value: utils.GlobalBig(ctx, ValueFlag.Name),
  186. Difficulty: genesisConfig.Difficulty,
  187. Time: new(big.Int).SetUint64(genesisConfig.Timestamp),
  188. Coinbase: genesisConfig.Coinbase,
  189. BlockNumber: new(big.Int).SetUint64(genesisConfig.Number),
  190. EVMConfig: vm.Config{
  191. Tracer: tracer,
  192. Debug: ctx.GlobalBool(DebugFlag.Name) || ctx.GlobalBool(MachineFlag.Name),
  193. EVMInterpreter: ctx.GlobalString(EVMInterpreterFlag.Name),
  194. },
  195. }
  196. if cpuProfilePath := ctx.GlobalString(CPUProfileFlag.Name); cpuProfilePath != "" {
  197. f, err := os.Create(cpuProfilePath)
  198. if err != nil {
  199. fmt.Println("could not create CPU profile: ", err)
  200. os.Exit(1)
  201. }
  202. if err := pprof.StartCPUProfile(f); err != nil {
  203. fmt.Println("could not start CPU profile: ", err)
  204. os.Exit(1)
  205. }
  206. defer pprof.StopCPUProfile()
  207. }
  208. if chainConfig != nil {
  209. runtimeConfig.ChainConfig = chainConfig
  210. } else {
  211. runtimeConfig.ChainConfig = params.AllEthashProtocolChanges
  212. }
  213. var hexInput []byte
  214. if inputFileFlag := ctx.GlobalString(InputFileFlag.Name); inputFileFlag != "" {
  215. var err error
  216. if hexInput, err = ioutil.ReadFile(inputFileFlag); err != nil {
  217. fmt.Printf("could not load input from file: %v\n", err)
  218. os.Exit(1)
  219. }
  220. } else {
  221. hexInput = []byte(ctx.GlobalString(InputFlag.Name))
  222. }
  223. input := common.FromHex(string(bytes.TrimSpace(hexInput)))
  224. var execFunc func() ([]byte, uint64, error)
  225. if ctx.GlobalBool(CreateFlag.Name) {
  226. input = append(code, input...)
  227. execFunc = func() ([]byte, uint64, error) {
  228. output, _, gasLeft, err := runtime.Create(input, &runtimeConfig)
  229. return output, gasLeft, err
  230. }
  231. } else {
  232. if len(code) > 0 {
  233. statedb.SetCode(receiver, code)
  234. }
  235. execFunc = func() ([]byte, uint64, error) {
  236. return runtime.Call(receiver, input, &runtimeConfig)
  237. }
  238. }
  239. output, leftOverGas, execTime, err := timedExec(ctx.GlobalBool(BenchFlag.Name), execFunc)
  240. if ctx.GlobalBool(DumpFlag.Name) {
  241. statedb.Commit(true)
  242. statedb.IntermediateRoot(true)
  243. fmt.Println(string(statedb.Dump(false, false, true)))
  244. }
  245. if memProfilePath := ctx.GlobalString(MemProfileFlag.Name); memProfilePath != "" {
  246. f, err := os.Create(memProfilePath)
  247. if err != nil {
  248. fmt.Println("could not create memory profile: ", err)
  249. os.Exit(1)
  250. }
  251. if err := pprof.WriteHeapProfile(f); err != nil {
  252. fmt.Println("could not write memory profile: ", err)
  253. os.Exit(1)
  254. }
  255. f.Close()
  256. }
  257. if ctx.GlobalBool(DebugFlag.Name) {
  258. if debugLogger != nil {
  259. fmt.Fprintln(os.Stderr, "#### TRACE ####")
  260. vm.WriteTrace(os.Stderr, debugLogger.StructLogs())
  261. }
  262. fmt.Fprintln(os.Stderr, "#### LOGS ####")
  263. vm.WriteLogs(os.Stderr, statedb.Logs())
  264. }
  265. if ctx.GlobalBool(StatDumpFlag.Name) {
  266. var mem goruntime.MemStats
  267. goruntime.ReadMemStats(&mem)
  268. fmt.Fprintf(os.Stderr, `evm execution time: %v
  269. heap objects: %d
  270. allocations: %d
  271. total allocations: %d
  272. GC calls: %d
  273. Gas used: %d
  274. `, execTime, mem.HeapObjects, mem.Alloc, mem.TotalAlloc, mem.NumGC, initialGas-leftOverGas)
  275. }
  276. if tracer == nil {
  277. fmt.Printf("0x%x\n", output)
  278. if err != nil {
  279. fmt.Printf(" error: %v\n", err)
  280. }
  281. }
  282. return nil
  283. }