github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/cmd/evm/staterunner.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  	"encoding/json"
    21  	"errors"
    22  	"fmt"
    23  	"io/ioutil"
    24  	"os"
    25  
    26  	"github.com/SmartMeshFoundation/Spectrum/core/state"
    27  	"github.com/SmartMeshFoundation/Spectrum/core/vm"
    28  	"github.com/SmartMeshFoundation/Spectrum/log"
    29  	"github.com/SmartMeshFoundation/Spectrum/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  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 Spectrum logger
    54  	glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
    55  	glogger.Verbosity(log.Lvl(ctx.GlobalInt(VerbosityFlag.Name)))
    56  	log.Root().SetHandler(glogger)
    57  
    58  	// Configure the EVM logger
    59  	config := &vm.LogConfig{
    60  		DisableMemory: ctx.GlobalBool(DisableMemoryFlag.Name),
    61  		DisableStack:  ctx.GlobalBool(DisableStackFlag.Name),
    62  	}
    63  	var (
    64  		tracer   vm.Tracer
    65  		debugger *vm.StructLogger
    66  	)
    67  	switch {
    68  	case ctx.GlobalBool(MachineFlag.Name):
    69  		tracer = NewJSONLogger(config, os.Stderr)
    70  
    71  	case ctx.GlobalBool(DebugFlag.Name):
    72  		debugger = vm.NewStructLogger(config)
    73  		tracer = debugger
    74  
    75  	default:
    76  		debugger = vm.NewStructLogger(config)
    77  	}
    78  	// Load the test content from the input file
    79  	src, err := ioutil.ReadFile(ctx.Args().First())
    80  	if err != nil {
    81  		return err
    82  	}
    83  	var tests map[string]tests.StateTest
    84  	if err = json.Unmarshal(src, &tests); err != nil {
    85  		return err
    86  	}
    87  	// Iterate over all the tests, run them and aggregate the results
    88  	cfg := vm.Config{
    89  		Tracer: tracer,
    90  		Debug:  ctx.GlobalBool(DebugFlag.Name) || ctx.GlobalBool(MachineFlag.Name),
    91  	}
    92  	results := make([]StatetestResult, 0, len(tests))
    93  	for key, test := range tests {
    94  		for _, st := range test.Subtests() {
    95  			// Run the test and aggregate the result
    96  			result := &StatetestResult{Name: key, Fork: st.Fork, Pass: true}
    97  			state, err := test.Run(st, cfg)
    98  			if err != nil {
    99  				// Test failed, mark as so and dump any state to aid debugging
   100  				result.Pass, result.Error = false, err.Error()
   101  				if ctx.GlobalBool(DumpFlag.Name) && state != nil {
   102  					dump := state.RawDump()
   103  					result.State = &dump
   104  				}
   105  			}
   106  			// print state root for evmlab tracing (already committed above, so no need to delete objects again
   107  			if ctx.GlobalBool(MachineFlag.Name) && state != nil {
   108  				fmt.Fprintf(os.Stderr, "{\"stateRoot\": \"%x\"}\n", state.IntermediateRoot(false))
   109  			}
   110  
   111  			results = append(results, *result)
   112  
   113  			// Print any structured logs collected
   114  			if ctx.GlobalBool(DebugFlag.Name) {
   115  				if debugger != nil {
   116  					fmt.Fprintln(os.Stderr, "#### TRACE ####")
   117  					vm.WriteTrace(os.Stderr, debugger.StructLogs())
   118  				}
   119  			}
   120  		}
   121  	}
   122  	out, _ := json.MarshalIndent(results, "", "  ")
   123  	fmt.Println(string(out))
   124  	return nil
   125  }