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