runner.go 8.1 KB

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