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