runner.go 9.55 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright 2017 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.

package main

import (
20
	"bytes"
21
	"encoding/json"
22 23
	"fmt"
	"io/ioutil"
24
	"math/big"
25
	"os"
26
	goruntime "runtime"
27
	"runtime/pprof"
28
	"testing"
29 30
	"time"

31
	"github.com/ethereum/go-ethereum/cmd/evm/internal/compiler"
32 33
	"github.com/ethereum/go-ethereum/cmd/utils"
	"github.com/ethereum/go-ethereum/common"
34
	"github.com/ethereum/go-ethereum/core"
35
	"github.com/ethereum/go-ethereum/core/rawdb"
36 37 38 39
	"github.com/ethereum/go-ethereum/core/state"
	"github.com/ethereum/go-ethereum/core/vm"
	"github.com/ethereum/go-ethereum/core/vm/runtime"
	"github.com/ethereum/go-ethereum/log"
40
	"github.com/ethereum/go-ethereum/params"
41
	"gopkg.in/urfave/cli.v1"
42 43 44 45 46 47 48 49 50 51
)

var runCommand = cli.Command{
	Action:      runCmd,
	Name:        "run",
	Usage:       "run arbitrary evm binary",
	ArgsUsage:   "<code>",
	Description: `The run command runs arbitrary EVM code.`,
}

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
// readGenesis will read the given JSON format genesis file and return
// the initialized Genesis structure
func readGenesis(genesisPath string) *core.Genesis {
	// Make sure we have a valid genesis JSON
	//genesisPath := ctx.Args().First()
	if len(genesisPath) == 0 {
		utils.Fatalf("Must supply path to genesis JSON file")
	}
	file, err := os.Open(genesisPath)
	if err != nil {
		utils.Fatalf("Failed to read genesis file: %v", err)
	}
	defer file.Close()

	genesis := new(core.Genesis)
	if err := json.NewDecoder(file).Decode(genesis); err != nil {
		utils.Fatalf("invalid genesis file: %v", err)
	}
	return genesis
}

73 74 75 76 77
type execStats struct {
	time           time.Duration // The execution time.
	allocs         int64         // The number of heap allocations during execution.
	bytesAllocated int64         // The cumulative number of bytes allocated during execution.
}
78

79
func timedExec(bench bool, execFunc func() ([]byte, uint64, error)) (output []byte, gasLeft uint64, stats execStats, err error) {
80 81 82 83 84 85 86 87 88
	if bench {
		result := testing.Benchmark(func(b *testing.B) {
			for i := 0; i < b.N; i++ {
				output, gasLeft, err = execFunc()
			}
		})

		// Get the average execution time from the benchmarking result.
		// There are other useful stats here that could be reported.
89 90 91
		stats.time = time.Duration(result.NsPerOp())
		stats.allocs = result.AllocsPerOp()
		stats.bytesAllocated = result.AllocedBytesPerOp()
92
	} else {
93 94
		var memStatsBefore, memStatsAfter goruntime.MemStats
		goruntime.ReadMemStats(&memStatsBefore)
95 96
		startTime := time.Now()
		output, gasLeft, err = execFunc()
97 98 99 100
		stats.time = time.Since(startTime)
		goruntime.ReadMemStats(&memStatsAfter)
		stats.allocs = int64(memStatsAfter.Mallocs - memStatsBefore.Mallocs)
		stats.bytesAllocated = int64(memStatsAfter.TotalAlloc - memStatsBefore.TotalAlloc)
101 102
	}

103
	return output, gasLeft, stats, err
104 105
}

106 107 108 109
func runCmd(ctx *cli.Context) error {
	glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
	glogger.Verbosity(log.Lvl(ctx.GlobalInt(VerbosityFlag.Name)))
	log.Root().SetHandler(glogger)
110
	logconfig := &vm.LogConfig{
111 112 113 114 115
		DisableMemory:     ctx.GlobalBool(DisableMemoryFlag.Name),
		DisableStack:      ctx.GlobalBool(DisableStackFlag.Name),
		DisableStorage:    ctx.GlobalBool(DisableStorageFlag.Name),
		DisableReturnData: ctx.GlobalBool(DisableReturnDataFlag.Name),
		Debug:             ctx.GlobalBool(DebugFlag.Name),
116
	}
117 118

	var (
119 120 121 122 123 124 125
		tracer        vm.Tracer
		debugLogger   *vm.StructLogger
		statedb       *state.StateDB
		chainConfig   *params.ChainConfig
		sender        = common.BytesToAddress([]byte("sender"))
		receiver      = common.BytesToAddress([]byte("receiver"))
		genesisConfig *core.Genesis
126
	)
127
	if ctx.GlobalBool(MachineFlag.Name) {
128
		tracer = vm.NewJSONLogger(logconfig, os.Stdout)
129
	} else if ctx.GlobalBool(DebugFlag.Name) {
130
		debugLogger = vm.NewStructLogger(logconfig)
131 132
		tracer = debugLogger
	} else {
133
		debugLogger = vm.NewStructLogger(logconfig)
134 135 136
	}
	if ctx.GlobalString(GenesisFlag.Name) != "" {
		gen := readGenesis(ctx.GlobalString(GenesisFlag.Name))
137
		genesisConfig = gen
138
		db := rawdb.NewMemoryDatabase()
139
		genesis := gen.ToBlock(db)
140
		statedb, _ = state.New(genesis.Root(), state.NewDatabase(db), nil)
141 142
		chainConfig = gen.Config
	} else {
143
		statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
144
		genesisConfig = new(core.Genesis)
145 146 147 148
	}
	if ctx.GlobalString(SenderFlag.Name) != "" {
		sender = common.HexToAddress(ctx.GlobalString(SenderFlag.Name))
	}
149 150
	statedb.CreateAccount(sender)

151 152 153 154
	if ctx.GlobalString(ReceiverFlag.Name) != "" {
		receiver = common.HexToAddress(ctx.GlobalString(ReceiverFlag.Name))
	}

155
	var code []byte
156 157 158
	codeFileFlag := ctx.GlobalString(CodeFileFlag.Name)
	codeFlag := ctx.GlobalString(CodeFlag.Name)

159
	// The '--code' or '--codefile' flag overrides code in state
160
	if codeFileFlag != "" || codeFlag != "" {
161
		var hexcode []byte
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
		if codeFileFlag != "" {
			var err error
			// If - is specified, it means that code comes from stdin
			if codeFileFlag == "-" {
				//Try reading from stdin
				if hexcode, err = ioutil.ReadAll(os.Stdin); err != nil {
					fmt.Printf("Could not load code from stdin: %v\n", err)
					os.Exit(1)
				}
			} else {
				// Codefile with hex assembly
				if hexcode, err = ioutil.ReadFile(codeFileFlag); err != nil {
					fmt.Printf("Could not load code from file: %v\n", err)
					os.Exit(1)
				}
177 178
			}
		} else {
179
			hexcode = []byte(codeFlag)
180
		}
181
		hexcode = bytes.TrimSpace(hexcode)
182 183 184 185 186
		if len(hexcode)%2 != 0 {
			fmt.Printf("Invalid input length for hex data (%d)\n", len(hexcode))
			os.Exit(1)
		}
		code = common.FromHex(string(hexcode))
187 188
	} else if fn := ctx.Args().First(); len(fn) > 0 {
		// EASM-file to compile
189 190 191 192 193 194 195 196 197
		src, err := ioutil.ReadFile(fn)
		if err != nil {
			return err
		}
		bin, err := compiler.Compile(fn, src, false)
		if err != nil {
			return err
		}
		code = common.Hex2Bytes(bin)
198
	}
199
	initialGas := ctx.GlobalUint64(GasFlag.Name)
200 201 202
	if genesisConfig.GasLimit != 0 {
		initialGas = genesisConfig.GasLimit
	}
203
	runtimeConfig := runtime.Config{
204 205 206 207 208
		Origin:      sender,
		State:       statedb,
		GasLimit:    initialGas,
		GasPrice:    utils.GlobalBig(ctx, PriceFlag.Name),
		Value:       utils.GlobalBig(ctx, ValueFlag.Name),
209 210 211 212
		Difficulty:  genesisConfig.Difficulty,
		Time:        new(big.Int).SetUint64(genesisConfig.Timestamp),
		Coinbase:    genesisConfig.Coinbase,
		BlockNumber: new(big.Int).SetUint64(genesisConfig.Number),
213
		EVMConfig: vm.Config{
214 215 216
			Tracer:         tracer,
			Debug:          ctx.GlobalBool(DebugFlag.Name) || ctx.GlobalBool(MachineFlag.Name),
			EVMInterpreter: ctx.GlobalString(EVMInterpreterFlag.Name),
217 218 219
		},
	}

220 221 222
	if cpuProfilePath := ctx.GlobalString(CPUProfileFlag.Name); cpuProfilePath != "" {
		f, err := os.Create(cpuProfilePath)
		if err != nil {
223
			fmt.Println("could not create CPU profile: ", err)
224 225 226
			os.Exit(1)
		}
		if err := pprof.StartCPUProfile(f); err != nil {
227
			fmt.Println("could not start CPU profile: ", err)
228 229 230 231 232
			os.Exit(1)
		}
		defer pprof.StopCPUProfile()
	}

233 234
	if chainConfig != nil {
		runtimeConfig.ChainConfig = chainConfig
235 236
	} else {
		runtimeConfig.ChainConfig = params.AllEthashProtocolChanges
237
	}
238

239 240
	var hexInput []byte
	if inputFileFlag := ctx.GlobalString(InputFileFlag.Name); inputFileFlag != "" {
241
		var err error
242 243 244 245 246 247 248 249
		if hexInput, err = ioutil.ReadFile(inputFileFlag); err != nil {
			fmt.Printf("could not load input from file: %v\n", err)
			os.Exit(1)
		}
	} else {
		hexInput = []byte(ctx.GlobalString(InputFlag.Name))
	}
	input := common.FromHex(string(bytes.TrimSpace(hexInput)))
250 251

	var execFunc func() ([]byte, uint64, error)
252
	if ctx.GlobalBool(CreateFlag.Name) {
253
		input = append(code, input...)
254 255 256 257
		execFunc = func() ([]byte, uint64, error) {
			output, _, gasLeft, err := runtime.Create(input, &runtimeConfig)
			return output, gasLeft, err
		}
258
	} else {
259 260 261
		if len(code) > 0 {
			statedb.SetCode(receiver, code)
		}
262 263 264
		execFunc = func() ([]byte, uint64, error) {
			return runtime.Call(receiver, input, &runtimeConfig)
		}
265
	}
266

267 268
	bench := ctx.GlobalBool(BenchFlag.Name)
	output, leftOverGas, stats, err := timedExec(bench, execFunc)
269 270

	if ctx.GlobalBool(DumpFlag.Name) {
271
		statedb.Commit(true)
272
		statedb.IntermediateRoot(true)
273
		fmt.Println(string(statedb.Dump(false, false, true)))
274
	}
275

276 277 278
	if memProfilePath := ctx.GlobalString(MemProfileFlag.Name); memProfilePath != "" {
		f, err := os.Create(memProfilePath)
		if err != nil {
279
			fmt.Println("could not create memory profile: ", err)
280 281 282
			os.Exit(1)
		}
		if err := pprof.WriteHeapProfile(f); err != nil {
283
			fmt.Println("could not write memory profile: ", err)
284 285 286 287 288
			os.Exit(1)
		}
		f.Close()
	}

289
	if ctx.GlobalBool(DebugFlag.Name) {
290
		if debugLogger != nil {
291 292
			fmt.Fprintln(os.Stderr, "#### TRACE ####")
			vm.WriteTrace(os.Stderr, debugLogger.StructLogs())
293
		}
294 295
		fmt.Fprintln(os.Stderr, "#### LOGS ####")
		vm.WriteLogs(os.Stderr, statedb.Logs())
296
	}
297

298 299 300 301 302 303
	if bench || ctx.GlobalBool(StatDumpFlag.Name) {
		fmt.Fprintf(os.Stderr, `EVM gas used:    %d
execution time:  %v
allocations:     %d
allocated bytes: %d
`, initialGas-leftOverGas, stats.time, stats.allocs, stats.bytesAllocated)
304
	}
305
	if tracer == nil {
306
		fmt.Printf("0x%x\n", output)
307
		if err != nil {
308
			fmt.Printf(" error: %v\n", err)
309
		}
310 311 312 313
	}

	return nil
}