Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Parent Genesis and Tests #418

Merged
merged 5 commits into from
Sep 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion docs/ibc/proto-docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -848,7 +848,6 @@ ChildState defines the state that the parent chain stores for each child chain
| `chain_id` | [string](#string) | | |
| `channel_id` | [string](#string) | | |
| `status` | [Status](#ibc.applications.ccv.v1.Status) | | |
| `pending_changes` | [tendermint.abci.ValidatorUpdate](#tendermint.abci.ValidatorUpdate) | repeated | |



Expand Down
6 changes: 3 additions & 3 deletions modules/apps/ccv/child/keeper/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ import (

// OnRecvPacket sets the pending validator set changes that will be flushed to ABCI on Endblock
// and set the unbonding time for the packet so that we can WriteAcknowledgement after unbonding time is over.
func (k Keeper) OnRecvPacket(ctx sdk.Context, packet channeltypes.Packet, data ccv.ValidatorSetChangePacketData) (*channeltypes.Acknowledgement, error) {
func (k Keeper) OnRecvPacket(ctx sdk.Context, packet channeltypes.Packet, data ccv.ValidatorSetChangePacketData) *channeltypes.Acknowledgement {
// packet is not sent on parent channel, return error acknowledgement and close channel
if parentChannel, ok := k.GetParentChannel(ctx); ok && parentChannel != packet.DestinationChannel {
ack := channeltypes.NewErrorAcknowledgement(
fmt.Sprintf("packet sent on a channel %s other than the established parent channel %s", packet.DestinationChannel, parentChannel),
)
chanCap, _ := k.scopedKeeper.GetCapability(ctx, host.ChannelCapabilityPath(packet.DestinationPort, packet.DestinationChannel))
k.channelKeeper.ChanCloseInit(ctx, packet.DestinationPort, packet.DestinationChannel, chanCap)
return &ack, nil
return &ack
}
if status := k.GetChannelStatus(ctx, packet.DestinationChannel); status != ccv.VALIDATING {
// Set CCV channel status to Validating and set parent channel
Expand All @@ -36,7 +36,7 @@ func (k Keeper) OnRecvPacket(ctx sdk.Context, packet channeltypes.Packet, data c
k.SetUnbondingTime(ctx, packet.Sequence, uint64(unbondingTime.UnixNano()))
k.SetUnbondingPacket(ctx, packet.Sequence, packet)
// ack will be sent asynchronously
return nil, nil
return nil
}

// UnbondMaturePackets will iterate over the unbonding packets in order and write acknowledgements for all
Expand Down
13 changes: 4 additions & 9 deletions modules/apps/ccv/child/keeper/relay_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,13 @@ func (suite *KeeperTestSuite) TestOnRecvPacket() {
// malleate packet for each case
tc.malleatePacket()

ack, recvErr := suite.childChain.GetSimApp().ChildKeeper.OnRecvPacket(suite.ctx, packet, pd)
ack := suite.childChain.GetSimApp().ChildKeeper.OnRecvPacket(suite.ctx, packet, pd)

if tc.expErrorAck {
suite.Require().NotNil(ack, "invalid test case: %s did not return ack", tc.name)
suite.Require().False(ack.Success(), "invalid test case: %s did not return an Error Acknowledgment")
suite.Require().Nil(recvErr, "returned error unexpectedly. should be nil to commit RecvPacket callback changes")
} else {
suite.Require().Nil(ack, "successful packet must send ack asynchronously. case: %s", tc.name)
suite.Require().NoError(recvErr, "received unexpected error on valid case: %s", tc.name)
suite.Require().Equal(ccv.VALIDATING, suite.childChain.GetSimApp().ChildKeeper.GetChannelStatus(suite.ctx, suite.path.EndpointA.ChannelID),
"channel status is not valdidating after receive packet for valid test case: %s", tc.name)
parentChannel, ok := suite.childChain.GetSimApp().ChildKeeper.GetParentChannel(suite.ctx)
Expand Down Expand Up @@ -127,26 +125,23 @@ func (suite *KeeperTestSuite) TestUnbondMaturePackets() {
// send first packet
packet := channeltypes.NewPacket(pd.GetBytes(), 1, parenttypes.PortID, suite.path.EndpointB.ChannelID, childtypes.PortID, suite.path.EndpointA.ChannelID,
clienttypes.NewHeight(1, 0), 0)
ack, err := suite.childChain.GetSimApp().ChildKeeper.OnRecvPacket(suite.ctx, packet, pd)
suite.Require().Nil(err)
ack := suite.childChain.GetSimApp().ChildKeeper.OnRecvPacket(suite.ctx, packet, pd)
suite.Require().Nil(ack)

// update time and send second packet
suite.ctx = suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(time.Hour))
pd.ValidatorUpdates[0].Power = 15
packet.Data = pd.GetBytes()
packet.Sequence = 2
ack, err = suite.childChain.GetSimApp().ChildKeeper.OnRecvPacket(suite.ctx, packet, pd)
suite.Require().Nil(err)
ack = suite.childChain.GetSimApp().ChildKeeper.OnRecvPacket(suite.ctx, packet, pd)
suite.Require().Nil(ack)

// update time and send third packet
suite.ctx = suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(24 * time.Hour))
pd.ValidatorUpdates[1].Power = 40
packet.Data = pd.GetBytes()
packet.Sequence = 3
ack, err = suite.childChain.GetSimApp().ChildKeeper.OnRecvPacket(suite.ctx, packet, pd)
suite.Require().Nil(err)
ack = suite.childChain.GetSimApp().ChildKeeper.OnRecvPacket(suite.ctx, packet, pd)
suite.Require().Nil(ack)

// move ctx time forward such that first two packets are unbonded but third is not.
Expand Down
13 changes: 5 additions & 8 deletions modules/apps/ccv/child/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,24 +322,21 @@ func (am AppModule) OnRecvPacket(
_ sdk.AccAddress,
) ibcexported.Acknowledgement {
var (
ack ibcexported.Acknowledgement
ack *channeltypes.Acknowledgement
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this a pointer?

data ccv.ValidatorSetChangePacketData
)
if err := ccv.ModuleCdc.UnmarshalJSON(packet.GetData(), &data); err != nil {
ack = channeltypes.NewErrorAcknowledgement(fmt.Sprintf("cannot unmarshal CCV packet data: %s", err.Error()))
errAck := channeltypes.NewErrorAcknowledgement(fmt.Sprintf("cannot unmarshal CCV packet data: %s", err.Error()))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error acknowledgement message cannot contain the unmarshal json error string

ack = &errAck
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is errAck initialized instead of being assigned directly to ack

} else {
var err error
ack, err = am.keeper.OnRecvPacket(ctx, packet, data)
if err != nil {
ack = channeltypes.NewErrorAcknowledgement(err.Error())
}
ack = am.keeper.OnRecvPacket(ctx, packet, data)
}

ctx.EventManager().EmitEvent(
sdk.NewEvent(
ccv.EventTypePacket,
sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName),
sdk.NewAttribute(ccv.AttributeKeyAckSuccess, fmt.Sprintf("%t", ack.Success())),
sdk.NewAttribute(ccv.AttributeKeyAckSuccess, fmt.Sprintf("%t", ack != nil)),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This returns true even on an error acknowledgement

),
)

Expand Down
45 changes: 40 additions & 5 deletions modules/apps/ccv/parent/keeper/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,55 @@ import (
"fmt"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/ibc-go/modules/apps/ccv/parent/types"
parenttypes "github.com/cosmos/ibc-go/modules/apps/ccv/parent/types"
"github.com/cosmos/ibc-go/modules/apps/ccv/types"
)

func (k Keeper) InitGenesis(ctx sdk.Context) {
k.SetPort(ctx, types.PortID)
func (k Keeper) InitGenesis(ctx sdk.Context, genState types.ParentGenesisState) {
k.SetPort(ctx, parenttypes.PortID)

// Only try to bind to port if it is not already bound, since we may already own
// port capability from capability InitGenesis
if !k.IsBound(ctx, types.PortID) {
if !k.IsBound(ctx, parenttypes.PortID) {
// transfer module binds to the transfer port on InitChain
// and claims the returned capability
err := k.BindPort(ctx, types.PortID)
err := k.BindPort(ctx, parenttypes.PortID)
if err != nil {
panic(fmt.Sprintf("could not claim port capability: %v", err))
}
}

// Set initial state for each child chain
for _, cc := range genState.ChildStates {
k.SetChainToChannel(ctx, cc.ChainId, cc.ChannelId)
k.SetChannelToChain(ctx, cc.ChannelId, cc.ChainId)
k.SetChannelStatus(ctx, cc.ChannelId, cc.Status)
}
}

func (k Keeper) ExportGenesis(ctx sdk.Context) types.ParentGenesisState {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

godoc

store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, []byte(parenttypes.ChannelToChainKeyPrefix+"/"))
defer iterator.Close()

if !iterator.Valid() {
return types.DefaultParentGenesisState()
}

var childStates []types.ChildState

for ; iterator.Valid(); iterator.Next() {
channelID := string(iterator.Key())
chainID := string(iterator.Value())

status := k.GetChannelStatus(ctx, channelID)
cc := types.ChildState{
ChainId: chainID,
ChannelId: channelID,
Status: status,
}
childStates = append(childStates, cc)
}

return types.NewParentGenesisState(childStates)
}
36 changes: 36 additions & 0 deletions modules/apps/ccv/parent/keeper/genesis_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package keeper_test

import (
"fmt"

"github.com/cosmos/ibc-go/modules/apps/ccv/types"
)

func (suite *KeeperTestSuite) TestGenesis() {
// set some chain-channel pairs before exporting
ctx := suite.parentChain.GetContext()
for i := 0; i < 4; i++ {
suite.parentChain.GetSimApp().ParentKeeper.SetChainToChannel(ctx, fmt.Sprintf("chainid-%d", i), fmt.Sprintf("channel-%d", i))
suite.parentChain.GetSimApp().ParentKeeper.SetChannelToChain(ctx, fmt.Sprintf("channel-%d", i), fmt.Sprintf("chainid-%d", i))
suite.parentChain.GetSimApp().ParentKeeper.SetChannelStatus(ctx, fmt.Sprintf("channel-%d", i), types.Status(i))
}

genState := suite.parentChain.GetSimApp().ParentKeeper.ExportGenesis(suite.parentChain.GetContext())

suite.childChain.GetSimApp().ParentKeeper.InitGenesis(suite.childChain.GetContext(), genState)

ctx = suite.childChain.GetContext()
for i := 0; i < 4; i++ {
expectedChainId := fmt.Sprintf("chainid-%d", i)
expectedChannelId := fmt.Sprintf("channelid-%d", i)
channelID, channelOk := suite.childChain.GetSimApp().ParentKeeper.GetChainToChannel(ctx, expectedChainId)
chainID, chainOk := suite.childChain.GetSimApp().ParentKeeper.GetChannelToChain(ctx, expectedChannelId)
suite.Require().True(channelOk)
suite.Require().True(chainOk)
suite.Require().Equal(expectedChainId, chainID, "did not store correct chain id for given channel id")
suite.Require().Equal(expectedChannelId, channelID, "did not store correct channel id for given chain id")

status := suite.childChain.GetSimApp().ParentKeeper.GetChannelStatus(ctx, channelID)
suite.Require().Equal(int32(i), status, "status is unexpected for given channel id: %s", channelID)
}
}
30 changes: 17 additions & 13 deletions modules/apps/ccv/parent/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
host "github.com/cosmos/ibc-go/modules/core/24-host"
ibcexported "github.com/cosmos/ibc-go/modules/core/exported"
ibctmtypes "github.com/cosmos/ibc-go/modules/light-clients/07-tendermint/types"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/log"
)

Expand Down Expand Up @@ -144,20 +143,25 @@ func (k Keeper) GetChannelToChain(ctx sdk.Context, channelID string) (string, bo
return string(bz), true
}

// SetUnbondingChanges sets the unbonding changes for a given baby chain and sequence
func (k Keeper) SetUnbondingChanges(ctx sdk.Context, chainID string, seq uint64, valUpdates []abci.ValidatorUpdate) {
// TODO
}
// IterateChannelToChain iterates over the channel to chain mappings and calls the provided callback until the iteration ends
// or the callback returns stop=true
func (k Keeper) IterateChannelToChain(ctx sdk.Context, cb func(ctx sdk.Context, channelID, chainID string) (stop bool)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this func needs a test

store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, []byte(types.ChannelToChainKeyPrefix+"/"))
defer iterator.Close()

// GetUnbondingChanges gets the unbonding changes for a given baby chain and sequence
func (k Keeper) GetUnbondingChanges(ctx sdk.Context, chainID string, seq uint64) []abci.ValidatorUpdate {
// TODO
return nil
}
if !iterator.Valid() {
return
}

for ; iterator.Valid(); iterator.Next() {
channelID := string(iterator.Key())
chainID := string(iterator.Value())

// DeleteUnbondingChanges deletes the unbonding changes for a given baby chain and sequence
func (k Keeper) DeleteUnbondingChanges(ctx sdk.Context, chainID string, seq uint64) {
// TODO
if cb(ctx, channelID, chainID) {
break
}
}
}

// SetChannelStatus sets the status of a CCV channel with the given status
Expand Down
71 changes: 71 additions & 0 deletions modules/apps/ccv/parent/keeper/keeper_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package keeper_test

import (
sdk "github.com/cosmos/cosmos-sdk/types"
childtypes "github.com/cosmos/ibc-go/modules/apps/ccv/child/types"
parenttypes "github.com/cosmos/ibc-go/modules/apps/ccv/parent/types"
"github.com/cosmos/ibc-go/modules/apps/ccv/types"
clienttypes "github.com/cosmos/ibc-go/modules/core/02-client/types"
channeltypes "github.com/cosmos/ibc-go/modules/core/04-channel/types"
commitmenttypes "github.com/cosmos/ibc-go/modules/core/23-commitment/types"
ibctmtypes "github.com/cosmos/ibc-go/modules/light-clients/07-tendermint/types"
ibctesting "github.com/cosmos/ibc-go/testing"
"github.com/stretchr/testify/suite"
)

type KeeperTestSuite struct {
suite.Suite

coordinator *ibctesting.Coordinator

// testing chains
parentChain *ibctesting.TestChain
childChain *ibctesting.TestChain

parentClient *ibctmtypes.ClientState
parentConsState *ibctmtypes.ConsensusState

path *ibctesting.Path

ctx sdk.Context
}

func (suite *KeeperTestSuite) SetupTest() {
suite.coordinator = ibctesting.NewCoordinator(suite.T(), 2)
suite.parentChain = suite.coordinator.GetChain(ibctesting.GetChainID(0))
suite.childChain = suite.coordinator.GetChain(ibctesting.GetChainID(1))

tmConfig := ibctesting.NewTendermintConfig()

// commit a block on parent chain before creating client
suite.coordinator.CommitBlock(suite.parentChain)

// create client and consensus state of parent chain to initialize child chain genesis.
height := suite.parentChain.LastHeader.GetHeight().(clienttypes.Height)
UpgradePath := []string{"upgrade", "upgradedIBCState"}

suite.parentClient = ibctmtypes.NewClientState(
suite.parentChain.ChainID, tmConfig.TrustLevel, tmConfig.TrustingPeriod, tmConfig.UnbondingPeriod, tmConfig.MaxClockDrift,
height, commitmenttypes.GetSDKSpecs(), UpgradePath, tmConfig.AllowUpdateAfterExpiry, tmConfig.AllowUpdateAfterMisbehaviour,
)
suite.parentConsState = suite.parentChain.LastHeader.ConsensusState()

childGenesis := types.NewInitialChildGenesisState(suite.parentClient, suite.parentConsState)
suite.childChain.GetSimApp().ChildKeeper.InitGenesis(suite.childChain.GetContext(), childGenesis)

suite.ctx = suite.parentChain.GetContext()

suite.path = ibctesting.NewPath(suite.childChain, suite.parentChain)
suite.path.EndpointA.ChannelConfig.PortID = childtypes.PortID
suite.path.EndpointB.ChannelConfig.PortID = parenttypes.PortID
suite.path.EndpointA.ChannelConfig.Version = types.Version
suite.path.EndpointB.ChannelConfig.Version = types.Version
suite.path.EndpointA.ChannelConfig.Order = channeltypes.ORDERED
suite.path.EndpointB.ChannelConfig.Order = channeltypes.ORDERED
parentClient, ok := suite.childChain.GetSimApp().ChildKeeper.GetParentClient(suite.childChain.GetContext())
if !ok {
panic("must already have parent client on child chain")
}
// set child endpoint's clientID
suite.path.EndpointA.ClientID = parentClient
}
2 changes: 0 additions & 2 deletions modules/apps/ccv/parent/keeper/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ func (k Keeper) SendPacket(ctx sdk.Context, chainID string, valUpdates []abci.Va
return err
}

k.SetUnbondingChanges(ctx, chainID, sequence, valUpdates)
return nil
}

Expand All @@ -61,7 +60,6 @@ func (k Keeper) OnAcknowledgementPacket(ctx sdk.Context, packet channeltypes.Pac
return err
}
k.registryKeeper.UnbondValidators(ctx, chainID, data.ValidatorUpdates)
k.DeleteUnbondingChanges(ctx, chainID, packet.Sequence)
return nil
}

Expand Down
4 changes: 3 additions & 1 deletion modules/apps/ccv/parent/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,9 @@ func (am AppModule) RegisterServices(cfg module.Configurator) {
// no validator updates.
// TODO
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate {
am.keeper.InitGenesis(ctx)
var genesisState ccv.ParentGenesisState
cdc.MustUnmarshalJSON(data, &genesisState)
am.keeper.InitGenesis(ctx, genesisState)
return []abci.ValidatorUpdate{}
}

Expand Down
10 changes: 0 additions & 10 deletions modules/apps/ccv/parent/types/keys.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package types

import "fmt"

type Status int

const (
Expand All @@ -27,9 +25,6 @@ const (
// ChannelToChainKeyPrefix is the key prefix for storing mapping
// from the CCV channel ID to the baby chain ID.
ChannelToChainKeyPrefix = "channeltochain"

// UnbondingChangesPrefix is the key prefix for storing unbonding changes
UnbondingChangesPrefix = "unbondingchanges"
)

var (
Expand All @@ -46,8 +41,3 @@ func ChainToChannelKey(chainID string) []byte {
func ChannelToChainKey(channelID string) []byte {
return []byte(ChannelToChainKeyPrefix + "/" + channelID)
}

// UnbondingChanges stores the validator set changes that are still unbonding
func UnbondingChanges(chainID string, sequence uint64) []byte {
return []byte(fmt.Sprintf("%s/%s/%d", UnbondingChangesPrefix, chainID, sequence))
}
Loading