-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Expand file tree
/
Copy pathsimulation_helpers.go
More file actions
188 lines (154 loc) · 5.17 KB
/
simulation_helpers.go
File metadata and controls
188 lines (154 loc) · 5.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package sims
import (
"bytes"
"encoding/json"
"fmt"
"os"
dbm "github.com/cosmos/cosmos-db"
"cosmossdk.io/log"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/runtime"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
"github.com/cosmos/cosmos-sdk/types/module"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
)
// SetupSimulation creates the config, db (levelDB), temporary directory and logger for the simulation tests.
// If `skip` is false it skips the current test. `skip` should be set using the `FlagEnabledValue` flag.
// Returns error on an invalid db intantiation or temp dir creation.
func SetupSimulation(config simtypes.Config, dirPrefix, dbName string, verbose, skip bool) (dbm.DB, string, log.Logger, bool, error) {
if !skip {
return nil, "", nil, true, nil
}
var logger log.Logger
if verbose {
logger = log.NewLogger(os.Stdout) // TODO(mr): enable selection of log destination.
} else {
logger = log.NewNopLogger()
}
dir, err := os.MkdirTemp("", dirPrefix)
if err != nil {
return nil, "", nil, false, err
}
db, err := dbm.NewDB(dbName, dbm.BackendType(config.DBBackend), dir)
if err != nil {
return nil, "", nil, false, err
}
return db, dir, logger, false, nil
}
// SimulationOperations retrieves the simulation params from the provided file path
// and returns all the modules weighted operations
func SimulationOperations(app runtime.AppI, cdc codec.JSONCodec, config simtypes.Config) []simtypes.WeightedOperation {
simState := module.SimulationState{
AppParams: make(simtypes.AppParams),
Cdc: cdc,
TxConfig: moduletestutil.MakeTestTxConfig(),
BondDenom: sdk.DefaultBondDenom,
}
if config.ParamsFile != "" {
bz, err := os.ReadFile(config.ParamsFile)
if err != nil {
panic(err)
}
err = json.Unmarshal(bz, &simState.AppParams)
if err != nil {
panic(err)
}
}
simState.LegacyProposalContents = app.SimulationManager().GetProposalContents(simState) //nolint:staticcheck // used for legacy testing
simState.ProposalMsgs = app.SimulationManager().GetProposalMsgs(simState)
return app.SimulationManager().WeightedOperations(simState)
}
// CheckExportSimulation exports the app state and simulation parameters to JSON
// if the export paths are defined.
func CheckExportSimulation(app runtime.AppI, config simtypes.Config, params simtypes.Params) error {
if config.ExportStatePath != "" {
fmt.Println("exporting app state...")
exported, err := app.ExportAppStateAndValidators(false, nil, nil)
if err != nil {
return err
}
if err := os.WriteFile(config.ExportStatePath, []byte(exported.AppState), 0o600); err != nil {
return err
}
}
if config.ExportParamsPath != "" {
fmt.Println("exporting simulation params...")
paramsBz, err := json.MarshalIndent(params, "", " ")
if err != nil {
return err
}
if err := os.WriteFile(config.ExportParamsPath, paramsBz, 0o600); err != nil {
return err
}
}
return nil
}
// PrintStats prints the corresponding statistics from the app DB.
func PrintStats(db dbm.DB) {
fmt.Println("\nLevelDB Stats")
fmt.Println(db.Stats()["leveldb.stats"])
fmt.Println("LevelDB cached block size", db.Stats()["leveldb.cachedblock"])
}
// GetSimulationLog unmarshals the KVPair's Value to the corresponding type based on the
// each's module store key and the prefix bytes of the KVPair's key.
func GetSimulationLog(storeName string, sdr simtypes.StoreDecoderRegistry, kvAs, kvBs []kv.Pair) (log string) {
for i := 0; i < len(kvAs); i++ {
if len(kvAs[i].Value) == 0 && len(kvBs[i].Value) == 0 {
// skip if the value doesn't have any bytes
continue
}
decoder, ok := sdr[storeName]
if ok {
log += decoder(kvAs[i], kvBs[i])
} else {
log += fmt.Sprintf("store A %X => %X\nstore B %X => %X\n", kvAs[i].Key, kvAs[i].Value, kvBs[i].Key, kvBs[i].Value)
}
}
return log
}
// DiffKVStores compares two KVstores and returns all the key/value pairs
// that differ from one another. It also skips value comparison for a set of provided prefixes.
func DiffKVStores(a, b storetypes.KVStore, prefixesToSkip [][]byte) (kvAs, kvBs []kv.Pair) {
iterA := a.Iterator(nil, nil)
defer iterA.Close()
iterB := b.Iterator(nil, nil)
defer iterB.Close()
for {
if !iterA.Valid() && !iterB.Valid() {
return kvAs, kvBs
}
var kvA, kvB kv.Pair
if iterA.Valid() {
kvA = kv.Pair{Key: iterA.Key(), Value: iterA.Value()}
iterA.Next()
}
if iterB.Valid() {
kvB = kv.Pair{Key: iterB.Key(), Value: iterB.Value()}
}
compareValue := true
for _, prefix := range prefixesToSkip {
// Skip value comparison if we matched a prefix
if bytes.HasPrefix(kvA.Key, prefix) {
compareValue = false
break
}
}
if !compareValue {
// We're skipping this key due to an exclusion prefix. If it's present in B, iterate past it. If it's
// absent don't iterate.
if bytes.Equal(kvA.Key, kvB.Key) {
iterB.Next()
}
continue
}
// always iterate B when comparing
iterB.Next()
if !bytes.Equal(kvA.Key, kvB.Key) || !bytes.Equal(kvA.Value, kvB.Value) {
kvAs = append(kvAs, kvA)
kvBs = append(kvBs, kvB)
}
}
}