runner.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. "encoding/json"
  19. "fmt"
  20. "io/ioutil"
  21. "math/big"
  22. "os"
  23. goruntime "runtime"
  24. "runtime/pprof"
  25. "time"
  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/rawdb"
  31. "github.com/ethereum/go-ethereum/core/state"
  32. "github.com/ethereum/go-ethereum/core/vm"
  33. "github.com/ethereum/go-ethereum/core/vm/runtime"
  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.BytesToAddress([]byte("sender"))
  79. receiver = common.BytesToAddress([]byte("receiver"))
  80. genesisConfig *core.Genesis
  81. )
  82. if ctx.GlobalBool(MachineFlag.Name) {
  83. tracer = vm.NewJSONLogger(logconfig, os.Stdout)
  84. } else if ctx.GlobalBool(DebugFlag.Name) {
  85. debugLogger = vm.NewStructLogger(logconfig)
  86. tracer = debugLogger
  87. } else {
  88. debugLogger = vm.NewStructLogger(logconfig)
  89. }
  90. if ctx.GlobalString(GenesisFlag.Name) != "" {
  91. gen := readGenesis(ctx.GlobalString(GenesisFlag.Name))
  92. genesisConfig = gen
  93. db := rawdb.NewMemoryDatabase()
  94. genesis := gen.ToBlock(db)
  95. statedb, _ = state.New(genesis.Root(), state.NewDatabase(db))
  96. chainConfig = gen.Config
  97. } else {
  98. statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()))
  99. genesisConfig = new(core.Genesis)
  100. }
  101. if ctx.GlobalString(SenderFlag.Name) != "" {
  102. sender = common.HexToAddress(ctx.GlobalString(SenderFlag.Name))
  103. }
  104. statedb.CreateAccount(sender)
  105. if ctx.GlobalString(ReceiverFlag.Name) != "" {
  106. receiver = common.HexToAddress(ctx.GlobalString(ReceiverFlag.Name))
  107. }
  108. var (
  109. code []byte
  110. ret []byte
  111. err error
  112. )
  113. codeFileFlag := ctx.GlobalString(CodeFileFlag.Name)
  114. codeFlag := ctx.GlobalString(CodeFlag.Name)
  115. // The '--code' or '--codefile' flag overrides code in state
  116. if codeFileFlag != "" || codeFlag != "" {
  117. var hexcode []byte
  118. if codeFileFlag != "" {
  119. var err error
  120. // If - is specified, it means that code comes from stdin
  121. if codeFileFlag == "-" {
  122. //Try reading from stdin
  123. if hexcode, err = ioutil.ReadAll(os.Stdin); err != nil {
  124. fmt.Printf("Could not load code from stdin: %v\n", err)
  125. os.Exit(1)
  126. }
  127. } else {
  128. // Codefile with hex assembly
  129. if hexcode, err = ioutil.ReadFile(codeFileFlag); err != nil {
  130. fmt.Printf("Could not load code from file: %v\n", err)
  131. os.Exit(1)
  132. }
  133. }
  134. } else {
  135. hexcode = []byte(codeFlag)
  136. }
  137. if len(hexcode)%2 != 0 {
  138. fmt.Printf("Invalid input length for hex data (%d)\n", len(hexcode))
  139. os.Exit(1)
  140. }
  141. code = common.FromHex(string(hexcode))
  142. } else if fn := ctx.Args().First(); len(fn) > 0 {
  143. // EASM-file to compile
  144. src, err := ioutil.ReadFile(fn)
  145. if err != nil {
  146. return err
  147. }
  148. bin, err := compiler.Compile(fn, src, false)
  149. if err != nil {
  150. return err
  151. }
  152. code = common.Hex2Bytes(bin)
  153. }
  154. initialGas := ctx.GlobalUint64(GasFlag.Name)
  155. if genesisConfig.GasLimit != 0 {
  156. initialGas = genesisConfig.GasLimit
  157. }
  158. runtimeConfig := runtime.Config{
  159. Origin: sender,
  160. State: statedb,
  161. GasLimit: initialGas,
  162. GasPrice: utils.GlobalBig(ctx, PriceFlag.Name),
  163. Value: utils.GlobalBig(ctx, ValueFlag.Name),
  164. Difficulty: genesisConfig.Difficulty,
  165. Time: new(big.Int).SetUint64(genesisConfig.Timestamp),
  166. Coinbase: genesisConfig.Coinbase,
  167. BlockNumber: new(big.Int).SetUint64(genesisConfig.Number),
  168. EVMConfig: vm.Config{
  169. Tracer: tracer,
  170. Debug: ctx.GlobalBool(DebugFlag.Name) || ctx.GlobalBool(MachineFlag.Name),
  171. EVMInterpreter: ctx.GlobalString(EVMInterpreterFlag.Name),
  172. },
  173. }
  174. if cpuProfilePath := ctx.GlobalString(CPUProfileFlag.Name); cpuProfilePath != "" {
  175. f, err := os.Create(cpuProfilePath)
  176. if err != nil {
  177. fmt.Println("could not create CPU profile: ", err)
  178. os.Exit(1)
  179. }
  180. if err := pprof.StartCPUProfile(f); err != nil {
  181. fmt.Println("could not start CPU profile: ", err)
  182. os.Exit(1)
  183. }
  184. defer pprof.StopCPUProfile()
  185. }
  186. if chainConfig != nil {
  187. runtimeConfig.ChainConfig = chainConfig
  188. }
  189. tstart := time.Now()
  190. var leftOverGas uint64
  191. if ctx.GlobalBool(CreateFlag.Name) {
  192. input := append(code, common.Hex2Bytes(ctx.GlobalString(InputFlag.Name))...)
  193. ret, _, leftOverGas, err = runtime.Create(input, &runtimeConfig)
  194. } else {
  195. if len(code) > 0 {
  196. statedb.SetCode(receiver, code)
  197. }
  198. ret, leftOverGas, err = runtime.Call(receiver, common.Hex2Bytes(ctx.GlobalString(InputFlag.Name)), &runtimeConfig)
  199. }
  200. execTime := time.Since(tstart)
  201. if ctx.GlobalBool(DumpFlag.Name) {
  202. statedb.Commit(true)
  203. statedb.IntermediateRoot(true)
  204. fmt.Println(string(statedb.Dump(false, false, true)))
  205. }
  206. if memProfilePath := ctx.GlobalString(MemProfileFlag.Name); memProfilePath != "" {
  207. f, err := os.Create(memProfilePath)
  208. if err != nil {
  209. fmt.Println("could not create memory profile: ", err)
  210. os.Exit(1)
  211. }
  212. if err := pprof.WriteHeapProfile(f); err != nil {
  213. fmt.Println("could not write memory profile: ", err)
  214. os.Exit(1)
  215. }
  216. f.Close()
  217. }
  218. if ctx.GlobalBool(DebugFlag.Name) {
  219. if debugLogger != nil {
  220. fmt.Fprintln(os.Stderr, "#### TRACE ####")
  221. vm.WriteTrace(os.Stderr, debugLogger.StructLogs())
  222. }
  223. fmt.Fprintln(os.Stderr, "#### LOGS ####")
  224. vm.WriteLogs(os.Stderr, statedb.Logs())
  225. }
  226. if ctx.GlobalBool(StatDumpFlag.Name) {
  227. var mem goruntime.MemStats
  228. goruntime.ReadMemStats(&mem)
  229. fmt.Fprintf(os.Stderr, `evm execution time: %v
  230. heap objects: %d
  231. allocations: %d
  232. total allocations: %d
  233. GC calls: %d
  234. Gas used: %d
  235. `, execTime, mem.HeapObjects, mem.Alloc, mem.TotalAlloc, mem.NumGC, initialGas-leftOverGas)
  236. }
  237. if tracer == nil {
  238. fmt.Printf("0x%x\n", ret)
  239. if err != nil {
  240. fmt.Printf(" error: %v\n", err)
  241. }
  242. }
  243. return nil
  244. }