runner.go 9.4 KB

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