github.com/Finschia/finschia-sdk@v0.48.1/simapp/utils.go (about)

     1  package simapp
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"os"
     7  
     8  	"github.com/Finschia/ostracon/libs/log"
     9  	dbm "github.com/tendermint/tm-db"
    10  
    11  	"github.com/Finschia/finschia-sdk/codec"
    12  	"github.com/Finschia/finschia-sdk/simapp/helpers"
    13  	sdk "github.com/Finschia/finschia-sdk/types"
    14  	"github.com/Finschia/finschia-sdk/types/kv"
    15  	"github.com/Finschia/finschia-sdk/types/module"
    16  	simtypes "github.com/Finschia/finschia-sdk/types/simulation"
    17  )
    18  
    19  // SetupSimulation creates the config, db (levelDB), temporary directory and logger for
    20  // the simulation tests. If `FlagEnabledValue` is false it skips the current test.
    21  // Returns error on an invalid db intantiation or temp dir creation.
    22  func SetupSimulation(dirPrefix, dbName string) (simtypes.Config, dbm.DB, string, log.Logger, bool, error) {
    23  	if !FlagEnabledValue {
    24  		return simtypes.Config{}, nil, "", nil, true, nil
    25  	}
    26  
    27  	config := NewConfigFromFlags()
    28  	config.ChainID = helpers.SimAppChainID
    29  
    30  	var logger log.Logger
    31  	if FlagVerboseValue {
    32  		logger = log.TestingLogger()
    33  	} else {
    34  		logger = log.NewNopLogger()
    35  	}
    36  
    37  	dir, err := os.MkdirTemp("", dirPrefix)
    38  	if err != nil {
    39  		return simtypes.Config{}, nil, "", nil, false, err
    40  	}
    41  
    42  	db, err := sdk.NewLevelDB(dbName, dir)
    43  	if err != nil {
    44  		return simtypes.Config{}, nil, "", nil, false, err
    45  	}
    46  
    47  	return config, db, dir, logger, false, nil
    48  }
    49  
    50  // SimulationOperations retrieves the simulation params from the provided file path
    51  // and returns all the modules weighted operations
    52  func SimulationOperations(app App, cdc codec.JSONCodec, config simtypes.Config) []simtypes.WeightedOperation {
    53  	simState := module.SimulationState{
    54  		AppParams: make(simtypes.AppParams),
    55  		Cdc:       cdc,
    56  	}
    57  
    58  	if config.ParamsFile != "" {
    59  		bz, err := os.ReadFile(config.ParamsFile)
    60  		if err != nil {
    61  			panic(err)
    62  		}
    63  
    64  		err = json.Unmarshal(bz, &simState.AppParams)
    65  		if err != nil {
    66  			panic(err)
    67  		}
    68  	}
    69  
    70  	simState.ParamChanges = app.SimulationManager().GenerateParamChanges(config.Seed)
    71  	simState.Contents = app.SimulationManager().GetProposalContents(simState)
    72  	return app.SimulationManager().WeightedOperations(simState)
    73  }
    74  
    75  // CheckExportSimulation exports the app state and simulation parameters to JSON
    76  // if the export paths are defined.
    77  func CheckExportSimulation(
    78  	app App, config simtypes.Config, params simtypes.Params,
    79  ) error {
    80  	if config.ExportStatePath != "" {
    81  		fmt.Println("exporting app state...")
    82  		exported, err := app.ExportAppStateAndValidators(false, nil)
    83  		if err != nil {
    84  			return err
    85  		}
    86  
    87  		if err := os.WriteFile(config.ExportStatePath, []byte(exported.AppState), 0o600); err != nil {
    88  			return err
    89  		}
    90  	}
    91  
    92  	if config.ExportParamsPath != "" {
    93  		fmt.Println("exporting simulation params...")
    94  		paramsBz, err := json.MarshalIndent(params, "", " ")
    95  		if err != nil {
    96  			return err
    97  		}
    98  
    99  		if err := os.WriteFile(config.ExportParamsPath, paramsBz, 0o600); err != nil {
   100  			return err
   101  		}
   102  	}
   103  	return nil
   104  }
   105  
   106  // PrintStats prints the corresponding statistics from the app DB.
   107  func PrintStats(db dbm.DB) {
   108  	fmt.Println("\nLevelDB Stats")
   109  	fmt.Println(db.Stats()["leveldb.stats"])
   110  	fmt.Println("LevelDB cached block size", db.Stats()["leveldb.cachedblock"])
   111  }
   112  
   113  // GetSimulationLog unmarshals the KVPair's Value to the corresponding type based on the
   114  // each's module store key and the prefix bytes of the KVPair's key.
   115  func GetSimulationLog(storeName string, sdr sdk.StoreDecoderRegistry, kvAs, kvBs []kv.Pair) (log string) {
   116  	for i := 0; i < len(kvAs); i++ {
   117  		if len(kvAs[i].Value) == 0 && len(kvBs[i].Value) == 0 {
   118  			// skip if the value doesn't have any bytes
   119  			continue
   120  		}
   121  
   122  		decoder, ok := sdr[storeName]
   123  		if ok {
   124  			log += decoder(kvAs[i], kvBs[i])
   125  		} else {
   126  			log += fmt.Sprintf("store A %X => %X\nstore B %X => %X\n", kvAs[i].Key, kvAs[i].Value, kvBs[i].Key, kvBs[i].Value)
   127  		}
   128  	}
   129  
   130  	return log
   131  }