Skip to content

Commit 4aeb053

Browse files
sontrinh16coderabbitai[bot]kocubinski
authored
refactor(genutil): Use sdk types genesis validator (#21678)
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> Co-authored-by: Matt Kocubinski <mkocubinski@gmail.com>
1 parent 325728a commit 4aeb053

24 files changed

Lines changed: 510 additions & 93 deletions

File tree

crypto/codec/pubkey.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package codec
2+
3+
import (
4+
"cosmossdk.io/errors"
5+
6+
cryptokeys "github.com/cosmos/cosmos-sdk/crypto/keys"
7+
bls12_381 "github.com/cosmos/cosmos-sdk/crypto/keys/bls12_381"
8+
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
9+
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
10+
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
11+
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
12+
)
13+
14+
func PubKeyToProto(pk cryptokeys.JSONPubkey) (cryptotypes.PubKey, error) {
15+
switch pk.KeyType {
16+
case ed25519.PubKeyName:
17+
return &ed25519.PubKey{
18+
Key: pk.Value,
19+
}, nil
20+
case secp256k1.PubKeyName:
21+
return &secp256k1.PubKey{
22+
Key: pk.Value,
23+
}, nil
24+
case bls12_381.PubKeyName:
25+
return &bls12_381.PubKey{
26+
Key: pk.Value,
27+
}, nil
28+
default:
29+
return nil, errors.Wrapf(sdkerrors.ErrInvalidType, "cannot convert %v to proto public key", pk)
30+
}
31+
}
32+
33+
func PubKeyFromProto(pk cryptotypes.PubKey) (cryptokeys.JSONPubkey, error) {
34+
switch pk := pk.(type) {
35+
case *ed25519.PubKey:
36+
return cryptokeys.JSONPubkey{
37+
KeyType: ed25519.PubKeyName,
38+
Value: pk.Bytes(),
39+
}, nil
40+
case *secp256k1.PubKey:
41+
return cryptokeys.JSONPubkey{
42+
KeyType: secp256k1.PubKeyName,
43+
Value: pk.Bytes(),
44+
}, nil
45+
case *bls12_381.PubKey:
46+
return cryptokeys.JSONPubkey{
47+
KeyType: bls12_381.PubKeyName,
48+
Value: pk.Bytes(),
49+
}, nil
50+
default:
51+
return cryptokeys.JSONPubkey{}, errors.Wrapf(sdkerrors.ErrInvalidType, "cannot convert %v from proto public key", pk)
52+
}
53+
}

crypto/keys/jsonkey.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package keys
2+
3+
import (
4+
"github.com/cosmos/cosmos-sdk/crypto/keys/bls12_381"
5+
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
6+
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
7+
"github.com/cosmos/cosmos-sdk/crypto/types"
8+
)
9+
10+
// JSONPubKey defines a public key that are parse from JSON file.
11+
// convert PubKey to JSONPubKey needs a in between step
12+
type JSONPubkey struct {
13+
KeyType string `json:"type"`
14+
Value []byte `json:"value"`
15+
}
16+
17+
func (pk JSONPubkey) Address() types.Address {
18+
switch pk.KeyType {
19+
case ed25519.PubKeyName:
20+
ed25519 := ed25519.PubKey{
21+
Key: pk.Value,
22+
}
23+
return ed25519.Address()
24+
case secp256k1.PubKeyName:
25+
secp256k1 := secp256k1.PubKey{
26+
Key: pk.Value,
27+
}
28+
return secp256k1.Address()
29+
case bls12_381.PubKeyName:
30+
bls12_381 := bls12_381.PubKey{
31+
Key: pk.Value,
32+
}
33+
return bls12_381.Address()
34+
default:
35+
return nil
36+
}
37+
}
38+
39+
func (pk JSONPubkey) Bytes() []byte {
40+
return pk.Value
41+
}

runtime/v2/app.go

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,11 +89,6 @@ func (a *App[T]) Close() error {
8989
return nil
9090
}
9191

92-
// GetStore returns the app store.
93-
func (a *App[T]) GetStore() Store {
94-
return a.db
95-
}
96-
9792
func (a *App[T]) GetAppManager() *appmanager.AppManager[T] {
9893
return a.AppManager
9994
}

runtime/v2/builder.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ func (a *AppBuilder[T]) Build(opts ...AppBuilderOption[T]) (*App[T], error) {
144144
return nil, errors.New("cannot init genesis on non-zero state")
145145
}
146146
genesisCtx := services.NewGenesisContext(a.branch(zeroState))
147-
genesisState, err := genesisCtx.Run(ctx, func(ctx context.Context) error {
147+
genesisState, err := genesisCtx.Mutate(ctx, func(ctx context.Context) error {
148148
err = a.app.moduleManager.InitGenesisJSON(ctx, genesisJSON, txHandler)
149149
if err != nil {
150150
return fmt.Errorf("failed to init genesis: %w", err)

runtime/v2/manager.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,15 +230,17 @@ func (m *MM[T]) ExportGenesisForModules(
230230
channels[moduleName] = make(chan genesisResult)
231231
go func(moduleI ModuleI, ch chan genesisResult) {
232232
genesisCtx := services.NewGenesisContext(stateFactory())
233-
_, _ = genesisCtx.Run(ctx, func(ctx context.Context) error {
233+
err := genesisCtx.Read(ctx, func(ctx context.Context) error {
234234
jm, err := moduleI.ExportGenesis(ctx)
235235
if err != nil {
236-
ch <- genesisResult{nil, err}
237236
return err
238237
}
239238
ch <- genesisResult{jm, nil}
240239
return nil
241240
})
241+
if err != nil {
242+
ch <- genesisResult{nil, err}
243+
}
242244
}(moduleI, channels[moduleName])
243245
}
244246

@@ -783,7 +785,9 @@ func messagePassingInterceptor(msg transaction.Msg) grpc.UnaryServerInterceptor
783785
}
784786

785787
// requestFullNameFromMethodDesc returns the fully-qualified name of the request message and response of the provided service's method.
786-
func requestFullNameFromMethodDesc(sd *grpc.ServiceDesc, method grpc.MethodDesc) (protoreflect.FullName, protoreflect.FullName, error) {
788+
func requestFullNameFromMethodDesc(sd *grpc.ServiceDesc, method grpc.MethodDesc) (
789+
protoreflect.FullName, protoreflect.FullName, error,
790+
) {
787791
methodFullName := protoreflect.FullName(fmt.Sprintf("%s.%s", sd.ServiceName, method.MethodName))
788792
desc, err := gogoproto.HybridResolver.FindDescriptorByName(methodFullName)
789793
if err != nil {

runtime/v2/services/genesis.go

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
var (
1212
_ store.KVStoreService = (*GenesisKVStoreService)(nil)
1313
_ header.Service = (*GenesisHeaderService)(nil)
14+
_ store.KVStore = (*readonlyKVStore)(nil)
1415
)
1516

1617
type genesisContextKeyType struct{}
@@ -21,28 +22,41 @@ var genesisContextKey = genesisContextKeyType{}
2122
// it backs the store.KVStoreService and header.Service interface implementations
2223
// defined in this file.
2324
type genesisContext struct {
24-
state store.WriterMap
25+
state store.ReaderMap
2526
}
2627

2728
// NewGenesisContext creates a new genesis context.
28-
func NewGenesisContext(state store.WriterMap) genesisContext {
29+
func NewGenesisContext(state store.ReaderMap) genesisContext {
2930
return genesisContext{
3031
state: state,
3132
}
3233
}
3334

34-
// Run runs the provided function within the genesis context and returns an
35+
// Mutate runs the provided function within the genesis context and returns an
3536
// updated store.WriterMap containing the state modifications made during InitGenesis.
36-
func (g *genesisContext) Run(
37+
func (g genesisContext) Mutate(
3738
ctx context.Context,
3839
fn func(ctx context.Context) error,
3940
) (store.WriterMap, error) {
41+
writerMap, ok := g.state.(store.WriterMap)
42+
if !ok {
43+
return nil, fmt.Errorf("mutate requires a store.WriterMap, got a %T", g.state)
44+
}
4045
ctx = context.WithValue(ctx, genesisContextKey, g)
4146
err := fn(ctx)
4247
if err != nil {
4348
return nil, err
4449
}
45-
return g.state, nil
50+
return writerMap, nil
51+
}
52+
53+
// Read runs the provided function within the genesis context.
54+
func (g genesisContext) Read(
55+
ctx context.Context,
56+
fn func(ctx context.Context) error,
57+
) error {
58+
ctx = context.WithValue(ctx, genesisContextKey, g)
59+
return fn(ctx)
4660
}
4761

4862
// GenesisKVStoreService is a store.KVStoreService implementation that is used during
@@ -71,15 +85,24 @@ func (g *GenesisKVStoreService) OpenKVStore(ctx context.Context) store.KVStore {
7185
if v == nil {
7286
return g.executionService.OpenKVStore(ctx)
7387
}
74-
genCtx, ok := v.(*genesisContext)
88+
genCtx, ok := v.(genesisContext)
7589
if !ok {
7690
panic(fmt.Errorf("unexpected genesis context type: %T", v))
7791
}
78-
state, err := genCtx.state.GetWriter(g.actor)
92+
writerMap, ok := genCtx.state.(store.WriterMap)
93+
if ok {
94+
state, err := writerMap.GetWriter(g.actor)
95+
if err != nil {
96+
panic(err)
97+
}
98+
return state
99+
100+
}
101+
state, err := genCtx.state.GetReader(g.actor)
79102
if err != nil {
80103
panic(err)
81104
}
82-
return state
105+
return readonlyKVStore{state}
83106
}
84107

85108
// GenesisHeaderService is a header.Service implementation that is used during
@@ -105,3 +128,15 @@ func NewGenesisHeaderService(executionService header.Service) *GenesisHeaderServ
105128
executionService: executionService,
106129
}
107130
}
131+
132+
type readonlyKVStore struct {
133+
store.Reader
134+
}
135+
136+
func (r readonlyKVStore) Set(key, value []byte) error {
137+
panic("tried to call Set on a readonly store")
138+
}
139+
140+
func (r readonlyKVStore) Delete(key []byte) error {
141+
panic("tried to call Delete on a readonly store")
142+
}

server/types/app.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66

77
cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1"
88
cmtcrypto "github.com/cometbft/cometbft/crypto"
9-
cmttypes "github.com/cometbft/cometbft/types"
109
"github.com/cosmos/gogoproto/grpc"
1110

1211
"cosmossdk.io/core/server"
@@ -18,6 +17,7 @@ import (
1817
"github.com/cosmos/cosmos-sdk/client"
1918
"github.com/cosmos/cosmos-sdk/server/api"
2019
"github.com/cosmos/cosmos-sdk/server/config"
20+
sdk "github.com/cosmos/cosmos-sdk/types"
2121
)
2222

2323
type (
@@ -76,7 +76,7 @@ type (
7676
// AppState is the application state as JSON.
7777
AppState json.RawMessage
7878
// Validators is the exported validator set.
79-
Validators []cmttypes.GenesisValidator
79+
Validators []sdk.GenesisValidator
8080
// Height is the app's latest block height.
8181
Height int64
8282
// ConsensusParams are the exported consensus params for ABCI.

simapp/export.go

Lines changed: 1 addition & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,13 @@ import (
55
"fmt"
66

77
cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1"
8-
cmttypes "github.com/cometbft/cometbft/types"
98

109
"cosmossdk.io/collections"
1110
storetypes "cosmossdk.io/store/types"
1211
slashingtypes "cosmossdk.io/x/slashing/types"
1312
"cosmossdk.io/x/staking"
1413
stakingtypes "cosmossdk.io/x/staking/types"
1514

16-
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
1715
servertypes "github.com/cosmos/cosmos-sdk/server/types"
1816
sdk "github.com/cosmos/cosmos-sdk/types"
1917
)
@@ -43,25 +41,10 @@ func (app *SimApp) ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAd
4341
}
4442

4543
validators, err := staking.WriteValidators(ctx, app.StakingKeeper)
46-
cmtValidators := []cmttypes.GenesisValidator{}
47-
for _, val := range validators {
48-
cmtPk, err := cryptocodec.ToCmtPubKeyInterface(val.PubKey)
49-
if err != nil {
50-
return servertypes.ExportedApp{}, err
51-
}
52-
cmtVal := cmttypes.GenesisValidator{
53-
Address: val.Address.Bytes(),
54-
PubKey: cmtPk,
55-
Power: val.Power,
56-
Name: val.Name,
57-
}
58-
59-
cmtValidators = append(cmtValidators, cmtVal)
60-
}
6144

6245
return servertypes.ExportedApp{
6346
AppState: appState,
64-
Validators: cmtValidators,
47+
Validators: validators,
6548
Height: height,
6649
ConsensusParams: app.BaseApp.GetConsensusParams(ctx),
6750
}, err

simapp/v2/app_di.go

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,12 @@ import (
1313
"cosmossdk.io/log"
1414
"cosmossdk.io/runtime/v2"
1515
serverstore "cosmossdk.io/server/v2/store"
16+
"cosmossdk.io/store/v2"
1617
"cosmossdk.io/store/v2/root"
1718
basedepinject "cosmossdk.io/x/accounts/defaults/base/depinject"
1819
lockupdepinject "cosmossdk.io/x/accounts/defaults/lockup/depinject"
1920
multisigdepinject "cosmossdk.io/x/accounts/defaults/multisig/depinject"
21+
stakingkeeper "cosmossdk.io/x/staking/keeper"
2022
upgradekeeper "cosmossdk.io/x/upgrade/keeper"
2123

2224
"github.com/cosmos/cosmos-sdk/client"
@@ -38,10 +40,12 @@ type SimApp[T transaction.Tx] struct {
3840
appCodec codec.Codec
3941
txConfig client.TxConfig
4042
interfaceRegistry codectypes.InterfaceRegistry
43+
store store.RootStore
4144

4245
// required keepers during wiring
4346
// others keepers are all in the app
4447
UpgradeKeeper *upgradekeeper.Keeper
48+
StakingKeeper *stakingkeeper.Keeper
4549
}
4650

4751
func init() {
@@ -161,6 +165,7 @@ func NewSimApp[T transaction.Tx](
161165
&app.txConfig,
162166
&app.interfaceRegistry,
163167
&app.UpgradeKeeper,
168+
&app.StakingKeeper,
164169
); err != nil {
165170
panic(err)
166171
}
@@ -170,7 +175,8 @@ func NewSimApp[T transaction.Tx](
170175
if err != nil {
171176
panic(err)
172177
}
173-
_, err = storeBuilder.Build(logger, storeConfig)
178+
179+
app.store, err = storeBuilder.Build(logger, storeConfig)
174180
if err != nil {
175181
panic(err)
176182
}
@@ -213,7 +219,6 @@ func (app *SimApp[T]) TxConfig() client.TxConfig {
213219
return app.txConfig
214220
}
215221

216-
// GetStore gets the app store.
217-
func (app *SimApp[T]) GetStore() any {
218-
return app.App.GetStore()
222+
func (app *SimApp[T]) GetStore() store.RootStore {
223+
return app.store
219224
}

simapp/v2/app_test.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import (
2020
sdkmath "cosmossdk.io/math"
2121
"cosmossdk.io/runtime/v2"
2222
serverv2 "cosmossdk.io/server/v2"
23-
comettypes "cosmossdk.io/server/v2/cometbft/types"
2423
serverv2store "cosmossdk.io/server/v2/store"
2524
"cosmossdk.io/store/v2/db"
2625
banktypes "cosmossdk.io/x/bank/types"
@@ -75,7 +74,7 @@ func NewTestApp(t *testing.T) (*SimApp[transaction.Tx], context.Context) {
7574
genesisBytes, err := json.Marshal(genesis)
7675
require.NoError(t, err)
7776

78-
st := app.GetStore().(comettypes.Store)
77+
st := app.GetStore()
7978
ci, err := st.LastCommitID()
8079
require.NoError(t, err)
8180

@@ -111,7 +110,7 @@ func MoveNextBlock(t *testing.T, app *SimApp[transaction.Tx], ctx context.Contex
111110

112111
bz := sha256.Sum256([]byte{})
113112

114-
st := app.GetStore().(comettypes.Store)
113+
st := app.GetStore()
115114
ci, err := st.LastCommitID()
116115
require.NoError(t, err)
117116

0 commit comments

Comments
 (0)