runner.go 9.5 KB

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