Skip to content

Commit f39b7fe

Browse files
julienrbrtmergify[bot]
authored andcommitted
refactor!: extract AppStateFn out of simapp (#14977)
(cherry picked from commit 4f13b5b) # Conflicts: # CHANGELOG.md # crypto/keys/secp256k1/secp256k1_test.go # testutil/sims/state_helpers.go
1 parent a393336 commit f39b7fe

File tree

7 files changed

+167
-38
lines changed

7 files changed

+167
-38
lines changed

CHANGELOG.md

+19
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,25 @@ Ref: https://keepachangelog.com/en/1.0.0/
240240

241241
### API Breaking Changes
242242

243+
<<<<<<< HEAD
244+
=======
245+
* (simapp) [#14977](https://github.com/cosmos/cosmos-sdk/pull/14977) Move simulation helpers functions (`AppStateFn` and `AppStateRandomizedFn`) to `testutil/sims`. These takes an extra genesisState argument which is the default state of the app.
246+
* (x/gov) [#14720](https://github.com/cosmos/cosmos-sdk/pull/14720) Add an expedited field in the gov v1 proposal and `MsgNewMsgProposal`.
247+
* [#14847](https://github.com/cosmos/cosmos-sdk/pull/14847) App and ModuleManager methods `InitGenesis`, `ExportGenesis`, `BeginBlock` and `EndBlock` now also return an error.
248+
* (simulation) [#14728](https://github.com/cosmos/cosmos-sdk/pull/14728) Rename the `ParamChanges` field to `LegacyParamChange` and `Contents` to `LegacyProposalContents` in `simulation.SimulationState`. Additionally it adds a `ProposalMsgs` field to `simulation.SimulationState`.
249+
* (x/upgrade) [#14764](https://github.com/cosmos/cosmos-sdk/pull/14764) The `x/upgrade` module is extracted to have a separate go.mod file which allows it to be a standalone module.
250+
* (x/gov) [#14782](https://github.com/cosmos/cosmos-sdk/pull/14782) Move the `metadata` argument in `govv1.NewProposal` alongside `title` and `summary`.
251+
* (store) [#14746](https://github.com/cosmos/cosmos-sdk/pull/14746) Extract Store in its own go.mod and rename the package to `cosmossdk.io/store`.
252+
* (simulation) [#14751](https://github.com/cosmos/cosmos-sdk/pull/14751) Remove the `MsgType` field from `simulation.OperationInput` struct.
253+
* (crypto/keyring) [#13734](https://github.com/cosmos/cosmos-sdk/pull/13834) The keyring's `Sign` method now takes a new `signMode` argument. It is only used if the signing key is a Ledger hardware device. You can set it to 0 in all other cases.
254+
* (x/evidence) [14724](https://github.com/cosmos/cosmos-sdk/pull/14724) Extract Evidence in its own go.mod and rename the package to `cosmossdk.io/x/evidence`.
255+
* (x/nft) [#14725](https://github.com/cosmos/cosmos-sdk/pull/14725) Extract NFT in its own go.mod and rename the package to `cosmossdk.io/x/nft`.
256+
* (tx) [#14634](https://github.com/cosmos/cosmos-sdk/pull/14634) Move the `tx` go module to `x/tx`.
257+
* (snapshots) [#14597](https://github.com/cosmos/cosmos-sdk/pull/14597) Move `snapshots` to `store/snapshots`, rename and bump proto package to v1.
258+
* (crypto/keyring) [#14151](https://github.com/cosmos/cosmos-sdk/pull/14151) Move keys presentation from `crypto/keyring` to `client/keys`
259+
* (modules) [#13850](https://github.com/cosmos/cosmos-sdk/pull/13850) and [#14046](https://github.com/cosmos/cosmos-sdk/pull/14046) Remove gogoproto stringer annotations. This removes the custom `String()` methods on all types that were using the annotations.
260+
* (x/auth) [#13850](https://github.com/cosmos/cosmos-sdk/pull/13850/) Remove `MarshalYAML` methods from module (`x/...`) types.
261+
>>>>>>> 4f13b5b31 (refactor!: extract `AppStateFn` out of simapp (#14977))
243262
* (x/auth) [#13877](https://github.com/cosmos/cosmos-sdk/pull/13877) Rename `AccountKeeper`'s `GetNextAccountNumber` to `NextAccountNumber`.
244263
* (x/evidence) [#13740](https://github.com/cosmos/cosmos-sdk/pull/13740) The `NewQueryEvidenceRequest` function now takes `hash` as a HEX encoded `string`.
245264
* (server) [#13485](https://github.com/cosmos/cosmos-sdk/pull/13485) The `Application` service now requires the `RegisterNodeService` method to be implemented.

crypto/keys/secp256k1/secp256k1_test.go

+86
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,92 @@ type keyData struct {
2727
addr string
2828
}
2929

30+
<<<<<<< HEAD
31+
=======
32+
/*
33+
The following code snippet has been used to generate test vectors. The purpose of these vectors are to check our
34+
implementation of secp256k1 against go-ethereum's one. It has been commented to avoid dependencies.
35+
36+
github.com/btcsuite/btcutil v1.0.2
37+
github.com/ethereum/go-ethereum v1.10.26
38+
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519
39+
40+
---
41+
42+
import (
43+
"crypto/ecdsa"
44+
"crypto/sha256"
45+
"encoding/hex"
46+
"fmt"
47+
"github.com/btcsuite/btcutil/base58"
48+
"github.com/ethereum/go-ethereum/crypto"
49+
"golang.org/x/crypto/ripemd160"
50+
)
51+
52+
func ethereumKeys() keyData {
53+
// Generate private key with the go-ethereum
54+
priv, err := crypto.GenerateKey()
55+
if err != nil {
56+
panic(err)
57+
}
58+
encPriv := make([]byte, len(priv.D.Bytes())*2)
59+
hex.Encode(encPriv, priv.D.Bytes())
60+
61+
// Get go-ethereum public key
62+
ethPub, ok := priv.Public().(*ecdsa.PublicKey)
63+
if !ok {
64+
panic(err)
65+
}
66+
ethPublicKeyBytes := crypto.FromECDSAPub(ethPub)
67+
68+
// Format byte depending on the oddness of the Y coordinate.
69+
format := 0x02
70+
if ethPub.Y.Bit(0) != 0 {
71+
format = 0x03
72+
}
73+
74+
// Public key in the 33-byte compressed format.
75+
pub := ethPublicKeyBytes[:33]
76+
encPub := make([]byte, len(pub)*2)
77+
pub[0] = byte(format)
78+
hex.Encode(encPub, pub)
79+
80+
// Bitcoin style addresses
81+
sha := sha256.Sum256(pub)
82+
hasherRIPEMD160 := ripemd160.New()
83+
hasherRIPEMD160.Write(sha[:])
84+
addr := hasherRIPEMD160.Sum(nil)
85+
return keyData{
86+
priv: string(encPriv),
87+
pub: string(encPub),
88+
addr: base58.CheckEncode(addr[:], 0),
89+
}
90+
}
91+
*/
92+
93+
/*
94+
generateKeyForCheckingConsistency was used to create test vectors that matches consistency against prior versions.
95+
Here are the specific versions used to generate the vectors.
96+
97+
github.com/cosmos/btcutil v1.0.5
98+
github.com/cosmos/cosmos-sdk v0.46.8
99+
*/
100+
var _ = func() keyData {
101+
priv := secp256k1.GenPrivKey()
102+
encPriv := make([]byte, len(priv.Key)*2)
103+
hex.Encode(encPriv, priv.Key)
104+
pub := priv.PubKey()
105+
encPub := make([]byte, len(pub.Bytes())*2)
106+
hex.Encode(encPub, pub.Bytes())
107+
addr := pub.Address()
108+
return keyData{
109+
priv: string(encPriv),
110+
pub: string(encPub),
111+
addr: base58.CheckEncode(addr, 0),
112+
}
113+
}
114+
115+
>>>>>>> 4f13b5b31 (refactor!: extract `AppStateFn` out of simapp (#14977))
30116
var secpDataTable = []keyData{
31117
{
32118
priv: "a96e62ed3955e65be32703f12d87b6b5cf26039ecfa948dc5107a495418e5330",

simapp/app_v2.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ func NewSimApp(
203203
// For providing a custom a base account type add it below.
204204
// By default the auth module uses authtypes.ProtoBaseAccount().
205205
//
206-
// func() authtypes.AccountI { return authtypes.ProtoBaseAccount() },
206+
// func() sdk.AccountI { return authtypes.ProtoBaseAccount() },
207207

208208
//
209209
// MINT

simapp/params/params.go

-7
This file was deleted.

simapp/sim_bench_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ func BenchmarkFullAppSimulation(b *testing.B) {
4949
b,
5050
os.Stdout,
5151
app.BaseApp,
52-
AppStateFn(app.AppCodec(), app.SimulationManager()),
52+
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
5353
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
5454
simtestutil.SimulationOperations(app, app.AppCodec(), config),
5555
BlockedAddresses(),
@@ -104,7 +104,7 @@ func BenchmarkInvariants(b *testing.B) {
104104
b,
105105
os.Stdout,
106106
app.BaseApp,
107-
AppStateFn(app.AppCodec(), app.SimulationManager()),
107+
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
108108
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
109109
simtestutil.SimulationOperations(app, app.AppCodec(), config),
110110
BlockedAddresses(),

simapp/sim_test.go

+5-5
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ func TestFullAppSimulation(t *testing.T) {
9292
t,
9393
os.Stdout,
9494
app.BaseApp,
95-
AppStateFn(app.AppCodec(), app.SimulationManager()),
95+
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
9696
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
9797
simtestutil.SimulationOperations(app, app.AppCodec(), config),
9898
BlockedAddresses(),
@@ -137,7 +137,7 @@ func TestAppImportExport(t *testing.T) {
137137
t,
138138
os.Stdout,
139139
app.BaseApp,
140-
AppStateFn(app.AppCodec(), app.SimulationManager()),
140+
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
141141
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
142142
simtestutil.SimulationOperations(app, app.AppCodec(), config),
143143
BlockedAddresses(),
@@ -253,7 +253,7 @@ func TestAppSimulationAfterImport(t *testing.T) {
253253
t,
254254
os.Stdout,
255255
app.BaseApp,
256-
AppStateFn(app.AppCodec(), app.SimulationManager()),
256+
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
257257
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
258258
simtestutil.SimulationOperations(app, app.AppCodec(), config),
259259
BlockedAddresses(),
@@ -301,7 +301,7 @@ func TestAppSimulationAfterImport(t *testing.T) {
301301
t,
302302
os.Stdout,
303303
newApp.BaseApp,
304-
AppStateFn(app.AppCodec(), app.SimulationManager()),
304+
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
305305
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
306306
simtestutil.SimulationOperations(newApp, newApp.AppCodec(), config),
307307
BlockedAddresses(),
@@ -356,7 +356,7 @@ func TestAppStateDeterminism(t *testing.T) {
356356
t,
357357
os.Stdout,
358358
app.BaseApp,
359-
AppStateFn(app.AppCodec(), app.SimulationManager()),
359+
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
360360
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
361361
simtestutil.SimulationOperations(app, app.AppCodec(), config),
362362
BlockedAddresses(),

simapp/state.go testutil/sims/state_helpers.go

+54-23
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package simapp
1+
package sims
22

33
import (
44
"encoding/json"
@@ -8,11 +8,18 @@ import (
88
"os"
99
"time"
1010

11+
<<<<<<< HEAD:simapp/state.go
1112
tmjson "github.com/tendermint/tendermint/libs/json"
1213
tmtypes "github.com/tendermint/tendermint/types"
1314

1415
"cosmossdk.io/math"
1516
simappparams "cosmossdk.io/simapp/params"
17+
=======
18+
"cosmossdk.io/math"
19+
cmtjson "github.com/cometbft/cometbft/libs/json"
20+
cmttypes "github.com/cometbft/cometbft/types"
21+
22+
>>>>>>> 4f13b5b31 (refactor!: extract `AppStateFn` out of simapp (#14977)):testutil/sims/state_helpers.go
1623
"github.com/cosmos/cosmos-sdk/codec"
1724
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
1825
sdk "github.com/cosmos/cosmos-sdk/types"
@@ -24,11 +31,21 @@ import (
2431
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
2532
)
2633

34+
// Simulation parameter constants
35+
const (
36+
StakePerAccount = "stake_per_account"
37+
InitiallyBondedValidators = "initially_bonded_validators"
38+
)
39+
2740
// AppStateFn returns the initial application state using a genesis or the simulation parameters.
2841
// It panics if the user provides files for both of them.
2942
// If a file is not given for the genesis or the sim params, it creates a randomized one.
30-
func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager) simtypes.AppStateFn {
31-
return func(r *rand.Rand, accs []simtypes.Account, config simtypes.Config,
43+
// genesisState is the default genesis state of the whole app.
44+
func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager, genesisState map[string]json.RawMessage) simtypes.AppStateFn {
45+
return func(
46+
r *rand.Rand,
47+
accs []simtypes.Account,
48+
config simtypes.Config,
3249
) (appState json.RawMessage, simAccs []simtypes.Account, chainID string, genesisTimestamp time.Time) {
3350
if simcli.FlagGenesisTimeValue == 0 {
3451
genesisTimestamp = simtypes.RandTimestamp(r)
@@ -43,7 +60,10 @@ func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager) simty
4360

4461
case config.GenesisFile != "":
4562
// override the default chain-id from simapp to set it later to the config
46-
genesisDoc, accounts := AppStateFromGenesisFileFn(r, cdc, config.GenesisFile)
63+
genesisDoc, accounts, err := AppStateFromGenesisFileFn(r, cdc, config.GenesisFile)
64+
if err != nil {
65+
panic(err)
66+
}
4767

4868
if simcli.FlagGenesisTimeValue == 0 {
4969
// use genesis timestamp if no custom timestamp is provided (i.e no random timestamp)
@@ -65,11 +85,11 @@ func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager) simty
6585
if err != nil {
6686
panic(err)
6787
}
68-
appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams)
88+
appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams, genesisState)
6989

7090
default:
7191
appParams := make(simtypes.AppParams)
72-
appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams)
92+
appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams, genesisState)
7393
}
7494

7595
rawState := make(map[string]json.RawMessage)
@@ -84,8 +104,7 @@ func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager) simty
84104
}
85105

86106
stakingState := new(stakingtypes.GenesisState)
87-
err = cdc.UnmarshalJSON(stakingStateBz, stakingState)
88-
if err != nil {
107+
if err = cdc.UnmarshalJSON(stakingStateBz, stakingState); err != nil {
89108
panic(err)
90109
}
91110
// compute not bonded balance
@@ -104,8 +123,7 @@ func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager) simty
104123
panic("bank genesis state is missing")
105124
}
106125
bankState := new(banktypes.GenesisState)
107-
err = cdc.UnmarshalJSON(bankStateBz, bankState)
108-
if err != nil {
126+
if err = cdc.UnmarshalJSON(bankStateBz, bankState); err != nil {
109127
panic(err)
110128
}
111129

@@ -140,24 +158,27 @@ func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager) simty
140158
// AppStateRandomizedFn creates calls each module's GenesisState generator function
141159
// and creates the simulation params
142160
func AppStateRandomizedFn(
143-
simManager *module.SimulationManager, r *rand.Rand, cdc codec.JSONCodec,
144-
accs []simtypes.Account, genesisTimestamp time.Time, appParams simtypes.AppParams,
161+
simManager *module.SimulationManager,
162+
r *rand.Rand,
163+
cdc codec.JSONCodec,
164+
accs []simtypes.Account,
165+
genesisTimestamp time.Time,
166+
appParams simtypes.AppParams,
167+
genesisState map[string]json.RawMessage,
145168
) (json.RawMessage, []simtypes.Account) {
146169
numAccs := int64(len(accs))
147-
genesisState := ModuleBasics.DefaultGenesis(cdc)
148-
149170
// generate a random amount of initial stake coins and a random initial
150171
// number of bonded accounts
151172
var (
152173
numInitiallyBonded int64
153174
initialStake math.Int
154175
)
155176
appParams.GetOrGenerate(
156-
cdc, simappparams.StakePerAccount, &initialStake, r,
177+
cdc, StakePerAccount, &initialStake, r,
157178
func(r *rand.Rand) { initialStake = math.NewInt(r.Int63n(1e12)) },
158179
)
159180
appParams.GetOrGenerate(
160-
cdc, simappparams.InitiallyBondedValidators, &numInitiallyBonded, r,
181+
cdc, InitiallyBondedValidators, &numInitiallyBonded, r,
161182
func(r *rand.Rand) { numInitiallyBonded = int64(r.Intn(300)) },
162183
)
163184

@@ -197,23 +218,33 @@ func AppStateRandomizedFn(
197218

198219
// AppStateFromGenesisFileFn util function to generate the genesis AppState
199220
// from a genesis.json file.
221+
<<<<<<< HEAD:simapp/state.go
200222
func AppStateFromGenesisFileFn(r io.Reader, cdc codec.JSONCodec, genesisFile string) (tmtypes.GenesisDoc, []simtypes.Account) {
223+
=======
224+
func AppStateFromGenesisFileFn(r io.Reader, cdc codec.JSONCodec, genesisFile string) (cmttypes.GenesisDoc, []simtypes.Account, error) {
225+
>>>>>>> 4f13b5b31 (refactor!: extract `AppStateFn` out of simapp (#14977)):testutil/sims/state_helpers.go
201226
bytes, err := os.ReadFile(genesisFile)
202227
if err != nil {
203228
panic(err)
204229
}
205230

231+
<<<<<<< HEAD:simapp/state.go
206232
var genesis tmtypes.GenesisDoc
207233
// NOTE: Tendermint uses a custom JSON decoder for GenesisDoc
208234
err = tmjson.Unmarshal(bytes, &genesis)
209235
if err != nil {
210236
panic(err)
237+
=======
238+
var genesis cmttypes.GenesisDoc
239+
// NOTE: CometBFT uses a custom JSON decoder for GenesisDoc
240+
if err = cmtjson.Unmarshal(bytes, &genesis); err != nil {
241+
return genesis, nil, err
242+
>>>>>>> 4f13b5b31 (refactor!: extract `AppStateFn` out of simapp (#14977)):testutil/sims/state_helpers.go
211243
}
212244

213-
var appState GenesisState
214-
err = json.Unmarshal(genesis.AppState, &appState)
215-
if err != nil {
216-
panic(err)
245+
var appState map[string]json.RawMessage
246+
if err = json.Unmarshal(genesis.AppState, &appState); err != nil {
247+
return genesis, nil, err
217248
}
218249

219250
var authGenesis authtypes.GenesisState
@@ -233,15 +264,15 @@ func AppStateFromGenesisFileFn(r io.Reader, cdc codec.JSONCodec, genesisFile str
233264

234265
privKey := secp256k1.GenPrivKeyFromSecret(privkeySeed)
235266

236-
a, ok := acc.GetCachedValue().(authtypes.AccountI)
267+
a, ok := acc.GetCachedValue().(sdk.AccountI)
237268
if !ok {
238-
panic("expected account")
269+
return genesis, nil, fmt.Errorf("expected account")
239270
}
240271

241272
// create simulator accounts
242273
simAcc := simtypes.Account{PrivKey: privKey, PubKey: privKey.PubKey(), Address: a.GetAddress()}
243274
newAccs[i] = simAcc
244275
}
245276

246-
return genesis, newAccs
277+
return genesis, newAccs, nil
247278
}

0 commit comments

Comments
 (0)