runner.go 9.6 KB

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