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