From a11ae68d9d53b0a3d781ac28edf25c5e7aa8a6e2 Mon Sep 17 00:00:00 2001 From: mpoke Date: Sun, 20 Oct 2024 20:32:45 +0200 Subject: [PATCH 01/12] deprecate PacketMaturityTimeKey --- x/ccv/consumer/keeper/keeper.go | 84 ------------------------------- x/ccv/consumer/types/keys.go | 27 ++-------- x/ccv/consumer/types/keys_test.go | 4 +- 3 files changed, 5 insertions(+), 110 deletions(-) diff --git a/x/ccv/consumer/keeper/keeper.go b/x/ccv/consumer/keeper/keeper.go index cd5b2f7255..ecb3f1abd3 100644 --- a/x/ccv/consumer/keeper/keeper.go +++ b/x/ccv/consumer/keeper/keeper.go @@ -4,7 +4,6 @@ import ( "encoding/binary" "fmt" "reflect" - "time" capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" @@ -357,89 +356,6 @@ func (k Keeper) GetLastStandaloneValidators(ctx sdk.Context) ([]stakingtypes.Val return k.GetLastBondedValidators(ctx) } -// GetElapsedPacketMaturityTimes returns a slice of already elapsed PacketMaturityTimes, sorted by maturity times, -// i.e., the slice contains the IDs of the matured VSCPackets. -func (k Keeper) GetElapsedPacketMaturityTimes(ctx sdk.Context) (maturingVSCPackets []types.MaturingVSCPacket) { - store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.PacketMaturityTimeKeyPrefix()) - - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var maturingVSCPacket types.MaturingVSCPacket - if err := maturingVSCPacket.Unmarshal(iterator.Value()); err != nil { - // An error here would indicate something is very wrong, - // the MaturingVSCPackets are assumed to be correctly serialized in SetPacketMaturityTime. - panic(fmt.Errorf("failed to unmarshal MaturingVSCPacket: %w", err)) - } - - // If the current block time is before maturity time then stop the iteration. - // This is possible since the iteration over PacketMaturityTimes is in order - // of maturity times - if ctx.BlockTime().Before(maturingVSCPacket.MaturityTime) { - break - } - - maturingVSCPackets = append(maturingVSCPackets, maturingVSCPacket) - } - return maturingVSCPackets -} - -// GetAllPacketMaturityTimes returns a slice of all PacketMaturityTimes, sorted by maturity times. -// -// Note that PacketMaturityTimes are stored under keys with the following format: -// PacketMaturityTimeKeyPrefix | maturityTime.UnixNano() | vscID -// Thus, the returned array is in ascending order of maturityTimes. -// If two entries have the same maturityTime, then they are ordered by vscID. -func (k Keeper) GetAllPacketMaturityTimes(ctx sdk.Context) (maturingVSCPackets []types.MaturingVSCPacket) { - store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.PacketMaturityTimeKeyPrefix()) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var maturingVSCPacket types.MaturingVSCPacket - if err := maturingVSCPacket.Unmarshal(iterator.Value()); err != nil { - // An error here would indicate something is very wrong, - // the MaturingVSCPackets are assumed to be correctly serialized in SetPacketMaturityTime. - panic(fmt.Errorf("failed to unmarshal MaturingVSCPacket: %w", err)) - } - - maturingVSCPackets = append(maturingVSCPackets, maturingVSCPacket) - } - return maturingVSCPackets -} - -// SetPacketMaturityTime sets the maturity time for a given received VSC packet id -func (k Keeper) SetPacketMaturityTime(ctx sdk.Context, vscId uint64, maturityTime time.Time) { - store := ctx.KVStore(k.storeKey) - maturingVSCPacket := types.MaturingVSCPacket{ - VscId: vscId, - MaturityTime: maturityTime, - } - bz, err := maturingVSCPacket.Marshal() - if err != nil { - // An error here would indicate something is very wrong, - // maturingVSCPacket is instantiated in this method and should be able to be marshaled. - panic(fmt.Errorf("failed to marshal MaturingVSCPacket: %w", err)) - } - store.Set(types.PacketMaturityTimeKey(vscId, maturityTime), bz) -} - -// PacketMaturityExists checks whether the packet maturity time for a given vscId and maturityTime exists. -// -// Note: this method is only used in testing. -func (k Keeper) PacketMaturityTimeExists(ctx sdk.Context, vscId uint64, maturityTime time.Time) bool { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.PacketMaturityTimeKey(vscId, maturityTime)) - return bz != nil -} - -// DeletePacketMaturityTimes deletes the packet maturity time for a given vscId and maturityTime -func (k Keeper) DeletePacketMaturityTimes(ctx sdk.Context, vscId uint64, maturityTime time.Time) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.PacketMaturityTimeKey(vscId, maturityTime)) -} - // VerifyProviderChain verifies that the chain trying to connect on the channel handshake // is the expected provider chain. func (k Keeper) VerifyProviderChain(ctx sdk.Context, connectionHops []string) error { diff --git a/x/ccv/consumer/types/keys.go b/x/ccv/consumer/types/keys.go index f551a5d79a..bded8ba3bd 100644 --- a/x/ccv/consumer/types/keys.go +++ b/x/ccv/consumer/types/keys.go @@ -4,11 +4,8 @@ import ( "encoding/binary" fmt "fmt" "sort" - time "time" sdk "github.com/cosmos/cosmos-sdk/types" - - ccvtypes "github.com/cosmos/interchain-security/v6/x/ccv/types" ) const ( @@ -59,7 +56,7 @@ const ( HistoricalInfoKeyName = "HistoricalInfoKey" - PacketMaturityTimeKeyName = "PacketMaturityTimeKey" + DeprecatedPacketMaturityTimeKeyName = "DeprecatedPacketMaturityTimeKey" HeightValsetUpdateIDKeyName = "HeightValsetUpdateIDKey" @@ -127,7 +124,9 @@ func getKeyPrefixes() map[string]byte { HistoricalInfoKeyName: 11, // PacketMaturityTimeKey is the key for storing maturity time for each received VSC packet - PacketMaturityTimeKeyName: 12, + // NOTE: This prefix is deprecated, but left in place to avoid state migrations + // [DEPRECATED] + DeprecatedPacketMaturityTimeKeyName: 12, // HeightValsetUpdateIDKey is the key for storing the mapping from block height to valset update ID HeightValsetUpdateIDKeyName: 13, @@ -263,24 +262,6 @@ func HistoricalInfoKey(height int64) []byte { return append(HistoricalInfoKeyPrefix(), hBytes...) } -// PacketMaturityTimeKeyPrefix returns the key prefix for storing maturity time for each received VSC packet -func PacketMaturityTimeKeyPrefix() []byte { - return []byte{mustGetKeyPrefix(PacketMaturityTimeKeyName)} -} - -// PacketMaturityTimeKey returns the key for storing the maturity time for a given received VSC packet id -func PacketMaturityTimeKey(vscID uint64, maturityTime time.Time) []byte { - ts := uint64(maturityTime.UTC().UnixNano()) - return ccvtypes.AppendMany( - // Append the prefix - PacketMaturityTimeKeyPrefix(), - // Append the time - sdk.Uint64ToBigEndian(ts), - // Append the vscID - sdk.Uint64ToBigEndian(vscID), - ) -} - // HeightValsetUpdateIDKeyPrefix returns the key for storing a valset update ID for a given block height func HeightValsetUpdateIDKeyPrefix() []byte { return []byte{mustGetKeyPrefix(HeightValsetUpdateIDKeyName)} diff --git a/x/ccv/consumer/types/keys_test.go b/x/ccv/consumer/types/keys_test.go index 059699a6d2..fe8522c698 100644 --- a/x/ccv/consumer/types/keys_test.go +++ b/x/ccv/consumer/types/keys_test.go @@ -3,7 +3,6 @@ package types_test import ( "strings" "testing" - "time" "github.com/stretchr/testify/require" @@ -49,7 +48,7 @@ func TestPreserveBytePrefix(t *testing.T) { i++ require.Equal(t, byte(11), consumertypes.HistoricalInfoKeyPrefix()[0]) i++ - require.Equal(t, byte(12), consumertypes.PacketMaturityTimeKeyPrefix()[0]) + // reserve 12 as deprecated i++ require.Equal(t, byte(13), consumertypes.HeightValsetUpdateIDKeyPrefix()[0]) i++ @@ -108,7 +107,6 @@ func getAllFullyDefinedKeys() [][]byte { consumertypes.ProviderChannelIDKey(), consumertypes.PendingChangesKey(), consumertypes.HistoricalInfoKey(0), - consumertypes.PacketMaturityTimeKey(0, time.Time{}), consumertypes.HeightValsetUpdateIDKey(0), consumertypes.OutstandingDowntimeKey(sdk.ConsAddress([]byte{0x05})), consumertypes.CrossChainValidatorKey([]byte{0x05}), From a13b8ba8743056e5bf167f8172596861ed09b7e8 Mon Sep 17 00:00:00 2001 From: mpoke Date: Sun, 20 Oct 2024 20:51:09 +0200 Subject: [PATCH 02/12] remove TestPacketMaturityTime --- x/ccv/consumer/keeper/keeper_test.go | 54 ---------------------------- 1 file changed, 54 deletions(-) diff --git a/x/ccv/consumer/keeper/keeper_test.go b/x/ccv/consumer/keeper/keeper_test.go index 89515033b5..28be9e0d5e 100644 --- a/x/ccv/consumer/keeper/keeper_test.go +++ b/x/ccv/consumer/keeper/keeper_test.go @@ -4,7 +4,6 @@ import ( "bytes" "sort" "testing" - "time" conntypes "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" "github.com/golang/mock/gomock" @@ -198,59 +197,6 @@ func TestGetLastSovereignValidators(t *testing.T) { lastSovVals[0].Description.Moniker) } -// TestPacketMaturityTime tests getter, setter, and iterator functionality for the packet maturity time of a received VSC packet -func TestPacketMaturityTime(t *testing.T) { - ck, ctx, ctrl, _ := testkeeper.GetConsumerKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - defer ctrl.Finish() - - now := time.Now().UTC() - packets := []types.MaturingVSCPacket{ - { - VscId: 2, - MaturityTime: now, - }, - { - VscId: 1, - MaturityTime: now.Add(-time.Hour), - }, - { - VscId: 5, - MaturityTime: now.Add(-2 * time.Hour), - }, - { - VscId: 6, - MaturityTime: now.Add(time.Hour), - }, - } - // sort by MaturityTime and not by VscId - expectedGetAllOrder := []types.MaturingVSCPacket{packets[2], packets[1], packets[0], packets[3]} - // only packets with MaturityTime before or equal to now - expectedGetElapsedOrder := []types.MaturingVSCPacket{packets[2], packets[1], packets[0]} - - // test SetPacketMaturityTime - for _, packet := range packets { - ck.SetPacketMaturityTime(ctx, packet.VscId, packet.MaturityTime) - } - - // test PacketMaturityTimeExists - for _, packet := range packets { - require.True(t, ck.PacketMaturityTimeExists(ctx, packet.VscId, packet.MaturityTime)) - } - - // test GetAllPacketMaturityTimes - maturingVSCPackets := ck.GetAllPacketMaturityTimes(ctx) - require.Len(t, maturingVSCPackets, len(packets)) - require.Equal(t, expectedGetAllOrder, maturingVSCPackets) - - // test GetElapsedPacketMaturityTimes - elapsedMaturingVSCPackets := ck.GetElapsedPacketMaturityTimes(ctx.WithBlockTime(now)) - require.Equal(t, expectedGetElapsedOrder, elapsedMaturingVSCPackets) - - // test DeletePacketMaturityTimes - ck.DeletePacketMaturityTimes(ctx, packets[0].VscId, packets[0].MaturityTime) - require.False(t, ck.PacketMaturityTimeExists(ctx, packets[0].VscId, packets[0].MaturityTime)) -} - // TestCrossChainValidator tests the getter, setter, and deletion method for cross chain validator records func TestCrossChainValidator(t *testing.T) { keeperParams := testkeeper.NewInMemKeeperParams(t) From 68545941173cb268c581affcf21f1b95938465b4 Mon Sep 17 00:00:00 2001 From: mpoke Date: Sun, 20 Oct 2024 20:51:55 +0200 Subject: [PATCH 03/12] update genesis logic --- x/ccv/consumer/keeper/genesis.go | 6 ---- x/ccv/consumer/keeper/genesis_test.go | 20 ----------- x/ccv/consumer/types/genesis.go | 24 ------------- x/ccv/consumer/types/genesis_test.go | 52 +++++---------------------- 4 files changed, 9 insertions(+), 93 deletions(-) diff --git a/x/ccv/consumer/keeper/genesis.go b/x/ccv/consumer/keeper/genesis.go index e45a5fa892..5e850ba351 100644 --- a/x/ccv/consumer/keeper/genesis.go +++ b/x/ccv/consumer/keeper/genesis.go @@ -73,10 +73,6 @@ func (k Keeper) InitGenesis(ctx sdk.Context, state *types.GenesisState) []abci.V if state.ProviderChannelId != "" { // set provider channel ID k.SetProviderChannel(ctx, state.ProviderChannelId) - // set all unbonding sequences - for _, mp := range state.MaturingPackets { - k.SetPacketMaturityTime(ctx, mp.VscId, mp.MaturityTime) - } // set outstanding downtime slashing requests for _, od := range state.OutstandingDowntimeSlashing { consAddr, err := sdk.ConsAddressFromBech32(od.ValidatorConsensusAddress) @@ -141,7 +137,6 @@ func (k Keeper) ExportGenesis(ctx sdk.Context) (genesis *types.GenesisState) { genesis = types.NewRestartGenesisState( clientID, channelID, - k.GetAllPacketMaturityTimes(ctx), valset, k.GetAllHeightToValsetUpdateIDs(ctx), pendingPacketsDepreciated, @@ -161,7 +156,6 @@ func (k Keeper) ExportGenesis(ctx sdk.Context) (genesis *types.GenesisState) { genesis = types.NewRestartGenesisState( clientID, "", - nil, valset, k.GetAllHeightToValsetUpdateIDs(ctx), pendingPacketsDepreciated, diff --git a/x/ccv/consumer/keeper/genesis_test.go b/x/ccv/consumer/keeper/genesis_test.go index 4ea693273a..677397cf07 100644 --- a/x/ccv/consumer/keeper/genesis_test.go +++ b/x/ccv/consumer/keeper/genesis_test.go @@ -61,12 +61,6 @@ func TestInitGenesis(t *testing.T) { []string{"upgrade", "upgradedIBCState"}, ) - matPackets := []consumertypes.MaturingVSCPacket{ - { - VscId: 1, - MaturityTime: time.Now().UTC(), - }, - } pendingDataPackets := consumertypes.ConsumerPacketDataList{ List: []ccv.ConsumerPacketData{ { @@ -137,7 +131,6 @@ func TestInitGenesis(t *testing.T) { consumertypes.NewRestartGenesisState( provClientID, "", - matPackets, valset, defaultHeightValsetUpdateIDs, pendingDataPackets, @@ -173,7 +166,6 @@ func TestInitGenesis(t *testing.T) { consumertypes.NewRestartGenesisState( provClientID, provChannelID, - matPackets, valset, updatedHeightValsetUpdateIDs, pendingDataPackets, @@ -190,8 +182,6 @@ func TestInitGenesis(t *testing.T) { require.True(t, ok) require.Equal(t, provChannelID, gotChannelID) - require.True(t, ck.PacketMaturityTimeExists(ctx, matPackets[0].VscId, matPackets[0].MaturityTime)) - obtainedPendingPackets := ck.GetPendingPackets(ctx) for idx, expectedPacketData := range pendingDataPackets.List { require.Equal(t, expectedPacketData.Type, obtainedPendingPackets[idx].Type) @@ -239,13 +229,6 @@ func TestExportGenesis(t *testing.T) { vscID := uint64(0) blockHeight := uint64(0) - matPackets := []consumertypes.MaturingVSCPacket{ - { - VscId: 1, - MaturityTime: time.Now().UTC(), - }, - } - // mock a validator set pubKey := ed25519.GenPrivKey().PubKey() tmPK, err := cryptocodec.ToCmtPubKeyInterface(pubKey) @@ -310,7 +293,6 @@ func TestExportGenesis(t *testing.T) { consumertypes.NewRestartGenesisState( provClientID, "", - nil, valset, defaultHeightValsetUpdateIDs, consPackets, @@ -339,14 +321,12 @@ func TestExportGenesis(t *testing.T) { } // populate the required states for an established CCV channel - ck.SetPacketMaturityTime(ctx, matPackets[0].VscId, matPackets[0].MaturityTime) ck.SetOutstandingDowntime(ctx, sdk.ConsAddress(validator.Address.Bytes())) ck.SetLastTransmissionBlockHeight(ctx, ltbh) }, consumertypes.NewRestartGenesisState( provClientID, provChannelID, - matPackets, valset, updatedHeightValsetUpdateIDs, consPackets, diff --git a/x/ccv/consumer/types/genesis.go b/x/ccv/consumer/types/genesis.go index 2a18846f6a..2d5ae3a848 100644 --- a/x/ccv/consumer/types/genesis.go +++ b/x/ccv/consumer/types/genesis.go @@ -13,7 +13,6 @@ import ( // NewRestartGenesisState returns a consumer GenesisState that has already been established. func NewRestartGenesisState( clientID, channelID string, - maturingPackets []MaturingVSCPacket, initValSet []abci.ValidatorUpdate, heightToValsetUpdateIDs []HeightToValsetUpdateID, pendingConsumerPackets ConsumerPacketDataList, @@ -27,7 +26,6 @@ func NewRestartGenesisState( Provider: ccv.ProviderInfo{ InitialValSet: initValSet, }, - MaturingPackets: maturingPackets, HeightToValsetUpdateId: heightToValsetUpdateIDs, PendingConsumerPackets: pendingConsumerPackets, OutstandingDowntimeSlashing: outstandingDowntimes, @@ -107,9 +105,6 @@ func (gs GenesisState) Validate() error { if gs.ProviderChannelId != "" { return errorsmod.Wrap(ccv.ErrInvalidGenesis, "provider channel id cannot be set for new chain. It must be established on handshake") } - if len(gs.MaturingPackets) != 0 { - return errorsmod.Wrap(ccv.ErrInvalidGenesis, "maturing packets must be empty for new chain") - } if len(gs.PendingConsumerPackets.List) != 0 { return errorsmod.Wrap(ccv.ErrInvalidGenesis, "pending consumer packets must be empty for new chain") } @@ -124,10 +119,6 @@ func (gs GenesisState) Validate() error { // handshake is still in progress handshakeInProgress := gs.ProviderChannelId == "" if handshakeInProgress { - if len(gs.MaturingPackets) != 0 { - return errorsmod.Wrap( - ccv.ErrInvalidGenesis, "maturing packets must be empty when handshake isn't completed") - } if len(gs.OutstandingDowntimeSlashing) != 0 { return errorsmod.Wrap( ccv.ErrInvalidGenesis, "outstanding downtime must be empty when handshake isn't completed") @@ -153,21 +144,6 @@ func (gs GenesisState) Validate() error { if gs.Provider.ClientState != nil || gs.Provider.ConsensusState != nil { return errorsmod.Wrap(ccv.ErrInvalidGenesis, "provider client state and consensus state must be nil for a restarting genesis state") } - for _, mat := range gs.MaturingPackets { - if err := mat.Validate(); err != nil { - return errorsmod.Wrap(err, "invalid unbonding sequences") - } - } - } - return nil -} - -func (mat MaturingVSCPacket) Validate() error { - if mat.MaturityTime.IsZero() { - return errorsmod.Wrap(ccv.ErrInvalidVSCMaturedTime, "cannot have 0 maturity time") - } - if mat.VscId == 0 { - return errorsmod.Wrap(ccv.ErrInvalidVSCMaturedId, "cannot have 0 maturity time") } return nil } diff --git a/x/ccv/consumer/types/genesis_test.go b/x/ccv/consumer/types/genesis_test.go index b77ee85f1a..4816457064 100644 --- a/x/ccv/consumer/types/genesis_test.go +++ b/x/ccv/consumer/types/genesis_test.go @@ -9,7 +9,6 @@ import ( ibctmtypes "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" "github.com/stretchr/testify/require" - sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" abci "github.com/cometbft/cometbft/abci/types" @@ -317,45 +316,20 @@ func TestValidateRestartConsumerGenesisState(t *testing.T) { }{ { "valid restart consumer genesis state: empty maturing packets", - types.NewRestartGenesisState("ccvclient", "ccvchannel", nil, valUpdates, heightToValsetUpdateID, + types.NewRestartGenesisState("ccvclient", "ccvchannel", valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{List: []ccv.ConsumerPacketData{matConsumerPacket, slashConsumerPacket}}, nil, types.LastTransmissionBlockHeight{Height: 100}, params), false, }, { "valid restart consumer genesis state: handshake in progress ", - types.NewRestartGenesisState("ccvclient", "", nil, valUpdates, heightToValsetUpdateID, + types.NewRestartGenesisState("ccvclient", "", valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{List: []ccv.ConsumerPacketData{slashConsumerPacket}}, nil, types.LastTransmissionBlockHeight{}, params), false, }, - { - "valid restart consumer genesis state: maturing packets", - types.NewRestartGenesisState("ccvclient", "ccvchannel", []types.MaturingVSCPacket{ - {VscId: 1, MaturityTime: time.Now().UTC()}, - {VscId: 3, MaturityTime: time.Now().UTC()}, - {VscId: 5, MaturityTime: time.Now().UTC()}, - }, valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{}, - []types.OutstandingDowntime{{ValidatorConsensusAddress: sdk.ConsAddress(validator.Address.Bytes()).String()}}, - types.LastTransmissionBlockHeight{}, params), - false, - }, { "invalid restart consumer genesis state: provider id is empty", - types.NewRestartGenesisState("", "ccvchannel", nil, valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, params), - true, - }, - { - "invalid restart consumer genesis state: maturing packet vscId is invalid", - types.NewRestartGenesisState("ccvclient", "ccvchannel", []types.MaturingVSCPacket{ - {VscId: 0, MaturityTime: time.Now().UTC()}, - }, valUpdates, nil, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, params), - true, - }, - { - "invalid restart consumer genesis state: maturing packet time is invalid", - types.NewRestartGenesisState("ccvclient", "ccvchannel", []types.MaturingVSCPacket{ - {VscId: 1, MaturityTime: time.Time{}}, - }, valUpdates, nil, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, params), + types.NewRestartGenesisState("", "ccvchannel", valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, params), true, }, { @@ -370,7 +344,6 @@ func TestValidateRestartConsumerGenesisState(t *testing.T) { ConsensusState: nil, InitialValSet: valUpdates, }, - MaturingPackets: nil, HeightToValsetUpdateId: nil, OutstandingDowntimeSlashing: nil, PendingConsumerPackets: types.ConsumerPacketDataList{}, @@ -391,7 +364,6 @@ func TestValidateRestartConsumerGenesisState(t *testing.T) { ConsensusState: consensusState, InitialValSet: valUpdates, }, - MaturingPackets: nil, HeightToValsetUpdateId: nil, OutstandingDowntimeSlashing: nil, PendingConsumerPackets: types.ConsumerPacketDataList{}, @@ -402,38 +374,32 @@ func TestValidateRestartConsumerGenesisState(t *testing.T) { }, { "invalid restart consumer genesis state: nil initial validator set", - types.NewRestartGenesisState("ccvclient", "ccvchannel", nil, nil, nil, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, params), + types.NewRestartGenesisState("ccvclient", "ccvchannel", nil, nil, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, params), true, }, { "invalid restart consumer genesis state: nil height to validator set id mapping", types.NewRestartGenesisState("ccvclient", "", - []types.MaturingVSCPacket{{VscId: 1, MaturityTime: time.Time{}}}, valUpdates, nil, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, params), - true, - }, - { - "invalid restart consumer genesis state: maturing packet defined when handshake is still in progress", - types.NewRestartGenesisState("ccvclient", "", - []types.MaturingVSCPacket{{VscId: 1, MaturityTime: time.Time{}}}, valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, params), + valUpdates, nil, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, params), true, }, { "invalid restart consumer genesis state: outstanding downtime defined when handshake is still in progress", types.NewRestartGenesisState("ccvclient", "", - nil, valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{}, []types.OutstandingDowntime{{ValidatorConsensusAddress: "cosmosvalconsxxx"}}, + valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{}, []types.OutstandingDowntime{{ValidatorConsensusAddress: "cosmosvalconsxxx"}}, types.LastTransmissionBlockHeight{}, params), true, }, { "invalid restart consumer genesis state: last transmission block height defined when handshake is still in progress", types.NewRestartGenesisState("ccvclient", "", - nil, valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{Height: int64(1)}, params), + valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{Height: int64(1)}, params), true, }, { "invalid restart consumer genesis state: pending maturing packets defined when handshake is still in progress", types.NewRestartGenesisState("ccvclient", "", - nil, valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{ + valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{ List: []ccv.ConsumerPacketData{ { Type: ccv.VscMaturedPacket, @@ -445,7 +411,7 @@ func TestValidateRestartConsumerGenesisState(t *testing.T) { }, { "invalid restart consumer genesis state: invalid params", - types.NewRestartGenesisState("ccvclient", "ccvchannel", nil, valUpdates, nil, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, + types.NewRestartGenesisState("ccvclient", "ccvchannel", valUpdates, nil, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, ccv.NewParams( true, ccv.DefaultBlocksPerDistributionTransmission, From badfbcb13a07c92df7b92e9a2779f253c3678ed0 Mon Sep 17 00:00:00 2001 From: mpoke Date: Sun, 20 Oct 2024 20:56:54 +0200 Subject: [PATCH 04/12] remove maturity logic --- x/ccv/consumer/keeper/relay.go | 44 ----------------------------- x/ccv/consumer/keeper/relay_test.go | 12 -------- x/ccv/consumer/module.go | 4 --- 3 files changed, 60 deletions(-) diff --git a/x/ccv/consumer/keeper/relay.go b/x/ccv/consumer/keeper/relay.go index bcccb57e34..d32ac8f039 100644 --- a/x/ccv/consumer/keeper/relay.go +++ b/x/ccv/consumer/keeper/relay.go @@ -67,15 +67,6 @@ func (k Keeper) OnRecvVSCPacket(ctx sdk.Context, packet channeltypes.Packet, new ValidatorUpdates: pendingChanges, }) - // Save maturity time and packet - maturityTime := ctx.BlockTime().Add(k.GetUnbondingPeriod(ctx)) - k.SetPacketMaturityTime(ctx, newChanges.ValsetUpdateId, maturityTime) - k.Logger(ctx).Debug("packet maturity time was set", - "vscID", newChanges.ValsetUpdateId, - "maturity time (utc)", maturityTime.UTC(), - "maturity time (nano)", uint64(maturityTime.UnixNano()), - ) - // set height to VSC id mapping blockHeight := uint64(ctx.BlockHeight()) + 1 k.SetHeightValsetUpdateID(ctx, blockHeight, newChanges.ValsetUpdateId) @@ -106,41 +97,6 @@ func (k Keeper) OnRecvVSCPacket(ctx sdk.Context, packet channeltypes.Packet, new return nil } -// QueueVSCMaturedPackets appends matured VSCs to an internal queue. -// -// Note: Per spec, a VSC reaching maturity on a consumer chain means that all the unbonding -// operations that resulted in validator updates included in that VSC have matured on -// the consumer chain. -func (k Keeper) QueueVSCMaturedPackets(ctx sdk.Context) { - for _, maturityTime := range k.GetElapsedPacketMaturityTimes(ctx) { - // construct validator set change packet data - vscPacket := ccv.NewVSCMaturedPacketData(maturityTime.VscId) - - // Append VSCMatured packet to pending packets. - // Sending packets is attempted each EndBlock. - // Unsent packets remain in the queue until sent. - k.AppendPendingPacket(ctx, - ccv.VscMaturedPacket, - &ccv.ConsumerPacketData_VscMaturedPacketData{VscMaturedPacketData: vscPacket}, - ) - - k.DeletePacketMaturityTimes(ctx, maturityTime.VscId, maturityTime.MaturityTime) - - k.Logger(ctx).Info("VSCMaturedPacket enqueued", "vscID", vscPacket.ValsetUpdateId) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeVSCMatured, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(ccv.AttributeChainID, ctx.ChainID()), - sdk.NewAttribute(types.AttributeConsumerHeight, strconv.Itoa(int(ctx.BlockHeight()))), - sdk.NewAttribute(ccv.AttributeValSetUpdateID, strconv.Itoa(int(maturityTime.VscId))), - sdk.NewAttribute(types.AttributeTimestamp, ctx.BlockTime().String()), - ), - ) - } -} - // QueueSlashPacket appends a slash packet containing the given validator data and slashing info to queue. func (k Keeper) QueueSlashPacket(ctx sdk.Context, validator abci.Validator, valsetUpdateID uint64, infraction stakingtypes.Infraction) { consAddr := sdk.ConsAddress(validator.Address) diff --git a/x/ccv/consumer/keeper/relay_test.go b/x/ccv/consumer/keeper/relay_test.go index f21fa9fd25..1db62c9b5d 100644 --- a/x/ccv/consumer/keeper/relay_test.go +++ b/x/ccv/consumer/keeper/relay_test.go @@ -150,11 +150,6 @@ func TestOnRecvVSCPacket(t *testing.T) { // Set channel to provider, still in context of consumer chain consumerKeeper.SetProviderChannel(ctx, consumerCCVChannelID) - // Set module params with custom unbonding period - moduleParams := types.DefaultParams() - moduleParams.UnbondingPeriod = 100 * time.Hour - consumerKeeper.SetParams(ctx, moduleParams) - for _, tc := range testCases { var newChanges types.ValidatorSetChangePacketData err := types.ModuleCdc.UnmarshalJSON(tc.packet.GetData(), &newChanges) @@ -182,13 +177,6 @@ func TestOnRecvVSCPacket(t *testing.T) { return tc.expectedPendingChanges.ValidatorUpdates[i].PubKey.Compare(tc.expectedPendingChanges.ValidatorUpdates[j].PubKey) == -1 }) require.Equal(t, tc.expectedPendingChanges, *actualPendingChanges, "pending changes not equal to expected changes after successful packet receive. case: %s", tc.name) - - expectedTime := ctx.BlockTime().Add(consumerKeeper.GetUnbondingPeriod(ctx)) - require.True( - t, - consumerKeeper.PacketMaturityTimeExists(ctx, newChanges.ValsetUpdateId, expectedTime), - "no packet maturity time for case: %s", tc.name, - ) } } diff --git a/x/ccv/consumer/module.go b/x/ccv/consumer/module.go index 31e12ef380..c7ddef576a 100644 --- a/x/ccv/consumer/module.go +++ b/x/ccv/consumer/module.go @@ -197,10 +197,6 @@ func (am AppModule) EndBlock(goCtx context.Context) ([]abci.ValidatorUpdate, err // Execute EndBlock logic for the Reward Distribution sub-protocol am.keeper.EndBlockRD(ctx) - // NOTE: Slash packets are queued in BeginBlock via the Slash function - // Packet ordering is managed by the PendingPackets queue. - am.keeper.QueueVSCMaturedPackets(ctx) - // panics on invalid packets and unexpected send errors am.keeper.SendPackets(ctx) From db54129c4f88ab9537bf4a92a80cc2e3efc8ebba Mon Sep 17 00:00:00 2001 From: mpoke Date: Sun, 20 Oct 2024 21:05:54 +0200 Subject: [PATCH 05/12] add migration --- x/ccv/consumer/keeper/migrations.go | 9 ++++++++ x/ccv/consumer/migrations/v4/migration.go | 27 +++++++++++++++++++++++ x/ccv/consumer/module.go | 2 +- 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 x/ccv/consumer/migrations/v4/migration.go diff --git a/x/ccv/consumer/keeper/migrations.go b/x/ccv/consumer/keeper/migrations.go index ab3b45ffca..7bc776ea00 100644 --- a/x/ccv/consumer/keeper/migrations.go +++ b/x/ccv/consumer/keeper/migrations.go @@ -6,6 +6,7 @@ import ( v2 "github.com/cosmos/interchain-security/v6/x/ccv/consumer/migrations/v2" v3 "github.com/cosmos/interchain-security/v6/x/ccv/consumer/migrations/v3" + v4 "github.com/cosmos/interchain-security/v6/x/ccv/consumer/migrations/v4" ) // Migrator is a struct for handling in-place store migrations. @@ -32,3 +33,11 @@ func (m Migrator) Migrate2to3(ctx sdk.Context) error { cdc := m.keeper.cdc return v3.MigrateLegacyParams(ctx, cdc, store, m.paramSpace) } + +// Migrate3to4 migrates x/ccvconsumer from consensus version 3 to 4. +func (m Migrator) Migrate3to4(ctx sdk.Context) error { + store := ctx.KVStore(m.keeper.storeKey) + v4.CleanupState(store) + + return nil +} diff --git a/x/ccv/consumer/migrations/v4/migration.go b/x/ccv/consumer/migrations/v4/migration.go new file mode 100644 index 0000000000..3a65343a7e --- /dev/null +++ b/x/ccv/consumer/migrations/v4/migration.go @@ -0,0 +1,27 @@ +package v4 + +import ( + storetypes "cosmossdk.io/store/types" +) + +const ( + LegacyPacketMaturityTimeKeyName = byte(12) +) + +// CleanupState removes deprecated state +func CleanupState(store storetypes.KVStore) { + removePrefix(store, LegacyPacketMaturityTimeKeyName) +} + +func removePrefix(store storetypes.KVStore, prefix byte) { + iterator := storetypes.KVStorePrefixIterator(store, []byte{prefix}) + defer iterator.Close() + + var keysToDel [][]byte + for ; iterator.Valid(); iterator.Next() { + keysToDel = append(keysToDel, iterator.Key()) + } + for _, delKey := range keysToDel { + store.Delete(delKey) + } +} diff --git a/x/ccv/consumer/module.go b/x/ccv/consumer/module.go index c7ddef576a..452acdd652 100644 --- a/x/ccv/consumer/module.go +++ b/x/ccv/consumer/module.go @@ -150,7 +150,7 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw // ConsensusVersion implements AppModule/ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { - return 3 + return 4 } // BeginBlock implements the AppModule interface From 5d4b6d8771ceedbedfbcafc2c5a15164437168aa Mon Sep 17 00:00:00 2001 From: mpoke Date: Sun, 20 Oct 2024 21:18:15 +0200 Subject: [PATCH 06/12] fix UT --- x/ccv/consumer/types/genesis_test.go | 58 ---------------------------- 1 file changed, 58 deletions(-) diff --git a/x/ccv/consumer/types/genesis_test.go b/x/ccv/consumer/types/genesis_test.go index 4816457064..bbe031d0d7 100644 --- a/x/ccv/consumer/types/genesis_test.go +++ b/x/ccv/consumer/types/genesis_test.go @@ -94,7 +94,6 @@ func TestValidateInitialGenesisState(t *testing.T) { ConsensusState: consensusState, InitialValSet: valUpdates, }, - MaturingPackets: nil, HeightToValsetUpdateId: nil, OutstandingDowntimeSlashing: nil, PendingConsumerPackets: types.ConsumerPacketDataList{}, @@ -115,28 +114,6 @@ func TestValidateInitialGenesisState(t *testing.T) { ConsensusState: consensusState, InitialValSet: valUpdates, }, - MaturingPackets: nil, - HeightToValsetUpdateId: nil, - OutstandingDowntimeSlashing: nil, - PendingConsumerPackets: types.ConsumerPacketDataList{}, - LastTransmissionBlockHeight: types.LastTransmissionBlockHeight{}, - PreCCV: false, - }, - true, - }, - { - "invalid new consumer genesis state: non-empty unbonding sequences", - &types.GenesisState{ - Params: params, - ProviderClientId: "", - ProviderChannelId: "", - NewChain: true, - Provider: ccv.ProviderInfo{ - ClientState: cs, - ConsensusState: consensusState, - InitialValSet: valUpdates, - }, - MaturingPackets: []types.MaturingVSCPacket{{}}, HeightToValsetUpdateId: nil, OutstandingDowntimeSlashing: nil, PendingConsumerPackets: types.ConsumerPacketDataList{}, @@ -157,7 +134,6 @@ func TestValidateInitialGenesisState(t *testing.T) { ConsensusState: consensusState, InitialValSet: valUpdates, }, - MaturingPackets: nil, HeightToValsetUpdateId: nil, OutstandingDowntimeSlashing: nil, PendingConsumerPackets: types.ConsumerPacketDataList{}, @@ -178,7 +154,6 @@ func TestValidateInitialGenesisState(t *testing.T) { ConsensusState: consensusState, InitialValSet: valUpdates, }, - MaturingPackets: nil, HeightToValsetUpdateId: nil, OutstandingDowntimeSlashing: nil, PendingConsumerPackets: types.ConsumerPacketDataList{List: []ccv.ConsumerPacketData{{}}}, @@ -281,13 +256,6 @@ func TestValidateRestartConsumerGenesisState(t *testing.T) { valHash := valSet.Hash() valUpdates := tmtypes.TM2PB.ValidatorUpdates(valSet) - matConsumerPacket := ccv.ConsumerPacketData{ - Type: ccv.VscMaturedPacket, - Data: &ccv.ConsumerPacketData_VscMaturedPacketData{ - VscMaturedPacketData: ccv.NewVSCMaturedPacketData(1), - }, - } - slashConsumerPacket := ccv.ConsumerPacketData{ Type: ccv.SlashPacket, Data: &ccv.ConsumerPacketData_SlashPacketData{ @@ -314,13 +282,6 @@ func TestValidateRestartConsumerGenesisState(t *testing.T) { gs *types.GenesisState expError bool }{ - { - "valid restart consumer genesis state: empty maturing packets", - types.NewRestartGenesisState("ccvclient", "ccvchannel", valUpdates, heightToValsetUpdateID, - types.ConsumerPacketDataList{List: []ccv.ConsumerPacketData{matConsumerPacket, slashConsumerPacket}}, - nil, types.LastTransmissionBlockHeight{Height: 100}, params), - false, - }, { "valid restart consumer genesis state: handshake in progress ", types.NewRestartGenesisState("ccvclient", "", valUpdates, heightToValsetUpdateID, @@ -377,12 +338,6 @@ func TestValidateRestartConsumerGenesisState(t *testing.T) { types.NewRestartGenesisState("ccvclient", "ccvchannel", nil, nil, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, params), true, }, - { - "invalid restart consumer genesis state: nil height to validator set id mapping", - types.NewRestartGenesisState("ccvclient", "", - valUpdates, nil, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, params), - true, - }, { "invalid restart consumer genesis state: outstanding downtime defined when handshake is still in progress", types.NewRestartGenesisState("ccvclient", "", @@ -396,19 +351,6 @@ func TestValidateRestartConsumerGenesisState(t *testing.T) { valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{Height: int64(1)}, params), true, }, - { - "invalid restart consumer genesis state: pending maturing packets defined when handshake is still in progress", - types.NewRestartGenesisState("ccvclient", "", - valUpdates, heightToValsetUpdateID, types.ConsumerPacketDataList{ - List: []ccv.ConsumerPacketData{ - { - Type: ccv.VscMaturedPacket, - Data: &ccv.ConsumerPacketData_VscMaturedPacketData{VscMaturedPacketData: ccv.NewVSCMaturedPacketData(1)}, - }, - }, - }, nil, types.LastTransmissionBlockHeight{Height: int64(1)}, params), - true, - }, { "invalid restart consumer genesis state: invalid params", types.NewRestartGenesisState("ccvclient", "ccvchannel", valUpdates, nil, types.ConsumerPacketDataList{}, nil, types.LastTransmissionBlockHeight{}, From 9b5c5dfa24206ddaddebc5834b828f9427b65349 Mon Sep 17 00:00:00 2001 From: mpoke Date: Sun, 20 Oct 2024 21:36:42 +0200 Subject: [PATCH 07/12] fix integration tests --- tests/integration/expired_client.go | 21 ++--- tests/integration/valset_update.go | 132 ---------------------------- 2 files changed, 6 insertions(+), 147 deletions(-) diff --git a/tests/integration/expired_client.go b/tests/integration/expired_client.go index 099fdd1613..f07c8cc752 100644 --- a/tests/integration/expired_client.go +++ b/tests/integration/expired_client.go @@ -82,10 +82,6 @@ func (s *CCVTestSuite) TestVSCPacketSendExpiredClient() { s.nextEpoch() // - relay all VSC packet from provider to consumer relayAllCommittedPackets(s, s.providerChain, s.path, ccv.ProviderPortID, s.path.EndpointB.ChannelID, 3) - // - increment time so that the unbonding period ends on the consumer - incrementTimeByUnbondingPeriod(s, Consumer) - // - relay all VSCMatured packet from consumer to provider - relayAllCommittedPackets(s, s.consumerChain, s.path, ccv.ConsumerPortID, s.path.EndpointA.ChannelID, 3) } // TestConsumerPacketSendExpiredClient tests the consumer sending packets when the provider client is expired. @@ -134,10 +130,9 @@ func (s *CCVTestSuite) TestConsumerPacketSendExpiredClient() { consumerUnbondingPeriod := s.consumerApp.GetConsumerKeeper().GetUnbondingPeriod(s.consumerCtx()) incrementTimeWithoutUpdate(s, consumerUnbondingPeriod+time.Hour, Provider) - // check that the packets were added to the list of pending data packets + // check that no packets were added to the list of pending data packets consumerPackets := consumerKeeper.GetPendingPackets(s.consumerCtx()) - s.Require().NotEmpty(consumerPackets) - s.Require().Len(consumerPackets, 2, "unexpected number of pending data packets") + s.Require().Empty(consumerPackets) // try to send slash packet for downtime infraction addr := ed25519.GenPrivKey().PubKey().Address() @@ -151,8 +146,8 @@ func (s *CCVTestSuite) TestConsumerPacketSendExpiredClient() { // check that the packets were added to the list of pending data packets consumerPackets = consumerKeeper.GetPendingPackets(s.consumerCtx()) s.Require().NotEmpty(consumerPackets) - // At this point we expect 4 packets, two vsc matured packets and two trailing slash packets - s.Require().Len(consumerPackets, 4, "unexpected number of pending data packets") + // At this point we expect two trailing slash packets + s.Require().Len(consumerPackets, 2, "unexpected number of pending data packets") // upgrade expired client to the consumer upgradeExpiredClient(s, Provider) @@ -160,12 +155,12 @@ func (s *CCVTestSuite) TestConsumerPacketSendExpiredClient() { // go to next block to trigger SendPendingPackets s.consumerChain.NextBlock() - // Check that the leading vsc matured packets were sent and no longer pending + // Check that both slash packets are still pending consumerPackets = consumerKeeper.GetPendingPackets(s.consumerCtx()) s.Require().Len(consumerPackets, 2, "unexpected number of pending data packets") // relay committed packets from consumer to provider, first slash packet should be committed - relayAllCommittedPackets(s, s.consumerChain, s.path, ccv.ConsumerPortID, s.path.EndpointA.ChannelID, 3) // two vsc matured + one slash + relayAllCommittedPackets(s, s.consumerChain, s.path, ccv.ConsumerPortID, s.path.EndpointA.ChannelID, 1) // one slash // First slash has been acked, now only the second slash packet should remain as pending consumerPackets = consumerKeeper.GetPendingPackets(s.consumerCtx()) @@ -187,10 +182,6 @@ func (s *CCVTestSuite) TestConsumerPacketSendExpiredClient() { s.nextEpoch() // - relay 1 VSC packet from provider to consumer relayAllCommittedPackets(s, s.providerChain, s.path, ccv.ProviderPortID, s.path.EndpointB.ChannelID, 1) - // - increment time so that the unbonding period ends on the provider - incrementTimeByUnbondingPeriod(s, Consumer) - // - relay 1 VSCMatured packet from consumer to provider - relayAllCommittedPackets(s, s.consumerChain, s.path, ccv.ConsumerPortID, s.path.EndpointA.ChannelID, 1) } // expireClient expires the client to the `clientTo` chain diff --git a/tests/integration/valset_update.go b/tests/integration/valset_update.go index 89078bb26e..ac84d9de32 100644 --- a/tests/integration/valset_update.go +++ b/tests/integration/valset_update.go @@ -1,16 +1,8 @@ package integration import ( - "time" - - clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" - "cosmossdk.io/math" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - - abci "github.com/cometbft/cometbft/abci/types" - ccv "github.com/cosmos/interchain-security/v6/x/ccv/types" ) @@ -34,128 +26,4 @@ func (s *CCVTestSuite) TestPacketRoundtrip() { // Relay 1 VSC packet from provider to consumer relayAllCommittedPackets(s, s.providerChain, s.path, ccv.ProviderPortID, s.path.EndpointB.ChannelID, 1) - - // Increment time so that the unbonding period ends on the provider - incrementTimeByUnbondingPeriod(s, Provider) - - // Relay 1 VSCMatured packet from consumer to provider - relayAllCommittedPackets(s, s.consumerChain, s.path, ccv.ConsumerPortID, s.path.EndpointA.ChannelID, 1) -} - -// TestQueueAndSendVSCMaturedPackets tests the behavior of EndBlock QueueVSCMaturedPackets call and its integration with SendPackets call. -// @Long Description@ -// * Set up CCV channel. -// * Create and simulate the sending of three VSC packets from the provider chain to the consumer chain at different times. -// * Send the first packet and validate its processing. -// * Simulate the passage of one hour. -// * Send the second packet and validate its processing. -// * Simulate the passage of 24 more hours. -// * Send the third packet and validate its processing. -// * Retrieve all packet maturity times from the consumer, and use this to check the maturity status of the packets sent earlier. -// * Advance the time so that the first two packets reach their unbonding period, while the third packet does not. -// * Ensure first two packets are unbonded, their maturity times are deleted, and that VSCMatured packets are queued. -// * The third packet is still in the store and has not yet been processed for unbonding. -// * Checks that the packet commitments for the processed packets are correctly reflected in the consumer chain's state. -func (suite *CCVTestSuite) TestQueueAndSendVSCMaturedPackets() { - consumerKeeper := suite.consumerApp.GetConsumerKeeper() - - // setup CCV channel - suite.SetupCCVChannel(suite.path) - - // send 3 packets to consumer chain at different times - pk, err := cryptocodec.FromCmtPubKeyInterface(suite.providerChain.Vals.Validators[0].PubKey) - suite.Require().NoError(err) - pk1, err := cryptocodec.ToCmtProtoPublicKey(pk) - suite.Require().NoError(err) - pk, err = cryptocodec.FromCmtPubKeyInterface(suite.providerChain.Vals.Validators[1].PubKey) - suite.Require().NoError(err) - pk2, err := cryptocodec.ToCmtProtoPublicKey(pk) - suite.Require().NoError(err) - - pd := ccv.NewValidatorSetChangePacketData( - []abci.ValidatorUpdate{ - { - PubKey: pk1, - Power: 30, - }, - { - PubKey: pk2, - Power: 20, - }, - }, - 1, - nil, - ) - - // send first packet - packet := suite.newPacketFromProvider(pd.GetBytes(), 1, suite.path, clienttypes.NewHeight(1, 0), 0) - err = consumerKeeper.OnRecvVSCPacket(suite.consumerChain.GetContext(), packet, pd) - suite.Require().Nil(err, "OnRecvVSCPacket did return non-nil error") - - // increase time - incrementTime(suite, time.Hour) - - // update time and send second packet - pd.ValidatorUpdates[0].Power = 15 - pd.ValsetUpdateId = 2 - packet.Data = pd.GetBytes() - packet.Sequence = 2 - err = consumerKeeper.OnRecvVSCPacket(suite.consumerChain.GetContext(), packet, pd) - suite.Require().Nil(err, "OnRecvVSCPacket did return non-nil error") - - // increase time - incrementTime(suite, 24*time.Hour) - - // update time and send third packet - pd.ValidatorUpdates[1].Power = 40 - pd.ValsetUpdateId = 3 - packet.Data = pd.GetBytes() - packet.Sequence = 3 - err = consumerKeeper.OnRecvVSCPacket(suite.consumerChain.GetContext(), packet, pd) - suite.Require().Nil(err, "OnRecvVSCPacket did return non-nil error") - - packetMaturities := consumerKeeper.GetAllPacketMaturityTimes(suite.consumerChain.GetContext()) - - // increase time such that first two packets are unbonded but third is not. - unbondingPeriod := consumerKeeper.GetUnbondingPeriod(suite.consumerChain.GetContext()) - // increase time - incrementTime(suite, unbondingPeriod-time.Hour) - - // ensure first two packets are unbonded and VSCMatured packets are queued - // unbonded time is deleted - suite.Require().False( - consumerKeeper.PacketMaturityTimeExists( - suite.consumerChain.GetContext(), - packetMaturities[0].VscId, - packetMaturities[0].MaturityTime, - ), - "maturity time not deleted for mature packet 1", - ) - suite.Require().False( - consumerKeeper.PacketMaturityTimeExists( - suite.consumerChain.GetContext(), - packetMaturities[1].VscId, - packetMaturities[1].MaturityTime, - ), - "maturity time not deleted for mature packet 2", - ) - // ensure that third packet did not get unbonded and is still in store - suite.Require().True( - consumerKeeper.PacketMaturityTimeExists( - suite.consumerChain.GetContext(), - packetMaturities[2].VscId, - packetMaturities[2].MaturityTime, - ), - "maturity time for packet 3 is not after current time", - ) - - // check that the packets are committed in state - commitments := suite.consumerApp.GetIBCKeeper().ChannelKeeper.GetAllPacketCommitmentsAtChannel( - suite.consumerChain.GetContext(), - ccv.ConsumerPortID, - suite.path.EndpointA.ChannelID, - ) - suite.Require().Equal(2, len(commitments), "did not find packet commitments") - suite.Require().Equal(uint64(1), commitments[0].Sequence, "did not send VSCMatured packet for VSC packet 1") - suite.Require().Equal(uint64(2), commitments[1].Sequence, "did not send VSCMatured packet for VSC packet 2") } From e9fae28ebbd1a42230b638c3b2cdf7c4835a7c06 Mon Sep 17 00:00:00 2001 From: mpoke Date: Wed, 23 Oct 2024 14:31:02 +0400 Subject: [PATCH 08/12] update proto files --- .../ccv/consumer/v1/genesis.proto | 30 +- x/ccv/consumer/types/genesis.pb.go | 574 ++---------------- 2 files changed, 63 insertions(+), 541 deletions(-) diff --git a/proto/interchain_security/ccv/consumer/v1/genesis.proto b/proto/interchain_security/ccv/consumer/v1/genesis.proto index 69a765b8e2..499bb44b3a 100644 --- a/proto/interchain_security/ccv/consumer/v1/genesis.proto +++ b/proto/interchain_security/ccv/consumer/v1/genesis.proto @@ -20,6 +20,18 @@ import "tendermint/abci/types.proto"; // Note: this type is only used on consumer side and references shared types with // provider message GenesisState { + // Reserve 5th slot for removed provider_client_state field + reserved 5; + + // Reserve 6th slot for removed provider_consensus_state field + reserved 6; + + // Reserve 7th slot for removed maturing_packets field + reserved 7; + + // Reserve 8th slot for removed initial_val_set field + reserved 8; + // ConsumerParams is a shared type with provider module interchain_security.ccv.v1.ConsumerParams params = 1 [ (gogoproto.nullable) = false ]; @@ -29,15 +41,6 @@ message GenesisState { string provider_channel_id = 3; // true for new chain, false for chain restart. bool new_chain = 4; - // !!! DEPRECATED !!! ProviderClientState is deprecated. Use provider.client_state instead - ibc.lightclients.tendermint.v1.ClientState provider_client_state = 5 [ deprecated = true]; - // !!! DEPRECATED !!! ProviderConsensusState is deprecated. Use provider.consensus_state instead - ibc.lightclients.tendermint.v1.ConsensusState provider_consensus_state = 6 [ deprecated = true]; - // MaturingPackets nil on new chain, filled in on restart. - repeated MaturingVSCPacket maturing_packets = 7 - [ (gogoproto.nullable) = false ]; - // !!! DEPRECATED !!!! InitialValset is deprecated. Use provider.initial_val_set instead - repeated .tendermint.abci.ValidatorUpdate initial_val_set = 8 [ (gogoproto.nullable) = false, deprecated = true ]; // HeightToValsetUpdateId nil on new chain, filled in on restart. repeated HeightToValsetUpdateID height_to_valset_update_id = 9 [ (gogoproto.nullable) = false ]; @@ -73,15 +76,6 @@ message OutstandingDowntime { string validator_consensus_address = 1; } // to the consumer CCV module. message LastTransmissionBlockHeight { int64 height = 1; } -// MaturingVSCPacket represents a vsc packet that is maturing internal to the -// consumer CCV module, where the consumer has not yet relayed a VSCMatured -// packet back to the provider. -message MaturingVSCPacket { - uint64 vscId = 1; - google.protobuf.Timestamp maturity_time = 2 - [ (gogoproto.stdtime) = true, (gogoproto.nullable) = false ]; -} - // ConsumerPacketDataList is a list of consumer packet data packets. // // Note this type is used internally to the consumer CCV module diff --git a/x/ccv/consumer/types/genesis.pb.go b/x/ccv/consumer/types/genesis.pb.go index 34eeb43cfa..33350f3e2c 100644 --- a/x/ccv/consumer/types/genesis.pb.go +++ b/x/ccv/consumer/types/genesis.pb.go @@ -5,24 +5,21 @@ package types import ( fmt "fmt" - types1 "github.com/cometbft/cometbft/abci/types" + _ "github.com/cometbft/cometbft/abci/types" _ "github.com/cosmos/gogoproto/gogoproto" proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _07_tendermint "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" + _ "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" types "github.com/cosmos/interchain-security/v6/x/ccv/types" _ "google.golang.org/protobuf/types/known/timestamppb" io "io" math "math" math_bits "math/bits" - time "time" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -var _ = time.Kitchen // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. @@ -43,14 +40,6 @@ type GenesisState struct { ProviderChannelId string `protobuf:"bytes,3,opt,name=provider_channel_id,json=providerChannelId,proto3" json:"provider_channel_id,omitempty"` // true for new chain, false for chain restart. NewChain bool `protobuf:"varint,4,opt,name=new_chain,json=newChain,proto3" json:"new_chain,omitempty"` - // !!! DEPRECATED !!! ProviderClientState is deprecated. Use provider.client_state instead - ProviderClientState *_07_tendermint.ClientState `protobuf:"bytes,5,opt,name=provider_client_state,json=providerClientState,proto3" json:"provider_client_state,omitempty"` // Deprecated: Do not use. - // !!! DEPRECATED !!! ProviderConsensusState is deprecated. Use provider.consensus_state instead - ProviderConsensusState *_07_tendermint.ConsensusState `protobuf:"bytes,6,opt,name=provider_consensus_state,json=providerConsensusState,proto3" json:"provider_consensus_state,omitempty"` // Deprecated: Do not use. - // MaturingPackets nil on new chain, filled in on restart. - MaturingPackets []MaturingVSCPacket `protobuf:"bytes,7,rep,name=maturing_packets,json=maturingPackets,proto3" json:"maturing_packets"` - // !!! DEPRECATED !!!! InitialValset is deprecated. Use provider.initial_val_set instead - InitialValSet []types1.ValidatorUpdate `protobuf:"bytes,8,rep,name=initial_val_set,json=initialValSet,proto3" json:"initial_val_set"` // Deprecated: Do not use. // HeightToValsetUpdateId nil on new chain, filled in on restart. HeightToValsetUpdateId []HeightToValsetUpdateID `protobuf:"bytes,9,rep,name=height_to_valset_update_id,json=heightToValsetUpdateId,proto3" json:"height_to_valset_update_id"` // OutstandingDowntimes nil on new chain, filled in on restart. @@ -125,37 +114,6 @@ func (m *GenesisState) GetNewChain() bool { return false } -// Deprecated: Do not use. -func (m *GenesisState) GetProviderClientState() *_07_tendermint.ClientState { - if m != nil { - return m.ProviderClientState - } - return nil -} - -// Deprecated: Do not use. -func (m *GenesisState) GetProviderConsensusState() *_07_tendermint.ConsensusState { - if m != nil { - return m.ProviderConsensusState - } - return nil -} - -func (m *GenesisState) GetMaturingPackets() []MaturingVSCPacket { - if m != nil { - return m.MaturingPackets - } - return nil -} - -// Deprecated: Do not use. -func (m *GenesisState) GetInitialValSet() []types1.ValidatorUpdate { - if m != nil { - return m.InitialValSet - } - return nil -} - func (m *GenesisState) GetHeightToValsetUpdateId() []HeightToValsetUpdateID { if m != nil { return m.HeightToValsetUpdateId @@ -346,61 +304,6 @@ func (m *LastTransmissionBlockHeight) GetHeight() int64 { return 0 } -// MaturingVSCPacket represents a vsc packet that is maturing internal to the -// consumer CCV module, where the consumer has not yet relayed a VSCMatured -// packet back to the provider. -type MaturingVSCPacket struct { - VscId uint64 `protobuf:"varint,1,opt,name=vscId,proto3" json:"vscId,omitempty"` - MaturityTime time.Time `protobuf:"bytes,2,opt,name=maturity_time,json=maturityTime,proto3,stdtime" json:"maturity_time"` -} - -func (m *MaturingVSCPacket) Reset() { *m = MaturingVSCPacket{} } -func (m *MaturingVSCPacket) String() string { return proto.CompactTextString(m) } -func (*MaturingVSCPacket) ProtoMessage() {} -func (*MaturingVSCPacket) Descriptor() ([]byte, []int) { - return fileDescriptor_2db73a6057a27482, []int{4} -} -func (m *MaturingVSCPacket) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MaturingVSCPacket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MaturingVSCPacket.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MaturingVSCPacket) XXX_Merge(src proto.Message) { - xxx_messageInfo_MaturingVSCPacket.Merge(m, src) -} -func (m *MaturingVSCPacket) XXX_Size() int { - return m.Size() -} -func (m *MaturingVSCPacket) XXX_DiscardUnknown() { - xxx_messageInfo_MaturingVSCPacket.DiscardUnknown(m) -} - -var xxx_messageInfo_MaturingVSCPacket proto.InternalMessageInfo - -func (m *MaturingVSCPacket) GetVscId() uint64 { - if m != nil { - return m.VscId - } - return 0 -} - -func (m *MaturingVSCPacket) GetMaturityTime() time.Time { - if m != nil { - return m.MaturityTime - } - return time.Time{} -} - // ConsumerPacketDataList is a list of consumer packet data packets. // // Note this type is used internally to the consumer CCV module @@ -413,7 +316,7 @@ func (m *ConsumerPacketDataList) Reset() { *m = ConsumerPacketDataList{} func (m *ConsumerPacketDataList) String() string { return proto.CompactTextString(m) } func (*ConsumerPacketDataList) ProtoMessage() {} func (*ConsumerPacketDataList) Descriptor() ([]byte, []int) { - return fileDescriptor_2db73a6057a27482, []int{5} + return fileDescriptor_2db73a6057a27482, []int{4} } func (m *ConsumerPacketDataList) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -454,7 +357,6 @@ func init() { proto.RegisterType((*HeightToValsetUpdateID)(nil), "interchain_security.ccv.consumer.v1.HeightToValsetUpdateID") proto.RegisterType((*OutstandingDowntime)(nil), "interchain_security.ccv.consumer.v1.OutstandingDowntime") proto.RegisterType((*LastTransmissionBlockHeight)(nil), "interchain_security.ccv.consumer.v1.LastTransmissionBlockHeight") - proto.RegisterType((*MaturingVSCPacket)(nil), "interchain_security.ccv.consumer.v1.MaturingVSCPacket") proto.RegisterType((*ConsumerPacketDataList)(nil), "interchain_security.ccv.consumer.v1.ConsumerPacketDataList") } @@ -463,64 +365,54 @@ func init() { } var fileDescriptor_2db73a6057a27482 = []byte{ - // 912 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x56, 0xcf, 0x6f, 0x23, 0x35, - 0x14, 0xee, 0xb4, 0xdd, 0x90, 0xb8, 0xed, 0x6e, 0xd7, 0x5d, 0xa2, 0xa1, 0x11, 0x69, 0x14, 0x84, - 0x14, 0xf1, 0xc3, 0x43, 0x8a, 0x58, 0x21, 0x21, 0x10, 0x24, 0x95, 0x68, 0x50, 0x11, 0x55, 0xda, - 0x0d, 0xd2, 0x5e, 0x46, 0x8e, 0xc7, 0x3b, 0xb1, 0x76, 0xc6, 0x1e, 0x8d, 0x9d, 0x09, 0x15, 0xe2, - 0xc2, 0x95, 0xcb, 0xfe, 0x59, 0x7b, 0xdc, 0x03, 0x07, 0x4e, 0x80, 0xda, 0x7f, 0x04, 0xd9, 0xe3, - 0x99, 0x24, 0x34, 0xed, 0xe6, 0x16, 0xcf, 0x7b, 0xef, 0xfb, 0xde, 0xfb, 0xde, 0x7b, 0x76, 0x40, - 0x97, 0x71, 0x45, 0x53, 0x32, 0xc1, 0x8c, 0xfb, 0x92, 0x92, 0x69, 0xca, 0xd4, 0x95, 0x47, 0x48, - 0xe6, 0x11, 0xc1, 0xe5, 0x34, 0xa6, 0xa9, 0x97, 0x75, 0xbd, 0x90, 0x72, 0x2a, 0x99, 0x44, 0x49, - 0x2a, 0x94, 0x80, 0x1f, 0xac, 0x08, 0x41, 0x84, 0x64, 0xa8, 0x08, 0x41, 0x59, 0xf7, 0xf0, 0xb3, - 0xbb, 0x70, 0xb3, 0xae, 0x27, 0x27, 0x38, 0xa5, 0x81, 0x5f, 0xba, 0x1b, 0xd8, 0x43, 0x8f, 0x8d, - 0x89, 0x17, 0xb1, 0x70, 0xa2, 0x48, 0xc4, 0x28, 0x57, 0xd2, 0x53, 0x94, 0x07, 0x34, 0x8d, 0x19, - 0x57, 0x3a, 0x6a, 0x7e, 0xb2, 0x01, 0x4f, 0x42, 0x11, 0x0a, 0xf3, 0xd3, 0xd3, 0xbf, 0xec, 0xd7, - 0x0f, 0xef, 0x21, 0x9e, 0xb1, 0x94, 0x5a, 0xb7, 0xa3, 0x50, 0x88, 0x30, 0xa2, 0x9e, 0x39, 0x8d, - 0xa7, 0x2f, 0x3c, 0xc5, 0x62, 0x2a, 0x15, 0x8e, 0x13, 0xeb, 0xd0, 0x58, 0x60, 0xc7, 0x63, 0xc2, - 0x3c, 0x75, 0x95, 0x50, 0x2b, 0x41, 0xfb, 0xcf, 0x1a, 0xd8, 0xfd, 0x3e, 0x17, 0xe5, 0x42, 0x61, - 0x45, 0xe1, 0x29, 0xa8, 0x24, 0x38, 0xc5, 0xb1, 0x74, 0x9d, 0x96, 0xd3, 0xd9, 0x39, 0xfe, 0x08, - 0xdd, 0x25, 0x52, 0xd6, 0x45, 0x7d, 0x5b, 0xf8, 0xb9, 0x89, 0xe8, 0x6d, 0xbf, 0xfe, 0xfb, 0x68, - 0x63, 0x68, 0xe3, 0xe1, 0x27, 0x00, 0x26, 0xa9, 0xc8, 0x58, 0x40, 0x53, 0x3f, 0x17, 0xc2, 0x67, - 0x81, 0xbb, 0xd9, 0x72, 0x3a, 0xb5, 0xe1, 0x7e, 0x61, 0xe9, 0x1b, 0xc3, 0x20, 0x80, 0x08, 0x1c, - 0xcc, 0xbd, 0x27, 0x98, 0x73, 0x1a, 0x69, 0xf7, 0x2d, 0xe3, 0xfe, 0xb8, 0x74, 0xcf, 0x2d, 0x83, - 0x00, 0x36, 0x40, 0x8d, 0xd3, 0x99, 0x6f, 0xf2, 0x72, 0xb7, 0x5b, 0x4e, 0xa7, 0x3a, 0xac, 0x72, - 0x3a, 0xeb, 0xeb, 0x33, 0x24, 0xe0, 0xdd, 0xff, 0x53, 0x4b, 0x5d, 0x9d, 0xfb, 0xc0, 0xd4, 0xf4, - 0x31, 0x62, 0x63, 0x82, 0x16, 0x3b, 0x84, 0x16, 0x7a, 0xa2, 0xeb, 0x32, 0x5f, 0x8d, 0x20, 0xbd, - 0x4d, 0xd7, 0x19, 0x1e, 0x2c, 0xa7, 0x9b, 0x2b, 0x15, 0x01, 0x77, 0x4e, 0x22, 0xb8, 0xa4, 0x5c, - 0x4e, 0xa5, 0xe5, 0xa9, 0x18, 0x1e, 0xf4, 0x56, 0x9e, 0x22, 0x6c, 0x4e, 0x55, 0x2f, 0xa9, 0x96, - 0x6c, 0x30, 0x04, 0xfb, 0x31, 0x56, 0xd3, 0x94, 0xf1, 0xd0, 0x4f, 0x30, 0x79, 0x49, 0x95, 0x74, - 0xdf, 0x69, 0x6d, 0x75, 0x76, 0x8e, 0x9f, 0xa2, 0x35, 0xc6, 0x18, 0xfd, 0x68, 0x83, 0x47, 0x17, - 0xfd, 0x73, 0x13, 0x6e, 0xbb, 0xf5, 0xa8, 0x40, 0xcd, 0xbf, 0x4a, 0x78, 0x0e, 0x1e, 0x31, 0xce, - 0x14, 0xc3, 0x91, 0x9f, 0xe1, 0xc8, 0x97, 0x54, 0xb9, 0x55, 0xc3, 0xd3, 0x5a, 0x4c, 0x5e, 0x0f, - 0x12, 0x1a, 0xe1, 0x88, 0x05, 0x58, 0x89, 0xf4, 0x59, 0x12, 0xe8, 0xfc, 0x2b, 0x1a, 0xd1, 0x75, - 0x86, 0x7b, 0x16, 0x60, 0x84, 0xa3, 0x0b, 0xaa, 0xe0, 0x6f, 0xe0, 0x70, 0x42, 0xb5, 0x08, 0xbe, - 0x12, 0x1a, 0x53, 0x52, 0xe5, 0x4f, 0x4d, 0x84, 0xee, 0x70, 0xcd, 0x80, 0x7f, 0xb5, 0x56, 0x11, - 0xa7, 0x06, 0xe6, 0x52, 0x8c, 0x0c, 0x48, 0xce, 0x3a, 0x38, 0xb1, 0x95, 0xd4, 0x27, 0xab, 0xac, - 0x01, 0xfc, 0xdd, 0x01, 0xef, 0x8b, 0xa9, 0x92, 0x0a, 0xf3, 0x40, 0xab, 0x17, 0x88, 0x19, 0xd7, - 0x3b, 0xe2, 0xcb, 0x08, 0xcb, 0x09, 0xe3, 0xa1, 0x0b, 0x4c, 0x0a, 0x5f, 0xae, 0x95, 0xc2, 0x4f, - 0x73, 0xa4, 0x13, 0x0b, 0x64, 0xf9, 0x1b, 0xe2, 0xb6, 0xe9, 0xc2, 0x52, 0xc0, 0x5f, 0x81, 0x9b, - 0xd0, 0x9c, 0xbf, 0x40, 0x2b, 0xdb, 0xb8, 0x63, 0x86, 0x65, 0x3d, 0x05, 0xe6, 0x1b, 0xa7, 0x63, - 0x4f, 0xb0, 0xc2, 0x67, 0x4c, 0x16, 0xbd, 0xac, 0x5b, 0x8a, 0x65, 0x27, 0x09, 0xff, 0x70, 0x40, - 0x33, 0xc2, 0x52, 0xf9, 0x2a, 0xc5, 0x5c, 0xc6, 0x4c, 0x4a, 0x26, 0xb8, 0x3f, 0x8e, 0x04, 0x79, - 0xe9, 0xe7, 0xa2, 0xb9, 0xbb, 0x26, 0x87, 0x6f, 0xd7, 0xca, 0xe1, 0x0c, 0x4b, 0x75, 0xb9, 0x80, - 0xd4, 0xd3, 0x40, 0x79, 0x6b, 0x0a, 0x29, 0xa2, 0xbb, 0x5d, 0x60, 0x1d, 0x54, 0x92, 0x94, 0xf6, - 0xfb, 0x23, 0x77, 0xcf, 0xac, 0xad, 0x3d, 0xc1, 0x1f, 0x40, 0xb5, 0x98, 0x7d, 0xf7, 0xa1, 0x49, - 0xa7, 0x73, 0xdf, 0xdd, 0x73, 0x6e, 0x7d, 0x07, 0xfc, 0x85, 0xb0, 0xb4, 0x65, 0x7c, 0xfb, 0x39, - 0xa8, 0xaf, 0x9e, 0x15, 0xcd, 0x6e, 0x4b, 0xd6, 0xf7, 0xdb, 0xf6, 0xd0, 0x9e, 0x60, 0x07, 0xec, - 0xdf, 0x1a, 0xcd, 0x4d, 0xe3, 0xf1, 0x30, 0x5b, 0x9a, 0xa7, 0xf6, 0x33, 0x70, 0xb0, 0x62, 0x08, - 0xe0, 0x37, 0xa0, 0x91, 0x15, 0xfb, 0xb0, 0x70, 0x1f, 0xe0, 0x20, 0x48, 0xa9, 0xcc, 0x6f, 0xd3, - 0xda, 0xf0, 0xbd, 0xd2, 0xa5, 0x5c, 0xef, 0xef, 0x72, 0x87, 0xf6, 0x17, 0xa0, 0x71, 0x76, 0xbf, - 0x6a, 0x0b, 0x79, 0x6f, 0x15, 0x79, 0xb7, 0x15, 0x78, 0x7c, 0x6b, 0xb5, 0xe1, 0x13, 0xf0, 0x20, - 0x93, 0x64, 0x10, 0xd8, 0x1a, 0xf3, 0x03, 0x1c, 0x80, 0xbd, 0x7c, 0xd9, 0xd5, 0x95, 0xaf, 0x53, - 0x36, 0xf5, 0xed, 0x1c, 0x1f, 0xa2, 0xfc, 0x05, 0x41, 0xc5, 0x0b, 0x82, 0x2e, 0x8b, 0x17, 0xa4, - 0x57, 0xd5, 0xba, 0xbe, 0xfa, 0xe7, 0xc8, 0x19, 0xee, 0x16, 0xa1, 0xda, 0xd8, 0x1e, 0x83, 0xfa, - 0xea, 0x49, 0x84, 0xa7, 0x60, 0x3b, 0x62, 0x52, 0x67, 0xb9, 0x95, 0xdf, 0x80, 0xeb, 0xbc, 0x1e, - 0x05, 0x82, 0xed, 0xa3, 0x41, 0xe8, 0xfd, 0xfc, 0xfa, 0xba, 0xe9, 0xbc, 0xb9, 0x6e, 0x3a, 0xff, - 0x5e, 0x37, 0x9d, 0x57, 0x37, 0xcd, 0x8d, 0x37, 0x37, 0xcd, 0x8d, 0xbf, 0x6e, 0x9a, 0x1b, 0xcf, - 0xbf, 0x0e, 0x99, 0x9a, 0x4c, 0xc7, 0x88, 0x88, 0xd8, 0x23, 0x42, 0xc6, 0x42, 0x7a, 0x73, 0x9a, - 0x4f, 0xcb, 0xb7, 0x32, 0x7b, 0xea, 0xfd, 0xb2, 0xfc, 0x0f, 0xc0, 0xbc, 0x7c, 0xe3, 0x8a, 0x29, - 0xf4, 0xf3, 0xff, 0x02, 0x00, 0x00, 0xff, 0xff, 0xe1, 0x67, 0x80, 0x40, 0x32, 0x08, 0x00, 0x00, + // 741 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x55, 0x4d, 0x6b, 0xdb, 0x4a, + 0x14, 0xb5, 0x12, 0x3d, 0x47, 0x9e, 0xe4, 0x05, 0x3f, 0xe5, 0x61, 0xf4, 0x62, 0x9e, 0x63, 0x5c, + 0x0a, 0xa6, 0xb4, 0x52, 0x9d, 0xd2, 0x52, 0x28, 0x2d, 0x6d, 0x1c, 0x68, 0x6c, 0x02, 0x0d, 0xce, + 0x47, 0x21, 0x9b, 0x61, 0x2c, 0x4d, 0xa4, 0x21, 0xd2, 0x8c, 0xd0, 0x8c, 0xe5, 0x86, 0xd2, 0x4d, + 0xb7, 0xdd, 0xf4, 0x67, 0x65, 0x99, 0x65, 0x57, 0xa1, 0x24, 0x7f, 0xa4, 0x68, 0x34, 0xb2, 0x13, + 0xe2, 0x04, 0xef, 0x34, 0xbe, 0xe7, 0x9e, 0x7b, 0x74, 0xee, 0xd1, 0x18, 0x74, 0x08, 0x15, 0x38, + 0x71, 0x03, 0x44, 0x28, 0xe4, 0xd8, 0x1d, 0x25, 0x44, 0x9c, 0x39, 0xae, 0x9b, 0x3a, 0x2e, 0xa3, + 0x7c, 0x14, 0xe1, 0xc4, 0x49, 0x3b, 0x8e, 0x8f, 0x29, 0xe6, 0x84, 0xdb, 0x71, 0xc2, 0x04, 0x33, + 0x1f, 0xcd, 0x68, 0xb1, 0x5d, 0x37, 0xb5, 0x8b, 0x16, 0x3b, 0xed, 0xac, 0x3f, 0xbf, 0x8f, 0x37, + 0xed, 0x38, 0x3c, 0x40, 0x09, 0xf6, 0xe0, 0x04, 0x2e, 0x69, 0xd7, 0x1d, 0x32, 0x74, 0x9d, 0x90, + 0xf8, 0x81, 0x70, 0x43, 0x82, 0xa9, 0xe0, 0x8e, 0xc0, 0xd4, 0xc3, 0x49, 0x44, 0xa8, 0xc8, 0xba, + 0xa6, 0x27, 0xd5, 0xf0, 0xaf, 0xcf, 0x7c, 0x26, 0x1f, 0x9d, 0xec, 0x49, 0xfd, 0xfa, 0xf8, 0x81, + 0xc1, 0x63, 0x92, 0x60, 0x05, 0xdb, 0xf0, 0x19, 0xf3, 0x43, 0xec, 0xc8, 0xd3, 0x70, 0x74, 0xe2, + 0x08, 0x12, 0x61, 0x2e, 0x50, 0x14, 0x2b, 0x40, 0xfd, 0xc6, 0x74, 0x34, 0x74, 0x89, 0x23, 0xce, + 0x62, 0xac, 0x2c, 0x68, 0x5d, 0x96, 0xc1, 0xca, 0xc7, 0xdc, 0x94, 0x7d, 0x81, 0x04, 0x36, 0x77, + 0x40, 0x39, 0x46, 0x09, 0x8a, 0xb8, 0xa5, 0x35, 0xb5, 0xf6, 0xf2, 0xe6, 0x13, 0xfb, 0x3e, 0x93, + 0xd2, 0x8e, 0xdd, 0x55, 0x2f, 0xbe, 0x27, 0x3b, 0xb6, 0xf4, 0xf3, 0xcb, 0x8d, 0xd2, 0x40, 0xf5, + 0x9b, 0x4f, 0x81, 0x19, 0x27, 0x2c, 0x25, 0x1e, 0x4e, 0x60, 0x6e, 0x04, 0x24, 0x9e, 0xb5, 0xd0, + 0xd4, 0xda, 0x95, 0x41, 0xb5, 0xa8, 0x74, 0x65, 0xa1, 0xe7, 0x99, 0x36, 0x58, 0x9b, 0xa2, 0x03, + 0x44, 0x29, 0x0e, 0x33, 0xf8, 0xa2, 0x84, 0xff, 0x33, 0x81, 0xe7, 0x95, 0x9e, 0x67, 0xd6, 0x41, + 0x85, 0xe2, 0x31, 0x94, 0xba, 0x2c, 0xbd, 0xa9, 0xb5, 0x8d, 0x81, 0x41, 0xf1, 0xb8, 0x9b, 0x9d, + 0xcd, 0x6f, 0x60, 0x3d, 0xc0, 0xd9, 0x02, 0xa0, 0x60, 0x30, 0x45, 0x21, 0xc7, 0x02, 0x8e, 0x62, + 0x0f, 0x09, 0x9c, 0x71, 0x56, 0x9a, 0x8b, 0xed, 0xe5, 0xcd, 0x37, 0xf6, 0x1c, 0xdb, 0xb7, 0x77, + 0x24, 0xcd, 0x01, 0x3b, 0x92, 0x24, 0x87, 0x92, 0xa3, 0xb7, 0xad, 0xde, 0xb4, 0x16, 0xcc, 0xaa, + 0x7a, 0xe6, 0x77, 0x0d, 0xfc, 0xcf, 0x46, 0x82, 0x0b, 0x44, 0x3d, 0x42, 0x7d, 0xe8, 0xb1, 0x31, + 0xcd, 0xb6, 0x02, 0x79, 0x88, 0x78, 0x40, 0xa8, 0x6f, 0x01, 0x29, 0xe1, 0xf5, 0x5c, 0x12, 0x3e, + 0x4d, 0x99, 0xb6, 0x15, 0x91, 0x9a, 0x5f, 0x67, 0x77, 0x4b, 0xfb, 0x6a, 0x84, 0xf9, 0x15, 0x58, + 0x31, 0xce, 0xe7, 0x17, 0x6c, 0x30, 0x46, 0xee, 0x29, 0x16, 0xdc, 0x5a, 0x96, 0xab, 0x9d, 0xcf, + 0x81, 0xe9, 0x8e, 0xb3, 0xde, 0x6d, 0x24, 0xd0, 0x2e, 0xe1, 0xa2, 0x70, 0x40, 0x8d, 0xb8, 0x0d, + 0xe2, 0xe6, 0x0f, 0x0d, 0x34, 0x42, 0xc4, 0x05, 0x14, 0x09, 0xa2, 0x3c, 0x22, 0x9c, 0x13, 0x46, + 0xe1, 0x30, 0x64, 0xee, 0x29, 0xcc, 0x4d, 0xb3, 0x56, 0xa4, 0x86, 0xf7, 0x73, 0x69, 0xd8, 0x45, + 0x5c, 0x1c, 0xdc, 0x60, 0xda, 0xca, 0x88, 0xf2, 0xd5, 0x14, 0x56, 0x84, 0xf7, 0x43, 0xcc, 0x1a, + 0x28, 0xc7, 0x09, 0xee, 0x76, 0x8f, 0xac, 0xbf, 0x65, 0x50, 0xd4, 0xc9, 0xec, 0x03, 0xa3, 0x08, + 0x96, 0xb5, 0x2a, 0xe5, 0xb4, 0x1f, 0x4a, 0xfb, 0x9e, 0xc2, 0xf6, 0xe8, 0x09, 0x53, 0x63, 0x27, + 0xfd, 0x7d, 0xdd, 0xf8, 0xab, 0x5a, 0xee, 0xeb, 0x46, 0xb9, 0xba, 0xd4, 0xd7, 0x8d, 0xa5, 0xaa, + 0xd1, 0xd7, 0x0d, 0xa3, 0x5a, 0x69, 0x1d, 0x83, 0xda, 0xec, 0x0c, 0x65, 0xaa, 0x94, 0x15, 0xd9, + 0x97, 0xa6, 0x0f, 0xd4, 0xc9, 0x6c, 0x83, 0xea, 0x9d, 0xc8, 0x2e, 0x48, 0xc4, 0x6a, 0x7a, 0x2b, + 0x67, 0xad, 0x43, 0xb0, 0x36, 0x23, 0x1c, 0xe6, 0x3b, 0x50, 0x4f, 0x51, 0x48, 0x3c, 0x24, 0x58, + 0x22, 0x77, 0x8f, 0x29, 0x1f, 0x71, 0x88, 0x3c, 0x2f, 0xc1, 0x3c, 0xff, 0xae, 0x2b, 0x83, 0xff, + 0x26, 0x90, 0x6e, 0x81, 0xf8, 0x90, 0x03, 0x5a, 0x2f, 0x41, 0x7d, 0xf7, 0x61, 0x37, 0x6f, 0xe8, + 0x5e, 0x2c, 0x74, 0xb7, 0x86, 0xa0, 0x36, 0x3b, 0x2b, 0xe6, 0x0e, 0xd0, 0x43, 0xc2, 0x33, 0x7c, + 0x96, 0x7a, 0x7b, 0xbe, 0x1b, 0xa5, 0x60, 0x50, 0x4e, 0x4b, 0x86, 0xad, 0xcf, 0xe7, 0x57, 0x0d, + 0xed, 0xe2, 0xaa, 0xa1, 0xfd, 0xbe, 0x6a, 0x68, 0x3f, 0xaf, 0x1b, 0xa5, 0x8b, 0xeb, 0x46, 0xe9, + 0xd7, 0x75, 0xa3, 0x74, 0xfc, 0xd6, 0x27, 0x22, 0x18, 0x0d, 0x6d, 0x97, 0x45, 0x8e, 0xcb, 0x78, + 0xc4, 0xb8, 0x33, 0x1d, 0xf3, 0x6c, 0x72, 0x7f, 0xa6, 0xaf, 0x9c, 0x2f, 0xb7, 0xff, 0x15, 0xe4, + 0x6d, 0x38, 0x2c, 0xcb, 0xeb, 0xf0, 0xc5, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xfd, 0xe7, 0x1e, + 0x4d, 0x46, 0x06, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { @@ -611,58 +503,6 @@ func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { dAtA[i] = 0x4a } } - if len(m.InitialValSet) > 0 { - for iNdEx := len(m.InitialValSet) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.InitialValSet[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - if len(m.MaturingPackets) > 0 { - for iNdEx := len(m.MaturingPackets) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MaturingPackets[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - } - if m.ProviderConsensusState != nil { - { - size, err := m.ProviderConsensusState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - if m.ProviderClientState != nil { - { - size, err := m.ProviderClientState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } if m.NewChain { i-- if m.NewChain { @@ -791,42 +631,6 @@ func (m *LastTransmissionBlockHeight) MarshalToSizedBuffer(dAtA []byte) (int, er return len(dAtA) - i, nil } -func (m *MaturingVSCPacket) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MaturingVSCPacket) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MaturingVSCPacket) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n7, err7 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.MaturityTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.MaturityTime):]) - if err7 != nil { - return 0, err7 - } - i -= n7 - i = encodeVarintGenesis(dAtA, i, uint64(n7)) - i-- - dAtA[i] = 0x12 - if m.VscId != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.VscId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - func (m *ConsumerPacketDataList) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -894,26 +698,6 @@ func (m *GenesisState) Size() (n int) { if m.NewChain { n += 2 } - if m.ProviderClientState != nil { - l = m.ProviderClientState.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - if m.ProviderConsensusState != nil { - l = m.ProviderConsensusState.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - if len(m.MaturingPackets) > 0 { - for _, e := range m.MaturingPackets { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.InitialValSet) > 0 { - for _, e := range m.InitialValSet { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } if len(m.HeightToValsetUpdateId) > 0 { for _, e := range m.HeightToValsetUpdateId { l = e.Size() @@ -978,20 +762,6 @@ func (m *LastTransmissionBlockHeight) Size() (n int) { return n } -func (m *MaturingVSCPacket) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.VscId != 0 { - n += 1 + sovGenesis(uint64(m.VscId)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.MaturityTime) - n += 1 + l + sovGenesis(uint64(l)) - return n -} - func (m *ConsumerPacketDataList) Size() (n int) { if m == nil { return 0 @@ -1159,146 +929,6 @@ func (m *GenesisState) Unmarshal(dAtA []byte) error { } } m.NewChain = bool(v != 0) - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ProviderClientState", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.ProviderClientState == nil { - m.ProviderClientState = &_07_tendermint.ClientState{} - } - if err := m.ProviderClientState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ProviderConsensusState", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.ProviderConsensusState == nil { - m.ProviderConsensusState = &_07_tendermint.ConsensusState{} - } - if err := m.ProviderConsensusState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaturingPackets", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MaturingPackets = append(m.MaturingPackets, MaturingVSCPacket{}) - if err := m.MaturingPackets[len(m.MaturingPackets)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InitialValSet", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.InitialValSet = append(m.InitialValSet, types1.ValidatorUpdate{}) - if err := m.InitialValSet[len(m.InitialValSet)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex case 9: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field HeightToValsetUpdateId", wireType) @@ -1746,108 +1376,6 @@ func (m *LastTransmissionBlockHeight) Unmarshal(dAtA []byte) error { } return nil } -func (m *MaturingVSCPacket) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MaturingVSCPacket: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MaturingVSCPacket: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field VscId", wireType) - } - m.VscId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.VscId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaturityTime", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.MaturityTime, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} func (m *ConsumerPacketDataList) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 From 89b1d05a1c6d0eee92c4db2cccdc6e5d549d4a90 Mon Sep 17 00:00:00 2001 From: mpoke Date: Wed, 23 Oct 2024 14:43:19 +0400 Subject: [PATCH 09/12] remove genesis transformation --- app/consumer/genesis.go | 335 ------------ app/consumer/genesis_test.go | 680 ------------------------- cmd/interchain-security-cd/cmd/root.go | 15 +- 3 files changed, 2 insertions(+), 1028 deletions(-) delete mode 100644 app/consumer/genesis_test.go diff --git a/app/consumer/genesis.go b/app/consumer/genesis.go index be56824856..5bf0c1da80 100644 --- a/app/consumer/genesis.go +++ b/app/consumer/genesis.go @@ -2,22 +2,8 @@ package app import ( "encoding/json" - "fmt" - "os" - "path/filepath" - "regexp" - "strings" - "github.com/spf13/cobra" - "golang.org/x/exp/maps" - - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - consumerTypes "github.com/cosmos/interchain-security/v6/x/ccv/consumer/types" - "github.com/cosmos/interchain-security/v6/x/ccv/types" ) // The genesis state of the blockchain is represented here as a map of raw json @@ -29,328 +15,7 @@ import ( // object provided to it during init. type GenesisState map[string]json.RawMessage -// Map of supported versions for consumer genesis transformation -type IcsVersion string - -const ( - v2_x IcsVersion = "v2.x" - v3_0_x IcsVersion = "v3.0.x" - v3_1_x IcsVersion = "v3.1.x" - v3_2_x IcsVersion = "v3.2.x" - v3_3_x IcsVersion = "v3.3.x" - v4_x_x IcsVersion = "v4.x" -) - -var TransformationVersions map[string]IcsVersion = map[string]IcsVersion{ - "v2.x": v2_x, - "v3.0.x": v3_0_x, - "v3.1.x": v3_1_x, - "v3.2.x": v3_2_x, - "v3.3.x": v3_3_x, - "v4.x": v4_x_x, -} - -// Transformation of consumer genesis content as it is exported from a provider version v1,2,3 -// to a format readable by current consumer implementation. -func transformToNew(jsonRaw []byte, ctx client.Context) (json.RawMessage, error) { - // v1,2,3 uses deprecated fields of GenesisState type - oldConsumerGenesis := consumerTypes.GenesisState{} - err := ctx.Codec.UnmarshalJSON(jsonRaw, &oldConsumerGenesis) - if err != nil { - return nil, fmt.Errorf("reading consumer genesis data failed: %s", err) - } - - initialValSet := oldConsumerGenesis.InitialValSet - // transformation from >= v3.3.x - if len(initialValSet) == 0 { - initialValSet = oldConsumerGenesis.Provider.InitialValSet - } - - clientState := oldConsumerGenesis.ProviderClientState - if clientState == nil { - clientState = oldConsumerGenesis.Provider.ClientState - } - - consensusState := oldConsumerGenesis.ProviderConsensusState - if consensusState == nil { - consensusState = oldConsumerGenesis.Provider.ConsensusState - } - - // Use DefaultRetryDelayPeriod if not set - if oldConsumerGenesis.Params.RetryDelayPeriod == 0 { - oldConsumerGenesis.Params.RetryDelayPeriod = types.DefaultRetryDelayPeriod - } - - // `SoftOptOutThreshold` is deprecated in the current consumer implementation, so set to zero - oldConsumerGenesis.Params.SoftOptOutThreshold = "0" - - // Versions before v3.3.x of provider genesis data fills up deprecated fields - // ProviderClientState, ConsensusState and InitialValSet in type GenesisState - newGenesis := types.ConsumerGenesisState{ - Params: oldConsumerGenesis.Params, - Provider: types.ProviderInfo{ - ClientState: clientState, - ConsensusState: consensusState, - InitialValSet: initialValSet, - }, - NewChain: oldConsumerGenesis.NewChain, - } - - newJson, err := ctx.Codec.MarshalJSON(&newGenesis) - if err != nil { - return nil, fmt.Errorf("failed marshalling data to new type: %s", err) - } - return newJson, nil -} - -// Transformation of consumer genesis content as it is exported by current provider version -// to a format supported by consumer version v3.3.x -func transformToV33(jsonRaw []byte, ctx client.Context) ([]byte, error) { - // v1,2,3 uses deprecated fields of GenesisState type - srcConGen := consumerTypes.GenesisState{} - err := ctx.Codec.UnmarshalJSON(jsonRaw, &srcConGen) - if err != nil { - return nil, fmt.Errorf("reading consumer genesis data failed: %s", err) - } - - // Remove retry_delay_period from 'params' - params, err := ctx.Codec.MarshalJSON(&srcConGen.Params) - if err != nil { - return nil, err - } - tmp := map[string]json.RawMessage{} - if err := json.Unmarshal(params, &tmp); err != nil { - return nil, fmt.Errorf("unmarshalling 'params' failed: %v", err) - } - _, exists := tmp["retry_delay_period"] - if exists { - delete(tmp, "retry_delay_period") - } - params, err = json.Marshal(tmp) - if err != nil { - return nil, err - } - - // Marshal GenesisState and patch 'params' value - result, err := ctx.Codec.MarshalJSON(&srcConGen) - if err != nil { - return nil, err - } - genState := map[string]json.RawMessage{} - if err := json.Unmarshal(result, &genState); err != nil { - return nil, fmt.Errorf("unmarshalling 'GenesisState' failed: %v", err) - } - genState["params"] = params - - result, err = json.Marshal(genState) - if err != nil { - return nil, fmt.Errorf("marshalling transformation result failed: %v", err) - } - return result, nil -} - -// Transformation of consumer genesis content as it is exported from current provider version -// to a format readable by consumer implementation of version v2.x -// Use removePreHashKey to remove prehash_key_before_comparison from result. -func transformToV2(jsonRaw []byte, ctx client.Context, removePreHashKey bool) (json.RawMessage, error) { - // populate deprecated fields of GenesisState used by version v2.x - srcConGen := consumerTypes.GenesisState{} - err := ctx.Codec.UnmarshalJSON(jsonRaw, &srcConGen) - if err != nil { - return nil, fmt.Errorf("reading consumer genesis data failed: %s", err) - } - - // remove retry_delay_period from 'params' if present (introduced in v4.x) - params, err := ctx.Codec.MarshalJSON(&srcConGen.Params) - if err != nil { - return nil, err - } - paramsMap := map[string]json.RawMessage{} - if err := json.Unmarshal(params, ¶msMap); err != nil { - return nil, fmt.Errorf("unmarshalling 'params' failed: %v", err) - } - _, exists := paramsMap["retry_delay_period"] - if exists { - delete(paramsMap, "retry_delay_period") - } - params, err = json.Marshal(paramsMap) - if err != nil { - return nil, err - } - - // marshal GenesisState and patch 'params' value - result, err := ctx.Codec.MarshalJSON(&srcConGen) - if err != nil { - return nil, err - } - genState := map[string]json.RawMessage{} - if err := json.Unmarshal(result, &genState); err != nil { - return nil, fmt.Errorf("unmarshalling 'GenesisState' failed: %v", err) - } - genState["params"] = params - - provider, err := ctx.Codec.MarshalJSON(&srcConGen.Provider) - if err != nil { - return nil, fmt.Errorf("marshalling 'Provider' failed: %v", err) - } - providerMap := map[string]json.RawMessage{} - if err := json.Unmarshal(provider, &providerMap); err != nil { - return nil, fmt.Errorf("unmarshalling 'provider' failed: %v", err) - } - - // patch .initial_val_set form .provider.initial_val_set if needed - if len(srcConGen.Provider.InitialValSet) > 0 { - valSet, exists := providerMap["initial_val_set"] - if !exists { - return nil, fmt.Errorf("'initial_val_set' not found in provider data") - } - _, exists = genState["initial_val_set"] - if exists { - genState["initial_val_set"] = valSet - } - } - - // patch .provider_consensus_state from provider.consensus_state if needed - if srcConGen.Provider.ConsensusState != nil { - valSet, exists := providerMap["consensus_state"] - if !exists { - return nil, fmt.Errorf("'consensus_state' not found in provider data") - } - _, exists = genState["provider_consensus_state"] - if exists { - genState["provider_consensus_state"] = valSet - } - } - - // patch .provider_client_state from provider.client_state if needed - if srcConGen.Provider.ClientState != nil { - clientState, exists := providerMap["client_state"] - if !exists { - return nil, fmt.Errorf("'client_state' not found in provider data") - } - _, exists = genState["provider_client_state"] - if exists { - genState["provider_client_state"] = clientState - } - } - - // delete .provider entry (introduced in v3.3.x) - delete(genState, "provider") - - // Marshall final result - result, err = json.Marshal(genState) - if err != nil { - return nil, fmt.Errorf("marshalling transformation result failed: %v", err) - } - - if removePreHashKey { - // remove all `prehash_key_before_comparison` entries not supported in v2.x (see ics23) - re := regexp.MustCompile(`,\s*"prehash_key_before_comparison"\s*:\s*(false|true)`) - result = re.ReplaceAll(result, []byte{}) - } - return result, nil -} - -// transformGenesis transforms ccv consumer genesis data to the specified target version -// Returns the transformed data or an error in case the transformation failed or the format is not supported by current implementation -func transformGenesis(ctx client.Context, targetVersion IcsVersion, jsonRaw []byte) (json.RawMessage, error) { - var newConsumerGenesis json.RawMessage = nil - var err error - - switch targetVersion { - // v2.x, v3.0-v3.2 share same consumer genesis type - case v2_x: - newConsumerGenesis, err = transformToV2(jsonRaw, ctx, true) - case v3_0_x, v3_1_x, v3_2_x: - // same as v2 replacement without need of `prehash_key_before_comparison` removal - newConsumerGenesis, err = transformToV2(jsonRaw, ctx, false) - case v3_3_x: - newConsumerGenesis, err = transformToV33(jsonRaw, ctx) - case v4_x_x: - newConsumerGenesis, err = transformToNew(jsonRaw, ctx) - default: - err = fmt.Errorf("unsupported target version '%s'. Run %s --help", - targetVersion, version.AppName) - } - - if err != nil { - return nil, fmt.Errorf("transformation failed: %v", err) - } - return newConsumerGenesis, err -} - -// Transform a consumer genesis json file exported from a given ccv provider version -// to a consumer genesis json format supported by current ccv consumer version or v2.x -// This allows user to patch consumer genesis of -// - current implementation from exports of provider of < v3.3.x -// - v2.x from exports of provider >= v3.2.x -// -// Result will be written to defined output. -func TransformConsumerGenesis(cmd *cobra.Command, args []string) error { - sourceFile := args[0] - jsonRaw, err := os.ReadFile(filepath.Clean(sourceFile)) - if err != nil { - return err - } - - clientCtx := client.GetClientContextFromCmd(cmd) - version, err := cmd.Flags().GetString("to") - if err != nil { - return fmt.Errorf("error getting targetVersion %v", err) - } - targetVersion, exists := TransformationVersions[version] - if !exists { - return fmt.Errorf("unsupported target version '%s'", version) - } - - // try to transform data to target format - newConsumerGenesis, err := transformGenesis(clientCtx, targetVersion, jsonRaw) - if err != nil { - return err - } - - bz, err := newConsumerGenesis.MarshalJSON() - if err != nil { - return fmt.Errorf("failed exporting new consumer genesis to JSON: %s", err) - } - - sortedBz, err := sdk.SortJSON(bz) - if err != nil { - return fmt.Errorf("failed sorting transformed consumer genesis JSON: %s", err) - } - - cmd.Println(string(sortedBz)) - return nil -} - // NewDefaultGenesisState generates the default state for the application. func NewDefaultGenesisState(cdc codec.JSONCodec) GenesisState { return ModuleBasics.DefaultGenesis(cdc) } - -// GetConsumerGenesisTransformCmd transforms Consumer Genesis JSON content exported from a -// provider version v1,v2 or v3 to a JSON format supported by this consumer version. -func GetConsumerGenesisTransformCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "transform [-to version] genesis-file", - Short: "Transform CCV consumer genesis data exported to a specific target format", - Long: strings.TrimSpace( - fmt.Sprintf(` -Transform the consumer genesis data exported from a provider version v1,v2, v3, v4 to a specified consumer target version. -The result is printed to STDOUT. - -Note: Content to be transformed is not the consumer genesis file itself but the exported content from provider chain which is used to patch the consumer genesis file! - -Example: -$ %s transform /path/to/ccv_consumer_genesis.json -$ %s --to v2.x transform /path/to/ccv_consumer_genesis.json -`, version.AppName, version.AppName), - ), - Args: cobra.RangeArgs(1, 2), - RunE: TransformConsumerGenesis, - } - cmd.Flags().String("to", string(v4_x_x), - fmt.Sprintf("target version for consumer genesis. Supported versions %s", - maps.Keys(TransformationVersions))) - return cmd -} diff --git a/app/consumer/genesis_test.go b/app/consumer/genesis_test.go deleted file mode 100644 index 144dbd74c9..0000000000 --- a/app/consumer/genesis_test.go +++ /dev/null @@ -1,680 +0,0 @@ -package app_test - -import ( - "bytes" - "context" - "fmt" - "io/fs" - "os" - "path/filepath" - "testing" - "time" - - "github.com/spf13/cobra" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/x/auth/types" - - app "github.com/cosmos/interchain-security/v6/app/consumer" - consumerTypes "github.com/cosmos/interchain-security/v6/x/ccv/consumer/types" - ccvtypes "github.com/cosmos/interchain-security/v6/x/ccv/types" -) - -const ( - V4x = "v4.x" - V33x = "v3.3.x" - V2x = "v2.x" -) - -// Testdata mapping consumer genesis exports to a provider module version as -// used by transformation function for consumer genesis content. -var consumerGenesisStates map[string]string = map[string]string{ - "v2.x": ` - { - "params": { - "enabled": true, - "blocks_per_distribution_transmission": "1500", - "distribution_transmission_channel": "", - "provider_fee_pool_addr_str": "", - "ccv_timeout_period": "2419200s", - "transfer_timeout_period": "3600s", - "consumer_redistribution_fraction": "0.75", - "historical_entries": "10000", - "unbonding_period": "1728000s", - "soft_opt_out_threshold": "", - "reward_denoms": [], - "provider_reward_denoms": [] - }, - "provider_client_id": "", - "provider_channel_id": "", - "new_chain": true, - "provider_client_state": { - "chain_id": "cosmoshub-4", - "trust_level": { - "numerator": "1", - "denominator": "3" - }, - "trusting_period": "1197504s", - "unbonding_period": "1814400s", - "max_clock_drift": "10s", - "frozen_height": { - "revision_number": "0", - "revision_height": "0" - }, - "latest_height": { - "revision_number": "4", - "revision_height": "15211521" - }, - "proof_specs": [ - { - "leaf_spec": { - "hash": "SHA256", - "prehash_key": "NO_HASH", - "prehash_value": "SHA256", - "length": "VAR_PROTO", - "prefix": "AA==" - }, - "inner_spec": { - "child_order": [ - 0, - 1 - ], - "child_size": 33, - "min_prefix_length": 4, - "max_prefix_length": 12, - "empty_child": null, - "hash": "SHA256" - }, - "max_depth": 0, - "min_depth": 0 - }, - { - "leaf_spec": { - "hash": "SHA256", - "prehash_key": "NO_HASH", - "prehash_value": "SHA256", - "length": "VAR_PROTO", - "prefix": "AA==" - }, - "inner_spec": { - "child_order": [ - 0, - 1 - ], - "child_size": 32, - "min_prefix_length": 1, - "max_prefix_length": 1, - "empty_child": null, - "hash": "SHA256" - }, - "max_depth": 0, - "min_depth": 0 - } - ], - "upgrade_path": [ - "upgrade", - "upgradedIBCState" - ], - "allow_update_after_expiry": true, - "allow_update_after_misbehaviour": true - }, - "provider_consensus_state": { - "timestamp": "2023-05-08T11:00:01.563901871Z", - "root": { - "hash": "qKVnVSXlsjDHC8ekKcy/0zSjzr3YekCurld9R4W07EI=" - }, - "next_validators_hash": "E08978F493101A3C5D459FB3087B8CFBA9E82D7A1FE1441E7D77E11AC0586BAC" - }, - "maturing_packets": [], - "initial_val_set": [ - { - "pub_key": { - "ed25519": "cOQZvh/h9ZioSeUMZB/1Vy1Xo5x2sjrVjlE/qHnYifM=" - }, - "power": "2345194" - }, - { - "pub_key": { - "ed25519": "vGSKfbQyKApvBhinpOOA0XQAdjxceihYNwtGskfZGyQ=" - }, - "power": "463811" - } - ], - "height_to_valset_update_id": [], - "outstanding_downtime_slashing": [], - "pending_consumer_packets": { - "list": [] - }, - "last_transmission_block_height": { - "height": "0" - }, - "preCCV": false - } - - `, - "v3.3.x": ` - { - "params": { - "enabled": true, - "blocks_per_distribution_transmission": "1000", - "distribution_transmission_channel": "", - "provider_fee_pool_addr_str": "", - "ccv_timeout_period": "2419200s", - "transfer_timeout_period": "3600s", - "consumer_redistribution_fraction": "0.75", - "historical_entries": "10000", - "unbonding_period": "1209600s", - "soft_opt_out_threshold": "0.05", - "reward_denoms": [], - "provider_reward_denoms": [] - }, - "provider": { - "client_state": { - "chain_id": "provi", - "trust_level": { - "numerator": "1", - "denominator": "3" - }, - "trusting_period": "1197504s", - "unbonding_period": "1814400s", - "max_clock_drift": "10s", - "frozen_height": { - "revision_number": "0", - "revision_height": "0" - }, - "latest_height": { - "revision_number": "0", - "revision_height": "20" - }, - "proof_specs": [ - { - "leaf_spec": { - "hash": "SHA256", - "prehash_key": "NO_HASH", - "prehash_value": "SHA256", - "length": "VAR_PROTO", - "prefix": "AA==" - }, - "inner_spec": { - "child_order": [ - 0, - 1 - ], - "child_size": 33, - "min_prefix_length": 4, - "max_prefix_length": 12, - "empty_child": null, - "hash": "SHA256" - }, - "max_depth": 0, - "min_depth": 0, - "prehash_key_before_comparison": false - }, - { - "leaf_spec": { - "hash": "SHA256", - "prehash_key": "NO_HASH", - "prehash_value": "SHA256", - "length": "VAR_PROTO", - "prefix": "AA==" - }, - "inner_spec": { - "child_order": [ - 0, - 1 - ], - "child_size": 32, - "min_prefix_length": 1, - "max_prefix_length": 1, - "empty_child": null, - "hash": "SHA256" - }, - "max_depth": 0, - "min_depth": 0, - "prehash_key_before_comparison": false - } - ], - "upgrade_path": [ - "upgrade", - "upgradedIBCState" - ], - "allow_update_after_expiry": false, - "allow_update_after_misbehaviour": false - }, - "consensus_state": { - "timestamp": "2023-12-15T09:25:46.098392003Z", - "root": { - "hash": "0aoNOwWy67aQKs2r+FcDf2RxIq2UJtBb3g9ZWn0Gkas=" - }, - "next_validators_hash": "632730A03DEF630F77B61DF4092629007AE020B789713158FABCB104962FA54F" - }, - "initial_val_set": [ - { - "pub_key": { - "ed25519": "RrclQz9bIhkIy/gfL485g3PYMeiIku4qeo495787X10=" - }, - "power": "500" - }, - { - "pub_key": { - "ed25519": "Ui5Gf1+mtWUdH8u3xlmzdKID+F3PK0sfXZ73GZ6q6is=" - }, - "power": "500" - }, - { - "pub_key": { - "ed25519": "mAN6RXYxSM4MNGSIriYiS7pHuwAcOHDQAy9/wnlSzOI=" - }, - "power": "500" - } - ] - }, - "new_chain": true - } - `, - "v4.x": ` - { - "params": { - "enabled": true, - "blocks_per_distribution_transmission": "1000", - "distribution_transmission_channel": "", - "provider_fee_pool_addr_str": "", - "ccv_timeout_period": "2419200s", - "transfer_timeout_period": "3600s", - "consumer_redistribution_fraction": "0.75", - "historical_entries": "10000", - "unbonding_period": "1209600s", - "soft_opt_out_threshold": "0.05", - "reward_denoms": [], - "provider_reward_denoms": [], - "retry_delay_period": "3600s" - }, - "provider": { - "client_state": { - "chain_id": "provi", - "trust_level": { - "numerator": "1", - "denominator": "3" - }, - "trusting_period": "1197504s", - "unbonding_period": "1814400s", - "max_clock_drift": "10s", - "frozen_height": { - "revision_number": "0", - "revision_height": "0" - }, - "latest_height": { - "revision_number": "0", - "revision_height": "20" - }, - "proof_specs": [ - { - "leaf_spec": { - "hash": "SHA256", - "prehash_key": "NO_HASH", - "prehash_value": "SHA256", - "length": "VAR_PROTO", - "prefix": "AA==" - }, - "inner_spec": { - "child_order": [ - 0, - 1 - ], - "child_size": 33, - "min_prefix_length": 4, - "max_prefix_length": 12, - "empty_child": null, - "hash": "SHA256" - }, - "max_depth": 0, - "min_depth": 0, - "prehash_key_before_comparison": false - }, - { - "leaf_spec": { - "hash": "SHA256", - "prehash_key": "NO_HASH", - "prehash_value": "SHA256", - "length": "VAR_PROTO", - "prefix": "AA==" - }, - "inner_spec": { - "child_order": [ - 0, - 1 - ], - "child_size": 32, - "min_prefix_length": 1, - "max_prefix_length": 1, - "empty_child": null, - "hash": "SHA256" - }, - "max_depth": 0, - "min_depth": 0, - "prehash_key_before_comparison": false - } - ], - "upgrade_path": [ - "upgrade", - "upgradedIBCState" - ], - "allow_update_after_expiry": false, - "allow_update_after_misbehaviour": false - }, - "consensus_state": { - "timestamp": "2023-12-15T09:57:02.687079137Z", - "root": { - "hash": "EH9YbrWC3Qojy8ycl5GhOdVEC1ifPIGUUItL70bTkHo=" - }, - "next_validators_hash": "632730A03DEF630F77B61DF4092629007AE020B789713158FABCB104962FA54F" - }, - "initial_val_set": [ - { - "pub_key": { - "ed25519": "RrclQz9bIhkIy/gfL485g3PYMeiIku4qeo495787X10=" - }, - "power": "500" - }, - { - "pub_key": { - "ed25519": "Ui5Gf1+mtWUdH8u3xlmzdKID+F3PK0sfXZ73GZ6q6is=" - }, - "power": "500" - }, - { - "pub_key": { - "ed25519": "mAN6RXYxSM4MNGSIriYiS7pHuwAcOHDQAy9/wnlSzOI=" - }, - "power": "500" - } - ] - }, - "new_chain": true - } - `, -} - -// creates ccv consumer genesis data content for a given version -// as it was exported from a provider -func createConsumerDataGenesisFile(t *testing.T, version string) string { - t.Helper() - filePath := filepath.Join(t.TempDir(), fmt.Sprintf("ConsumerGenesis_%s.json", version)) - err := os.WriteFile( - filePath, - []byte(consumerGenesisStates[version]), - fs.FileMode(0o644)) - require.NoError(t, err, "Error creating source genesis data for version %s", version) - return filePath -} - -func getClientCtx() client.Context { - encodingConfig := app.MakeTestEncodingConfig() - return client.Context{}. - WithCodec(encodingConfig.Codec). - WithInterfaceRegistry(encodingConfig.InterfaceRegistry). - WithTxConfig(encodingConfig.TxConfig). - WithLegacyAmino(encodingConfig.Amino). - WithInput(os.Stdin). - WithAccountRetriever(types.AccountRetriever{}) -} - -// getGenesisTransformCmd sets up client context and returns -// genesis transformation command (UUT) -func getGenesisTransformCmd() (*cobra.Command, error) { - cmd := app.GetConsumerGenesisTransformCmd() - clientCtx := getClientCtx() - ctx := context.WithValue(context.Background(), client.ClientContextKey, &clientCtx) - cmd.SetContext(ctx) - err := client.SetCmdClientContext(cmd, clientCtx) - return cmd, err -} - -// transformConsumerGenesis transform json content in a given file and return -// the consumer genesis transformation result or an error -// - filePath file with consumer genesis content in json format -// - version ICS version to which the data should be transformed to -func transformConsumerGenesis(filePath string, version *string) ([]byte, error) { - cmd, err := getGenesisTransformCmd() - if err != nil { - return nil, fmt.Errorf("Error setting up transformation command: %s", err) - } - - args := []string{} - if version != nil { - args = append(args, fmt.Sprintf("--to=%s", *version)) - } - args = append(args, filePath) - - cmd.SetArgs(args) - - result := new(bytes.Buffer) - cmd.SetOutput(result) - _, err = cmd.ExecuteC() - if err != nil { - return nil, fmt.Errorf("Error running transformation command: %v", err) - } - return result.Bytes(), nil -} - -// Check transformation of a version 2 ConsumerGenesis export to -// consumer genesis json format used by current consumer implementation. -func TestConsumerGenesisTransformationFromV2ToCurrent(t *testing.T) { - version := V2x - ctx := getClientCtx() - - srcGenesis := consumerTypes.GenesisState{} - err := ctx.Codec.UnmarshalJSON([]byte(consumerGenesisStates[version]), &srcGenesis) - require.NoError(t, err, "Error parsing old version of ccv genesis content for consumer") - - filePath := createConsumerDataGenesisFile(t, version) - defer os.Remove(filePath) - resultGenesis := consumerTypes.GenesisState{} - result, err := transformConsumerGenesis(filePath, nil) - require.NoError(t, err) - err = ctx.Codec.UnmarshalJSON(result, &resultGenesis) - require.NoError(t, err) - - // Some basic sanity checks on the content. - require.NotNil(t, resultGenesis.Provider.ClientState) - require.Equal(t, "cosmoshub-4", resultGenesis.Provider.ClientState.ChainId) - - require.Empty(t, resultGenesis.InitialValSet) - require.NotEmpty(t, resultGenesis.Provider.InitialValSet) - require.Equal(t, resultGenesis.Params.RetryDelayPeriod, ccvtypes.DefaultRetryDelayPeriod) - - // Check params: retry_delay_period prevents direct comparison - require.EqualValues(t, srcGenesis.Params.Enabled, resultGenesis.Params.Enabled) - require.EqualValues(t, srcGenesis.Params.BlocksPerDistributionTransmission, resultGenesis.Params.BlocksPerDistributionTransmission) - require.EqualValues(t, srcGenesis.Params.DistributionTransmissionChannel, resultGenesis.Params.DistributionTransmissionChannel) - require.EqualValues(t, srcGenesis.Params.ProviderFeePoolAddrStr, resultGenesis.Params.ProviderFeePoolAddrStr) - require.EqualValues(t, srcGenesis.Params.CcvTimeoutPeriod, resultGenesis.Params.CcvTimeoutPeriod) - require.EqualValues(t, srcGenesis.Params.TransferTimeoutPeriod, resultGenesis.Params.TransferTimeoutPeriod) - require.EqualValues(t, srcGenesis.Params.ConsumerRedistributionFraction, resultGenesis.Params.ConsumerRedistributionFraction) - require.EqualValues(t, srcGenesis.Params.HistoricalEntries, resultGenesis.Params.HistoricalEntries) - require.EqualValues(t, srcGenesis.Params.UnbondingPeriod, resultGenesis.Params.UnbondingPeriod) - - // `SoftOptOutThreshold` is deprecated, so it should be set to zero the current version - require.EqualValues(t, "0", resultGenesis.Params.SoftOptOutThreshold) - require.EqualValues(t, srcGenesis.Params.RewardDenoms, resultGenesis.Params.RewardDenoms) - require.EqualValues(t, srcGenesis.Params.ProviderRewardDenoms, resultGenesis.Params.ProviderRewardDenoms) - - require.Equal(t, srcGenesis.ProviderClientState, resultGenesis.Provider.ClientState) - require.Nil(t, resultGenesis.ProviderClientState) - - require.Equal(t, srcGenesis.Provider.ConsensusState, resultGenesis.ProviderConsensusState) - require.Nil(t, resultGenesis.ProviderConsensusState) - - require.Equal(t, srcGenesis.NewChain, resultGenesis.NewChain) - require.Equal(t, "", resultGenesis.ProviderClientId) - require.Equal(t, "", resultGenesis.ProviderChannelId) - require.Equal(t, srcGenesis.InitialValSet, resultGenesis.Provider.InitialValSet) - require.Empty(t, resultGenesis.InitialValSet) -} - -// Check transformation of provider v3.3.x implementation to consumer V2 -func TestConsumerGenesisTransformationV330ToV2(t *testing.T) { - version := V33x - filePath := createConsumerDataGenesisFile(t, version) - defer os.Remove(filePath) - - var srcGenesis consumerTypes.GenesisState - ctx := getClientCtx() - err := ctx.Codec.UnmarshalJSON([]byte(consumerGenesisStates[version]), &srcGenesis) - require.NoError(t, err) - - targetVersion := V2x - result, err := transformConsumerGenesis(filePath, &targetVersion) - require.NoError(t, err) - - resultGenesis := consumerTypes.GenesisState{} - err = ctx.Codec.UnmarshalJSON(result, &resultGenesis) - require.NoError(t, err) - - require.Equal(t, srcGenesis.Params, resultGenesis.Params) - require.Equal(t, srcGenesis.Provider.ClientState, resultGenesis.ProviderClientState) - require.Equal(t, srcGenesis.Provider.ConsensusState, resultGenesis.ProviderConsensusState) - require.Equal(t, srcGenesis.NewChain, resultGenesis.NewChain) - require.Equal(t, "", resultGenesis.ProviderClientId) - require.Equal(t, "", resultGenesis.ProviderChannelId) -} - -// Check transformation of provider v3.3.x implementation to current consumer version -func TestConsumerGenesisTransformationV330ToCurrent(t *testing.T) { - version := V33x - filePath := createConsumerDataGenesisFile(t, version) - defer os.Remove(filePath) - - var srcGenesis consumerTypes.GenesisState - ctx := getClientCtx() - err := ctx.Codec.UnmarshalJSON([]byte(consumerGenesisStates[version]), &srcGenesis) - require.NoError(t, err) - - result, err := transformConsumerGenesis(filePath, nil) - require.NoError(t, err) - - resultGenesis := consumerTypes.GenesisState{} - err = ctx.Codec.UnmarshalJSON(result, &resultGenesis) - require.NoError(t, err) - - require.Equal(t, srcGenesis.Params.Enabled, resultGenesis.Params.Enabled) - require.Equal(t, srcGenesis.Params.BlocksPerDistributionTransmission, resultGenesis.Params.BlocksPerDistributionTransmission) - require.Equal(t, srcGenesis.Params.DistributionTransmissionChannel, resultGenesis.Params.DistributionTransmissionChannel) - require.Equal(t, srcGenesis.Params.ProviderFeePoolAddrStr, resultGenesis.Params.ProviderFeePoolAddrStr) - require.Equal(t, srcGenesis.Params.CcvTimeoutPeriod, resultGenesis.Params.CcvTimeoutPeriod) - require.Equal(t, srcGenesis.Params.TransferTimeoutPeriod, resultGenesis.Params.TransferTimeoutPeriod) - require.Equal(t, srcGenesis.Params.ConsumerRedistributionFraction, resultGenesis.Params.ConsumerRedistributionFraction) - require.Equal(t, srcGenesis.Params.HistoricalEntries, resultGenesis.Params.HistoricalEntries) - require.Equal(t, srcGenesis.Params.UnbondingPeriod, resultGenesis.Params.UnbondingPeriod) - - // `SoftOptOutThreshold` is deprecated, so it should be set to zero the current version - require.Equal(t, "0", resultGenesis.Params.SoftOptOutThreshold) - - require.Equal(t, srcGenesis.Params.RewardDenoms, resultGenesis.Params.RewardDenoms) - require.Equal(t, srcGenesis.Params.ProviderRewardDenoms, resultGenesis.Params.ProviderRewardDenoms) - - require.Equal(t, resultGenesis.Params.RetryDelayPeriod, ccvtypes.DefaultRetryDelayPeriod) - - require.Equal(t, srcGenesis.Provider.ClientState, resultGenesis.Provider.ClientState) - require.Nil(t, resultGenesis.ProviderClientState) - require.Nil(t, resultGenesis.ProviderConsensusState) - - require.Equal(t, srcGenesis.Provider.ConsensusState, resultGenesis.Provider.ConsensusState) - require.Equal(t, srcGenesis.NewChain, resultGenesis.NewChain) - require.Equal(t, "", resultGenesis.ProviderClientId) - require.Equal(t, "", resultGenesis.ProviderChannelId) -} - -// Check transformation of provider v4.x implementation to consumer V2 -func TestConsumerGenesisTransformationV4ToV2(t *testing.T) { - version := V4x - filePath := createConsumerDataGenesisFile(t, version) - defer os.Remove(filePath) - - var srcGenesis consumerTypes.GenesisState - ctx := getClientCtx() - err := ctx.Codec.UnmarshalJSON([]byte(consumerGenesisStates[version]), &srcGenesis) - require.NoError(t, err) - - targetVersion := V2x - result, err := transformConsumerGenesis(filePath, &targetVersion) - require.NoError(t, err) - - resultGenesis := consumerTypes.GenesisState{} - err = ctx.Codec.UnmarshalJSON(result, &resultGenesis) - require.NoError(t, err) - - // Check params: retry_delay_period prevents direct comparison - require.EqualValues(t, srcGenesis.Params.Enabled, resultGenesis.Params.Enabled) - require.EqualValues(t, srcGenesis.Params.BlocksPerDistributionTransmission, resultGenesis.Params.BlocksPerDistributionTransmission) - require.EqualValues(t, srcGenesis.Params.DistributionTransmissionChannel, resultGenesis.Params.DistributionTransmissionChannel) - require.EqualValues(t, srcGenesis.Params.ProviderFeePoolAddrStr, resultGenesis.Params.ProviderFeePoolAddrStr) - require.EqualValues(t, srcGenesis.Params.CcvTimeoutPeriod, resultGenesis.Params.CcvTimeoutPeriod) - require.EqualValues(t, srcGenesis.Params.TransferTimeoutPeriod, resultGenesis.Params.TransferTimeoutPeriod) - require.EqualValues(t, srcGenesis.Params.ConsumerRedistributionFraction, resultGenesis.Params.ConsumerRedistributionFraction) - require.EqualValues(t, srcGenesis.Params.HistoricalEntries, resultGenesis.Params.HistoricalEntries) - require.EqualValues(t, srcGenesis.Params.UnbondingPeriod, resultGenesis.Params.UnbondingPeriod) - require.EqualValues(t, srcGenesis.Params.SoftOptOutThreshold, resultGenesis.Params.SoftOptOutThreshold) - require.EqualValues(t, srcGenesis.Params.RewardDenoms, resultGenesis.Params.RewardDenoms) - require.EqualValues(t, srcGenesis.Params.ProviderRewardDenoms, resultGenesis.Params.ProviderRewardDenoms) - require.Equal(t, resultGenesis.Params.RetryDelayPeriod, time.Duration(0)) - - require.Equal(t, srcGenesis.Provider.ClientState, resultGenesis.ProviderClientState) - require.Nil(t, resultGenesis.Provider.ClientState) - require.Equal(t, srcGenesis.Provider.ConsensusState, resultGenesis.ProviderConsensusState) - require.Nil(t, resultGenesis.Provider.ConsensusState) - require.Equal(t, "", resultGenesis.ProviderClientId) - require.Equal(t, "", resultGenesis.ProviderChannelId) - - require.Equal(t, 0, len(resultGenesis.Provider.InitialValSet)) - require.Equal(t, srcGenesis.Provider.InitialValSet, resultGenesis.InitialValSet) - require.Empty(t, resultGenesis.Provider.InitialValSet) - - require.Equal(t, srcGenesis.NewChain, resultGenesis.NewChain) -} - -// Check transformation of provider v3.3.x implementation to consumer V2 -func TestConsumerGenesisTransformationV4ToV33(t *testing.T) { - version := V4x - filePath := createConsumerDataGenesisFile(t, version) - defer os.Remove(filePath) - - var srcGenesis ccvtypes.ConsumerGenesisState - ctx := getClientCtx() - err := ctx.Codec.UnmarshalJSON([]byte(consumerGenesisStates[version]), &srcGenesis) - require.NoError(t, err) - - targetVersion := V33x - result, err := transformConsumerGenesis(filePath, &targetVersion) - require.NoError(t, err) - resultGenesis := consumerTypes.GenesisState{} // Only difference to v33 is no RetryDelayPeriod - err = ctx.Codec.UnmarshalJSON(result, &resultGenesis) - require.NoError(t, err) - - // Check params: retry_delay_period prevents direct comparison - require.EqualValues(t, srcGenesis.Params.Enabled, resultGenesis.Params.Enabled) - require.EqualValues(t, srcGenesis.Params.BlocksPerDistributionTransmission, resultGenesis.Params.BlocksPerDistributionTransmission) - require.EqualValues(t, srcGenesis.Params.DistributionTransmissionChannel, resultGenesis.Params.DistributionTransmissionChannel) - require.EqualValues(t, srcGenesis.Params.ProviderFeePoolAddrStr, resultGenesis.Params.ProviderFeePoolAddrStr) - require.EqualValues(t, srcGenesis.Params.CcvTimeoutPeriod, resultGenesis.Params.CcvTimeoutPeriod) - require.EqualValues(t, srcGenesis.Params.TransferTimeoutPeriod, resultGenesis.Params.TransferTimeoutPeriod) - require.EqualValues(t, srcGenesis.Params.ConsumerRedistributionFraction, resultGenesis.Params.ConsumerRedistributionFraction) - require.EqualValues(t, srcGenesis.Params.HistoricalEntries, resultGenesis.Params.HistoricalEntries) - require.EqualValues(t, srcGenesis.Params.UnbondingPeriod, resultGenesis.Params.UnbondingPeriod) - require.EqualValues(t, srcGenesis.Params.SoftOptOutThreshold, resultGenesis.Params.SoftOptOutThreshold) - require.EqualValues(t, srcGenesis.Params.RewardDenoms, resultGenesis.Params.RewardDenoms) - require.EqualValues(t, srcGenesis.Params.ProviderRewardDenoms, resultGenesis.Params.ProviderRewardDenoms) - - require.Equal(t, srcGenesis.Provider.ClientState, resultGenesis.Provider.ClientState) - require.Nil(t, resultGenesis.ProviderClientState) - - require.Equal(t, srcGenesis.Provider.ConsensusState, resultGenesis.Provider.ConsensusState) - require.Nil(t, resultGenesis.ProviderConsensusState) - - require.Equal(t, srcGenesis.NewChain, resultGenesis.NewChain) - require.Equal(t, "", resultGenesis.ProviderClientId) - require.Equal(t, "", resultGenesis.ProviderChannelId) - require.Equal(t, srcGenesis.Provider.InitialValSet, resultGenesis.Provider.InitialValSet) - require.Empty(t, resultGenesis.InitialValSet) -} diff --git a/cmd/interchain-security-cd/cmd/root.go b/cmd/interchain-security-cd/cmd/root.go index 42cd15c482..7067fea12a 100644 --- a/cmd/interchain-security-cd/cmd/root.go +++ b/cmd/interchain-security-cd/cmd/root.go @@ -88,7 +88,7 @@ func NewRootCmd() *cobra.Command { }, } - initRootCmd(rootCmd, encodingConfig) + initRootCmd(rootCmd) autoCliOpts, err := enrichAutoCliOpts(tempApp.AutoCliOpts(), initClientCtx) if err != nil { panic(err) @@ -203,7 +203,7 @@ lru_size = 0` return customAppTemplate, customAppConfig } -func initRootCmd(rootCmd *cobra.Command, encodingConfig appencoding.EncodingConfig) { +func initRootCmd(rootCmd *cobra.Command) { rootCmd.AddCommand( genutilcli.InitCmd(consumer.ModuleBasics, consumer.DefaultNodeHome), debug.Cmd(), @@ -216,7 +216,6 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig appencoding.EncodingConf // add keybase, auxiliary RPC, query, genesis, and tx child commands rootCmd.AddCommand( server.StatusCommand(), - genesisCommand(encodingConfig, consumer.GetConsumerGenesisTransformCmd()), queryCommand(), txCommand(), keys.Commands(), @@ -286,16 +285,6 @@ func addModuleInitFlags(startCmd *cobra.Command) { crisis.AddModuleInitFlags(startCmd) } -// genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter -func genesisCommand(encodingConfig appencoding.EncodingConfig, cmds ...*cobra.Command) *cobra.Command { - cmd := genutilcli.GenesisCoreCommand(encodingConfig.TxConfig, consumer.ModuleBasics, consumer.DefaultNodeHome) - - for _, sub_cmd := range cmds { - cmd.AddCommand(sub_cmd) - } - return cmd -} - func queryCommand() *cobra.Command { cmd := &cobra.Command{ Use: "query", From 633ffb6f8747e02dd3f435c0906eacd8f076238b Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 25 Oct 2024 08:27:44 +0000 Subject: [PATCH 10/12] Update testing documentation --- scripts/test_doc/test_documentation.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/scripts/test_doc/test_documentation.md b/scripts/test_doc/test_documentation.md index 1bdbaee73d..661d684949 100644 --- a/scripts/test_doc/test_documentation.md +++ b/scripts/test_doc/test_documentation.md @@ -49,7 +49,7 @@ | Function | Short Description | |----------|-------------------| [TestVSCPacketSendExpiredClient](../../tests/integration/expired_client.go#L29) | TestVSCPacketSendExpiredClient tests queueing of VSCPackets when the consumer client is expired.
Details* Set up a CCV channel and expire the client on consumer chain.
* Bond tokens to provider, send CCV packet to consumer and check pending packets.
* While the consumer client is expired (or inactive for some reason) all packets will be queued.
* The packet sending and checks are then repeated.
* More tokens are bonded on provider to change validator powers.
* Upgrade expired client to the consumer and all packets are cleared once the consumer client is established.
| - [TestConsumerPacketSendExpiredClient](../../tests/integration/expired_client.go#L99) | TestConsumerPacketSendExpiredClient tests the consumer sending packets when the provider client is expired.
Details* Set up a CCV channel and bond tokens on provider.
* Send CCV packet to consumer and rebond tokens on provider.
* Check for pending VSC packets and relay all VSC packets to consumer.
* The provider client is then expired.
* Confirm that while the provider client is expired all packets will be queued and then cleared
once the provider client is upgraded.
| + [TestConsumerPacketSendExpiredClient](../../tests/integration/expired_client.go#L95) | TestConsumerPacketSendExpiredClient tests the consumer sending packets when the provider client is expired.
Details* Set up a CCV channel and bond tokens on provider.
* Send CCV packet to consumer and rebond tokens on provider.
* Check for pending VSC packets and relay all VSC packets to consumer.
* The provider client is then expired.
* Confirm that while the provider client is expired all packets will be queued and then cleared
once the provider client is upgraded.
| # [key_assignment.go](../../tests/integration/key_assignment.go) @@ -136,7 +136,6 @@ | Function | Short Description | |----------|-------------------| - [TestPacketRoundtrip](../../tests/integration/valset_update.go#L23) | TestPacketRoundtrip tests a CCV packet roundtrip when tokens are bonded on the provider.
Details* Set up CCV and transfer channels.
* Bond some tokens on the provider side in order to change validator power.
* Relay a packet from the provider chain to the consumer chain.
* Relays a matured packet from the consumer chain back to the provider chain.
| - [TestQueueAndSendVSCMaturedPackets](../../tests/integration/valset_update.go#L59) | TestQueueAndSendVSCMaturedPackets tests the behavior of EndBlock QueueVSCMaturedPackets call and its integration with SendPackets call.
Details* Set up CCV channel.
* Create and simulate the sending of three VSC packets from the provider chain to the consumer chain at different times.
* Send the first packet and validate its processing.
* Simulate the passage of one hour.
* Send the second packet and validate its processing.
* Simulate the passage of 24 more hours.
* Send the third packet and validate its processing.
* Retrieve all packet maturity times from the consumer, and use this to check the maturity status of the packets sent earlier.
* Advance the time so that the first two packets reach their unbonding period, while the third packet does not.
* Ensure first two packets are unbonded, their maturity times are deleted, and that VSCMatured packets are queued.
* The third packet is still in the store and has not yet been processed for unbonding.
* Checks that the packet commitments for the processed packets are correctly reflected in the consumer chain's state.
| + [TestPacketRoundtrip](../../tests/integration/valset_update.go#L15) | TestPacketRoundtrip tests a CCV packet roundtrip when tokens are bonded on the provider.
Details* Set up CCV and transfer channels.
* Bond some tokens on the provider side in order to change validator power.
* Relay a packet from the provider chain to the consumer chain.
* Relays a matured packet from the consumer chain back to the provider chain.
| From 7bbbbb6cd3d2369c92d57d1b7991c8e25fbcf637 Mon Sep 17 00:00:00 2001 From: mpoke Date: Tue, 5 Nov 2024 09:40:21 +0100 Subject: [PATCH 11/12] Revert "remove genesis transformation" This reverts commit 89b1d05a1c6d0eee92c4db2cccdc6e5d549d4a90. --- app/consumer/genesis.go | 335 ++++++++++++ app/consumer/genesis_test.go | 680 +++++++++++++++++++++++++ cmd/interchain-security-cd/cmd/root.go | 15 +- 3 files changed, 1028 insertions(+), 2 deletions(-) create mode 100644 app/consumer/genesis_test.go diff --git a/app/consumer/genesis.go b/app/consumer/genesis.go index 5bf0c1da80..be56824856 100644 --- a/app/consumer/genesis.go +++ b/app/consumer/genesis.go @@ -2,8 +2,22 @@ package app import ( "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "github.com/spf13/cobra" + "golang.org/x/exp/maps" + + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/version" + + consumerTypes "github.com/cosmos/interchain-security/v6/x/ccv/consumer/types" + "github.com/cosmos/interchain-security/v6/x/ccv/types" ) // The genesis state of the blockchain is represented here as a map of raw json @@ -15,7 +29,328 @@ import ( // object provided to it during init. type GenesisState map[string]json.RawMessage +// Map of supported versions for consumer genesis transformation +type IcsVersion string + +const ( + v2_x IcsVersion = "v2.x" + v3_0_x IcsVersion = "v3.0.x" + v3_1_x IcsVersion = "v3.1.x" + v3_2_x IcsVersion = "v3.2.x" + v3_3_x IcsVersion = "v3.3.x" + v4_x_x IcsVersion = "v4.x" +) + +var TransformationVersions map[string]IcsVersion = map[string]IcsVersion{ + "v2.x": v2_x, + "v3.0.x": v3_0_x, + "v3.1.x": v3_1_x, + "v3.2.x": v3_2_x, + "v3.3.x": v3_3_x, + "v4.x": v4_x_x, +} + +// Transformation of consumer genesis content as it is exported from a provider version v1,2,3 +// to a format readable by current consumer implementation. +func transformToNew(jsonRaw []byte, ctx client.Context) (json.RawMessage, error) { + // v1,2,3 uses deprecated fields of GenesisState type + oldConsumerGenesis := consumerTypes.GenesisState{} + err := ctx.Codec.UnmarshalJSON(jsonRaw, &oldConsumerGenesis) + if err != nil { + return nil, fmt.Errorf("reading consumer genesis data failed: %s", err) + } + + initialValSet := oldConsumerGenesis.InitialValSet + // transformation from >= v3.3.x + if len(initialValSet) == 0 { + initialValSet = oldConsumerGenesis.Provider.InitialValSet + } + + clientState := oldConsumerGenesis.ProviderClientState + if clientState == nil { + clientState = oldConsumerGenesis.Provider.ClientState + } + + consensusState := oldConsumerGenesis.ProviderConsensusState + if consensusState == nil { + consensusState = oldConsumerGenesis.Provider.ConsensusState + } + + // Use DefaultRetryDelayPeriod if not set + if oldConsumerGenesis.Params.RetryDelayPeriod == 0 { + oldConsumerGenesis.Params.RetryDelayPeriod = types.DefaultRetryDelayPeriod + } + + // `SoftOptOutThreshold` is deprecated in the current consumer implementation, so set to zero + oldConsumerGenesis.Params.SoftOptOutThreshold = "0" + + // Versions before v3.3.x of provider genesis data fills up deprecated fields + // ProviderClientState, ConsensusState and InitialValSet in type GenesisState + newGenesis := types.ConsumerGenesisState{ + Params: oldConsumerGenesis.Params, + Provider: types.ProviderInfo{ + ClientState: clientState, + ConsensusState: consensusState, + InitialValSet: initialValSet, + }, + NewChain: oldConsumerGenesis.NewChain, + } + + newJson, err := ctx.Codec.MarshalJSON(&newGenesis) + if err != nil { + return nil, fmt.Errorf("failed marshalling data to new type: %s", err) + } + return newJson, nil +} + +// Transformation of consumer genesis content as it is exported by current provider version +// to a format supported by consumer version v3.3.x +func transformToV33(jsonRaw []byte, ctx client.Context) ([]byte, error) { + // v1,2,3 uses deprecated fields of GenesisState type + srcConGen := consumerTypes.GenesisState{} + err := ctx.Codec.UnmarshalJSON(jsonRaw, &srcConGen) + if err != nil { + return nil, fmt.Errorf("reading consumer genesis data failed: %s", err) + } + + // Remove retry_delay_period from 'params' + params, err := ctx.Codec.MarshalJSON(&srcConGen.Params) + if err != nil { + return nil, err + } + tmp := map[string]json.RawMessage{} + if err := json.Unmarshal(params, &tmp); err != nil { + return nil, fmt.Errorf("unmarshalling 'params' failed: %v", err) + } + _, exists := tmp["retry_delay_period"] + if exists { + delete(tmp, "retry_delay_period") + } + params, err = json.Marshal(tmp) + if err != nil { + return nil, err + } + + // Marshal GenesisState and patch 'params' value + result, err := ctx.Codec.MarshalJSON(&srcConGen) + if err != nil { + return nil, err + } + genState := map[string]json.RawMessage{} + if err := json.Unmarshal(result, &genState); err != nil { + return nil, fmt.Errorf("unmarshalling 'GenesisState' failed: %v", err) + } + genState["params"] = params + + result, err = json.Marshal(genState) + if err != nil { + return nil, fmt.Errorf("marshalling transformation result failed: %v", err) + } + return result, nil +} + +// Transformation of consumer genesis content as it is exported from current provider version +// to a format readable by consumer implementation of version v2.x +// Use removePreHashKey to remove prehash_key_before_comparison from result. +func transformToV2(jsonRaw []byte, ctx client.Context, removePreHashKey bool) (json.RawMessage, error) { + // populate deprecated fields of GenesisState used by version v2.x + srcConGen := consumerTypes.GenesisState{} + err := ctx.Codec.UnmarshalJSON(jsonRaw, &srcConGen) + if err != nil { + return nil, fmt.Errorf("reading consumer genesis data failed: %s", err) + } + + // remove retry_delay_period from 'params' if present (introduced in v4.x) + params, err := ctx.Codec.MarshalJSON(&srcConGen.Params) + if err != nil { + return nil, err + } + paramsMap := map[string]json.RawMessage{} + if err := json.Unmarshal(params, ¶msMap); err != nil { + return nil, fmt.Errorf("unmarshalling 'params' failed: %v", err) + } + _, exists := paramsMap["retry_delay_period"] + if exists { + delete(paramsMap, "retry_delay_period") + } + params, err = json.Marshal(paramsMap) + if err != nil { + return nil, err + } + + // marshal GenesisState and patch 'params' value + result, err := ctx.Codec.MarshalJSON(&srcConGen) + if err != nil { + return nil, err + } + genState := map[string]json.RawMessage{} + if err := json.Unmarshal(result, &genState); err != nil { + return nil, fmt.Errorf("unmarshalling 'GenesisState' failed: %v", err) + } + genState["params"] = params + + provider, err := ctx.Codec.MarshalJSON(&srcConGen.Provider) + if err != nil { + return nil, fmt.Errorf("marshalling 'Provider' failed: %v", err) + } + providerMap := map[string]json.RawMessage{} + if err := json.Unmarshal(provider, &providerMap); err != nil { + return nil, fmt.Errorf("unmarshalling 'provider' failed: %v", err) + } + + // patch .initial_val_set form .provider.initial_val_set if needed + if len(srcConGen.Provider.InitialValSet) > 0 { + valSet, exists := providerMap["initial_val_set"] + if !exists { + return nil, fmt.Errorf("'initial_val_set' not found in provider data") + } + _, exists = genState["initial_val_set"] + if exists { + genState["initial_val_set"] = valSet + } + } + + // patch .provider_consensus_state from provider.consensus_state if needed + if srcConGen.Provider.ConsensusState != nil { + valSet, exists := providerMap["consensus_state"] + if !exists { + return nil, fmt.Errorf("'consensus_state' not found in provider data") + } + _, exists = genState["provider_consensus_state"] + if exists { + genState["provider_consensus_state"] = valSet + } + } + + // patch .provider_client_state from provider.client_state if needed + if srcConGen.Provider.ClientState != nil { + clientState, exists := providerMap["client_state"] + if !exists { + return nil, fmt.Errorf("'client_state' not found in provider data") + } + _, exists = genState["provider_client_state"] + if exists { + genState["provider_client_state"] = clientState + } + } + + // delete .provider entry (introduced in v3.3.x) + delete(genState, "provider") + + // Marshall final result + result, err = json.Marshal(genState) + if err != nil { + return nil, fmt.Errorf("marshalling transformation result failed: %v", err) + } + + if removePreHashKey { + // remove all `prehash_key_before_comparison` entries not supported in v2.x (see ics23) + re := regexp.MustCompile(`,\s*"prehash_key_before_comparison"\s*:\s*(false|true)`) + result = re.ReplaceAll(result, []byte{}) + } + return result, nil +} + +// transformGenesis transforms ccv consumer genesis data to the specified target version +// Returns the transformed data or an error in case the transformation failed or the format is not supported by current implementation +func transformGenesis(ctx client.Context, targetVersion IcsVersion, jsonRaw []byte) (json.RawMessage, error) { + var newConsumerGenesis json.RawMessage = nil + var err error + + switch targetVersion { + // v2.x, v3.0-v3.2 share same consumer genesis type + case v2_x: + newConsumerGenesis, err = transformToV2(jsonRaw, ctx, true) + case v3_0_x, v3_1_x, v3_2_x: + // same as v2 replacement without need of `prehash_key_before_comparison` removal + newConsumerGenesis, err = transformToV2(jsonRaw, ctx, false) + case v3_3_x: + newConsumerGenesis, err = transformToV33(jsonRaw, ctx) + case v4_x_x: + newConsumerGenesis, err = transformToNew(jsonRaw, ctx) + default: + err = fmt.Errorf("unsupported target version '%s'. Run %s --help", + targetVersion, version.AppName) + } + + if err != nil { + return nil, fmt.Errorf("transformation failed: %v", err) + } + return newConsumerGenesis, err +} + +// Transform a consumer genesis json file exported from a given ccv provider version +// to a consumer genesis json format supported by current ccv consumer version or v2.x +// This allows user to patch consumer genesis of +// - current implementation from exports of provider of < v3.3.x +// - v2.x from exports of provider >= v3.2.x +// +// Result will be written to defined output. +func TransformConsumerGenesis(cmd *cobra.Command, args []string) error { + sourceFile := args[0] + jsonRaw, err := os.ReadFile(filepath.Clean(sourceFile)) + if err != nil { + return err + } + + clientCtx := client.GetClientContextFromCmd(cmd) + version, err := cmd.Flags().GetString("to") + if err != nil { + return fmt.Errorf("error getting targetVersion %v", err) + } + targetVersion, exists := TransformationVersions[version] + if !exists { + return fmt.Errorf("unsupported target version '%s'", version) + } + + // try to transform data to target format + newConsumerGenesis, err := transformGenesis(clientCtx, targetVersion, jsonRaw) + if err != nil { + return err + } + + bz, err := newConsumerGenesis.MarshalJSON() + if err != nil { + return fmt.Errorf("failed exporting new consumer genesis to JSON: %s", err) + } + + sortedBz, err := sdk.SortJSON(bz) + if err != nil { + return fmt.Errorf("failed sorting transformed consumer genesis JSON: %s", err) + } + + cmd.Println(string(sortedBz)) + return nil +} + // NewDefaultGenesisState generates the default state for the application. func NewDefaultGenesisState(cdc codec.JSONCodec) GenesisState { return ModuleBasics.DefaultGenesis(cdc) } + +// GetConsumerGenesisTransformCmd transforms Consumer Genesis JSON content exported from a +// provider version v1,v2 or v3 to a JSON format supported by this consumer version. +func GetConsumerGenesisTransformCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "transform [-to version] genesis-file", + Short: "Transform CCV consumer genesis data exported to a specific target format", + Long: strings.TrimSpace( + fmt.Sprintf(` +Transform the consumer genesis data exported from a provider version v1,v2, v3, v4 to a specified consumer target version. +The result is printed to STDOUT. + +Note: Content to be transformed is not the consumer genesis file itself but the exported content from provider chain which is used to patch the consumer genesis file! + +Example: +$ %s transform /path/to/ccv_consumer_genesis.json +$ %s --to v2.x transform /path/to/ccv_consumer_genesis.json +`, version.AppName, version.AppName), + ), + Args: cobra.RangeArgs(1, 2), + RunE: TransformConsumerGenesis, + } + cmd.Flags().String("to", string(v4_x_x), + fmt.Sprintf("target version for consumer genesis. Supported versions %s", + maps.Keys(TransformationVersions))) + return cmd +} diff --git a/app/consumer/genesis_test.go b/app/consumer/genesis_test.go new file mode 100644 index 0000000000..144dbd74c9 --- /dev/null +++ b/app/consumer/genesis_test.go @@ -0,0 +1,680 @@ +package app_test + +import ( + "bytes" + "context" + "fmt" + "io/fs" + "os" + "path/filepath" + "testing" + "time" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/x/auth/types" + + app "github.com/cosmos/interchain-security/v6/app/consumer" + consumerTypes "github.com/cosmos/interchain-security/v6/x/ccv/consumer/types" + ccvtypes "github.com/cosmos/interchain-security/v6/x/ccv/types" +) + +const ( + V4x = "v4.x" + V33x = "v3.3.x" + V2x = "v2.x" +) + +// Testdata mapping consumer genesis exports to a provider module version as +// used by transformation function for consumer genesis content. +var consumerGenesisStates map[string]string = map[string]string{ + "v2.x": ` + { + "params": { + "enabled": true, + "blocks_per_distribution_transmission": "1500", + "distribution_transmission_channel": "", + "provider_fee_pool_addr_str": "", + "ccv_timeout_period": "2419200s", + "transfer_timeout_period": "3600s", + "consumer_redistribution_fraction": "0.75", + "historical_entries": "10000", + "unbonding_period": "1728000s", + "soft_opt_out_threshold": "", + "reward_denoms": [], + "provider_reward_denoms": [] + }, + "provider_client_id": "", + "provider_channel_id": "", + "new_chain": true, + "provider_client_state": { + "chain_id": "cosmoshub-4", + "trust_level": { + "numerator": "1", + "denominator": "3" + }, + "trusting_period": "1197504s", + "unbonding_period": "1814400s", + "max_clock_drift": "10s", + "frozen_height": { + "revision_number": "0", + "revision_height": "0" + }, + "latest_height": { + "revision_number": "4", + "revision_height": "15211521" + }, + "proof_specs": [ + { + "leaf_spec": { + "hash": "SHA256", + "prehash_key": "NO_HASH", + "prehash_value": "SHA256", + "length": "VAR_PROTO", + "prefix": "AA==" + }, + "inner_spec": { + "child_order": [ + 0, + 1 + ], + "child_size": 33, + "min_prefix_length": 4, + "max_prefix_length": 12, + "empty_child": null, + "hash": "SHA256" + }, + "max_depth": 0, + "min_depth": 0 + }, + { + "leaf_spec": { + "hash": "SHA256", + "prehash_key": "NO_HASH", + "prehash_value": "SHA256", + "length": "VAR_PROTO", + "prefix": "AA==" + }, + "inner_spec": { + "child_order": [ + 0, + 1 + ], + "child_size": 32, + "min_prefix_length": 1, + "max_prefix_length": 1, + "empty_child": null, + "hash": "SHA256" + }, + "max_depth": 0, + "min_depth": 0 + } + ], + "upgrade_path": [ + "upgrade", + "upgradedIBCState" + ], + "allow_update_after_expiry": true, + "allow_update_after_misbehaviour": true + }, + "provider_consensus_state": { + "timestamp": "2023-05-08T11:00:01.563901871Z", + "root": { + "hash": "qKVnVSXlsjDHC8ekKcy/0zSjzr3YekCurld9R4W07EI=" + }, + "next_validators_hash": "E08978F493101A3C5D459FB3087B8CFBA9E82D7A1FE1441E7D77E11AC0586BAC" + }, + "maturing_packets": [], + "initial_val_set": [ + { + "pub_key": { + "ed25519": "cOQZvh/h9ZioSeUMZB/1Vy1Xo5x2sjrVjlE/qHnYifM=" + }, + "power": "2345194" + }, + { + "pub_key": { + "ed25519": "vGSKfbQyKApvBhinpOOA0XQAdjxceihYNwtGskfZGyQ=" + }, + "power": "463811" + } + ], + "height_to_valset_update_id": [], + "outstanding_downtime_slashing": [], + "pending_consumer_packets": { + "list": [] + }, + "last_transmission_block_height": { + "height": "0" + }, + "preCCV": false + } + + `, + "v3.3.x": ` + { + "params": { + "enabled": true, + "blocks_per_distribution_transmission": "1000", + "distribution_transmission_channel": "", + "provider_fee_pool_addr_str": "", + "ccv_timeout_period": "2419200s", + "transfer_timeout_period": "3600s", + "consumer_redistribution_fraction": "0.75", + "historical_entries": "10000", + "unbonding_period": "1209600s", + "soft_opt_out_threshold": "0.05", + "reward_denoms": [], + "provider_reward_denoms": [] + }, + "provider": { + "client_state": { + "chain_id": "provi", + "trust_level": { + "numerator": "1", + "denominator": "3" + }, + "trusting_period": "1197504s", + "unbonding_period": "1814400s", + "max_clock_drift": "10s", + "frozen_height": { + "revision_number": "0", + "revision_height": "0" + }, + "latest_height": { + "revision_number": "0", + "revision_height": "20" + }, + "proof_specs": [ + { + "leaf_spec": { + "hash": "SHA256", + "prehash_key": "NO_HASH", + "prehash_value": "SHA256", + "length": "VAR_PROTO", + "prefix": "AA==" + }, + "inner_spec": { + "child_order": [ + 0, + 1 + ], + "child_size": 33, + "min_prefix_length": 4, + "max_prefix_length": 12, + "empty_child": null, + "hash": "SHA256" + }, + "max_depth": 0, + "min_depth": 0, + "prehash_key_before_comparison": false + }, + { + "leaf_spec": { + "hash": "SHA256", + "prehash_key": "NO_HASH", + "prehash_value": "SHA256", + "length": "VAR_PROTO", + "prefix": "AA==" + }, + "inner_spec": { + "child_order": [ + 0, + 1 + ], + "child_size": 32, + "min_prefix_length": 1, + "max_prefix_length": 1, + "empty_child": null, + "hash": "SHA256" + }, + "max_depth": 0, + "min_depth": 0, + "prehash_key_before_comparison": false + } + ], + "upgrade_path": [ + "upgrade", + "upgradedIBCState" + ], + "allow_update_after_expiry": false, + "allow_update_after_misbehaviour": false + }, + "consensus_state": { + "timestamp": "2023-12-15T09:25:46.098392003Z", + "root": { + "hash": "0aoNOwWy67aQKs2r+FcDf2RxIq2UJtBb3g9ZWn0Gkas=" + }, + "next_validators_hash": "632730A03DEF630F77B61DF4092629007AE020B789713158FABCB104962FA54F" + }, + "initial_val_set": [ + { + "pub_key": { + "ed25519": "RrclQz9bIhkIy/gfL485g3PYMeiIku4qeo495787X10=" + }, + "power": "500" + }, + { + "pub_key": { + "ed25519": "Ui5Gf1+mtWUdH8u3xlmzdKID+F3PK0sfXZ73GZ6q6is=" + }, + "power": "500" + }, + { + "pub_key": { + "ed25519": "mAN6RXYxSM4MNGSIriYiS7pHuwAcOHDQAy9/wnlSzOI=" + }, + "power": "500" + } + ] + }, + "new_chain": true + } + `, + "v4.x": ` + { + "params": { + "enabled": true, + "blocks_per_distribution_transmission": "1000", + "distribution_transmission_channel": "", + "provider_fee_pool_addr_str": "", + "ccv_timeout_period": "2419200s", + "transfer_timeout_period": "3600s", + "consumer_redistribution_fraction": "0.75", + "historical_entries": "10000", + "unbonding_period": "1209600s", + "soft_opt_out_threshold": "0.05", + "reward_denoms": [], + "provider_reward_denoms": [], + "retry_delay_period": "3600s" + }, + "provider": { + "client_state": { + "chain_id": "provi", + "trust_level": { + "numerator": "1", + "denominator": "3" + }, + "trusting_period": "1197504s", + "unbonding_period": "1814400s", + "max_clock_drift": "10s", + "frozen_height": { + "revision_number": "0", + "revision_height": "0" + }, + "latest_height": { + "revision_number": "0", + "revision_height": "20" + }, + "proof_specs": [ + { + "leaf_spec": { + "hash": "SHA256", + "prehash_key": "NO_HASH", + "prehash_value": "SHA256", + "length": "VAR_PROTO", + "prefix": "AA==" + }, + "inner_spec": { + "child_order": [ + 0, + 1 + ], + "child_size": 33, + "min_prefix_length": 4, + "max_prefix_length": 12, + "empty_child": null, + "hash": "SHA256" + }, + "max_depth": 0, + "min_depth": 0, + "prehash_key_before_comparison": false + }, + { + "leaf_spec": { + "hash": "SHA256", + "prehash_key": "NO_HASH", + "prehash_value": "SHA256", + "length": "VAR_PROTO", + "prefix": "AA==" + }, + "inner_spec": { + "child_order": [ + 0, + 1 + ], + "child_size": 32, + "min_prefix_length": 1, + "max_prefix_length": 1, + "empty_child": null, + "hash": "SHA256" + }, + "max_depth": 0, + "min_depth": 0, + "prehash_key_before_comparison": false + } + ], + "upgrade_path": [ + "upgrade", + "upgradedIBCState" + ], + "allow_update_after_expiry": false, + "allow_update_after_misbehaviour": false + }, + "consensus_state": { + "timestamp": "2023-12-15T09:57:02.687079137Z", + "root": { + "hash": "EH9YbrWC3Qojy8ycl5GhOdVEC1ifPIGUUItL70bTkHo=" + }, + "next_validators_hash": "632730A03DEF630F77B61DF4092629007AE020B789713158FABCB104962FA54F" + }, + "initial_val_set": [ + { + "pub_key": { + "ed25519": "RrclQz9bIhkIy/gfL485g3PYMeiIku4qeo495787X10=" + }, + "power": "500" + }, + { + "pub_key": { + "ed25519": "Ui5Gf1+mtWUdH8u3xlmzdKID+F3PK0sfXZ73GZ6q6is=" + }, + "power": "500" + }, + { + "pub_key": { + "ed25519": "mAN6RXYxSM4MNGSIriYiS7pHuwAcOHDQAy9/wnlSzOI=" + }, + "power": "500" + } + ] + }, + "new_chain": true + } + `, +} + +// creates ccv consumer genesis data content for a given version +// as it was exported from a provider +func createConsumerDataGenesisFile(t *testing.T, version string) string { + t.Helper() + filePath := filepath.Join(t.TempDir(), fmt.Sprintf("ConsumerGenesis_%s.json", version)) + err := os.WriteFile( + filePath, + []byte(consumerGenesisStates[version]), + fs.FileMode(0o644)) + require.NoError(t, err, "Error creating source genesis data for version %s", version) + return filePath +} + +func getClientCtx() client.Context { + encodingConfig := app.MakeTestEncodingConfig() + return client.Context{}. + WithCodec(encodingConfig.Codec). + WithInterfaceRegistry(encodingConfig.InterfaceRegistry). + WithTxConfig(encodingConfig.TxConfig). + WithLegacyAmino(encodingConfig.Amino). + WithInput(os.Stdin). + WithAccountRetriever(types.AccountRetriever{}) +} + +// getGenesisTransformCmd sets up client context and returns +// genesis transformation command (UUT) +func getGenesisTransformCmd() (*cobra.Command, error) { + cmd := app.GetConsumerGenesisTransformCmd() + clientCtx := getClientCtx() + ctx := context.WithValue(context.Background(), client.ClientContextKey, &clientCtx) + cmd.SetContext(ctx) + err := client.SetCmdClientContext(cmd, clientCtx) + return cmd, err +} + +// transformConsumerGenesis transform json content in a given file and return +// the consumer genesis transformation result or an error +// - filePath file with consumer genesis content in json format +// - version ICS version to which the data should be transformed to +func transformConsumerGenesis(filePath string, version *string) ([]byte, error) { + cmd, err := getGenesisTransformCmd() + if err != nil { + return nil, fmt.Errorf("Error setting up transformation command: %s", err) + } + + args := []string{} + if version != nil { + args = append(args, fmt.Sprintf("--to=%s", *version)) + } + args = append(args, filePath) + + cmd.SetArgs(args) + + result := new(bytes.Buffer) + cmd.SetOutput(result) + _, err = cmd.ExecuteC() + if err != nil { + return nil, fmt.Errorf("Error running transformation command: %v", err) + } + return result.Bytes(), nil +} + +// Check transformation of a version 2 ConsumerGenesis export to +// consumer genesis json format used by current consumer implementation. +func TestConsumerGenesisTransformationFromV2ToCurrent(t *testing.T) { + version := V2x + ctx := getClientCtx() + + srcGenesis := consumerTypes.GenesisState{} + err := ctx.Codec.UnmarshalJSON([]byte(consumerGenesisStates[version]), &srcGenesis) + require.NoError(t, err, "Error parsing old version of ccv genesis content for consumer") + + filePath := createConsumerDataGenesisFile(t, version) + defer os.Remove(filePath) + resultGenesis := consumerTypes.GenesisState{} + result, err := transformConsumerGenesis(filePath, nil) + require.NoError(t, err) + err = ctx.Codec.UnmarshalJSON(result, &resultGenesis) + require.NoError(t, err) + + // Some basic sanity checks on the content. + require.NotNil(t, resultGenesis.Provider.ClientState) + require.Equal(t, "cosmoshub-4", resultGenesis.Provider.ClientState.ChainId) + + require.Empty(t, resultGenesis.InitialValSet) + require.NotEmpty(t, resultGenesis.Provider.InitialValSet) + require.Equal(t, resultGenesis.Params.RetryDelayPeriod, ccvtypes.DefaultRetryDelayPeriod) + + // Check params: retry_delay_period prevents direct comparison + require.EqualValues(t, srcGenesis.Params.Enabled, resultGenesis.Params.Enabled) + require.EqualValues(t, srcGenesis.Params.BlocksPerDistributionTransmission, resultGenesis.Params.BlocksPerDistributionTransmission) + require.EqualValues(t, srcGenesis.Params.DistributionTransmissionChannel, resultGenesis.Params.DistributionTransmissionChannel) + require.EqualValues(t, srcGenesis.Params.ProviderFeePoolAddrStr, resultGenesis.Params.ProviderFeePoolAddrStr) + require.EqualValues(t, srcGenesis.Params.CcvTimeoutPeriod, resultGenesis.Params.CcvTimeoutPeriod) + require.EqualValues(t, srcGenesis.Params.TransferTimeoutPeriod, resultGenesis.Params.TransferTimeoutPeriod) + require.EqualValues(t, srcGenesis.Params.ConsumerRedistributionFraction, resultGenesis.Params.ConsumerRedistributionFraction) + require.EqualValues(t, srcGenesis.Params.HistoricalEntries, resultGenesis.Params.HistoricalEntries) + require.EqualValues(t, srcGenesis.Params.UnbondingPeriod, resultGenesis.Params.UnbondingPeriod) + + // `SoftOptOutThreshold` is deprecated, so it should be set to zero the current version + require.EqualValues(t, "0", resultGenesis.Params.SoftOptOutThreshold) + require.EqualValues(t, srcGenesis.Params.RewardDenoms, resultGenesis.Params.RewardDenoms) + require.EqualValues(t, srcGenesis.Params.ProviderRewardDenoms, resultGenesis.Params.ProviderRewardDenoms) + + require.Equal(t, srcGenesis.ProviderClientState, resultGenesis.Provider.ClientState) + require.Nil(t, resultGenesis.ProviderClientState) + + require.Equal(t, srcGenesis.Provider.ConsensusState, resultGenesis.ProviderConsensusState) + require.Nil(t, resultGenesis.ProviderConsensusState) + + require.Equal(t, srcGenesis.NewChain, resultGenesis.NewChain) + require.Equal(t, "", resultGenesis.ProviderClientId) + require.Equal(t, "", resultGenesis.ProviderChannelId) + require.Equal(t, srcGenesis.InitialValSet, resultGenesis.Provider.InitialValSet) + require.Empty(t, resultGenesis.InitialValSet) +} + +// Check transformation of provider v3.3.x implementation to consumer V2 +func TestConsumerGenesisTransformationV330ToV2(t *testing.T) { + version := V33x + filePath := createConsumerDataGenesisFile(t, version) + defer os.Remove(filePath) + + var srcGenesis consumerTypes.GenesisState + ctx := getClientCtx() + err := ctx.Codec.UnmarshalJSON([]byte(consumerGenesisStates[version]), &srcGenesis) + require.NoError(t, err) + + targetVersion := V2x + result, err := transformConsumerGenesis(filePath, &targetVersion) + require.NoError(t, err) + + resultGenesis := consumerTypes.GenesisState{} + err = ctx.Codec.UnmarshalJSON(result, &resultGenesis) + require.NoError(t, err) + + require.Equal(t, srcGenesis.Params, resultGenesis.Params) + require.Equal(t, srcGenesis.Provider.ClientState, resultGenesis.ProviderClientState) + require.Equal(t, srcGenesis.Provider.ConsensusState, resultGenesis.ProviderConsensusState) + require.Equal(t, srcGenesis.NewChain, resultGenesis.NewChain) + require.Equal(t, "", resultGenesis.ProviderClientId) + require.Equal(t, "", resultGenesis.ProviderChannelId) +} + +// Check transformation of provider v3.3.x implementation to current consumer version +func TestConsumerGenesisTransformationV330ToCurrent(t *testing.T) { + version := V33x + filePath := createConsumerDataGenesisFile(t, version) + defer os.Remove(filePath) + + var srcGenesis consumerTypes.GenesisState + ctx := getClientCtx() + err := ctx.Codec.UnmarshalJSON([]byte(consumerGenesisStates[version]), &srcGenesis) + require.NoError(t, err) + + result, err := transformConsumerGenesis(filePath, nil) + require.NoError(t, err) + + resultGenesis := consumerTypes.GenesisState{} + err = ctx.Codec.UnmarshalJSON(result, &resultGenesis) + require.NoError(t, err) + + require.Equal(t, srcGenesis.Params.Enabled, resultGenesis.Params.Enabled) + require.Equal(t, srcGenesis.Params.BlocksPerDistributionTransmission, resultGenesis.Params.BlocksPerDistributionTransmission) + require.Equal(t, srcGenesis.Params.DistributionTransmissionChannel, resultGenesis.Params.DistributionTransmissionChannel) + require.Equal(t, srcGenesis.Params.ProviderFeePoolAddrStr, resultGenesis.Params.ProviderFeePoolAddrStr) + require.Equal(t, srcGenesis.Params.CcvTimeoutPeriod, resultGenesis.Params.CcvTimeoutPeriod) + require.Equal(t, srcGenesis.Params.TransferTimeoutPeriod, resultGenesis.Params.TransferTimeoutPeriod) + require.Equal(t, srcGenesis.Params.ConsumerRedistributionFraction, resultGenesis.Params.ConsumerRedistributionFraction) + require.Equal(t, srcGenesis.Params.HistoricalEntries, resultGenesis.Params.HistoricalEntries) + require.Equal(t, srcGenesis.Params.UnbondingPeriod, resultGenesis.Params.UnbondingPeriod) + + // `SoftOptOutThreshold` is deprecated, so it should be set to zero the current version + require.Equal(t, "0", resultGenesis.Params.SoftOptOutThreshold) + + require.Equal(t, srcGenesis.Params.RewardDenoms, resultGenesis.Params.RewardDenoms) + require.Equal(t, srcGenesis.Params.ProviderRewardDenoms, resultGenesis.Params.ProviderRewardDenoms) + + require.Equal(t, resultGenesis.Params.RetryDelayPeriod, ccvtypes.DefaultRetryDelayPeriod) + + require.Equal(t, srcGenesis.Provider.ClientState, resultGenesis.Provider.ClientState) + require.Nil(t, resultGenesis.ProviderClientState) + require.Nil(t, resultGenesis.ProviderConsensusState) + + require.Equal(t, srcGenesis.Provider.ConsensusState, resultGenesis.Provider.ConsensusState) + require.Equal(t, srcGenesis.NewChain, resultGenesis.NewChain) + require.Equal(t, "", resultGenesis.ProviderClientId) + require.Equal(t, "", resultGenesis.ProviderChannelId) +} + +// Check transformation of provider v4.x implementation to consumer V2 +func TestConsumerGenesisTransformationV4ToV2(t *testing.T) { + version := V4x + filePath := createConsumerDataGenesisFile(t, version) + defer os.Remove(filePath) + + var srcGenesis consumerTypes.GenesisState + ctx := getClientCtx() + err := ctx.Codec.UnmarshalJSON([]byte(consumerGenesisStates[version]), &srcGenesis) + require.NoError(t, err) + + targetVersion := V2x + result, err := transformConsumerGenesis(filePath, &targetVersion) + require.NoError(t, err) + + resultGenesis := consumerTypes.GenesisState{} + err = ctx.Codec.UnmarshalJSON(result, &resultGenesis) + require.NoError(t, err) + + // Check params: retry_delay_period prevents direct comparison + require.EqualValues(t, srcGenesis.Params.Enabled, resultGenesis.Params.Enabled) + require.EqualValues(t, srcGenesis.Params.BlocksPerDistributionTransmission, resultGenesis.Params.BlocksPerDistributionTransmission) + require.EqualValues(t, srcGenesis.Params.DistributionTransmissionChannel, resultGenesis.Params.DistributionTransmissionChannel) + require.EqualValues(t, srcGenesis.Params.ProviderFeePoolAddrStr, resultGenesis.Params.ProviderFeePoolAddrStr) + require.EqualValues(t, srcGenesis.Params.CcvTimeoutPeriod, resultGenesis.Params.CcvTimeoutPeriod) + require.EqualValues(t, srcGenesis.Params.TransferTimeoutPeriod, resultGenesis.Params.TransferTimeoutPeriod) + require.EqualValues(t, srcGenesis.Params.ConsumerRedistributionFraction, resultGenesis.Params.ConsumerRedistributionFraction) + require.EqualValues(t, srcGenesis.Params.HistoricalEntries, resultGenesis.Params.HistoricalEntries) + require.EqualValues(t, srcGenesis.Params.UnbondingPeriod, resultGenesis.Params.UnbondingPeriod) + require.EqualValues(t, srcGenesis.Params.SoftOptOutThreshold, resultGenesis.Params.SoftOptOutThreshold) + require.EqualValues(t, srcGenesis.Params.RewardDenoms, resultGenesis.Params.RewardDenoms) + require.EqualValues(t, srcGenesis.Params.ProviderRewardDenoms, resultGenesis.Params.ProviderRewardDenoms) + require.Equal(t, resultGenesis.Params.RetryDelayPeriod, time.Duration(0)) + + require.Equal(t, srcGenesis.Provider.ClientState, resultGenesis.ProviderClientState) + require.Nil(t, resultGenesis.Provider.ClientState) + require.Equal(t, srcGenesis.Provider.ConsensusState, resultGenesis.ProviderConsensusState) + require.Nil(t, resultGenesis.Provider.ConsensusState) + require.Equal(t, "", resultGenesis.ProviderClientId) + require.Equal(t, "", resultGenesis.ProviderChannelId) + + require.Equal(t, 0, len(resultGenesis.Provider.InitialValSet)) + require.Equal(t, srcGenesis.Provider.InitialValSet, resultGenesis.InitialValSet) + require.Empty(t, resultGenesis.Provider.InitialValSet) + + require.Equal(t, srcGenesis.NewChain, resultGenesis.NewChain) +} + +// Check transformation of provider v3.3.x implementation to consumer V2 +func TestConsumerGenesisTransformationV4ToV33(t *testing.T) { + version := V4x + filePath := createConsumerDataGenesisFile(t, version) + defer os.Remove(filePath) + + var srcGenesis ccvtypes.ConsumerGenesisState + ctx := getClientCtx() + err := ctx.Codec.UnmarshalJSON([]byte(consumerGenesisStates[version]), &srcGenesis) + require.NoError(t, err) + + targetVersion := V33x + result, err := transformConsumerGenesis(filePath, &targetVersion) + require.NoError(t, err) + resultGenesis := consumerTypes.GenesisState{} // Only difference to v33 is no RetryDelayPeriod + err = ctx.Codec.UnmarshalJSON(result, &resultGenesis) + require.NoError(t, err) + + // Check params: retry_delay_period prevents direct comparison + require.EqualValues(t, srcGenesis.Params.Enabled, resultGenesis.Params.Enabled) + require.EqualValues(t, srcGenesis.Params.BlocksPerDistributionTransmission, resultGenesis.Params.BlocksPerDistributionTransmission) + require.EqualValues(t, srcGenesis.Params.DistributionTransmissionChannel, resultGenesis.Params.DistributionTransmissionChannel) + require.EqualValues(t, srcGenesis.Params.ProviderFeePoolAddrStr, resultGenesis.Params.ProviderFeePoolAddrStr) + require.EqualValues(t, srcGenesis.Params.CcvTimeoutPeriod, resultGenesis.Params.CcvTimeoutPeriod) + require.EqualValues(t, srcGenesis.Params.TransferTimeoutPeriod, resultGenesis.Params.TransferTimeoutPeriod) + require.EqualValues(t, srcGenesis.Params.ConsumerRedistributionFraction, resultGenesis.Params.ConsumerRedistributionFraction) + require.EqualValues(t, srcGenesis.Params.HistoricalEntries, resultGenesis.Params.HistoricalEntries) + require.EqualValues(t, srcGenesis.Params.UnbondingPeriod, resultGenesis.Params.UnbondingPeriod) + require.EqualValues(t, srcGenesis.Params.SoftOptOutThreshold, resultGenesis.Params.SoftOptOutThreshold) + require.EqualValues(t, srcGenesis.Params.RewardDenoms, resultGenesis.Params.RewardDenoms) + require.EqualValues(t, srcGenesis.Params.ProviderRewardDenoms, resultGenesis.Params.ProviderRewardDenoms) + + require.Equal(t, srcGenesis.Provider.ClientState, resultGenesis.Provider.ClientState) + require.Nil(t, resultGenesis.ProviderClientState) + + require.Equal(t, srcGenesis.Provider.ConsensusState, resultGenesis.Provider.ConsensusState) + require.Nil(t, resultGenesis.ProviderConsensusState) + + require.Equal(t, srcGenesis.NewChain, resultGenesis.NewChain) + require.Equal(t, "", resultGenesis.ProviderClientId) + require.Equal(t, "", resultGenesis.ProviderChannelId) + require.Equal(t, srcGenesis.Provider.InitialValSet, resultGenesis.Provider.InitialValSet) + require.Empty(t, resultGenesis.InitialValSet) +} diff --git a/cmd/interchain-security-cd/cmd/root.go b/cmd/interchain-security-cd/cmd/root.go index 7067fea12a..42cd15c482 100644 --- a/cmd/interchain-security-cd/cmd/root.go +++ b/cmd/interchain-security-cd/cmd/root.go @@ -88,7 +88,7 @@ func NewRootCmd() *cobra.Command { }, } - initRootCmd(rootCmd) + initRootCmd(rootCmd, encodingConfig) autoCliOpts, err := enrichAutoCliOpts(tempApp.AutoCliOpts(), initClientCtx) if err != nil { panic(err) @@ -203,7 +203,7 @@ lru_size = 0` return customAppTemplate, customAppConfig } -func initRootCmd(rootCmd *cobra.Command) { +func initRootCmd(rootCmd *cobra.Command, encodingConfig appencoding.EncodingConfig) { rootCmd.AddCommand( genutilcli.InitCmd(consumer.ModuleBasics, consumer.DefaultNodeHome), debug.Cmd(), @@ -216,6 +216,7 @@ func initRootCmd(rootCmd *cobra.Command) { // add keybase, auxiliary RPC, query, genesis, and tx child commands rootCmd.AddCommand( server.StatusCommand(), + genesisCommand(encodingConfig, consumer.GetConsumerGenesisTransformCmd()), queryCommand(), txCommand(), keys.Commands(), @@ -285,6 +286,16 @@ func addModuleInitFlags(startCmd *cobra.Command) { crisis.AddModuleInitFlags(startCmd) } +// genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter +func genesisCommand(encodingConfig appencoding.EncodingConfig, cmds ...*cobra.Command) *cobra.Command { + cmd := genutilcli.GenesisCoreCommand(encodingConfig.TxConfig, consumer.ModuleBasics, consumer.DefaultNodeHome) + + for _, sub_cmd := range cmds { + cmd.AddCommand(sub_cmd) + } + return cmd +} + func queryCommand() *cobra.Command { cmd := &cobra.Command{ Use: "query", From 0db617bd216b4ed41afb13d77fd747c0f42f6bc0 Mon Sep 17 00:00:00 2001 From: mpoke Date: Thu, 7 Nov 2024 09:33:27 +0100 Subject: [PATCH 12/12] add changelog entries --- .../unreleased/features/2101-introduce-priority-validators.md | 2 ++ .changelog/unreleased/features/2372-vscmatured-packets.md | 2 ++ .changelog/unreleased/features/2378-allow-chain-id-updates.md | 2 +- .../features/provider/2101-introduce-priority-validators.md | 2 -- .../state-breaking/2101-introduce-priority-validators.md | 2 +- .changelog/unreleased/state-breaking/2372-vscmatured-packets.md | 2 ++ 6 files changed, 8 insertions(+), 4 deletions(-) create mode 100644 .changelog/unreleased/features/2101-introduce-priority-validators.md create mode 100644 .changelog/unreleased/features/2372-vscmatured-packets.md delete mode 100644 .changelog/unreleased/features/provider/2101-introduce-priority-validators.md create mode 100644 .changelog/unreleased/state-breaking/2372-vscmatured-packets.md diff --git a/.changelog/unreleased/features/2101-introduce-priority-validators.md b/.changelog/unreleased/features/2101-introduce-priority-validators.md new file mode 100644 index 0000000000..24b2684433 --- /dev/null +++ b/.changelog/unreleased/features/2101-introduce-priority-validators.md @@ -0,0 +1,2 @@ +- `[x/provider]` Allow consumer chains to specify a list of priority validators that are included in the validator set before other validators are considered + ([\#2101](https://github.com/cosmos/interchain-security/pull/2101)) \ No newline at end of file diff --git a/.changelog/unreleased/features/2372-vscmatured-packets.md b/.changelog/unreleased/features/2372-vscmatured-packets.md new file mode 100644 index 0000000000..cd51735056 --- /dev/null +++ b/.changelog/unreleased/features/2372-vscmatured-packets.md @@ -0,0 +1,2 @@ +- `[x/consumer]` Remove `VSCMaturedPackets`. Consumer-side changes for [ADR 018](https://cosmos.github.io/interchain-security/adrs/adr-018-remove-vscmatured#consumer-changes-r2). + ([\#2372](https://github.com/cosmos/interchain-security/pull/2372)) \ No newline at end of file diff --git a/.changelog/unreleased/features/2378-allow-chain-id-updates.md b/.changelog/unreleased/features/2378-allow-chain-id-updates.md index cab2fdc62b..c12277e63a 100644 --- a/.changelog/unreleased/features/2378-allow-chain-id-updates.md +++ b/.changelog/unreleased/features/2378-allow-chain-id-updates.md @@ -1,2 +1,2 @@ -- Allow the chain id of a consumer chain to be updated before the chain +- `[x/provider]` Allow the chain id of a consumer chain to be updated before the chain launches. ([\#2378](https://github.com/cosmos/interchain-security/pull/2378)) \ No newline at end of file diff --git a/.changelog/unreleased/features/provider/2101-introduce-priority-validators.md b/.changelog/unreleased/features/provider/2101-introduce-priority-validators.md deleted file mode 100644 index a90e0a6e26..0000000000 --- a/.changelog/unreleased/features/provider/2101-introduce-priority-validators.md +++ /dev/null @@ -1,2 +0,0 @@ -- Allow consumer chains to specify a list of priority validators that are included in the validator set before other validators are considered - ([\#2101](https://github.com/cosmos/interchain-security/pull/2101)) \ No newline at end of file diff --git a/.changelog/unreleased/state-breaking/2101-introduce-priority-validators.md b/.changelog/unreleased/state-breaking/2101-introduce-priority-validators.md index a90e0a6e26..24b2684433 100644 --- a/.changelog/unreleased/state-breaking/2101-introduce-priority-validators.md +++ b/.changelog/unreleased/state-breaking/2101-introduce-priority-validators.md @@ -1,2 +1,2 @@ -- Allow consumer chains to specify a list of priority validators that are included in the validator set before other validators are considered +- `[x/provider]` Allow consumer chains to specify a list of priority validators that are included in the validator set before other validators are considered ([\#2101](https://github.com/cosmos/interchain-security/pull/2101)) \ No newline at end of file diff --git a/.changelog/unreleased/state-breaking/2372-vscmatured-packets.md b/.changelog/unreleased/state-breaking/2372-vscmatured-packets.md new file mode 100644 index 0000000000..cd51735056 --- /dev/null +++ b/.changelog/unreleased/state-breaking/2372-vscmatured-packets.md @@ -0,0 +1,2 @@ +- `[x/consumer]` Remove `VSCMaturedPackets`. Consumer-side changes for [ADR 018](https://cosmos.github.io/interchain-security/adrs/adr-018-remove-vscmatured#consumer-changes-r2). + ([\#2372](https://github.com/cosmos/interchain-security/pull/2372)) \ No newline at end of file