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