github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/cmd/evm/staterunner.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  	"encoding/json"
    21  	"errors"
    22  	"fmt"
    23  	"io/ioutil"
    24  	"os"
    25  
    26  	"github.com/zhiqiangxu/go-ethereum/core/state"
    27  	"github.com/zhiqiangxu/go-ethereum/core/vm"
    28  	"github.com/zhiqiangxu/go-ethereum/log"
    29  	"github.com/zhiqiangxu/go-ethereum/tests"
    30  
    31  	cli "gopkg.in/urfave/cli.v1"
    32  )
    33  
    34  var stateTestCommand = cli.Command{
    35  	Action:    stateTestCmd,
    36  	Name:      "statetest",
    37  	Usage:     "executes the given state tests",
    38  	ArgsUsage: "<file>",
    39  }
    40  
    41  // StatetestResult contains the execution status after running a state test, any
    42  // error that might have occurred and a dump of the final state if requested.
    43  type StatetestResult struct {
    44  	Name  string      `json:"name"`
    45  	Pass  bool        `json:"pass"`
    46  	Fork  string      `json:"fork"`
    47  	Error string      `json:"error,omitempty"`
    48  	State *state.Dump `json:"state,omitempty"`
    49  }
    50  
    51  func stateTestCmd(ctx *cli.Context) error {
    52  	if len(ctx.Args().First()) == 0 {
    53  		return errors.New("path-to-test argument required")
    54  	}
    55  	// Configure the go-ethereum logger
    56  	glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
    57  	glogger.Verbosity(log.Lvl(ctx.GlobalInt(VerbosityFlag.Name)))
    58  	log.Root().SetHandler(glogger)
    59  
    60  	// Configure the EVM logger
    61  	config := &vm.LogConfig{
    62  		DisableMemory: ctx.GlobalBool(DisableMemoryFlag.Name),
    63  		DisableStack:  ctx.GlobalBool(DisableStackFlag.Name),
    64  	}
    65  	var (
    66  		tracer   vm.Tracer
    67  		debugger *vm.StructLogger
    68  	)
    69  	switch {
    70  	case ctx.GlobalBool(MachineFlag.Name):
    71  		tracer = vm.NewJSONLogger(config, os.Stderr)
    72  
    73  	case ctx.GlobalBool(DebugFlag.Name):
    74  		debugger = vm.NewStructLogger(config)
    75  		tracer = debugger
    76  
    77  	default:
    78  		debugger = vm.NewStructLogger(config)
    79  	}
    80  	// Load the test content from the input file
    81  	src, err := ioutil.ReadFile(ctx.Args().First())
    82  	if err != nil {
    83  		return err
    84  	}
    85  	var tests map[string]tests.StateTest
    86  	if err = json.Unmarshal(src, &tests); err != nil {
    87  		return err
    88  	}
    89  	// Iterate over all the tests, run them and aggregate the results
    90  	cfg := vm.Config{
    91  		Tracer: tracer,
    92  		Debug:  ctx.GlobalBool(DebugFlag.Name) || ctx.GlobalBool(MachineFlag.Name),
    93  	}
    94  	results := make([]StatetestResult, 0, len(tests))
    95  	for key, test := range tests {
    96  		for _, st := range test.Subtests() {
    97  			// Run the test and aggregate the result
    98  			result := &StatetestResult{Name: key, Fork: st.Fork, Pass: true}
    99  			_, state, err := test.Run(st, cfg, false)
   100  			// print state root for evmlab tracing
   101  			if ctx.GlobalBool(MachineFlag.Name) && state != nil {
   102  				fmt.Fprintf(os.Stderr, "{\"stateRoot\": \"%x\"}\n", state.IntermediateRoot(false))
   103  			}
   104  			if err != nil {
   105  				// Test failed, mark as so and dump any state to aid debugging
   106  				result.Pass, result.Error = false, err.Error()
   107  				if ctx.GlobalBool(DumpFlag.Name) && state != nil {
   108  					dump := state.RawDump(false, false, true)
   109  					result.State = &dump
   110  				}
   111  			}
   112  
   113  			results = append(results, *result)
   114  
   115  			// Print any structured logs collected
   116  			if ctx.GlobalBool(DebugFlag.Name) {
   117  				if debugger != nil {
   118  					fmt.Fprintln(os.Stderr, "#### TRACE ####")
   119  					vm.WriteTrace(os.Stderr, debugger.StructLogs())
   120  				}
   121  			}
   122  		}
   123  	}
   124  	out, _ := json.MarshalIndent(results, "", "  ")
   125  	fmt.Println(string(out))
   126  	return nil
   127  }