diff --git a/app/consumer-democracy/app.go b/app/consumer-democracy/app.go index f954ddd03a..ed4e8d81fa 100644 --- a/app/consumer-democracy/app.go +++ b/app/consumer-democracy/app.go @@ -877,10 +877,10 @@ func (app *App) GetTestSlashingKeeper() testutil.TestSlashingKeeper { return app.SlashingKeeper } -// // GetTestEvidenceKeeper implements the ConsumerApp interface. -// func (app *App) GetTestEvidenceKeeper() testutil.TestEvidenceKeeper { -// return app.EvidenceKeeper -// } +// GetTestEvidenceKeeper implements the ConsumerApp interface. +func (app *App) GetTestEvidenceKeeper() evidencekeeper.Keeper { + return app.EvidenceKeeper +} // GetTestStakingKeeper implements the ConsumerApp interface. func (app *App) GetTestStakingKeeper() testutil.TestStakingKeeper { @@ -892,15 +892,15 @@ func (app *App) GetTestDistributionKeeper() testutil.TestDistributionKeeper { return app.DistrKeeper } -// // GetTestMintKeeper implements the ConsumerApp interface. -// func (app *App) GetTestMintKeeper() testutil.TestMintKeeper { -// return app.MintKeeper -// } +// GetTestMintKeeper implements the ConsumerApp interface. +func (app *App) GetTestMintKeeper() mintkeeper.Keeper { + return app.MintKeeper +} -// // GetTestGovKeeper implements the ConsumerApp interface. -// func (app *App) GetTestGovKeeper() testutil.TestGovKeeper { -// return app.GovKeeper -// } +// GetTestGovKeeper implements the ConsumerApp interface. +func (app *App) GetTestGovKeeper() govkeeper.Keeper { + return app.GovKeeper +} // TestingApp functions diff --git a/app/consumer/app.go b/app/consumer/app.go index cdfcf17867..4e2601626a 100644 --- a/app/consumer/app.go +++ b/app/consumer/app.go @@ -746,6 +746,11 @@ func (app *App) GetTestSlashingKeeper() testutil.TestSlashingKeeper { return app.SlashingKeeper } +// GetTestEvidenceKeeper implements the ConsumerApp interface. +func (app *App) GetTestEvidenceKeeper() evidencekeeper.Keeper { + return app.EvidenceKeeper +} + // TestingApp functions // GetBaseApp implements the TestingApp interface. diff --git a/app/sovereign/app.go b/app/sovereign/app.go index 33744b3ba7..f8d52fae5b 100644 --- a/app/sovereign/app.go +++ b/app/sovereign/app.go @@ -757,9 +757,9 @@ func (app *App) GetTestSlashingKeeper() testutil.TestSlashingKeeper { return app.SlashingKeeper } -// func (app *App) GetTestEvidenceKeeper() testutil.TestEvidenceKeeper { -// return app.EvidenceKeeper -// } +func (app *App) GetTestEvidenceKeeper() evidencekeeper.Keeper { + return app.EvidenceKeeper +} func (app *App) GetTestStakingKeeper() testutil.TestStakingKeeper { return app.StakingKeeper @@ -769,13 +769,13 @@ func (app *App) GetTestDistributionKeeper() testutil.TestDistributionKeeper { return app.DistrKeeper } -// func (app *App) GetTestMintKeeper() testutil.TestMintKeeper { -// return app.MintKeeper -// } +func (app *App) GetTestMintKeeper() mintkeeper.Keeper { + return app.MintKeeper +} -// func (app *App) GetTestGovKeeper() testutil.TestGovKeeper { -// return app.GovKeeper -// } +func (app *App) GetTestGovKeeper() govkeeper.Keeper { + return app.GovKeeper +} // TestingApp functions diff --git a/tests/integration/common.go b/tests/integration/common.go index 04710fbdf9..13488bd7e6 100644 --- a/tests/integration/common.go +++ b/tests/integration/common.go @@ -67,8 +67,8 @@ func (s *CCVTestSuite) getValByIdx(index int) (validator stakingtypes.Validator, } func (s *CCVTestSuite) getVal(ctx sdk.Context, valAddr sdk.ValAddress) stakingtypes.Validator { - validator, found := s.providerApp.GetTestStakingKeeper().GetValidator(s.providerCtx(), valAddr) - s.Require().True(found) + validator, err := s.providerApp.GetTestStakingKeeper().GetValidator(s.providerCtx(), valAddr) + s.Require().NoError(err) return validator } @@ -175,7 +175,7 @@ func delegateByIdx(s *CCVTestSuite, delAddr sdk.AccAddress, bondAmt math.Int, id // undelegate unbonds an amount of delegator shares from a given validator func undelegate(s *CCVTestSuite, delAddr sdk.AccAddress, valAddr sdk.ValAddress, sharesAmount math.LegacyDec) (valsetUpdateId uint64) { - _, err := s.providerApp.GetTestStakingKeeper().Undelegate(s.providerCtx(), delAddr, valAddr, sharesAmount) + _, _, err := s.providerApp.GetTestStakingKeeper().Undelegate(s.providerCtx(), delAddr, valAddr, sharesAmount) s.Require().NoError(err) // save the current valset update ID @@ -202,10 +202,11 @@ func redelegate(s *CCVTestSuite, delAddr sdk.AccAddress, valSrcAddr sdk.ValAddre ) s.Require().NoError(err) - providerUnbondingPeriod := stakingKeeper.UnbondingTime(ctx) + providerUnbondingPeriod, err := stakingKeeper.UnbondingTime(ctx) + s.Require().NoError(err) - valSrc, found := stakingKeeper.GetValidator(ctx, valSrcAddr) - s.Require().True(found) + valSrc, err := stakingKeeper.GetValidator(ctx, valSrcAddr) + s.Require().NoError(err) // Completion time of redelegation operation will be after unbonding period if source val is bonded if valSrc.IsBonded() { @@ -302,7 +303,8 @@ func relayAllCommittedPackets( // to be one day larger than the consumer unbonding period. func incrementTimeByUnbondingPeriod(s *CCVTestSuite, chainType ChainType) { // Get unboding periods - providerUnbondingPeriod := s.providerApp.GetTestStakingKeeper().UnbondingTime(s.providerCtx()) + providerUnbondingPeriod, err := s.providerApp.GetTestStakingKeeper().UnbondingTime(s.providerCtx()) + s.Require().NoError(err) consumerUnbondingPeriod := s.consumerApp.GetConsumerKeeper().GetUnbondingPeriod(s.consumerCtx()) var jumpPeriod time.Duration if chainType == Provider { @@ -355,8 +357,8 @@ func checkCCVUnbondingOp(s *CCVTestSuite, providerCtx sdk.Context, chainID strin func checkRedelegations(s *CCVTestSuite, delAddr sdk.AccAddress, expect uint16, ) []stakingtypes.Redelegation { - redelegations := s.providerApp.GetTestStakingKeeper().GetRedelegations(s.providerCtx(), delAddr, 2) - + redelegations, err := s.providerApp.GetTestStakingKeeper().GetRedelegations(s.providerCtx(), delAddr, 2) + s.Require().NoError(err) s.Require().Len(redelegations, int(expect)) return redelegations } @@ -369,8 +371,12 @@ func checkRedelegationEntryCompletionTime( } func getStakingUnbondingDelegationEntry(ctx sdk.Context, k testutil.TestStakingKeeper, id uint64) (stakingUnbondingOp stakingtypes.UnbondingDelegationEntry, found bool) { - stakingUbd, found := k.GetUnbondingDelegationByUnbondingID(ctx, id) + stakingUbd, err := k.GetUnbondingDelegationByUnbondingID(ctx, id) + if err != nil { + panic(fmt.Sprintf("could not get unbonding delegation", err)) + } + found = false for _, entry := range stakingUbd.Entries { if entry.UnbondingId == id { stakingUnbondingOp = entry @@ -604,8 +610,11 @@ func (s *CCVTestSuite) setupValidatorPowers() { stakingKeeper := s.providerApp.GetTestStakingKeeper() for _, val := range s.providerChain.Vals.Validators { - power := stakingKeeper.GetLastValidatorPower(s.providerCtx(), sdk.ValAddress(val.Address)) + power, err := stakingKeeper.GetLastValidatorPower(s.providerCtx(), sdk.ValAddress(val.Address)) + s.Require().NoError(err) s.Require().Equal(int64(1000), power) } - s.Require().Equal(int64(4000), stakingKeeper.GetLastTotalPower(s.providerCtx()).Int64()) + totalPower, err := stakingKeeper.GetLastTotalPower(s.providerCtx()) + s.Require().NoError(err) + s.Require().Equal(int64(4000), totalPower.Int64()) } diff --git a/tests/integration/democracy.go b/tests/integration/democracy.go index 6e1c0d74ba..8b98e97dbe 100644 --- a/tests/integration/democracy.go +++ b/tests/integration/democracy.go @@ -10,10 +10,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + sdkdistrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" icstestingutils "github.com/cosmos/interchain-security/v3/testutil/ibc_testing" testutil "github.com/cosmos/interchain-security/v3/testutil/integration" consumertypes "github.com/cosmos/interchain-security/v3/x/ccv/consumer/types" @@ -74,13 +76,16 @@ func (s *ConsumerDemocracyTestSuite) TestDemocracyRewardsDistribution() { accountKeeper := s.consumerApp.GetTestAccountKeeper() distrKeeper := s.consumerApp.GetTestDistributionKeeper() bankKeeper := s.consumerApp.GetTestBankKeeper() - bondDenom := stakingKeeper.BondDenom(s.consumerCtx()) + bondDenom, err := stakingKeeper.BondDenom(s.consumerCtx()) + s.Require().NoError(err) currentRepresentativesRewards := map[string]math.LegacyDec{} nextRepresentativesRewards := map[string]math.LegacyDec{} representativesTokens := map[string]math.Int{} - for _, representative := range stakingKeeper.GetAllValidators(s.consumerCtx()) { + representatives, err := stakingKeeper.GetAllValidators(s.consumerCtx()) + s.Require().NoError(err) + for _, representative := range representatives { currentRepresentativesRewards[representative.OperatorAddress] = math.LegacyNewDec(0) nextRepresentativesRewards[representative.OperatorAddress] = math.LegacyNewDec(0) representativesTokens[representative.OperatorAddress] = representative.GetTokens() @@ -90,24 +95,31 @@ func (s *ConsumerDemocracyTestSuite) TestDemocracyRewardsDistribution() { providerRedistributeAccount := accountKeeper.GetModuleAccount(s.consumerCtx(), consumertypes.ConsumerToSendToProviderName) // balance of consumer redistribute address will always be 0 when checked between 2 NextBlock() calls + dk, ok := distrKeeper.(sdkdistrkeeper.Keeper) + s.Require().True(ok) + feePool, err := dk.FeePool.Get(s.consumerCtx().Context()) + s.Require().NoError(err) + s.Require().NotEmpty(feePool) currentDistrModuleAccountBalance := math.LegacyNewDecFromInt(bankKeeper.GetBalance(s.consumerCtx(), distrModuleAccount.GetAddress(), bondDenom).Amount) currentProviderFeeAccountBalance := math.LegacyNewDecFromInt(bankKeeper.GetBalance(s.consumerCtx(), providerRedistributeAccount.GetAddress(), bondDenom).Amount) - currentCommunityPoolBalance := distrKeeper.GetFeePoolCommunityCoins(s.consumerCtx()).AmountOf(bondDenom) + currentCommunityPoolBalance := feePool.GetCommunityPool().AmountOf(bondDenom) for key := range currentRepresentativesRewards { representativeAddr, _ := sdk.ValAddressFromBech32(key) - representativeReward := distrKeeper.GetValidatorOutstandingRewards(s.consumerCtx(), representativeAddr).Rewards.AmountOf(bondDenom) - currentRepresentativesRewards[key] = representativeReward + representativeReward, err := distrKeeper.GetValidatorOutstandingRewards(s.consumerCtx(), representativeAddr) + s.Require().NoError(err) + currentRepresentativesRewards[key] = representativeReward.Rewards.AmountOf(bondDenom) } s.consumerChain.NextBlock() nextDistrModuleAccountBalance := math.LegacyNewDecFromInt(bankKeeper.GetBalance(s.consumerCtx(), distrModuleAccount.GetAddress(), bondDenom).Amount) nextProviderFeeAccountBalance := math.LegacyNewDecFromInt(bankKeeper.GetBalance(s.consumerCtx(), providerRedistributeAccount.GetAddress(), bondDenom).Amount) - nextCommunityPoolBalance := distrKeeper.GetFeePoolCommunityCoins(s.consumerCtx()).AmountOf(bondDenom) + nextCommunityPoolBalance := feePool.GetCommunityPool().AmountOf(bondDenom) for key := range nextRepresentativesRewards { representativeAddr, _ := sdk.ValAddressFromBech32(key) - representativeReward := distrKeeper.GetValidatorOutstandingRewards(s.consumerCtx(), representativeAddr).Rewards.AmountOf(bondDenom) - nextRepresentativesRewards[key] = representativeReward + representativeReward, err := distrKeeper.GetValidatorOutstandingRewards(s.consumerCtx(), representativeAddr) + s.Require().NoError(err) + nextRepresentativesRewards[key] = representativeReward.Rewards.AmountOf(bondDenom) } distrModuleDifference := nextDistrModuleAccountBalance.Sub(currentDistrModuleAccountBalance) @@ -126,8 +138,9 @@ func (s *ConsumerDemocracyTestSuite) TestDemocracyRewardsDistribution() { // confirm that the total amount given to the community pool plus all representatives is equal to the total amount taken out of distribution s.Require().Equal(distrModuleDifference, consumerRedistributeDifference) // confirm that the percentage given to the community pool is equal to the configured community tax percentage. - s.Require().Equal(communityPoolDifference.Quo(consumerRedistributeDifference), - distrKeeper.GetCommunityTax(s.consumerCtx())) + tax, err := distrKeeper.GetCommunityTax(s.consumerCtx()) + s.Require().NoError(err) + s.Require().Equal(communityPoolDifference.Quo(consumerRedistributeDifference), tax) // check that the fraction actually kept by the consumer is the correct fraction. using InEpsilon because the math code uses truncations s.Require().InEpsilon(distrModuleDifference.Quo( providerDifference.Add(distrModuleDifference)).MustFloat64(), @@ -147,9 +160,12 @@ func (s *ConsumerDemocracyTestSuite) TestDemocracyRewardsDistribution() { } } +// @MSalopek -> this is broken for v50 func (s *ConsumerDemocracyTestSuite) TestDemocracyGovernanceWhitelisting() { govKeeper := s.consumerApp.GetTestGovKeeper() - params := govKeeper.GetParams(s.consumerCtx()) + params, err := govKeeper.Params.Get(s.consumerCtx()) + s.Require().NoError(err) + stakingKeeper := s.consumerApp.GetTestStakingKeeper() bankKeeper := s.consumerApp.GetTestBankKeeper() accountKeeper := s.consumerApp.GetTestAccountKeeper() @@ -157,18 +173,20 @@ func (s *ConsumerDemocracyTestSuite) TestDemocracyGovernanceWhitelisting() { newAuthParamValue := uint64(128) newMintParamValue := math.LegacyNewDecWithPrec(1, 1) // "0.100000000000000000" votingAccounts := s.consumerChain.SenderAccounts - bondDenom := stakingKeeper.BondDenom(s.consumerCtx()) + bondDenom, err := stakingKeeper.BondDenom(s.consumerCtx()) + s.Require().NoError(err) depositAmount := params.MinDeposit duration := (3 * time.Second) params.VotingPeriod = &duration - err := govKeeper.SetParams(s.consumerCtx(), params) + err = govKeeper.Params.Set(s.consumerCtx(), params) s.Assert().NoError(err) proposer := s.consumerChain.SenderAccount s.consumerChain.NextBlock() votersOldBalances := getAccountsBalances(s.consumerCtx(), bankKeeper, bondDenom, votingAccounts) // submit proposal with forbidden and allowed changes - mintParams := mintKeeper.GetParams(s.consumerCtx()) + mintParams, err := mintKeeper.Params.Get(s.consumerCtx()) + s.Require().NoError(err) mintParams.InflationMax = newMintParamValue msg_1 := &minttypes.MsgUpdateParams{ Authority: authtypes.NewModuleAddress(govtypes.ModuleName).String(), @@ -188,11 +206,15 @@ func (s *ConsumerDemocracyTestSuite) TestDemocracyGovernanceWhitelisting() { s.consumerChain.NextBlock() // at this moment, proposal is added, but not yet executed. we are saving old param values for comparison oldAuthParamValue := accountKeeper.GetParams(s.consumerCtx()).MaxMemoCharacters - oldMintParamValue := mintKeeper.GetParams(s.consumerCtx()).InflationMax + oldMintParams, err := mintKeeper.Params.Get(s.consumerCtx()) + s.Require().NoError(err) + oldMintParamValue := oldMintParams.InflationMax s.consumerChain.NextBlock() // at this moment, proposal is executed or deleted if forbidden currentAuthParamValue := accountKeeper.GetParams(s.consumerCtx()).MaxMemoCharacters - currentMintParamValue := mintKeeper.GetParams(s.consumerCtx()).InflationMax + currentMintParam, err := mintKeeper.Params.Get(s.consumerCtx()) + s.Require().NoError(err) + currentMintParamValue := currentMintParam.InflationMax // check that parameters are not changed, since the proposal contained both forbidden and allowed changes s.Assert().Equal(oldAuthParamValue, currentAuthParamValue) s.Assert().NotEqual(newAuthParamValue, currentAuthParamValue) @@ -206,9 +228,14 @@ func (s *ConsumerDemocracyTestSuite) TestDemocracyGovernanceWhitelisting() { s.Assert().NoError(err) s.consumerChain.CurrentHeader.Time = s.consumerChain.CurrentHeader.Time.Add(*params.VotingPeriod) s.consumerChain.NextBlock() - oldMintParamValue = mintKeeper.GetParams(s.consumerCtx()).InflationMax + oldMintParam, err := mintKeeper.Params.Get(s.consumerCtx()) + s.Require().NoError(err) + oldMintParamValue = oldMintParam.InflationMax s.consumerChain.NextBlock() - currentMintParamValue = mintKeeper.GetParams(s.consumerCtx()).InflationMax + currentMintParam, err = mintKeeper.Params.Get(s.consumerCtx()) + s.Require().NoError(err) + + currentMintParamValue = currentMintParam.InflationMax // check that parameters are changed, since the proposal contained only allowed changes s.Assert().Equal(newMintParamValue, currentMintParamValue) s.Assert().NotEqual(oldMintParamValue, currentMintParamValue) @@ -231,10 +258,10 @@ func (s *ConsumerDemocracyTestSuite) TestDemocracyGovernanceWhitelisting() { s.Assert().Equal(votersOldBalances, getAccountsBalances(s.consumerCtx(), bankKeeper, bondDenom, votingAccounts)) } -func submitProposalWithDepositAndVote(govKeeper testutil.TestGovKeeper, ctx sdk.Context, msgs []sdk.Msg, +func submitProposalWithDepositAndVote(govKeeper govkeeper.Keeper, ctx sdk.Context, msgs []sdk.Msg, accounts []ibctesting.SenderAccount, proposer sdk.AccAddress, depositAmount sdk.Coins, ) error { - proposal, err := govKeeper.SubmitProposal(ctx, msgs, "", "title", "summary", proposer) + proposal, err := govKeeper.SubmitProposal(ctx, msgs, "", "title", "summary", proposer, false) if err != nil { return err } diff --git a/tests/integration/distribution.go b/tests/integration/distribution.go index 367fedd1b6..410837fb5b 100644 --- a/tests/integration/distribution.go +++ b/tests/integration/distribution.go @@ -8,6 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + sdkdistrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" icstestingutils "github.com/cosmos/interchain-security/v3/testutil/integration" consumerkeeper "github.com/cosmos/interchain-security/v3/x/ccv/consumer/keeper" @@ -111,7 +112,17 @@ func (s *CCVTestSuite) TestRewardsDistribution() { s.Require().Equal(0, len(rewardCoins)) // check that the fee pool has the expected amount of coins - communityCoins := s.providerApp.GetTestDistributionKeeper().GetFeePoolCommunityCoins(s.providerCtx()) + testDistKeeper := s.providerApp.GetTestDistributionKeeper() + // try casting to the sdk distribution keeper + sdkDistKeeper, ok := testDistKeeper.(sdkdistrkeeper.Keeper) + s.Require().True(ok) + s.Require().NotEmpty(sdkDistKeeper) + + feePool, err := sdkDistKeeper.FeePool.Get(s.consumerCtx().Context()) + s.Require().NoError(err) + s.Require().NotEmpty(feePool) + + communityCoins := feePool.GetCommunityPool() s.Require().True(communityCoins[ibcCoinIndex].Amount.Equal(sdk.NewDecCoinFromCoin(providerExpectedRewards[0]).Amount)) } diff --git a/tests/integration/expired_client.go b/tests/integration/expired_client.go index c04d6f525b..8151c97c38 100644 --- a/tests/integration/expired_client.go +++ b/tests/integration/expired_client.go @@ -285,10 +285,11 @@ func upgradeExpiredClient(s *CCVTestSuite, clientTo ChainType) { tmClientState.AllowUpdateAfterExpiry = true hostChain.App.GetIBCKeeper().ClientKeeper.SetClientState(hostChain.GetContext(), substitute, tmClientState) - content := clienttypes.NewClientUpdateProposal(ibctesting.Title, ibctesting.Description, subject, substitute) + recoverMsg := clienttypes.NewMsgRecoverClient(hostChain.App.GetIBCKeeper().GetAuthority(), subject, substitute) + err = recoverMsg.ValidateBasic() + s.Require().NoError(err) - updateProp, ok := content.(*clienttypes.ClientUpdateProposal) - s.Require().True(ok) - err = hostChain.App.GetIBCKeeper().ClientKeeper.ClientUpdateProposal(hostChain.GetContext(), updateProp) + res, err := hostChain.App.GetIBCKeeper().RecoverClient(hostChain.GetContext(), recoverMsg) s.Require().NoError(err) + s.Require().NotNil(res) } diff --git a/tests/integration/setup.go b/tests/integration/setup.go index 351fd7148a..f3cc6ae7f7 100644 --- a/tests/integration/setup.go +++ b/tests/integration/setup.go @@ -334,7 +334,8 @@ func (s CCVTestSuite) validateEndpointsClientConfig(consumerBundle icstestinguti "unexpected unbonding period in consumer client state", ) - providerUnbondingPeriod := providerStakingKeeper.UnbondingTime(s.providerCtx()) + providerUnbondingPeriod, err := providerStakingKeeper.UnbondingTime(s.providerCtx()) + s.Require().NoError(err) cs, ok = consumerBundle.App.GetIBCKeeper().ClientKeeper.GetClientState( consumerBundle.GetCtx(), consumerBundle.Path.EndpointA.ClientID) s.Require().True(ok) diff --git a/tests/integration/slashing.go b/tests/integration/slashing.go index 00f3434f63..7df282f327 100644 --- a/tests/integration/slashing.go +++ b/tests/integration/slashing.go @@ -7,6 +7,7 @@ import ( clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" channeltypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" + "cosmossdk.io/core/comet" "cosmossdk.io/math" evidencetypes "cosmossdk.io/x/evidence/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" @@ -56,8 +57,8 @@ func (s *CCVTestSuite) TestRelayAndApplyDowntimePacket() { ) s.Require().True(found) - stakingVal, found := providerStakingKeeper.GetValidatorByConsAddr(s.providerCtx(), providerConsAddr.ToSdkConsAddr()) - s.Require().True(found) + stakingVal, err := providerStakingKeeper.GetValidatorByConsAddr(s.providerCtx(), providerConsAddr.ToSdkConsAddr()) + s.Require().NoError(err) valOldBalance := stakingVal.Tokens // Setup first val with mapped consensus addresss to be jailed on provider by setting signing info @@ -133,16 +134,16 @@ func (s *CCVTestSuite) TestRelayAndApplyDowntimePacket() { } // Get staking keeper's validator obj after the relayed slash packet - stakingValAfter, ok := providerStakingKeeper.GetValidatorByConsAddr(s.providerCtx(), providerConsAddr.ToSdkConsAddr()) - s.Require().True(ok) + stakingValAfter, err := providerStakingKeeper.GetValidatorByConsAddr(s.providerCtx(), providerConsAddr.ToSdkConsAddr()) + s.Require().NoError(err) // check that the validator's tokens were NOT slashed on provider valNewBalance := stakingValAfter.GetTokens() s.Require().Equal(valOldBalance, valNewBalance) // Get signing info for the validator - valSignInfo, found := providerSlashingKeeper.GetValidatorSigningInfo(s.providerCtx(), providerConsAddr.ToSdkConsAddr()) - s.Require().True(found) + valSignInfo, err := providerSlashingKeeper.GetValidatorSigningInfo(s.providerCtx(), providerConsAddr.ToSdkConsAddr()) + s.Require().NoError(err) // check that the validator is successfully jailed on provider s.Require().True(stakingValAfter.Jailed) @@ -189,8 +190,8 @@ func (s *CCVTestSuite) TestRelayAndApplyDoubleSignPacket() { consumerConsAddr) s.Require().True(found) - stakingVal, found := providerStakingKeeper.GetValidatorByConsAddr(s.providerCtx(), providerConsAddr.ToSdkConsAddr()) - s.Require().True(found) + stakingVal, err := providerStakingKeeper.GetValidatorByConsAddr(s.providerCtx(), providerConsAddr.ToSdkConsAddr()) + s.Require().NoError(err) valOldBalance := stakingVal.Tokens // Setup first val with mapped consensus addresss to be jailed on provider by setting signing info @@ -218,16 +219,16 @@ func (s *CCVTestSuite) TestRelayAndApplyDoubleSignPacket() { s.Require().Len(s.providerChain.Vals.Validators, validatorsPerChain) // Get staking keeper's validator obj after the relayed slash packet - stakingValAfter, ok := providerStakingKeeper.GetValidatorByConsAddr(s.providerCtx(), providerConsAddr.ToSdkConsAddr()) - s.Require().True(ok) + stakingValAfter, err := providerStakingKeeper.GetValidatorByConsAddr(s.providerCtx(), providerConsAddr.ToSdkConsAddr()) + s.Require().NoError(err) // check that the validator's tokens were NOT slashed on provider valNewBalance := stakingValAfter.GetTokens() s.Require().Equal(valOldBalance, valNewBalance) // Get signing info for the validator - valSignInfo, found := providerSlashingKeeper.GetValidatorSigningInfo(s.providerCtx(), providerConsAddr.ToSdkConsAddr()) - s.Require().True(found) + valSignInfo, err := providerSlashingKeeper.GetValidatorSigningInfo(s.providerCtx(), providerConsAddr.ToSdkConsAddr()) + s.Require().NoError(err) // check that the validator's unjailing time is NOT updated on provider s.Require().Zero(valSignInfo.JailedUntil) @@ -296,8 +297,8 @@ func (suite *CCVTestSuite) TestHandleSlashPacketDowntime() { consAddr := sdk.ConsAddress(tmVal.Address) // check that validator bonded status - validator, found := providerStakingKeeper.GetValidatorByConsAddr(suite.providerCtx(), consAddr) - suite.Require().True(found) + validator, err := providerStakingKeeper.GetValidatorByConsAddr(suite.providerCtx(), consAddr) + suite.Require().NoError(err) suite.Require().Equal(stakingtypes.Bonded, validator.GetStatus()) // set init VSC id for chain0 @@ -322,7 +323,8 @@ func (suite *CCVTestSuite) TestHandleSlashPacketDowntime() { suite.Require().True(providerStakingKeeper.IsValidatorJailed(suite.providerCtx(), consAddr)) signingInfo, _ := providerSlashingKeeper.GetValidatorSigningInfo(suite.providerCtx(), consAddr) - jailDuration := providerSlashingKeeper.DowntimeJailDuration(suite.providerCtx()) + jailDuration, err := providerSlashingKeeper.DowntimeJailDuration(suite.providerCtx()) + suite.Require().NoError(err) suite.Require().Equal(suite.providerCtx().BlockTime().Add(jailDuration), signingInfo.JailedUntil) } @@ -470,13 +472,17 @@ func (suite *CCVTestSuite) TestValidatorDowntime() { // Sign 100 blocks valPower := int64(1) - height, signedBlocksWindow := int64(0), consumerSlashingKeeper.SignedBlocksWindow(ctx) + height := int64(0) + signedBlocksWindow, err := consumerSlashingKeeper.SignedBlocksWindow(ctx) + suite.Require().NoError(err) for ; height < signedBlocksWindow; height++ { ctx = ctx.WithBlockHeight(height) - consumerSlashingKeeper.HandleValidatorSignature(ctx, vals[0].Address, valPower, true) + consumerSlashingKeeper.HandleValidatorSignature(ctx, vals[0].Address, valPower, comet.BlockIDFlagCommit) } - missedBlockThreshold := (2 * signedBlocksWindow) - consumerSlashingKeeper.MinSignedPerWindow(ctx) + minSigned, err := consumerSlashingKeeper.MinSignedPerWindow(ctx) + suite.Require().NoError(err) + missedBlockThreshold := (2 * signedBlocksWindow) - minSigned ctx = suite.consumerCtx() // construct slash packet to be sent and get its commit @@ -491,7 +497,7 @@ func (suite *CCVTestSuite) TestValidatorDowntime() { // Miss 50 blocks and expect a slash packet to be sent for ; height <= missedBlockThreshold; height++ { ctx = ctx.WithBlockHeight(height) - consumerSlashingKeeper.HandleValidatorSignature(ctx, vals[0].Address, valPower, false) + consumerSlashingKeeper.HandleValidatorSignature(ctx, vals[0].Address, valPower, comet.BlockIDFlagAbsent) } ctx = suite.consumerCtx() @@ -499,11 +505,13 @@ func (suite *CCVTestSuite) TestValidatorDowntime() { // check validator signing info res, _ := consumerSlashingKeeper.GetValidatorSigningInfo(ctx, consAddr) // expect increased jail time - suite.Require().True(res.JailedUntil.Equal(ctx.BlockTime().Add(consumerSlashingKeeper.DowntimeJailDuration(ctx))), "did not update validator jailed until signing info") + jailDuration, err := consumerSlashingKeeper.DowntimeJailDuration(ctx) + suite.Require().NoError(err) + suite.Require().True(res.JailedUntil.Equal(ctx.BlockTime().Add(jailDuration)), "did not update validator jailed until signing info") // expect missed block counters reseted suite.Require().Zero(res.MissedBlocksCounter, "did not reset validator missed block counter") suite.Require().Zero(res.IndexOffset) - consumerSlashingKeeper.IterateValidatorMissedBlockBitArray(ctx, consAddr, func(_ int64, missed bool) bool { + consumerSlashingKeeper.IterateMissedBlockBitmap(ctx, consAddr, func(_ int64, missed bool) bool { suite.Require().True(missed) return false }) @@ -534,22 +542,25 @@ func (suite *CCVTestSuite) TestValidatorDowntime() { // verify that the slash packet was sent suite.Require().True(consumerKeeper.OutstandingDowntime(ctx, consAddr)) + // @MSalopek -> not sure how to handle this // check that the outstanding slashing flag prevents the jailed validator to keep missing block for ; height < missedBlockThreshold+signedBlocksWindow; height++ { ctx = ctx.WithBlockHeight(height) - consumerSlashingKeeper.HandleValidatorSignature(ctx, vals[0].Address, valPower, false) + consumerSlashingKeeper.HandleValidatorSignature(ctx, vals[0].Address, valPower, comet.BlockIDFlagAbsent) } res, _ = consumerSlashingKeeper.GetValidatorSigningInfo(ctx, consAddr) suite.Require().Zero(res.MissedBlocksCounter, "did not reset validator missed block counter") suite.Require().Zero(res.IndexOffset) - consumerSlashingKeeper.IterateValidatorMissedBlockBitArray(ctx, consAddr, func(_ int64, missed bool) bool { + consumerSlashingKeeper.IterateMissedBlockBitmap(ctx, consAddr, func(_ int64, missed bool) bool { suite.Require().True(missed, "did not reset validator missed block bit array") return false }) } +// @MSalopek -> this test might be broken for v50 -> HandleEquivocationEvidence is deprecated so we must submit evidence using a Msg +// HandleEquivocationEvidence is deprecated so we must submit evidence using a Msg // TestValidatorDoubleSigning tests if a slash packet is sent // when a double-signing evidence is handled by the evidence module func (suite *CCVTestSuite) TestValidatorDoubleSigning() { @@ -599,7 +610,13 @@ func (suite *CCVTestSuite) TestValidatorDoubleSigning() { expCommit := suite.commitSlashPacket(ctx, *packetData) // expect to send slash packet when handling double-sign evidence - suite.consumerApp.GetTestEvidenceKeeper().HandleEquivocationEvidence(ctx, e) + // NOTE: using IBCKeeper Authority as msg submitter (equal to gov module addr) + addr, err := sdk.AccAddressFromBech32(suite.consumerApp.GetIBCKeeper().GetAuthority()) + suite.Require().NoError(err) + evidenceMsg, err := evidencetypes.NewMsgSubmitEvidence(addr, e) + suite.Require().NoError(err) + suite.Require().NotEmpty(evidenceMsg) + suite.consumerApp.GetTestEvidenceKeeper().SubmitEvidence(ctx, e) // check slash packet is queued pendingPackets := suite.consumerApp.GetConsumerKeeper().GetPendingPackets(ctx) diff --git a/tests/integration/stop_consumer.go b/tests/integration/stop_consumer.go index 76a6f5ffd2..ed996f7d3f 100644 --- a/tests/integration/stop_consumer.go +++ b/tests/integration/stop_consumer.go @@ -23,8 +23,8 @@ func (s *CCVTestSuite) TestStopConsumerChain() { valAddr, err := sdk.ValAddressFromHex(tmValidator.Address.String()) s.Require().NoError(err) - validator, found := providerStakingKeeper.GetValidator(s.providerCtx(), valAddr) - s.Require().True(found) + validator, err := providerStakingKeeper.GetValidator(s.providerCtx(), valAddr) + s.Require().NoError(err) // get delegator address delAddr := s.providerChain.SenderAccount.GetAddress() @@ -64,7 +64,7 @@ func (s *CCVTestSuite) TestStopConsumerChain() { func(suite *CCVTestSuite) error { for i := 0; i < ubdOpsNum; i++ { // undelegate one quarter of the shares - _, err := providerStakingKeeper.Undelegate(s.providerCtx(), delAddr, valAddr, testShares.QuoInt64(int64(ubdOpsNum))) + _, _, err := providerStakingKeeper.Undelegate(s.providerCtx(), delAddr, valAddr, testShares.QuoInt64(int64(ubdOpsNum))) if err != nil { return err } diff --git a/tests/integration/throttle.go b/tests/integration/throttle.go index 089049cc34..73762b6b59 100644 --- a/tests/integration/throttle.go +++ b/tests/integration/throttle.go @@ -56,7 +56,8 @@ func (s *CCVTestSuite) TestBasicSlashPacketThrottling() { s.Require().Equal(tc.expectedMeterBeforeFirstSlash, slashMeter.Int64()) // Assert that we start out with no jailings - vals := providerStakingKeeper.GetAllValidators(s.providerCtx()) + vals, err := providerStakingKeeper.GetAllValidators(s.providerCtx()) + s.Require().NoError(err) for _, val := range vals { s.Require().False(val.IsJailed()) } @@ -72,13 +73,15 @@ func (s *CCVTestSuite) TestBasicSlashPacketThrottling() { sendOnConsumerRecvOnProvider(s, s.getFirstBundle().Path, timeoutHeight, timeoutTimestamp, slashPacket.GetBytes()) // Assert validator 0 is jailed and has no power - vals = providerStakingKeeper.GetAllValidators(s.providerCtx()) + vals, err = providerStakingKeeper.GetAllValidators(s.providerCtx()) + s.Require().NoError(err) slashedVal := vals[0] s.Require().True(slashedVal.IsJailed()) slashedValOperator, err := sdk.ValAddressFromHex(slashedVal.GetOperator()) s.Require().NoError(err) - lastValPower := providerStakingKeeper.GetLastValidatorPower(s.providerCtx(), slashedValOperator) + lastValPower, err := providerStakingKeeper.GetLastValidatorPower(s.providerCtx(), slashedValOperator) + s.Require().NoError(err) s.Require().Equal(int64(0), lastValPower) // Assert expected slash meter and allowance value @@ -94,7 +97,8 @@ func (s *CCVTestSuite) TestBasicSlashPacketThrottling() { sendOnConsumerRecvOnProvider(s, s.getFirstBundle().Path, timeoutHeight, timeoutTimestamp, slashPacket.GetBytes()) // Require that slash packet has not been handled - vals = providerStakingKeeper.GetAllValidators(s.providerCtx()) + vals, err = providerStakingKeeper.GetAllValidators(s.providerCtx()) + s.Require().NoError(err) s.Require().False(vals[2].IsJailed()) // Assert slash meter value is still the same @@ -145,7 +149,8 @@ func (s *CCVTestSuite) TestBasicSlashPacketThrottling() { // Assert validator 2 is jailed once pending slash packets are handled in ccv endblocker. s.providerChain.NextBlock() - vals = providerStakingKeeper.GetAllValidators(cacheCtx) + vals, err = providerStakingKeeper.GetAllValidators(cacheCtx) + s.Require().NoError(err) slashedVal = vals[2] s.Require().True(slashedVal.IsJailed()) @@ -155,7 +160,8 @@ func (s *CCVTestSuite) TestBasicSlashPacketThrottling() { slashedValOperator, err = sdk.ValAddressFromHex(slashedVal.GetOperator()) s.Require().NoError(err) - lastValPower = providerStakingKeeper.GetLastValidatorPower(cacheCtx, slashedValOperator) + lastValPower, err = providerStakingKeeper.GetLastValidatorPower(cacheCtx, slashedValOperator) + s.Require().NoError(err) s.Require().Equal(int64(0), lastValPower) } } @@ -242,8 +248,10 @@ func (s *CCVTestSuite) TestMultiConsumerSlashPacketThrottling() { s.providerCtx(), senderBundles[2].Chain.ChainID)) // Total power is now 3000 + power, err := providerStakingKeeper.GetLastTotalPower(s.providerCtx()) + s.Require().NoError(err) s.Require().Equal(int64(3000), - providerStakingKeeper.GetLastTotalPower(s.providerCtx()).Int64()) + power.Int64()) // Now replenish the slash meter and confirm one of two queued slash // packet entries are then handled. Order is irrelevant here since those @@ -255,8 +263,10 @@ func (s *CCVTestSuite) TestMultiConsumerSlashPacketThrottling() { s.providerChain.NextBlock() // If one of the entires was handled, total power will be 2000 (1000 power was slashed) + power, err = providerStakingKeeper.GetLastTotalPower(s.providerCtx()) + s.Require().NoError(err) s.Require().Equal(int64(2000), - providerStakingKeeper.GetLastTotalPower(s.providerCtx()).Int64()) + power.Int64()) // Now replenish one more time, and handle final slash packet. s.replenishSlashMeterTillPositive() @@ -266,8 +276,10 @@ func (s *CCVTestSuite) TestMultiConsumerSlashPacketThrottling() { s.providerChain.NextBlock() // Total power is now 1000 (just a single validator left) + power, err = providerStakingKeeper.GetLastTotalPower(s.providerCtx()) + s.Require().NoError(err) s.Require().Equal(int64(1000), - providerStakingKeeper.GetLastTotalPower(s.providerCtx()).Int64()) + power.Int64()) // Now all 3 expected vals are jailed, and there are no more queued // slash/vsc matured packets. @@ -424,12 +436,11 @@ func (s *CCVTestSuite) TestDoubleSignDoesNotAffectThrottling() { stakingKeeper := s.providerApp.GetTestStakingKeeper() for _, val := range s.providerChain.Vals.Validators { - power := stakingKeeper.GetLastValidatorPower(s.providerCtx(), sdk.ValAddress(val.Address)) + power, err := stakingKeeper.GetLastValidatorPower(s.providerCtx(), sdk.ValAddress(val.Address)) + s.Require().NoError(err) s.Require().Equal(int64(1000), power) - stakingVal, found := stakingKeeper.GetValidatorByConsAddr(s.providerCtx(), sdk.ConsAddress(val.Address)) - if !found { - s.Require().Fail("validator not found") - } + stakingVal, err := stakingKeeper.GetValidatorByConsAddr(s.providerCtx(), sdk.ConsAddress(val.Address)) + s.Require().Error(err) s.Require().False(stakingVal.Jailed) // 4th validator should have no slash log, all the others do @@ -578,7 +589,8 @@ func (s *CCVTestSuite) TestQueueOrdering() { // Confirm total power is now 3000 once updated by staking end blocker s.providerChain.NextBlock() - totalPower := s.providerApp.GetTestStakingKeeper().GetLastTotalPower(s.providerCtx()) + totalPower, err := s.providerApp.GetTestStakingKeeper().GetLastTotalPower(s.providerCtx()) + s.Require().NoError(err) s.Require().Equal(math.NewInt(3000), totalPower) // Now change replenish frac to 0.67 and fully replenish the meter. @@ -617,7 +629,8 @@ func (s *CCVTestSuite) TestSlashingSmallValidators() { // Assert that we start out with no jailings providerStakingKeeper := s.providerApp.GetTestStakingKeeper() - vals := providerStakingKeeper.GetAllValidators(s.providerCtx()) + vals, err := providerStakingKeeper.GetAllValidators(s.providerCtx()) + s.Require().NoError(err) for _, val := range vals { s.Require().False(val.IsJailed()) } @@ -643,31 +656,36 @@ func (s *CCVTestSuite) TestSlashingSmallValidators() { sendOnConsumerRecvOnProvider(s, s.getFirstBundle().Path, timeoutHeight, timeoutTimestamp, slashPacket3.GetBytes()) // Default slash meter replenish fraction is 0.05, so all sent packets should be handled immediately. - vals = providerStakingKeeper.GetAllValidators(s.providerCtx()) + vals, err = providerStakingKeeper.GetAllValidators(s.providerCtx()) + s.Require().NoError(err) val0Operator, err := sdk.ValAddressFromHex(vals[0].GetOperator()) + power, err := providerStakingKeeper.GetLastValidatorPower(s.providerCtx(), val0Operator) + s.Require().NoError(err) s.Require().NoError(err) s.Require().False(vals[0].IsJailed()) - s.Require().Equal(int64(1000), - providerStakingKeeper.GetLastValidatorPower(s.providerCtx(), val0Operator)) + s.Require().Equal(int64(1000), power) val1Operator, err := sdk.ValAddressFromHex(vals[1].GetOperator()) + power, err = providerStakingKeeper.GetLastValidatorPower(s.providerCtx(), val1Operator) + s.Require().NoError(err) s.Require().NoError(err) s.Require().True(vals[1].IsJailed()) - s.Require().Equal(int64(0), - providerStakingKeeper.GetLastValidatorPower(s.providerCtx(), val1Operator)) + s.Require().Equal(int64(0), power) val2Operator, err := sdk.ValAddressFromHex(vals[2].GetOperator()) + power, err = providerStakingKeeper.GetLastValidatorPower(s.providerCtx(), val2Operator) + s.Require().NoError(err) s.Require().NoError(err) s.Require().True(vals[2].IsJailed()) - s.Require().Equal(int64(0), - providerStakingKeeper.GetLastValidatorPower(s.providerCtx(), val2Operator)) + s.Require().Equal(int64(0), power) val3Operator, err := sdk.ValAddressFromHex(vals[3].GetOperator()) + power, err = providerStakingKeeper.GetLastValidatorPower(s.providerCtx(), val3Operator) + s.Require().NoError(err) s.Require().NoError(err) s.Require().True(vals[3].IsJailed()) - s.Require().Equal(int64(0), - providerStakingKeeper.GetLastValidatorPower(s.providerCtx(), val3Operator)) + s.Require().Equal(int64(0), power) } // TestSlashMeterAllowanceChanges tests scenarios where the slash meter allowance is expected to change. @@ -981,29 +999,31 @@ func (s *CCVTestSuite) TestVscMaturedHandledPerBlockLimit() { } func (s *CCVTestSuite) confirmValidatorJailed(tmVal tmtypes.Validator, checkPower bool) { - sdkVal, found := s.providerApp.GetTestStakingKeeper().GetValidator( + sdkVal, err := s.providerApp.GetTestStakingKeeper().GetValidator( s.providerCtx(), sdk.ValAddress(tmVal.Address)) - s.Require().True(found) + s.Require().NoError(err) s.Require().True(sdkVal.IsJailed()) if checkPower { valOperator, err := sdk.ValAddressFromHex(sdkVal.GetOperator()) s.Require().NoError(err) - valPower := s.providerApp.GetTestStakingKeeper().GetLastValidatorPower( + valPower, err := s.providerApp.GetTestStakingKeeper().GetLastValidatorPower( s.providerCtx(), valOperator) + s.Require().NoError(err) s.Require().Equal(int64(0), valPower) } } func (s *CCVTestSuite) confirmValidatorNotJailed(tmVal tmtypes.Validator, expectedPower int64) { - sdkVal, found := s.providerApp.GetTestStakingKeeper().GetValidator( + sdkVal, err := s.providerApp.GetTestStakingKeeper().GetValidator( s.providerCtx(), sdk.ValAddress(tmVal.Address)) - s.Require().True(found) + s.Require().NoError(err) valOperator, err := sdk.ValAddressFromHex(sdkVal.GetOperator()) s.Require().NoError(err) - valPower := s.providerApp.GetTestStakingKeeper().GetLastValidatorPower( + valPower, err := s.providerApp.GetTestStakingKeeper().GetLastValidatorPower( s.providerCtx(), valOperator) + s.Require().NoError(err) s.Require().Equal(expectedPower, valPower) s.Require().False(sdkVal.IsJailed()) } diff --git a/tests/integration/throttle_retry.go b/tests/integration/throttle_retry.go index a02bdca4dc..26557c9953 100644 --- a/tests/integration/throttle_retry.go +++ b/tests/integration/throttle_retry.go @@ -33,7 +33,8 @@ func (s *CCVTestSuite) TestSlashRetries() { providerKeeper.InitializeSlashMeter(s.providerCtx()) // Assert that we start out with no jailings providerStakingKeeper := s.providerApp.GetTestStakingKeeper() - vals := providerStakingKeeper.GetAllValidators(s.providerCtx()) + vals, err := providerStakingKeeper.GetAllValidators(s.providerCtx()) + s.Require().NoError(err) for _, val := range vals { s.Require().False(val.IsJailed()) } @@ -82,14 +83,16 @@ func (s *CCVTestSuite) TestSlashRetries() { s.providerChain.NextBlock() // Default slash meter replenish fraction is 0.05, so packet should be handled on provider. - vals = s.providerApp.GetTestStakingKeeper().GetAllValidators(s.providerCtx()) + vals, err = s.providerApp.GetTestStakingKeeper().GetAllValidators(s.providerCtx()) + s.Require().NoError(err) s.Require().True(vals[1].IsJailed()) val1Operator, err := sdk.ValAddressFromHex(vals[1].GetOperator()) s.Require().NoError(err) - s.Require().Equal(int64(0), - s.providerApp.GetTestStakingKeeper().GetLastValidatorPower(s.providerCtx(), val1Operator)) + power1, err := s.providerApp.GetTestStakingKeeper().GetLastValidatorPower(s.providerCtx(), val1Operator) + s.Require().NoError(err) + s.Require().Equal(int64(0), power1) s.Require().Equal(uint64(0), providerKeeper.GetThrottledPacketDataSize(s.providerCtx(), s.getFirstBundle().Chain.ChainID)) @@ -144,8 +147,9 @@ func (s *CCVTestSuite) TestSlashRetries() { val2Operator, err := sdk.ValAddressFromHex(vals[2].GetOperator()) s.Require().NoError(err) - s.Require().Equal(int64(1000), - providerStakingKeeper.GetLastValidatorPower(s.providerCtx(), val2Operator)) + power2, err := providerStakingKeeper.GetLastValidatorPower(s.providerCtx(), val2Operator) + s.Require().NoError(err) + s.Require().Equal(int64(1000), power2) s.Require().Equal(uint64(1), providerKeeper.GetThrottledPacketDataSize(s.providerCtx(), s.getFirstBundle().Chain.ChainID)) diff --git a/tests/integration/unbonding.go b/tests/integration/unbonding.go index 2fed6f033a..57d523d771 100644 --- a/tests/integration/unbonding.go +++ b/tests/integration/unbonding.go @@ -82,7 +82,8 @@ func (s *CCVTestSuite) TestUndelegationNormalOperation() { s.SetupCCVChannel(s.path) // set VSC timeout period to not trigger the removal of the consumer chain - providerUnbondingPeriod := stakingKeeper.UnbondingTime(s.providerCtx()) + providerUnbondingPeriod, err := stakingKeeper.UnbondingTime(s.providerCtx()) + s.Require().NoError(err) consumerUnbondingPeriod := consumerKeeper.GetUnbondingPeriod(s.consumerCtx()) providerKeeper.SetVscTimeoutPeriod(s.providerCtx(), providerUnbondingPeriod+consumerUnbondingPeriod+24*time.Hour) @@ -225,7 +226,8 @@ func (s *CCVTestSuite) TestUndelegationDuringInit() { checkCCVUnbondingOp(s, s.providerCtx(), s.consumerChain.ChainID, valsetUpdateID, true, "test: "+tc.name) // get provider unbonding period - providerUnbondingPeriod := stakingKeeper.UnbondingTime(s.providerCtx()) + providerUnbondingPeriod, err := stakingKeeper.UnbondingTime(s.providerCtx()) + s.Require().NoError(err) // update init timeout timestamp tc.updateInitTimeoutTimestamp(&providerKeeper, providerUnbondingPeriod) @@ -321,7 +323,8 @@ func (s *CCVTestSuite) TestUnbondingNoConsumer() { // increment time so that the unbonding period ends on the provider; // cannot use incrementTimeByUnbondingPeriod() since it tries // to also update the provider's client on the consumer - providerUnbondingPeriod := providerStakingKeeper.UnbondingTime(s.providerCtx()) + providerUnbondingPeriod, err := providerStakingKeeper.UnbondingTime(s.providerCtx()) + s.Require().NoError(err) s.coordinator.IncrementTimeBy(providerUnbondingPeriod + time.Hour) // call NextBlock on the provider (which increments the height) @@ -360,12 +363,13 @@ func (s *CCVTestSuite) TestRedelegationNoConsumer() { // 1 redelegation record should exist for original delegator redelegations := checkRedelegations(s, delAddr, 1) - + unbondingTime, err := stakingKeeper.UnbondingTime(s.providerCtx()) + s.Require().NoError(err) // Check that the only entry has appropriate maturation time, the unbonding period from now checkRedelegationEntryCompletionTime( s, redelegations[0].Entries[0], - s.providerCtx().BlockTime().Add(stakingKeeper.UnbondingTime(s.providerCtx())), + s.providerCtx().BlockTime().Add(unbondingTime), ) // required before call to incrementTimeByUnbondingPeriod or else a panic @@ -393,7 +397,8 @@ func (s *CCVTestSuite) TestRedelegationProviderFirst() { stakingKeeper := s.providerApp.GetTestStakingKeeper() // set VSC timeout period to not trigger the removal of the consumer chain - providerUnbondingPeriod := stakingKeeper.UnbondingTime(s.providerCtx()) + providerUnbondingPeriod, err := stakingKeeper.UnbondingTime(s.providerCtx()) + s.Require().NoError(err) consumerUnbondingPeriod := consumerKeeper.GetUnbondingPeriod(s.consumerCtx()) providerKeeper.SetVscTimeoutPeriod(s.providerCtx(), providerUnbondingPeriod+consumerUnbondingPeriod+24*time.Hour) @@ -414,11 +419,13 @@ func (s *CCVTestSuite) TestRedelegationProviderFirst() { // 1 redelegation record should exist for original delegator redelegations := checkRedelegations(s, delAddr, 1) + unbondingTime, err := stakingKeeper.UnbondingTime(s.providerCtx()) + s.Require().NoError(err) // Check that the only entry has appropriate maturation time, the unbonding period from now checkRedelegationEntryCompletionTime( s, redelegations[0].Entries[0], - s.providerCtx().BlockTime().Add(stakingKeeper.UnbondingTime(s.providerCtx())), + s.providerCtx().BlockTime().Add(unbondingTime), ) // Save the current valset update ID diff --git a/testutil/ibc_testing/specific_setup.go b/testutil/ibc_testing/specific_setup.go index f1352c9cc8..f128f3c2fb 100644 --- a/testutil/ibc_testing/specific_setup.go +++ b/testutil/ibc_testing/specific_setup.go @@ -65,7 +65,7 @@ func ConsumerAppIniter(initValPowers []types.ValidatorUpdate) AppIniter { func DemocracyConsumerAppIniter(initValPowers []types.ValidatorUpdate) AppIniter { return func() (ibctesting.TestingApp, map[string]json.RawMessage) { encoding := appConsumerDemocracy.MakeTestEncodingConfig() - testApp := appConsumerDemocracy.New(log.NewNopLogger(), tmdb.NewMemDB(), nil, true, simtestutil.EmptyAppOptions{}) + testApp := appConsumerDemocracy.New(log.NewNopLogger(), db.NewMemDB(), nil, true, simtestutil.EmptyAppOptions{}) genesisState := appConsumerDemocracy.NewDefaultGenesisState(encoding.Codec) // Feed consumer genesis with provider validators // TODO See if useful for democracy diff --git a/testutil/integration/interfaces.go b/testutil/integration/interfaces.go index cfc1cc731b..13ef4b1d19 100644 --- a/testutil/integration/interfaces.go +++ b/testutil/integration/interfaces.go @@ -10,13 +10,13 @@ import ( "cosmossdk.io/core/comet" - evidencetypes "cosmossdk.io/x/evidence/types" + evidencekeeper "cosmossdk.io/x/evidence/keeper" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" + mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -69,7 +69,7 @@ type ConsumerApp interface { // Tests a slashing keeper interface with more capabilities than the expected_keepers interface GetTestSlashingKeeper() TestSlashingKeeper // Tests an evidence keeper interface with more capabilities than the expected_keepers interface - GetTestEvidenceKeeper() TestEvidenceKeeper + GetTestEvidenceKeeper() evidencekeeper.Keeper } type DemocConsumerApp interface { @@ -79,9 +79,10 @@ type DemocConsumerApp interface { // Tests a staking keeper interface with more capabilities than the expected_keepers interface GetTestStakingKeeper() TestStakingKeeper // Tests a mint keeper interface with more capabilities than the expected_keepers interface - GetTestMintKeeper() TestMintKeeper - // Tests a gov keeper interface with more capabilities than the expected_keepers interface - GetTestGovKeeper() TestGovKeeper + GetTestMintKeeper() mintkeeper.Keeper + + // @MSalopek -> on v50 we need to access the Params collection which does not have a getter + GetTestGovKeeper() govkeeper.Keeper } // @@ -131,10 +132,7 @@ type TestSlashingKeeper interface { // NOTE: @MSalopek deprecated in v50 // IterateValidatorMissedBlockBitArray(ctx sdk.Context, // address sdk.ConsAddress, handler func(index int64, missed bool) (stop bool)) -} - -type TestEvidenceKeeper interface { - HandleEquivocationEvidence(ctx sdk.Context, evidence *evidencetypes.Equivocation) + IterateMissedBlockBitmap(ctx context.Context, addr sdk.ConsAddress, cb func(index int64, missed bool) (stop bool)) error } type TestDistributionKeeper interface { @@ -144,15 +142,3 @@ type TestDistributionKeeper interface { GetValidatorOutstandingRewards(ctx context.Context, val sdk.ValAddress) (rewards distributiontypes.ValidatorOutstandingRewards, err error) GetCommunityTax(ctx context.Context) (math.LegacyDec, error) } - -type TestMintKeeper interface { - GetParams(ctx sdk.Context) (params minttypes.Params) -} - -type TestGovKeeper interface { - GetParams(ctx sdk.Context) govv1.Params - SetParams(ctx sdk.Context, params govv1.Params) error - SubmitProposal(ctx sdk.Context, messages []sdk.Msg, metadata, title, summary string, proposer sdk.AccAddress) (govv1.Proposal, error) - AddDeposit(ctx sdk.Context, proposalID uint64, depositorAddr sdk.AccAddress, depositAmount sdk.Coins) (bool, error) - AddVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress, options govv1.WeightedVoteOptions, metadata string) error -} diff --git a/testutil/simibc/README.md b/testutil/simibc/README.md deleted file mode 100644 index 14d342ebd9..0000000000 --- a/testutil/simibc/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# simibc - -## What is this? - -A collection of utilities based on [ibc-go/testing](https://github.com/cosmos/ibc-go/tree/main/testing) which make it easier to write test scenarios involving precise orderings of - -- BeginBlock, EndBlock on each IBC connected chain -- Packet delivery -- Updating the client - -## Why is this useful? - -It is very hard to reason about tests written using vanilla [ibc-go/testing](https://github.com/cosmos/ibc-go/tree/main/testing) because the methods included in that library have many side effects. For example, that library has a notion of global time, so calling EndBlock on one chain will influence the future block times of another chain. As another example, sending a packet from chain A to B will automatically progress the block height on chain A. These behaviors make it very hard to understand, especially if your applications have business logic in BeginBlock or EndBlock. - -The utilities in simibc do not have any side effects, making it very easy to understand what is happening. It also makes it very easy to write data driven tests (like table tests, model based tests or property based tests). - -## How do I use this? - -Please see the function docstrings to get an idea of how you could use this package. This README is intentionally short because it is easier to maintain code and docstrings instead of markdown. diff --git a/testutil/simibc/ordered_outbox.go b/testutil/simibc/ordered_outbox.go deleted file mode 100644 index 2e2d9a9520..0000000000 --- a/testutil/simibc/ordered_outbox.go +++ /dev/null @@ -1,114 +0,0 @@ -package simibc - -import channeltypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" - -// Ack represents a (sent) ack committed to block state -type Ack struct { - Ack []byte - // The packet to which this ack is a response - Packet channeltypes.Packet - // The number of App.Commits that have occurred since this ack was sent - // For example, if the ack was sent at height h, and the blockchain - // has headers ..., h, h+1, h+2 then Commits = 3 - Commits int -} - -// Packet represents a (sent) packet committed to block state -type Packet struct { - Packet channeltypes.Packet - // The number of App.Commits that have occurred since this packet was sent - // For example, if the ack was sent at height h, and the blockchain - // has headers ..., h, h+1, h+2 then Commits = 3 - Commits int -} - -// OrderedOutbox is a collection of ORDERED packets and acks that have been sent -// by different chains, but have not yet been delivered to their target. -// The methods take care of bookkeeping, making it easier to simulate -// a real relayed IBC connection. -// -// Each sent packet or ack can be added here. When a sufficient number of -// block commits have followed each sent packet or ack, they can be consumed: -// delivered to their target. Since the sequences are ordered, this is useful -// for testing ORDERED ibc channels. -// -// NOTE: OrderedOutbox MAY be used independently of the rest of simibc. -type OrderedOutbox struct { - // An ordered sequence of packets from each sender - OutboxPackets map[string][]Packet - // An ordered sequence of acks from each sender - OutboxAcks map[string][]Ack -} - -// MakeOrderedOutbox creates a new empty OrderedOutbox. -func MakeOrderedOutbox() OrderedOutbox { - return OrderedOutbox{ - OutboxPackets: map[string][]Packet{}, - OutboxAcks: map[string][]Ack{}, - } -} - -// AddPacket adds an outbound packet from the sender. -func (n OrderedOutbox) AddPacket(sender string, packet channeltypes.Packet) { - n.OutboxPackets[sender] = append(n.OutboxPackets[sender], Packet{packet, 0}) -} - -// AddAck adds an outbound ack from the sender. The ack is a response to the packet. -func (n OrderedOutbox) AddAck(sender string, ack []byte, packet channeltypes.Packet) { - n.OutboxAcks[sender] = append(n.OutboxAcks[sender], Ack{ack, packet, 0}) -} - -// ConsumePackets returns the first num packets with 2 or more commits. Returned -// packets are removed from the outbox and will not be returned again (consumed). -func (n OrderedOutbox) ConsumePackets(sender string, num int) []Packet { - ret := []Packet{} - sz := len(n.OutboxPackets[sender]) - if sz < num { - num = sz - } - for _, p := range n.OutboxPackets[sender][:num] { - if 1 < p.Commits { - ret = append(ret, p) - } else { - break - } - } - n.OutboxPackets[sender] = n.OutboxPackets[sender][len(ret):] - return ret -} - -// ConsumerAcks returns the first num packets with 2 or more commits. Returned -// acks are removed from the outbox and will not be returned again (consumed). -func (n OrderedOutbox) ConsumeAcks(sender string, num int) []Ack { - ret := []Ack{} - sz := len(n.OutboxAcks[sender]) - if sz < num { - num = sz - } - for _, a := range n.OutboxAcks[sender][:num] { - if 1 < a.Commits { - ret = append(ret, a) - } else { - break - } - } - n.OutboxAcks[sender] = n.OutboxAcks[sender][len(ret):] - return ret -} - -// Commit marks a block commit, increasing the commit count for all -// packets and acks in the sender's outbox. -// When a packet or ack has 2 or more commits, it is available for -// delivery to the counterparty chain. -// Note that 2 commits are necessary instead of 1: -// - 1st commit is necessary for the packet to included in the block -// - 2nd commit is necessary because in practice the ibc light client -// needs to have block h + 1 to be able to verify the packet in block h. -func (n OrderedOutbox) Commit(sender string) { - for i := range n.OutboxPackets[sender] { - n.OutboxPackets[sender][i].Commits += 1 - } - for i := range n.OutboxAcks[sender] { - n.OutboxAcks[sender][i].Commits += 1 - } -} diff --git a/testutil/simibc/relay_util.go b/testutil/simibc/relay_util.go deleted file mode 100644 index 072a80e501..0000000000 --- a/testutil/simibc/relay_util.go +++ /dev/null @@ -1,179 +0,0 @@ -package simibc - -import ( - clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" - host "github.com/cosmos/ibc-go/v8/modules/core/24-host" - ibctmtypes "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" - ibctesting "github.com/cosmos/ibc-go/v8/testing" - simapp "github.com/cosmos/ibc-go/v8/testing/simapp" - "github.com/stretchr/testify/require" - - errorsmod "cosmossdk.io/errors" - - sdk "github.com/cosmos/cosmos-sdk/types" - - tmtypes "github.com/cometbft/cometbft/types" -) - -// UpdateReceiverClient DELIVERs a header to the receiving endpoint -// and update the respective client of the receiving chain. -// -// The header is a header of the sender chain. The receiver chain -// must have a client of the sender chain that it can update. -// -// NOTE: this function MAY be used independently of the rest of simibc. -func UpdateReceiverClient(sender, receiver *ibctesting.Endpoint, header *ibctmtypes.Header) (err error) { - err = augmentHeader(sender.Chain, receiver.Chain, receiver.ClientID, header) - - if err != nil { - return err - } - - msg, err := clienttypes.NewMsgUpdateClient( - receiver.ClientID, header, - receiver.Chain.SenderAccount.GetAddress().String(), - ) - - require.NoError(receiver.Chain.T, err) - - _, _, err = simapp.SignAndDeliver( - receiver.Chain.T, - receiver.Chain.TxConfig, - receiver.Chain.App.GetBaseApp(), - receiver.Chain.GetContext().BlockHeader(), - []sdk.Msg{msg}, - receiver.Chain.ChainID, - []uint64{receiver.Chain.SenderAccount.GetAccountNumber()}, - []uint64{receiver.Chain.SenderAccount.GetSequence()}, - true, true, receiver.Chain.SenderPrivKey, - ) - - if err != nil { - return err - } - - err = receiver.Chain.SenderAccount.SetSequence(receiver.Chain.SenderAccount.GetSequence() + 1) - - if err != nil { - return err - } - - return nil -} - -// TryRecvPacket will try once to DELIVER a packet from sender to receiver. If successful, -// it will return the acknowledgement bytes. -// -// The packet must be sent from the sender chain to the receiver chain, and the -// receiver chain must have a client for the sender chain which has been updated -// to a recent height of the sender chain so that it can verify the packet. -func TryRecvPacket(sender, receiver *ibctesting.Endpoint, packet channeltypes.Packet) (ack []byte, err error) { - packetKey := host.PacketCommitmentKey(packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) - proof, proofHeight := sender.Chain.QueryProof(packetKey) - - RPmsg := channeltypes.NewMsgRecvPacket(packet, proof, proofHeight, receiver.Chain.SenderAccount.GetAddress().String()) - - _, resWithAck, err := simapp.SignAndDeliver( - receiver.Chain.T, - receiver.Chain.TxConfig, - receiver.Chain.App.GetBaseApp(), - receiver.Chain.GetContext().BlockHeader(), - []sdk.Msg{RPmsg}, - receiver.Chain.ChainID, - []uint64{receiver.Chain.SenderAccount.GetAccountNumber()}, - []uint64{receiver.Chain.SenderAccount.GetSequence()}, - true, true, receiver.Chain.SenderPrivKey, - ) - if err != nil { - return nil, err - } - - err = receiver.Chain.SenderAccount.SetSequence(receiver.Chain.SenderAccount.GetSequence() + 1) - - if err != nil { - return nil, err - } - - ack, err = ibctesting.ParseAckFromEvents(resWithAck.GetEvents()) - - if err != nil { - return nil, err - } - - return ack, nil -} - -// TryRecvAck will try once to DELIVER an ack from sender to receiver. -// -// The ack must have been sent from the sender to the receiver, in response -// to packet which was previously delivered from the receiver to the sender. -// The receiver chain must have a client for the sender chain which has been -// updated to a recent height of the sender chain so that it can verify the packet. -func TryRecvAck(sender, receiver *ibctesting.Endpoint, packet channeltypes.Packet, ack []byte) (err error) { - p := packet - packetKey := host.PacketAcknowledgementKey(p.GetDestPort(), p.GetDestChannel(), p.GetSequence()) - proof, proofHeight := sender.Chain.QueryProof(packetKey) - - ackMsg := channeltypes.NewMsgAcknowledgement(p, ack, proof, proofHeight, receiver.Chain.SenderAccount.GetAddress().String()) - - _, _, err = simapp.SignAndDeliver( - receiver.Chain.T, - receiver.Chain.TxConfig, - receiver.Chain.App.GetBaseApp(), - receiver.Chain.GetContext().BlockHeader(), - []sdk.Msg{ackMsg}, - receiver.Chain.ChainID, - []uint64{receiver.Chain.SenderAccount.GetAccountNumber()}, - []uint64{receiver.Chain.SenderAccount.GetSequence()}, - true, true, receiver.Chain.SenderPrivKey, - ) - - if err != nil { - return err - } - - err = receiver.Chain.SenderAccount.SetSequence(receiver.Chain.SenderAccount.GetSequence() + 1) - - if err != nil { - return err - } - - return nil -} - -// augmentHeader is a helper that augments the header with the height and validators that are most recently trusted -// by the receiver chain. If there is an error, the header will not be modified. -func augmentHeader(sender, receiver *ibctesting.TestChain, clientID string, header *ibctmtypes.Header) error { - trustedHeight := receiver.GetClientState(clientID).GetLatestHeight().(clienttypes.Height) - - var ( - tmTrustedVals *tmtypes.ValidatorSet - ok bool - ) - // Once we get TrustedHeight from client, we must query the validators from the counterparty chain - // If the LatestHeight == LastHeader.Height, then TrustedValidators are current validators - // If LatestHeight < LastHeader.Height, we can query the historical validator set from HistoricalInfo - if trustedHeight == sender.LastHeader.GetHeight() { - tmTrustedVals = sender.Vals - } else { - // NOTE: We need to get validators from counterparty at height: trustedHeight+1 - // since the last trusted validators for a header at height h - // is the NextValidators at h+1 committed to in header h by - // NextValidatorsHash - tmTrustedVals, ok = sender.GetValsAtHeight(int64(trustedHeight.RevisionHeight + 1)) - if !ok { - return errorsmod.Wrapf(ibctmtypes.ErrInvalidHeaderHeight, "could not retrieve trusted validators at trustedHeight: %d", trustedHeight) - } - } - trustedVals, err := tmTrustedVals.ToProto() - if err != nil { - return err - } - // inject trusted fields into last header - // for now assume revision number is 0 - header.TrustedHeight = trustedHeight - header.TrustedValidators = trustedVals - - return nil -} diff --git a/testutil/simibc/relayed_path.go b/testutil/simibc/relayed_path.go deleted file mode 100644 index a59c8014ed..0000000000 --- a/testutil/simibc/relayed_path.go +++ /dev/null @@ -1,153 +0,0 @@ -package simibc - -import ( - "testing" - "time" - - ibctmtypes "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" - ibctesting "github.com/cosmos/ibc-go/v8/testing" -) - -// RelayedPath is a wrapper around ibctesting.Path gives fine-grained -// control over delivery packets and acks, and client updates. Specifically, -// the path represents a bidirectional ORDERED channel between two chains. -// It is possible to control the precise order that packets and acks are -// delivered, and the precise independent and relative order and timing of -// new blocks on each chain. -type RelayedPath struct { - t *testing.T - path *ibctesting.Path - // clientHeaders is a map from chainID to an ordered list of headers that - // have been committed to that chain. The headers are used to update the - // client of the counterparty chain. - clientHeaders map[string][]*ibctmtypes.Header - // TODO: Make this private and expose methods to add packets and acks. - // Currently, packets and acks are added directly to the outboxes, - // but we should hide this implementation detail. - Outboxes OrderedOutbox -} - -// MakeRelayedPath returns an initialized RelayedPath without any -// packets, acks or headers. Requires a fully initialised path where -// the connection and any channel handshakes have been COMPLETED. -func MakeRelayedPath(t *testing.T, path *ibctesting.Path) RelayedPath { - t.Helper() - return RelayedPath{ - t: t, - clientHeaders: map[string][]*ibctmtypes.Header{}, - path: path, - Outboxes: MakeOrderedOutbox(), - } -} - -// Chain returns the chain with chainID -func (f *RelayedPath) Chain(chainID string) *ibctesting.TestChain { - if f.path.EndpointA.Chain.ChainID == chainID { - return f.path.EndpointA.Chain - } - if f.path.EndpointB.Chain.ChainID == chainID { - return f.path.EndpointB.Chain - } - f.t.Fatal("no chain found in relayed path with chainID: ", chainID) - return nil -} - -// UpdateClient updates the chain with the latest sequence -// of available headers committed by the counterparty chain since -// the last call to UpdateClient (or all for the first call). -func (f *RelayedPath) UpdateClient(chainID string) { - for _, header := range f.clientHeaders[f.counterparty(chainID)] { - err := UpdateReceiverClient(f.endpoint(f.counterparty(chainID)), f.endpoint(chainID), header) - if err != nil { - f.t.Fatal("in relayed path could not update client of chain: ", chainID, " with header: ", header, " err: ", err) - } - } - f.clientHeaders[f.counterparty(chainID)] = []*ibctmtypes.Header{} -} - -// DeliverPackets delivers UP TO packets to the chain which have been -// sent to it by the counterparty chain and are ready to be delivered. -// -// A packet is ready to be delivered if the sender chain has progressed -// a sufficient number of blocks since the packet was sent. This is because -// all sent packets must be committed to block state before they can be queried. -// Additionally, in practice, light clients require a header (h+1) to deliver a -// packet sent in header h. -// -// In order to deliver packets, the chain must have an up-to-date client -// of the counterparty chain. Ie. UpdateClient should be called before this. -func (f *RelayedPath) DeliverPackets(chainID string, num int) { - for _, p := range f.Outboxes.ConsumePackets(f.counterparty(chainID), num) { - ack, err := TryRecvPacket(f.endpoint(f.counterparty(chainID)), f.endpoint(chainID), p.Packet) - if err != nil { - f.t.Fatal("deliver") - } - f.Outboxes.AddAck(chainID, ack, p.Packet) - } -} - -// DeliverPackets delivers UP TO acks to the chain which have been -// sent to it by the counterparty chain and are ready to be delivered. -// -// An ack is ready to be delivered if the sender chain has progressed -// a sufficient number of blocks since the ack was sent. This is because -// all sent acks must be committed to block state before they can be queried. -// Additionally, in practice, light clients require a header (h+1) to deliver -// an ack sent in header h. -// -// In order to deliver acks, the chain must have an up-to-date client -// of the counterparty chain. Ie. UpdateClient should be called before this. -func (f *RelayedPath) DeliverAcks(chainID string, num int) { - for _, ack := range f.Outboxes.ConsumeAcks(f.counterparty(chainID), num) { - err := TryRecvAck(f.endpoint(f.counterparty(chainID)), f.endpoint(chainID), ack.Packet, ack.Ack) - if err != nil { - f.t.Fatal("deliverAcks") - } - } -} - -// EndAndBeginBlock calls EndBlock and commits block state, storing the header which can later -// be used to update the client on the counterparty chain. After committing, the chain local -// time progresses by dt, and BeginBlock is called with a header timestamped for the new time. -// -// preCommitCallback is called after EndBlock and before Commit, allowing arbitrary access to -// the sdk.Context after EndBlock. The callback is useful for testing purposes to execute -// arbitrary code before the chain sdk context is cleared in .Commit(). -// For example, app.EndBlock may lead to a new state, which you would like to query -// to check that it is correct. However, the sdk context is cleared after .Commit(), -// so you can query the state inside the callback. -func (f *RelayedPath) EndAndBeginBlock(chainID string, dt time.Duration, preCommitCallback func()) { - c := f.Chain(chainID) - - header, packets := EndBlock(c, preCommitCallback) - f.clientHeaders[chainID] = append(f.clientHeaders[chainID], header) - for _, p := range packets { - f.Outboxes.AddPacket(chainID, p) - } - f.Outboxes.Commit(chainID) - BeginBlock(c, dt) -} - -// counterparty is a helper returning the counterparty chainID -func (f *RelayedPath) counterparty(chainID string) string { - if f.path.EndpointA.Chain.ChainID == chainID { - return f.path.EndpointB.Chain.ChainID - } - if f.path.EndpointB.Chain.ChainID == chainID { - return f.path.EndpointA.Chain.ChainID - } - f.t.Fatal("no chain found in relayed path with chainID: ", chainID) - return "" -} - -// endpoint is a helper returning the endpoint for the chain -func (f *RelayedPath) endpoint(chainID string) *ibctesting.Endpoint { - if chainID == f.path.EndpointA.Chain.ChainID { - return f.path.EndpointA - } - if chainID == f.path.EndpointB.Chain.ChainID { - return f.path.EndpointB - } - f.t.Fatal("no chain found in relayed path with chainID: ", chainID) - return nil -}