Skip to content

Commit

Permalink
refactor(genutil): Use sdk types genesis validator (#21678)
Browse files Browse the repository at this point in the history
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Matt Kocubinski <mkocubinski@gmail.com>
  • Loading branch information
3 people authored Oct 9, 2024
1 parent 325728a commit 4aeb053
Show file tree
Hide file tree
Showing 24 changed files with 510 additions and 93 deletions.
53 changes: 53 additions & 0 deletions crypto/codec/pubkey.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package codec

import (
"cosmossdk.io/errors"

cryptokeys "github.com/cosmos/cosmos-sdk/crypto/keys"
bls12_381 "github.com/cosmos/cosmos-sdk/crypto/keys/bls12_381"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)

func PubKeyToProto(pk cryptokeys.JSONPubkey) (cryptotypes.PubKey, error) {
switch pk.KeyType {
case ed25519.PubKeyName:
return &ed25519.PubKey{
Key: pk.Value,
}, nil
case secp256k1.PubKeyName:
return &secp256k1.PubKey{
Key: pk.Value,
}, nil
case bls12_381.PubKeyName:
return &bls12_381.PubKey{
Key: pk.Value,
}, nil
default:
return nil, errors.Wrapf(sdkerrors.ErrInvalidType, "cannot convert %v to proto public key", pk)
}
}

func PubKeyFromProto(pk cryptotypes.PubKey) (cryptokeys.JSONPubkey, error) {
switch pk := pk.(type) {
case *ed25519.PubKey:
return cryptokeys.JSONPubkey{
KeyType: ed25519.PubKeyName,
Value: pk.Bytes(),
}, nil
case *secp256k1.PubKey:
return cryptokeys.JSONPubkey{
KeyType: secp256k1.PubKeyName,
Value: pk.Bytes(),
}, nil
case *bls12_381.PubKey:
return cryptokeys.JSONPubkey{
KeyType: bls12_381.PubKeyName,
Value: pk.Bytes(),
}, nil
default:
return cryptokeys.JSONPubkey{}, errors.Wrapf(sdkerrors.ErrInvalidType, "cannot convert %v from proto public key", pk)
}
}
41 changes: 41 additions & 0 deletions crypto/keys/jsonkey.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package keys

import (
"github.com/cosmos/cosmos-sdk/crypto/keys/bls12_381"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/crypto/types"
)

// JSONPubKey defines a public key that are parse from JSON file.
// convert PubKey to JSONPubKey needs a in between step
type JSONPubkey struct {
KeyType string `json:"type"`
Value []byte `json:"value"`
}

func (pk JSONPubkey) Address() types.Address {
switch pk.KeyType {
case ed25519.PubKeyName:
ed25519 := ed25519.PubKey{
Key: pk.Value,
}
return ed25519.Address()
case secp256k1.PubKeyName:
secp256k1 := secp256k1.PubKey{
Key: pk.Value,
}
return secp256k1.Address()
case bls12_381.PubKeyName:
bls12_381 := bls12_381.PubKey{
Key: pk.Value,
}
return bls12_381.Address()
default:
return nil
}
}

func (pk JSONPubkey) Bytes() []byte {
return pk.Value
}
5 changes: 0 additions & 5 deletions runtime/v2/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,6 @@ func (a *App[T]) Close() error {
return nil
}

// GetStore returns the app store.
func (a *App[T]) GetStore() Store {
return a.db
}

func (a *App[T]) GetAppManager() *appmanager.AppManager[T] {
return a.AppManager
}
Expand Down
2 changes: 1 addition & 1 deletion runtime/v2/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ func (a *AppBuilder[T]) Build(opts ...AppBuilderOption[T]) (*App[T], error) {
return nil, errors.New("cannot init genesis on non-zero state")
}
genesisCtx := services.NewGenesisContext(a.branch(zeroState))
genesisState, err := genesisCtx.Run(ctx, func(ctx context.Context) error {
genesisState, err := genesisCtx.Mutate(ctx, func(ctx context.Context) error {
err = a.app.moduleManager.InitGenesisJSON(ctx, genesisJSON, txHandler)
if err != nil {
return fmt.Errorf("failed to init genesis: %w", err)
Expand Down
10 changes: 7 additions & 3 deletions runtime/v2/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,15 +230,17 @@ func (m *MM[T]) ExportGenesisForModules(
channels[moduleName] = make(chan genesisResult)
go func(moduleI ModuleI, ch chan genesisResult) {
genesisCtx := services.NewGenesisContext(stateFactory())
_, _ = genesisCtx.Run(ctx, func(ctx context.Context) error {
err := genesisCtx.Read(ctx, func(ctx context.Context) error {
jm, err := moduleI.ExportGenesis(ctx)
if err != nil {
ch <- genesisResult{nil, err}
return err
}
ch <- genesisResult{jm, nil}
return nil
})
if err != nil {
ch <- genesisResult{nil, err}
}
}(moduleI, channels[moduleName])
}

Expand Down Expand Up @@ -783,7 +785,9 @@ func messagePassingInterceptor(msg transaction.Msg) grpc.UnaryServerInterceptor
}

// requestFullNameFromMethodDesc returns the fully-qualified name of the request message and response of the provided service's method.
func requestFullNameFromMethodDesc(sd *grpc.ServiceDesc, method grpc.MethodDesc) (protoreflect.FullName, protoreflect.FullName, error) {
func requestFullNameFromMethodDesc(sd *grpc.ServiceDesc, method grpc.MethodDesc) (
protoreflect.FullName, protoreflect.FullName, error,
) {
methodFullName := protoreflect.FullName(fmt.Sprintf("%s.%s", sd.ServiceName, method.MethodName))
desc, err := gogoproto.HybridResolver.FindDescriptorByName(methodFullName)
if err != nil {
Expand Down
51 changes: 43 additions & 8 deletions runtime/v2/services/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
var (
_ store.KVStoreService = (*GenesisKVStoreService)(nil)
_ header.Service = (*GenesisHeaderService)(nil)
_ store.KVStore = (*readonlyKVStore)(nil)
)

type genesisContextKeyType struct{}
Expand All @@ -21,28 +22,41 @@ var genesisContextKey = genesisContextKeyType{}
// it backs the store.KVStoreService and header.Service interface implementations
// defined in this file.
type genesisContext struct {
state store.WriterMap
state store.ReaderMap
}

// NewGenesisContext creates a new genesis context.
func NewGenesisContext(state store.WriterMap) genesisContext {
func NewGenesisContext(state store.ReaderMap) genesisContext {
return genesisContext{
state: state,
}
}

// Run runs the provided function within the genesis context and returns an
// Mutate runs the provided function within the genesis context and returns an
// updated store.WriterMap containing the state modifications made during InitGenesis.
func (g *genesisContext) Run(
func (g genesisContext) Mutate(
ctx context.Context,
fn func(ctx context.Context) error,
) (store.WriterMap, error) {
writerMap, ok := g.state.(store.WriterMap)
if !ok {
return nil, fmt.Errorf("mutate requires a store.WriterMap, got a %T", g.state)
}
ctx = context.WithValue(ctx, genesisContextKey, g)
err := fn(ctx)
if err != nil {
return nil, err
}
return g.state, nil
return writerMap, nil
}

// Read runs the provided function within the genesis context.
func (g genesisContext) Read(
ctx context.Context,
fn func(ctx context.Context) error,
) error {
ctx = context.WithValue(ctx, genesisContextKey, g)
return fn(ctx)
}

// GenesisKVStoreService is a store.KVStoreService implementation that is used during
Expand Down Expand Up @@ -71,15 +85,24 @@ func (g *GenesisKVStoreService) OpenKVStore(ctx context.Context) store.KVStore {
if v == nil {
return g.executionService.OpenKVStore(ctx)
}
genCtx, ok := v.(*genesisContext)
genCtx, ok := v.(genesisContext)
if !ok {
panic(fmt.Errorf("unexpected genesis context type: %T", v))
}
state, err := genCtx.state.GetWriter(g.actor)
writerMap, ok := genCtx.state.(store.WriterMap)
if ok {
state, err := writerMap.GetWriter(g.actor)
if err != nil {
panic(err)
}
return state

}
state, err := genCtx.state.GetReader(g.actor)
if err != nil {
panic(err)
}
return state
return readonlyKVStore{state}
}

// GenesisHeaderService is a header.Service implementation that is used during
Expand All @@ -105,3 +128,15 @@ func NewGenesisHeaderService(executionService header.Service) *GenesisHeaderServ
executionService: executionService,
}
}

type readonlyKVStore struct {
store.Reader
}

func (r readonlyKVStore) Set(key, value []byte) error {
panic("tried to call Set on a readonly store")
}

func (r readonlyKVStore) Delete(key []byte) error {
panic("tried to call Delete on a readonly store")
}
4 changes: 2 additions & 2 deletions server/types/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (

cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1"
cmtcrypto "github.com/cometbft/cometbft/crypto"
cmttypes "github.com/cometbft/cometbft/types"
"github.com/cosmos/gogoproto/grpc"

"cosmossdk.io/core/server"
Expand All @@ -18,6 +17,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/server/api"
"github.com/cosmos/cosmos-sdk/server/config"
sdk "github.com/cosmos/cosmos-sdk/types"
)

type (
Expand Down Expand Up @@ -76,7 +76,7 @@ type (
// AppState is the application state as JSON.
AppState json.RawMessage
// Validators is the exported validator set.
Validators []cmttypes.GenesisValidator
Validators []sdk.GenesisValidator
// Height is the app's latest block height.
Height int64
// ConsensusParams are the exported consensus params for ABCI.
Expand Down
19 changes: 1 addition & 18 deletions simapp/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@ import (
"fmt"

cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1"
cmttypes "github.com/cometbft/cometbft/types"

"cosmossdk.io/collections"
storetypes "cosmossdk.io/store/types"
slashingtypes "cosmossdk.io/x/slashing/types"
"cosmossdk.io/x/staking"
stakingtypes "cosmossdk.io/x/staking/types"

cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
Expand Down Expand Up @@ -43,25 +41,10 @@ func (app *SimApp) ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAd
}

validators, err := staking.WriteValidators(ctx, app.StakingKeeper)
cmtValidators := []cmttypes.GenesisValidator{}
for _, val := range validators {
cmtPk, err := cryptocodec.ToCmtPubKeyInterface(val.PubKey)
if err != nil {
return servertypes.ExportedApp{}, err
}
cmtVal := cmttypes.GenesisValidator{
Address: val.Address.Bytes(),
PubKey: cmtPk,
Power: val.Power,
Name: val.Name,
}

cmtValidators = append(cmtValidators, cmtVal)
}

return servertypes.ExportedApp{
AppState: appState,
Validators: cmtValidators,
Validators: validators,
Height: height,
ConsensusParams: app.BaseApp.GetConsensusParams(ctx),
}, err
Expand Down
13 changes: 9 additions & 4 deletions simapp/v2/app_di.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ import (
"cosmossdk.io/log"
"cosmossdk.io/runtime/v2"
serverstore "cosmossdk.io/server/v2/store"
"cosmossdk.io/store/v2"
"cosmossdk.io/store/v2/root"
basedepinject "cosmossdk.io/x/accounts/defaults/base/depinject"
lockupdepinject "cosmossdk.io/x/accounts/defaults/lockup/depinject"
multisigdepinject "cosmossdk.io/x/accounts/defaults/multisig/depinject"
stakingkeeper "cosmossdk.io/x/staking/keeper"
upgradekeeper "cosmossdk.io/x/upgrade/keeper"

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

// required keepers during wiring
// others keepers are all in the app
UpgradeKeeper *upgradekeeper.Keeper
StakingKeeper *stakingkeeper.Keeper
}

func init() {
Expand Down Expand Up @@ -161,6 +165,7 @@ func NewSimApp[T transaction.Tx](
&app.txConfig,
&app.interfaceRegistry,
&app.UpgradeKeeper,
&app.StakingKeeper,
); err != nil {
panic(err)
}
Expand All @@ -170,7 +175,8 @@ func NewSimApp[T transaction.Tx](
if err != nil {
panic(err)
}
_, err = storeBuilder.Build(logger, storeConfig)

app.store, err = storeBuilder.Build(logger, storeConfig)
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -213,7 +219,6 @@ func (app *SimApp[T]) TxConfig() client.TxConfig {
return app.txConfig
}

// GetStore gets the app store.
func (app *SimApp[T]) GetStore() any {
return app.App.GetStore()
func (app *SimApp[T]) GetStore() store.RootStore {
return app.store
}
5 changes: 2 additions & 3 deletions simapp/v2/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
sdkmath "cosmossdk.io/math"
"cosmossdk.io/runtime/v2"
serverv2 "cosmossdk.io/server/v2"
comettypes "cosmossdk.io/server/v2/cometbft/types"
serverv2store "cosmossdk.io/server/v2/store"
"cosmossdk.io/store/v2/db"
banktypes "cosmossdk.io/x/bank/types"
Expand Down Expand Up @@ -75,7 +74,7 @@ func NewTestApp(t *testing.T) (*SimApp[transaction.Tx], context.Context) {
genesisBytes, err := json.Marshal(genesis)
require.NoError(t, err)

st := app.GetStore().(comettypes.Store)
st := app.GetStore()
ci, err := st.LastCommitID()
require.NoError(t, err)

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

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

st := app.GetStore().(comettypes.Store)
st := app.GetStore()
ci, err := st.LastCommitID()
require.NoError(t, err)

Expand Down
Loading

0 comments on commit 4aeb053

Please sign in to comment.