github.com/ethxdao/go-ethereum@v0.0.0-20221218102228-5ae34a9cc189/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  	"os"
    24  
    25  	"github.com/ethxdao/go-ethereum/core/state"
    26  	"github.com/ethxdao/go-ethereum/core/vm"
    27  	"github.com/ethxdao/go-ethereum/eth/tracers/logger"
    28  	"github.com/ethxdao/go-ethereum/log"
    29  	"github.com/ethxdao/go-ethereum/tests"
    30  )
    31  
    32  var stateTestCommand = &cli.Command{
    33  	Action:    stateTestCmd,
    34  	Name:      "statetest",
    35  	Usage:     "executes the given state tests",
    36  	ArgsUsage: "<file>",
    37  }
    38  
    39  // StatetestResult contains the execution status after running a state test, any
    40  // error that might have occurred and a dump of the final state if requested.
    41  type StatetestResult struct {
    42  	Name  string      `json:"name"`
    43  	Pass  bool        `json:"pass"`
    44  	Fork  string      `json:"fork"`
    45  	Error string      `json:"error,omitempty"`
    46  	State *state.Dump `json:"state,omitempty"`
    47  }
    48  
    49  func stateTestCmd(ctx *cli.Context) error {
    50  	if len(ctx.Args().First()) == 0 {
    51  		return errors.New("path-to-test argument required")
    52  	}
    53  	// Configure the go-ethereum logger
    54  	glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
    55  	glogger.Verbosity(log.Lvl(ctx.Int(VerbosityFlag.Name)))
    56  	log.Root().SetHandler(glogger)
    57  
    58  	// Configure the EVM logger
    59  	config := &logger.Config{
    60  		EnableMemory:     !ctx.Bool(DisableMemoryFlag.Name),
    61  		DisableStack:     ctx.Bool(DisableStackFlag.Name),
    62  		DisableStorage:   ctx.Bool(DisableStorageFlag.Name),
    63  		EnableReturnData: !ctx.Bool(DisableReturnDataFlag.Name),
    64  	}
    65  	var (
    66  		tracer   vm.EVMLogger
    67  		debugger *logger.StructLogger
    68  	)
    69  	switch {
    70  	case ctx.Bool(MachineFlag.Name):
    71  		tracer = logger.NewJSONLogger(config, os.Stderr)
    72  
    73  	case ctx.Bool(DebugFlag.Name):
    74  		debugger = logger.NewStructLogger(config)
    75  		tracer = debugger
    76  
    77  	default:
    78  		debugger = logger.NewStructLogger(config)
    79  	}
    80  	// Load the test content from the input file
    81  	src, err := os.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.Bool(DebugFlag.Name) || ctx.Bool(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  			_, s, err := test.Run(st, cfg, false)
   100  			// print state root for evmlab tracing
   101  			if ctx.Bool(MachineFlag.Name) && s != nil {
   102  				fmt.Fprintf(os.Stderr, "{\"stateRoot\": \"%x\"}\n", s.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.Bool(DumpFlag.Name) && s != nil {
   108  					dump := s.RawDump(nil)
   109  					result.State = &dump
   110  				}
   111  			}
   112  
   113  			results = append(results, *result)
   114  
   115  			// Print any structured logs collected
   116  			if ctx.Bool(DebugFlag.Name) {
   117  				if debugger != nil {
   118  					fmt.Fprintln(os.Stderr, "#### TRACE ####")
   119  					logger.WriteTrace(os.Stderr, debugger.StructLogs())
   120  				}
   121  			}
   122  		}
   123  	}
   124  	out, _ := json.MarshalIndent(results, "", "  ")
   125  	fmt.Println(string(out))
   126  	return nil
   127  }