From 9d9c19c0f854c203ba1a202846eb9067124d4eff Mon Sep 17 00:00:00 2001 From: Marko Date: Mon, 2 Dec 2024 18:34:30 +0100 Subject: [PATCH 1/5] fix(crypto): bls compilation (#22717) --- .github/workflows/build.yml | 6 ++++++ crypto/keys/bls12_381/key_cgo.go | 13 +------------ scripts/build/build.mk | 6 ------ 3 files changed, 7 insertions(+), 18 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2911e9d98952..e6c6f4ee640c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -55,6 +55,12 @@ jobs: - name: Build with rocksdb backend if: matrix.go-arch == 'amd64' run: GOARCH=${{ matrix.go-arch }} COSMOS_BUILD_OPTIONS="rocksdb" make build + - name: Build with BLS12381 + if: matrix.go-arch == 'amd64' + run: GOARCH=${{ matrix.go-arch }} COSMOS_BUILD_OPTIONS="bls12381" make build + - name: Build with Secp_cgo + if: matrix.go-arch == 'amd64' + run: GOARCH=${{ matrix.go-arch }} COSMOS_BUILD_OPTIONS="secp" make build ################### ## Build Tooling ## ################### diff --git a/crypto/keys/bls12_381/key_cgo.go b/crypto/keys/bls12_381/key_cgo.go index 2470e2c6ab6b..86c6a6644690 100644 --- a/crypto/keys/bls12_381/key_cgo.go +++ b/crypto/keys/bls12_381/key_cgo.go @@ -4,13 +4,12 @@ package bls12_381 import ( "bytes" - "crypto/sha256" "errors" "fmt" "github.com/cometbft/cometbft/crypto" - "github.com/cometbft/cometbft/crypto/tmhash" "github.com/cometbft/cometbft/crypto/bls12381" + "github.com/cometbft/cometbft/crypto/tmhash" "github.com/cosmos/cosmos-sdk/codec" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -84,11 +83,6 @@ func (privKey PrivKey) Sign(msg []byte) ([]byte, error) { return nil, err } - if len(msg) > bls12381.MaxMsgLen { - hash := sha256.Sum256(msg) - return secretKey.Sign(hash[:]) - } - return secretKey.Sign(msg) } @@ -151,11 +145,6 @@ func (pubKey PubKey) VerifySignature(msg, sig []byte) bool { return false } - if len(msg) > bls12381.MaxMsgLen { - hash := sha256.Sum256(msg) - msg = hash[:] - } - return pubK.VerifySignature(msg, sig) } diff --git a/scripts/build/build.mk b/scripts/build/build.mk index 92f7b6a20e9f..4727b05e98a3 100644 --- a/scripts/build/build.mk +++ b/scripts/build/build.mk @@ -58,12 +58,6 @@ ifeq (v2,$(findstring v2,$(COSMOS_BUILD_OPTIONS))) endif # DB backend selection -ifeq (cleveldb,$(findstring cleveldb,$(COSMOS_BUILD_OPTIONS))) - build_tags += gcc -endif -ifeq (badgerdb,$(findstring badgerdb,$(COSMOS_BUILD_OPTIONS))) - build_tags += badgerdb -endif # handle rocksdb ifeq (rocksdb,$(findstring rocksdb,$(COSMOS_BUILD_OPTIONS))) CGO_ENABLED=1 From 1c4dc89ead78bf749818e84318c0529354d9964a Mon Sep 17 00:00:00 2001 From: Julien Robert Date: Tue, 3 Dec 2024 09:07:32 +0100 Subject: [PATCH 2/5] chore(schema): rename `ReferenceType` to `ReferenceableType` (#22698) --- schema/diff/field_diff.go | 12 ++++++------ schema/diff/field_diff_test.go | 2 +- schema/enum.go | 4 ++-- schema/type.go | 6 +++--- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/schema/diff/field_diff.go b/schema/diff/field_diff.go index ffc6c71ed1a4..8b2aaacaa144 100644 --- a/schema/diff/field_diff.go +++ b/schema/diff/field_diff.go @@ -3,7 +3,7 @@ package diff import "cosmossdk.io/schema" // FieldDiff represents the difference between two fields. -// The KindChanged, NullableChanged, and ReferenceTypeChanged methods can be used to determine +// The KindChanged, NullableChanged, and ReferenceableTypeChanged methods can be used to determine // what specific changes were made to the field. type FieldDiff struct { // Name is the name of the field. @@ -22,11 +22,11 @@ type FieldDiff struct { NewNullable bool // OldReferencedType is the name of the old referenced type. - // It will be empty if the field is not a reference type or if there was no change. + // It will be empty if the field is not a referenceable type or if there was no change. OldReferencedType string // NewReferencedType is the name of the new referenced type. - // It will be empty if the field is not a reference type or if there was no change. + // It will be empty if the field is not a referenceable type or if there was no change. NewReferencedType string } @@ -52,7 +52,7 @@ func compareField(oldField, newField schema.Field) FieldDiff { // Empty returns true if the field diff has no changes. func (d FieldDiff) Empty() bool { - return !d.KindChanged() && !d.NullableChanged() && !d.ReferenceTypeChanged() + return !d.KindChanged() && !d.NullableChanged() && !d.ReferenceableTypeChanged() } // KindChanged returns true if the field kind changed. @@ -65,7 +65,7 @@ func (d FieldDiff) NullableChanged() bool { return d.OldNullable != d.NewNullable } -// ReferenceTypeChanged returns true if the referenced type changed. -func (d FieldDiff) ReferenceTypeChanged() bool { +// ReferenceableTypeChanged returns true if the referenced type changed. +func (d FieldDiff) ReferenceableTypeChanged() bool { return d.OldReferencedType != d.NewReferencedType } diff --git a/schema/diff/field_diff_test.go b/schema/diff/field_diff_test.go index d584aae5a48c..925673820b53 100644 --- a/schema/diff/field_diff_test.go +++ b/schema/diff/field_diff_test.go @@ -45,7 +45,7 @@ func Test_compareField(t *testing.T) { OldReferencedType: "old", NewReferencedType: "new", }, - trueF: FieldDiff.ReferenceTypeChanged, + trueF: FieldDiff.ReferenceableTypeChanged, }, } diff --git a/schema/enum.go b/schema/enum.go index b52b01e1a522..c802eac875f5 100644 --- a/schema/enum.go +++ b/schema/enum.go @@ -41,8 +41,8 @@ func (e EnumType) TypeName() string { return e.Name } -func (EnumType) isType() {} -func (EnumType) isReferenceType() {} +func (EnumType) isType() {} +func (EnumType) isReferenceableType() {} // Validate validates the enum definition. func (e EnumType) Validate(TypeSet) error { diff --git a/schema/type.go b/schema/type.go index dfbc839ae0d4..bb02ea329e98 100644 --- a/schema/type.go +++ b/schema/type.go @@ -13,13 +13,13 @@ type Type interface { isType() } -// ReferenceType is a marker interface that all types that can be the target of Field.ReferencedType implement. +// ReferenceableType is a marker interface that all types that can be the target of Field.ReferencedType implement. // Currently, this is only EnumType. -type ReferenceType interface { +type ReferenceableType interface { Type // isReferenceType is implemented if this is a reference type. - isReferenceType() + isReferenceableType() } // TypeSet represents something that has types and allows them to be looked up by name. From 4d1adcf9552d63b47a997d3d3ca0391f196f2b09 Mon Sep 17 00:00:00 2001 From: Julien Robert Date: Tue, 3 Dec 2024 09:32:13 +0100 Subject: [PATCH 3/5] fix(x/auth): facultative vesting as well in simulation (#22721) --- x/auth/simulation/genesis.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 7c18882fd325..0e9f7e93eb4a 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -26,6 +26,13 @@ func RandomGenesisAccounts(simState *module.SimulationState) types.GenesisAccoun for i, acc := range simState.Accounts { bacc := types.NewBaseAccountWithAddress(acc.Address) + // check if vesting module is enabled + // if not, just use base account + if _, ok := simState.GenState["vesting"]; !ok { + genesisAccs[i] = bacc + continue + } + // Only consider making a vesting account once the initial bonded validator // set is exhausted due to needing to track DelegatedVesting. if !(int64(i) > simState.NumBonded && simState.Rand.Intn(100) < 50) { From 78c8057a1869148ea4f99bc1a279b4bd73699196 Mon Sep 17 00:00:00 2001 From: Dmytrol <46675332+Dimitrolito@users.noreply.github.com> Date: Tue, 3 Dec 2024 11:10:51 +0200 Subject: [PATCH 4/5] docs: fix typos in various documentation files (#22722) Co-authored-by: Julien Robert Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- CODING_GUIDELINES.md | 2 +- RELEASE_PROCESS.md | 4 ++-- ROADMAP.md | 4 ++-- docs/architecture/adr-008-dCERT-group.md | 2 +- docs/architecture/adr-033-protobuf-inter-module-comm.md | 2 +- docs/architecture/adr-049-state-sync-hooks.md | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/CODING_GUIDELINES.md b/CODING_GUIDELINES.md index 59cd1e25e9b6..1e6d2a71270b 100644 --- a/CODING_GUIDELINES.md +++ b/CODING_GUIDELINES.md @@ -148,7 +148,7 @@ Desired outcomes: As a developer, you must help the QA team by providing instructions for User Experience (UX) and functional testing. -### QA Team to cross check Acceptance Tests +### QA Team to cross-check Acceptance Tests Once the AT are defined, the QA team will have an overview of the behavior a user can expect and: diff --git a/RELEASE_PROCESS.md b/RELEASE_PROCESS.md index e676be0d4ab1..d3b773e8dce4 100644 --- a/RELEASE_PROCESS.md +++ b/RELEASE_PROCESS.md @@ -27,7 +27,7 @@ v1.0.0-beta1 → v1.0.0-beta2 → ... → v1.0.0-rc1 → v1.0.0-rc2 → ... → * All links must point to their respective pull request. * The `CHANGELOG.md` must contain only the changes of that specific released version. All other changelog entries must be deleted and linked to the `main` branch changelog ([example](https://github.com/cosmos/cosmos-sdk/blob/release/v0.46.x/CHANGELOG.md#previous-versions)). * Create release notes, in `RELEASE_NOTES.md`, highlighting the new features and changes in the version. This is needed so the bot knows which entries to add to the release page on GitHub. - * Additionally verify that the `UPGRADING.md` file is up to date and contains all the necessary information for upgrading to the new version. + * Additionally verify that the `UPGRADING.md` file is up-to-date and contains all the necessary information for upgrading to the new version. * Remove GitHub workflows that should not be in the release branch * `test.yml`: All standalone go module tests should be removed (expect `./simapp`, and `./tests`, SDK and modules tests). * These packages are tracked and tested directly on main. @@ -57,7 +57,7 @@ A _patch release_ is an increment of the patch number (eg: `v1.2.0` → `v1.2.1` **Patch release must not break API nor consensus.** -Updates to the release branch should come from `main` by backporting PRs (usually done by automatic cherry pick followed by a PRs to the release branch). The backports must be marked using `backport/Y` label in PR for main. +Updates to the release branch should come from `main` by backporting PRs (usually done by automatic cherry-pick followed by PRs to the release branch). The backports must be marked using `backport/Y` label in PR for main. It is the PR author's responsibility to fix merge conflicts, update changelog entries, and ensure CI passes. If a PR originates from an external contributor, a core team member assumes responsibility to perform this process instead of the original author. diff --git a/ROADMAP.md b/ROADMAP.md index 86bd7e25c528..cc59ca813fbf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -145,7 +145,7 @@ Issue: https://github.com/cosmos/iavl/issues/548 * Toolkit/SDK ADR. * Objective: - * Produce a RFC/ADR on how to make core composable + * Produce an RFC/ADR on how to make core composable * Merge RFC/ADR into main * Progress: * on pause until abci 2.0 integration is completed @@ -267,4 +267,4 @@ Issue: https://github.com/cosmos/iavl/issues/548 -This document will be updated at the end of the quarter on what was achieved and what was not. Shortly before the quarter concludes a new section will be added for the next quarter. We are working on updating the complete one year roadmap and will be posting it here as well. +This document will be updated at the end of the quarter on what was achieved and what was not. Shortly before the quarter concludes a new section will be added for the next quarter. We are working on updating the complete one-year roadmap and will be posting it here as well. diff --git a/docs/architecture/adr-008-dCERT-group.md b/docs/architecture/adr-008-dCERT-group.md index 13d2b340a667..509eb36234b4 100644 --- a/docs/architecture/adr-008-dCERT-group.md +++ b/docs/architecture/adr-008-dCERT-group.md @@ -101,7 +101,7 @@ mechanism. If those tokens are unbonded then the dCERT member must be automatically kicked from the group. Slashing of a particular dCERT member due to soft-contract breach should be -performed by governance on a per member basis based on the magnitude of the +performed by governance on a per-member basis based on the magnitude of the breach. The process flow is anticipated to be that a dCERT member is suspended by the dCERT group prior to being slashed by governance. diff --git a/docs/architecture/adr-033-protobuf-inter-module-comm.md b/docs/architecture/adr-033-protobuf-inter-module-comm.md index 4f2769e6770f..1929975c9a27 100644 --- a/docs/architecture/adr-033-protobuf-inter-module-comm.md +++ b/docs/architecture/adr-033-protobuf-inter-module-comm.md @@ -154,7 +154,7 @@ func (foo *FooMsgServer) Bar(ctx context.Context, req *MsgBarRequest) (*MsgBarRe } ``` -This design is also intended to be extensible to cover use cases of more fine grained permissioning like minting by +This design is also intended to be extensible to cover use cases of more fine-grained permissioning like minting by denom prefix being restricted to certain modules (as discussed in [#7459](https://github.com/cosmos/cosmos-sdk/pull/7459#discussion_r529545528)). diff --git a/docs/architecture/adr-049-state-sync-hooks.md b/docs/architecture/adr-049-state-sync-hooks.md index 50c551ea2b8d..5a896613cbb9 100644 --- a/docs/architecture/adr-049-state-sync-hooks.md +++ b/docs/architecture/adr-049-state-sync-hooks.md @@ -116,7 +116,7 @@ type ExtensionPayloadReader = func() ([]byte, error) type ExtensionPayloadWriter = func([]byte) error // ExtensionSnapshotter is an extension Snapshotter that is appended to the snapshot stream. -// ExtensionSnapshotter has an unique name and manages it's own internal formats. +// ExtensionSnapshotter has a unique name and manages it's own internal formats. type ExtensionSnapshotter interface { // SnapshotName returns the name of snapshotter, it should be unique in the manager. SnapshotName() string From 6a52694ef7b8cb3e04bb51687faac0b81e5036ac Mon Sep 17 00:00:00 2001 From: son trinh Date: Tue, 3 Dec 2024 16:45:15 +0700 Subject: [PATCH 5/5] refactor(tests/integration): Port distribution integration tests to server v2 (#22667) --- .../distribution/keeper/common_test.go | 36 -- tests/integration/distribution/module_test.go | 31 -- tests/integration/v2/app.go | 15 +- tests/integration/v2/auth/app_test.go | 3 + .../v2/distribution/common_test.go | 29 ++ .../v2/distribution/fixture_test.go | 160 +++++++ .../distribution}/grpc_query_test.go | 76 +-- .../v2/distribution/module_test.go | 15 + .../distribution}/msg_server_test.go | 442 ++++++------------ tests/integration/v2/services.go | 14 + testutil/configurator/configurator.go | 14 +- x/staking/testutil/helpers.go | 14 +- 12 files changed, 445 insertions(+), 404 deletions(-) delete mode 100644 tests/integration/distribution/keeper/common_test.go delete mode 100644 tests/integration/distribution/module_test.go create mode 100644 tests/integration/v2/distribution/common_test.go create mode 100644 tests/integration/v2/distribution/fixture_test.go rename tests/integration/{distribution/keeper => v2/distribution}/grpc_query_test.go (84%) create mode 100644 tests/integration/v2/distribution/module_test.go rename tests/integration/{distribution/keeper => v2/distribution}/msg_server_test.go (58%) diff --git a/tests/integration/distribution/keeper/common_test.go b/tests/integration/distribution/keeper/common_test.go deleted file mode 100644 index e298225b7470..000000000000 --- a/tests/integration/distribution/keeper/common_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package keeper_test - -import ( - "testing" - - "gotest.tools/v3/assert" - - "cosmossdk.io/math" - "cosmossdk.io/x/distribution/types" - stakingtestutil "cosmossdk.io/x/staking/testutil" - stakingtypes "cosmossdk.io/x/staking/types" - - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var ( - PKS = simtestutil.CreateTestPubKeys(3) - - valConsPk0 = PKS[0] -) - -func setupValidatorWithCommission(t *testing.T, f *fixture, valAddr sdk.ValAddress, initialStake int64) { - t.Helper() - initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) - assert.NilError(t, f.bankKeeper.MintCoins(f.sdkCtx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens)))) - assert.NilError(t, f.stakingKeeper.Params.Set(f.sdkCtx, stakingtypes.DefaultParams())) - - funds := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) - assert.NilError(t, f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, types.ModuleName, sdk.AccAddress(valAddr), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, funds)))) - f.accountKeeper.SetAccount(f.sdkCtx, f.accountKeeper.NewAccountWithAddress(f.sdkCtx, sdk.AccAddress(valAddr))) - - tstaking := stakingtestutil.NewHelper(t, f.sdkCtx, f.stakingKeeper) - tstaking.Commission = stakingtypes.NewCommissionRates(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) - tstaking.CreateValidator(valAddr, valConsPk0, math.NewInt(initialStake), true) -} diff --git a/tests/integration/distribution/module_test.go b/tests/integration/distribution/module_test.go deleted file mode 100644 index ce6e902c6b7c..000000000000 --- a/tests/integration/distribution/module_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package distribution_test - -import ( - "testing" - - "gotest.tools/v3/assert" - - "cosmossdk.io/depinject" - "cosmossdk.io/log" - "cosmossdk.io/x/distribution/types" - - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { - var accountKeeper authkeeper.AccountKeeper - - app, err := simtestutil.SetupAtGenesis( - depinject.Configs( - AppConfig, - depinject.Supply(log.NewNopLogger()), - ), - &accountKeeper) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false) - acc := accountKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.ModuleName)) - assert.Assert(t, acc != nil) -} diff --git a/tests/integration/v2/app.go b/tests/integration/v2/app.go index 0554f9b148d8..257fc3c700b5 100644 --- a/tests/integration/v2/app.go +++ b/tests/integration/v2/app.go @@ -17,6 +17,7 @@ import ( corebranch "cosmossdk.io/core/branch" "cosmossdk.io/core/comet" corecontext "cosmossdk.io/core/context" + "cosmossdk.io/core/header" "cosmossdk.io/core/server" corestore "cosmossdk.io/core/store" "cosmossdk.io/core/transaction" @@ -96,6 +97,8 @@ type StartupConfig struct { // RouterServiceBuilder defines the custom builder // for msg router and query router service to be used in the app. RouterServiceBuilder runtime.RouterServiceBuilder + // HeaderService defines the custom header service to be used in the app. + HeaderService header.Service } func DefaultStartUpConfig(t *testing.T) StartupConfig { @@ -125,6 +128,7 @@ func DefaultStartUpConfig(t *testing.T) StartupConfig { RouterServiceBuilder: runtime.NewRouterBuilder( stf.NewMsgRouterService, stf.NewQueryRouterService(), ), + HeaderService: services.NewGenesisHeaderService(stf.HeaderService{}), } } @@ -182,13 +186,13 @@ func NewApp( "minimum-gas-prices": "0stake", }, }, - services.NewGenesisHeaderService(stf.HeaderService{}), cometService, kvFactory, &eventService{}, storeBuilder, startupConfig.BranchService, startupConfig.RouterServiceBuilder, + startupConfig.HeaderService, ), depinject.Invoke( std.RegisterInterfaces, @@ -313,6 +317,10 @@ type App struct { txConfig client.TxConfig } +func (a App) LastBlockHeight() uint64 { + return a.lastHeight +} + // Deliver delivers a block with the given transactions and returns the resulting state. func (a *App) Deliver( t *testing.T, ctx context.Context, txs []stateMachineTx, @@ -327,6 +335,11 @@ func (a *App) Deliver( resp, state, err := a.DeliverBlock(ctx, req) require.NoError(t, err) a.lastHeight++ + // update block heigh if integeration context is present + iCtx, ok := ctx.Value(contextKey).(*integrationContext) + if ok { + iCtx.header.Height = int64(a.lastHeight) + } return resp, state } diff --git a/tests/integration/v2/auth/app_test.go b/tests/integration/v2/auth/app_test.go index 5c3c5a7e95cf..36326783216f 100644 --- a/tests/integration/v2/auth/app_test.go +++ b/tests/integration/v2/auth/app_test.go @@ -11,6 +11,8 @@ import ( "cosmossdk.io/depinject" "cosmossdk.io/log" "cosmossdk.io/runtime/v2" + "cosmossdk.io/runtime/v2/services" + "cosmossdk.io/server/v2/stf" "cosmossdk.io/x/accounts" basedepinject "cosmossdk.io/x/accounts/defaults/base/depinject" accountsv1 "cosmossdk.io/x/accounts/v1" @@ -79,6 +81,7 @@ func createTestSuite(t *testing.T) *suite { startupCfg.BranchService = &integration.BranchService{} startupCfg.RouterServiceBuilder = serviceBuilder + startupCfg.HeaderService = services.NewGenesisHeaderService(stf.HeaderService{}) res.app, err = integration.NewApp( depinject.Configs(configurator.NewAppV2Config(moduleConfigs...), depinject.Provide( diff --git a/tests/integration/v2/distribution/common_test.go b/tests/integration/v2/distribution/common_test.go new file mode 100644 index 000000000000..ff30842d9a6f --- /dev/null +++ b/tests/integration/v2/distribution/common_test.go @@ -0,0 +1,29 @@ +package distribution + +import ( + "testing" + + "gotest.tools/v3/assert" + + "cosmossdk.io/math" + "cosmossdk.io/x/distribution/types" + stakingtestutil "cosmossdk.io/x/staking/testutil" + stakingtypes "cosmossdk.io/x/staking/types" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func setupValidatorWithCommission(t *testing.T, f *fixture, valAddr sdk.ValAddress, initialStake int64) { + t.Helper() + initTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, int64(1000)) + assert.NilError(t, f.bankKeeper.MintCoins(f.ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens)))) + assert.NilError(t, f.stakingKeeper.Params.Set(f.ctx, stakingtypes.DefaultParams())) + + funds := f.stakingKeeper.TokensFromConsensusPower(f.ctx, int64(1000)) + assert.NilError(t, f.bankKeeper.SendCoinsFromModuleToAccount(f.ctx, types.ModuleName, sdk.AccAddress(valAddr), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, funds)))) + f.authKeeper.SetAccount(f.ctx, f.authKeeper.NewAccountWithAddress(f.ctx, sdk.AccAddress(valAddr))) + + tstaking := stakingtestutil.NewHelper(t, f.ctx, f.stakingKeeper) + tstaking.Commission = stakingtypes.NewCommissionRates(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) + tstaking.CreateValidator(valAddr, valConsPk0, math.NewInt(initialStake), true) +} diff --git a/tests/integration/v2/distribution/fixture_test.go b/tests/integration/v2/distribution/fixture_test.go new file mode 100644 index 000000000000..d2ea156b5b69 --- /dev/null +++ b/tests/integration/v2/distribution/fixture_test.go @@ -0,0 +1,160 @@ +package distribution + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + + "cosmossdk.io/core/comet" + corecontext "cosmossdk.io/core/context" + "cosmossdk.io/core/router" + "cosmossdk.io/core/transaction" + "cosmossdk.io/depinject" + "cosmossdk.io/log" + "cosmossdk.io/runtime/v2" + _ "cosmossdk.io/x/accounts" // import as blank for app wiring + _ "cosmossdk.io/x/bank" // import as blank for app wiring + bankkeeper "cosmossdk.io/x/bank/keeper" + banktypes "cosmossdk.io/x/bank/types" + _ "cosmossdk.io/x/consensus" // import as blank for app wiring + _ "cosmossdk.io/x/distribution" // import as blank for app wiring + distrkeeper "cosmossdk.io/x/distribution/keeper" + _ "cosmossdk.io/x/mint" // import as blank for app wiring + _ "cosmossdk.io/x/protocolpool" // import as blank for app wiring + poolkeeper "cosmossdk.io/x/protocolpool/keeper" + _ "cosmossdk.io/x/staking" // import as blank for app wiring + stakingkeeper "cosmossdk.io/x/staking/keeper" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/tests/integration/v2" + "github.com/cosmos/cosmos-sdk/testutil/configurator" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" + _ "github.com/cosmos/cosmos-sdk/x/auth" // import as blank for app wiring + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + _ "github.com/cosmos/cosmos-sdk/x/auth/tx/config" // import as blank for app wiring`` + _ "github.com/cosmos/cosmos-sdk/x/auth/vesting" // import as blank for app wiring + _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring +) + +var ( + emptyDelAddr sdk.AccAddress + emptyValAddr sdk.ValAddress +) + +var ( + PKS = simtestutil.CreateTestPubKeys(3) + + valConsPk0 = PKS[0] +) + +type fixture struct { + app *integration.App + + ctx context.Context + cdc codec.Codec + + queryClient distrkeeper.Querier + + authKeeper authkeeper.AccountKeeper + bankKeeper bankkeeper.Keeper + distrKeeper distrkeeper.Keeper + stakingKeeper *stakingkeeper.Keeper + poolKeeper poolkeeper.Keeper + + addr sdk.AccAddress + valAddr sdk.ValAddress +} + +func createTestFixture(t *testing.T) *fixture { + t.Helper() + res := fixture{} + + moduleConfigs := []configurator.ModuleOption{ + configurator.AccountsModule(), + configurator.AuthModule(), + configurator.BankModule(), + configurator.StakingModule(), + configurator.TxModule(), + configurator.ValidateModule(), + configurator.ConsensusModule(), + configurator.GenutilModule(), + configurator.DistributionModule(), + configurator.MintModule(), + configurator.ProtocolPoolModule(), + } + + var err error + startupCfg := integration.DefaultStartUpConfig(t) + + msgRouterService := integration.NewRouterService() + res.registerMsgRouterService(msgRouterService) + + var routerFactory runtime.RouterServiceFactory = func(_ []byte) router.Service { + return msgRouterService + } + + queryRouterService := integration.NewRouterService() + res.registerQueryRouterService(queryRouterService) + + serviceBuilder := runtime.NewRouterBuilder(routerFactory, queryRouterService) + + startupCfg.BranchService = &integration.BranchService{} + startupCfg.RouterServiceBuilder = serviceBuilder + startupCfg.HeaderService = &integration.HeaderService{} + + res.app, err = integration.NewApp( + depinject.Configs(configurator.NewAppV2Config(moduleConfigs...), depinject.Supply(log.NewNopLogger())), + startupCfg, + &res.bankKeeper, &res.distrKeeper, &res.authKeeper, &res.stakingKeeper, &res.poolKeeper, &res.cdc) + require.NoError(t, err) + + addr := sdk.AccAddress(PKS[0].Address()) + valAddr := sdk.ValAddress(addr) + valConsAddr := sdk.ConsAddress(valConsPk0.Address()) + + ctx := res.app.StateLatestContext(t) + res.addr = addr + res.valAddr = valAddr + + // set proposer and vote infos + res.ctx = context.WithValue(ctx, corecontext.CometInfoKey, comet.Info{ + LastCommit: comet.CommitInfo{ + Votes: []comet.VoteInfo{ + { + Validator: comet.Validator{ + Address: valAddr, + Power: 100, + }, + BlockIDFlag: comet.BlockIDFlagCommit, + }, + }, + }, + ProposerAddress: valConsAddr, + }) + + res.queryClient = distrkeeper.NewQuerier(res.distrKeeper) + + return &res +} + +func (s *fixture) registerMsgRouterService(router *integration.RouterService) { + // register custom router service + bankSendHandler := func(ctx context.Context, req transaction.Msg) (transaction.Msg, error) { + msg, ok := req.(*banktypes.MsgSend) + if !ok { + return nil, integration.ErrInvalidMsgType + } + msgServer := bankkeeper.NewMsgServerImpl(s.bankKeeper) + resp, err := msgServer.Send(ctx, msg) + return resp, err + } + + router.RegisterHandler(bankSendHandler, "cosmos.bank.v1beta1.MsgSend") +} + +func (s *fixture) registerQueryRouterService(router *integration.RouterService) { + // register custom router service + +} diff --git a/tests/integration/distribution/keeper/grpc_query_test.go b/tests/integration/v2/distribution/grpc_query_test.go similarity index 84% rename from tests/integration/distribution/keeper/grpc_query_test.go rename to tests/integration/v2/distribution/grpc_query_test.go index f83671fc4eac..eba52d317718 100644 --- a/tests/integration/distribution/keeper/grpc_query_test.go +++ b/tests/integration/v2/distribution/grpc_query_test.go @@ -1,4 +1,4 @@ -package keeper_test +package distribution import ( "fmt" @@ -17,9 +17,9 @@ import ( func TestGRPCParams(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) - assert.NilError(t, f.distrKeeper.Params.Set(f.sdkCtx, types.DefaultParams())) + assert.NilError(t, f.distrKeeper.Params.Set(f.ctx, types.DefaultParams())) var ( params types.Params @@ -49,7 +49,7 @@ func TestGRPCParams(t *testing.T) { WithdrawAddrEnabled: true, } - assert.NilError(t, f.distrKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.distrKeeper.Params.Set(f.ctx, params)) expParams = params }, msg: &types.QueryParamsRequest{}, @@ -60,7 +60,7 @@ func TestGRPCParams(t *testing.T) { t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { tc.malleate() - paramsRes, err := f.queryClient.Params(f.sdkCtx, tc.msg) + paramsRes, err := f.queryClient.Params(f.ctx, tc.msg) assert.NilError(t, err) assert.Assert(t, paramsRes != nil) assert.DeepEqual(t, paramsRes.Params, expParams) @@ -71,9 +71,9 @@ func TestGRPCParams(t *testing.T) { func TestGRPCValidatorOutstandingRewards(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) - assert.NilError(t, f.distrKeeper.Params.Set(f.sdkCtx, types.DefaultParams())) + assert.NilError(t, f.distrKeeper.Params.Set(f.ctx, types.DefaultParams())) setupValidatorWithCommission(t, f, f.valAddr, 10) // Setup a validator with commission valCommission := sdk.DecCoins{ @@ -82,10 +82,10 @@ func TestGRPCValidatorOutstandingRewards(t *testing.T) { } // set outstanding rewards - err := f.distrKeeper.ValidatorOutstandingRewards.Set(f.sdkCtx, f.valAddr, types.ValidatorOutstandingRewards{Rewards: valCommission}) + err := f.distrKeeper.ValidatorOutstandingRewards.Set(f.ctx, f.valAddr, types.ValidatorOutstandingRewards{Rewards: valCommission}) assert.NilError(t, err) - rewards, err := f.distrKeeper.ValidatorOutstandingRewards.Get(f.sdkCtx, f.valAddr) + rewards, err := f.distrKeeper.ValidatorOutstandingRewards.Get(f.ctx, f.valAddr) assert.NilError(t, err) testCases := []struct { @@ -116,7 +116,7 @@ func TestGRPCValidatorOutstandingRewards(t *testing.T) { for _, testCase := range testCases { tc := testCase t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { - validatorOutstandingRewards, err := f.queryClient.ValidatorOutstandingRewards(f.sdkCtx, tc.msg) + validatorOutstandingRewards, err := f.queryClient.ValidatorOutstandingRewards(f.ctx, tc.msg) if tc.expPass { assert.NilError(t, err) @@ -132,13 +132,13 @@ func TestGRPCValidatorOutstandingRewards(t *testing.T) { func TestGRPCValidatorCommission(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) - assert.NilError(t, f.distrKeeper.Params.Set(f.sdkCtx, types.DefaultParams())) // Set default distribution parameters - setupValidatorWithCommission(t, f, f.valAddr, 10) // Setup a validator with commission + assert.NilError(t, f.distrKeeper.Params.Set(f.ctx, types.DefaultParams())) // Set default distribution parameters + setupValidatorWithCommission(t, f, f.valAddr, 10) // Setup a validator with commission commission := sdk.DecCoins{sdk.DecCoin{Denom: "token1", Amount: math.LegacyNewDec(4)}, {Denom: "token2", Amount: math.LegacyNewDec(2)}} - assert.NilError(t, f.distrKeeper.ValidatorsAccumulatedCommission.Set(f.sdkCtx, f.valAddr, types.ValidatorAccumulatedCommission{Commission: commission})) + assert.NilError(t, f.distrKeeper.ValidatorsAccumulatedCommission.Set(f.ctx, f.valAddr, types.ValidatorAccumulatedCommission{Commission: commission})) testCases := []struct { name string @@ -168,7 +168,7 @@ func TestGRPCValidatorCommission(t *testing.T) { for _, testCase := range testCases { tc := testCase t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { - commissionRes, err := f.queryClient.ValidatorCommission(f.sdkCtx, tc.msg) + commissionRes, err := f.queryClient.ValidatorCommission(f.ctx, tc.msg) if tc.expPass { assert.NilError(t, err) @@ -184,7 +184,7 @@ func TestGRPCValidatorCommission(t *testing.T) { func TestGRPCValidatorSlashes(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) addr2 := sdk.AccAddress(PKS[1].Address()) valAddr2 := sdk.ValAddress(addr2) @@ -198,7 +198,7 @@ func TestGRPCValidatorSlashes(t *testing.T) { for i, slash := range slashes { err := f.distrKeeper.ValidatorSlashEvents.Set( - f.sdkCtx, + f.ctx, collections.Join3(f.valAddr, uint64(i+2), uint64(0)), slash, ) @@ -320,7 +320,7 @@ func TestGRPCValidatorSlashes(t *testing.T) { t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { tc.malleate() - slashesRes, err := f.queryClient.ValidatorSlashes(f.sdkCtx, req) + slashesRes, err := f.queryClient.ValidatorSlashes(f.ctx, req) if tc.expPass { assert.NilError(t, err) @@ -335,13 +335,13 @@ func TestGRPCValidatorSlashes(t *testing.T) { func TestGRPCDelegatorWithdrawAddress(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) - assert.NilError(t, f.distrKeeper.Params.Set(f.sdkCtx, types.DefaultParams())) + assert.NilError(t, f.distrKeeper.Params.Set(f.ctx, types.DefaultParams())) addr2 := sdk.AccAddress(PKS[1].Address()) - err := f.distrKeeper.SetWithdrawAddr(f.sdkCtx, f.addr, addr2) + err := f.distrKeeper.SetWithdrawAddr(f.ctx, f.addr, addr2) assert.Assert(t, err == nil) testCases := []struct { @@ -366,7 +366,7 @@ func TestGRPCDelegatorWithdrawAddress(t *testing.T) { for _, testCase := range testCases { tc := testCase t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { - withdrawAddress, err := f.queryClient.DelegatorWithdrawAddress(f.sdkCtx, tc.msg) + withdrawAddress, err := f.queryClient.DelegatorWithdrawAddress(f.ctx, tc.msg) if tc.expPass { assert.NilError(t, err) @@ -381,7 +381,7 @@ func TestGRPCDelegatorWithdrawAddress(t *testing.T) { func TestGRPCCommunityPool(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) var ( req *types.QueryCommunityPoolRequest //nolint:staticcheck // we're using a deprecated call @@ -403,10 +403,10 @@ func TestGRPCCommunityPool(t *testing.T) { name: "valid request", malleate: func() { amount := sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 100)) - assert.NilError(t, f.bankKeeper.MintCoins(f.sdkCtx, types.ModuleName, amount)) - assert.NilError(t, f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, types.ModuleName, f.addr, amount)) + assert.NilError(t, f.bankKeeper.MintCoins(f.ctx, types.ModuleName, amount)) + assert.NilError(t, f.bankKeeper.SendCoinsFromModuleToAccount(f.ctx, types.ModuleName, f.addr, amount)) - err := f.poolKeeper.FundCommunityPool(f.sdkCtx, amount, f.addr) + err := f.poolKeeper.FundCommunityPool(f.ctx, amount, f.addr) assert.Assert(t, err == nil) req = &types.QueryCommunityPoolRequest{} //nolint:staticcheck // we're using a deprecated call @@ -420,7 +420,7 @@ func TestGRPCCommunityPool(t *testing.T) { t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { testCase.malleate() - pool, err := f.queryClient.CommunityPool(f.sdkCtx, req) //nolint:staticcheck // we're using a deprecated call + pool, err := f.queryClient.CommunityPool(f.ctx, req) //nolint:staticcheck // we're using a deprecated call assert.NilError(t, err) assert.DeepEqual(t, expPool, pool) @@ -430,20 +430,20 @@ func TestGRPCCommunityPool(t *testing.T) { func TestGRPCDelegationRewards(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) - assert.NilError(t, f.distrKeeper.FeePool.Set(f.sdkCtx, types.FeePool{ + assert.NilError(t, f.distrKeeper.FeePool.Set(f.ctx, types.FeePool{ CommunityPool: sdk.NewDecCoins(sdk.DecCoin{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(1000)}), })) initialStake := int64(10) - assert.NilError(t, f.distrKeeper.Params.Set(f.sdkCtx, types.DefaultParams())) + assert.NilError(t, f.distrKeeper.Params.Set(f.ctx, types.DefaultParams())) setupValidatorWithCommission(t, f, f.valAddr, initialStake) // Setup a validator with commission - val, found := f.stakingKeeper.GetValidator(f.sdkCtx, f.valAddr) + val, found := f.stakingKeeper.GetValidator(f.ctx, f.valAddr) assert.Assert(t, found) // Set default staking params - assert.NilError(t, f.stakingKeeper.Params.Set(f.sdkCtx, stakingtypes.DefaultParams())) + assert.NilError(t, f.stakingKeeper.Params.Set(f.ctx, stakingtypes.DefaultParams())) addr2 := sdk.AccAddress(PKS[1].Address()) valAddr2 := sdk.ValAddress(addr2) @@ -453,19 +453,19 @@ func TestGRPCDelegationRewards(t *testing.T) { delTokens := sdk.TokensFromConsensusPower(2, sdk.DefaultPowerReduction) validator, issuedShares := val.AddTokensFromDel(delTokens) delegation := stakingtypes.NewDelegation(delAddr.String(), f.valAddr.String(), issuedShares) - assert.NilError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, delegation)) + assert.NilError(t, f.stakingKeeper.SetDelegation(f.ctx, delegation)) valBz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) assert.NilError(t, err) - assert.NilError(t, f.distrKeeper.DelegatorStartingInfo.Set(f.sdkCtx, collections.Join(sdk.ValAddress(valBz), delAddr), types.NewDelegatorStartingInfo(2, math.LegacyNewDec(initialStake), 20))) + assert.NilError(t, f.distrKeeper.DelegatorStartingInfo.Set(f.ctx, collections.Join(sdk.ValAddress(valBz), delAddr), types.NewDelegatorStartingInfo(2, math.LegacyNewDec(initialStake), 20))) // setup validator rewards decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyOneDec())} historicalRewards := types.NewValidatorHistoricalRewards(decCoins, 2) - assert.NilError(t, f.distrKeeper.ValidatorHistoricalRewards.Set(f.sdkCtx, collections.Join(sdk.ValAddress(valBz), uint64(2)), historicalRewards)) + assert.NilError(t, f.distrKeeper.ValidatorHistoricalRewards.Set(f.ctx, collections.Join(sdk.ValAddress(valBz), uint64(2)), historicalRewards)) // setup current rewards and outstanding rewards currentRewards := types.NewValidatorCurrentRewards(decCoins, 3) - assert.NilError(t, f.distrKeeper.ValidatorCurrentRewards.Set(f.sdkCtx, f.valAddr, currentRewards)) - assert.NilError(t, f.distrKeeper.ValidatorOutstandingRewards.Set(f.sdkCtx, f.valAddr, types.ValidatorOutstandingRewards{Rewards: decCoins})) + assert.NilError(t, f.distrKeeper.ValidatorCurrentRewards.Set(f.ctx, f.valAddr, currentRewards)) + assert.NilError(t, f.distrKeeper.ValidatorOutstandingRewards.Set(f.ctx, f.valAddr, types.ValidatorOutstandingRewards{Rewards: decCoins})) expRes := &types.QueryDelegationRewardsResponse{ Rewards: sdk.DecCoins{sdk.DecCoin{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initialStake / 10)}}, @@ -524,7 +524,7 @@ func TestGRPCDelegationRewards(t *testing.T) { for _, testCase := range testCases { tc := testCase t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { - rewards, err := f.queryClient.DelegationRewards(f.sdkCtx, tc.msg) + rewards, err := f.queryClient.DelegationRewards(f.ctx, tc.msg) if tc.expPass { assert.NilError(t, err) diff --git a/tests/integration/v2/distribution/module_test.go b/tests/integration/v2/distribution/module_test.go new file mode 100644 index 000000000000..bb297800b8e5 --- /dev/null +++ b/tests/integration/v2/distribution/module_test.go @@ -0,0 +1,15 @@ +package distribution + +import ( + "testing" + + "cosmossdk.io/x/distribution/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "gotest.tools/v3/assert" +) + +func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { + f := createTestFixture(t) + acc := f.authKeeper.GetAccount(f.ctx, authtypes.NewModuleAddress(types.ModuleName)) + assert.Assert(t, acc != nil) +} diff --git a/tests/integration/distribution/keeper/msg_server_test.go b/tests/integration/v2/distribution/msg_server_test.go similarity index 58% rename from tests/integration/distribution/keeper/msg_server_test.go rename to tests/integration/v2/distribution/msg_server_test.go index 3fc0d2d265d9..0af9a7063f49 100644 --- a/tests/integration/distribution/keeper/msg_server_test.go +++ b/tests/integration/v2/distribution/msg_server_test.go @@ -1,4 +1,4 @@ -package keeper_test +package distribution import ( "context" @@ -6,211 +6,32 @@ import ( "testing" "github.com/stretchr/testify/require" - "go.uber.org/mock/gomock" "gotest.tools/v3/assert" "cosmossdk.io/collections" - "cosmossdk.io/core/appmodule" "cosmossdk.io/core/comet" - "cosmossdk.io/log" + corecontext "cosmossdk.io/core/context" + "cosmossdk.io/core/transaction" "cosmossdk.io/math" - storetypes "cosmossdk.io/store/types" - "cosmossdk.io/x/bank" - bankkeeper "cosmossdk.io/x/bank/keeper" - banktypes "cosmossdk.io/x/bank/types" - "cosmossdk.io/x/consensus" - consensusparamkeeper "cosmossdk.io/x/consensus/keeper" - consensustypes "cosmossdk.io/x/consensus/types" - "cosmossdk.io/x/distribution" distrkeeper "cosmossdk.io/x/distribution/keeper" distrtypes "cosmossdk.io/x/distribution/types" - "cosmossdk.io/x/protocolpool" - poolkeeper "cosmossdk.io/x/protocolpool/keeper" pooltypes "cosmossdk.io/x/protocolpool/types" - "cosmossdk.io/x/staking" - stakingkeeper "cosmossdk.io/x/staking/keeper" stakingtestutil "cosmossdk.io/x/staking/testutil" stakingtypes "cosmossdk.io/x/staking/types" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - addresscodec "github.com/cosmos/cosmos-sdk/codec/address" - codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil/integration" + "github.com/cosmos/cosmos-sdk/tests/integration/v2" sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/auth" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" - authtestutil "github.com/cosmos/cosmos-sdk/x/auth/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) -var ( - emptyDelAddr sdk.AccAddress - emptyValAddr sdk.ValAddress -) - -type fixture struct { - app *integration.App - - sdkCtx sdk.Context - cdc codec.Codec - keys map[string]*storetypes.KVStoreKey - - queryClient distrtypes.QueryClient - - accountKeeper authkeeper.AccountKeeper - bankKeeper bankkeeper.Keeper - distrKeeper distrkeeper.Keeper - stakingKeeper *stakingkeeper.Keeper - poolKeeper poolkeeper.Keeper - - addr sdk.AccAddress - valAddr sdk.ValAddress -} - -func initFixture(t *testing.T) *fixture { - t.Helper() - keys := storetypes.NewKVStoreKeys( - authtypes.StoreKey, banktypes.StoreKey, distrtypes.StoreKey, pooltypes.StoreKey, stakingtypes.StoreKey, - consensustypes.StoreKey, - ) - encodingCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, auth.AppModule{}, bank.AppModule{}) - cdc := encodingCfg.Codec - - logger := log.NewTestLogger(t) - authority := authtypes.NewModuleAddress("gov") - - maccPerms := map[string][]string{ - pooltypes.ModuleName: {}, - pooltypes.StreamAccount: {}, - pooltypes.ProtocolPoolDistrAccount: {}, - distrtypes.ModuleName: {authtypes.Minter}, - stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, - stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, - } - - // gomock initializations - ctrl := gomock.NewController(t) - acctsModKeeper := authtestutil.NewMockAccountsModKeeper(ctrl) - accNum := uint64(0) - acctsModKeeper.EXPECT().NextAccountNumber(gomock.Any()).AnyTimes().DoAndReturn(func(ctx context.Context) (uint64, error) { - currentNum := accNum - accNum++ - return currentNum, nil - }) - - accountKeeper := authkeeper.NewAccountKeeper( - runtime.NewEnvironment(runtime.NewKVStoreService(keys[authtypes.StoreKey]), log.NewNopLogger()), - cdc, - authtypes.ProtoBaseAccount, - acctsModKeeper, - maccPerms, - addresscodec.NewBech32Codec(sdk.Bech32MainPrefix), - sdk.Bech32MainPrefix, - authority.String(), - ) - - blockedAddresses := map[string]bool{ - accountKeeper.GetAuthority(): false, - } - bankKeeper := bankkeeper.NewBaseKeeper( - runtime.NewEnvironment(runtime.NewKVStoreService(keys[banktypes.StoreKey]), log.NewNopLogger()), - cdc, - accountKeeper, - blockedAddresses, - authority.String(), - ) - - msgRouter := baseapp.NewMsgServiceRouter() - grpcRouter := baseapp.NewGRPCQueryRouter() - cometService := runtime.NewContextAwareCometInfoService() - - consensusParamsKeeper := consensusparamkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[consensustypes.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(grpcRouter), runtime.EnvWithMsgRouterService(msgRouter)), authtypes.NewModuleAddress("gov").String()) - stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(grpcRouter), runtime.EnvWithMsgRouterService(msgRouter)), accountKeeper, bankKeeper, consensusParamsKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), cometService) - - poolKeeper := poolkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[pooltypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String()) - - distrKeeper := distrkeeper.NewKeeper( - cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[distrtypes.StoreKey]), logger), accountKeeper, bankKeeper, stakingKeeper, cometService, distrtypes.ModuleName, authority.String(), - ) - - authModule := auth.NewAppModule(cdc, accountKeeper, acctsModKeeper, authsims.RandomGenesisAccounts, nil) - bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) - stakingModule := staking.NewAppModule(cdc, stakingKeeper) - distrModule := distribution.NewAppModule(cdc, distrKeeper, stakingKeeper) - poolModule := protocolpool.NewAppModule(cdc, poolKeeper, accountKeeper, bankKeeper) - consensusModule := consensus.NewAppModule(cdc, consensusParamsKeeper) - - addr := sdk.AccAddress(PKS[0].Address()) - valAddr := sdk.ValAddress(addr) - valConsAddr := sdk.ConsAddress(valConsPk0.Address()) - - integrationApp := integration.NewIntegrationApp(logger, keys, cdc, - encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), - encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), - map[string]appmodule.AppModule{ - authtypes.ModuleName: authModule, - banktypes.ModuleName: bankModule, - stakingtypes.ModuleName: stakingModule, - distrtypes.ModuleName: distrModule, - pooltypes.ModuleName: poolModule, - consensustypes.ModuleName: consensusModule, - }, - msgRouter, - grpcRouter, - ) - - // set proposer and vote infos - sdkCtx := sdk.UnwrapSDKContext(integrationApp.Context()).WithProposer(valConsAddr).WithCometInfo(comet.Info{ - LastCommit: comet.CommitInfo{ - Votes: []comet.VoteInfo{ - { - Validator: comet.Validator{ - Address: valAddr, - Power: 100, - }, - BlockIDFlag: comet.BlockIDFlagCommit, - }, - }, - }, - ProposerAddress: valConsAddr, - }) - - // Register MsgServer and QueryServer - distrtypes.RegisterMsgServer(integrationApp.MsgServiceRouter(), distrkeeper.NewMsgServerImpl(distrKeeper)) - distrtypes.RegisterQueryServer(integrationApp.QueryHelper(), distrkeeper.NewQuerier(distrKeeper)) - - qr := integrationApp.QueryHelper() - distrQueryClient := distrtypes.NewQueryClient(qr) - - return &fixture{ - app: integrationApp, - sdkCtx: sdkCtx, - cdc: cdc, - keys: keys, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - distrKeeper: distrKeeper, - stakingKeeper: stakingKeeper, - poolKeeper: poolKeeper, - addr: addr, - valAddr: valAddr, - queryClient: distrQueryClient, - } -} - func TestMsgWithdrawDelegatorReward(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) - err := f.distrKeeper.FeePool.Set(f.sdkCtx, distrtypes.FeePool{ + err := f.distrKeeper.FeePool.Set(f.ctx, distrtypes.FeePool{ CommunityPool: sdk.NewDecCoins(sdk.DecCoin{Denom: "stake", Amount: math.LegacyNewDec(10000)}), }) require.NoError(t, err) - require.NoError(t, f.distrKeeper.Params.Set(f.sdkCtx, distrtypes.DefaultParams())) + require.NoError(t, f.distrKeeper.Params.Set(f.ctx, distrtypes.DefaultParams())) delAddr := sdk.AccAddress(PKS[1].Address()) @@ -227,17 +48,17 @@ func TestMsgWithdrawDelegatorReward(t *testing.T) { assert.NilError(t, err) validator.DelegatorShares = math.LegacyNewDec(100) validator.Tokens = math.NewInt(1000000) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validator)) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validator)) // set module account coins - initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) - err = f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + initTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, int64(1000)) + err = f.bankKeeper.MintCoins(f.ctx, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) require.NoError(t, err) // send funds to val addr - err = f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, distrtypes.ModuleName, sdk.AccAddress(f.valAddr), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + err = f.bankKeeper.SendCoinsFromModuleToAccount(f.ctx, distrtypes.ModuleName, sdk.AccAddress(f.valAddr), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) require.NoError(t, err) - initBalance := f.bankKeeper.GetAllBalances(f.sdkCtx, delAddr) + initBalance := f.bankKeeper.GetAllBalances(f.ctx, delAddr) // setup delegation delTokens := sdk.TokensFromConsensusPower(2, sdk.DefaultPowerReduction) @@ -245,18 +66,18 @@ func TestMsgWithdrawDelegatorReward(t *testing.T) { valBz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) require.NoError(t, err) delegation := stakingtypes.NewDelegation(delAddr.String(), validator.GetOperator(), issuedShares) - require.NoError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, delegation)) - require.NoError(t, f.distrKeeper.DelegatorStartingInfo.Set(f.sdkCtx, collections.Join(sdk.ValAddress(valBz), delAddr), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 20))) + require.NoError(t, f.stakingKeeper.SetDelegation(f.ctx, delegation)) + require.NoError(t, f.distrKeeper.DelegatorStartingInfo.Set(f.ctx, collections.Join(sdk.ValAddress(valBz), delAddr), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 20))) // setup validator rewards decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyOneDec())} historicalRewards := distrtypes.NewValidatorHistoricalRewards(decCoins, 2) - err = f.distrKeeper.ValidatorHistoricalRewards.Set(f.sdkCtx, collections.Join(sdk.ValAddress(valBz), uint64(2)), historicalRewards) + err = f.distrKeeper.ValidatorHistoricalRewards.Set(f.ctx, collections.Join(sdk.ValAddress(valBz), uint64(2)), historicalRewards) require.NoError(t, err) // setup current rewards and outstanding rewards currentRewards := distrtypes.NewValidatorCurrentRewards(decCoins, 3) - err = f.distrKeeper.ValidatorCurrentRewards.Set(f.sdkCtx, f.valAddr, currentRewards) + err = f.distrKeeper.ValidatorCurrentRewards.Set(f.ctx, f.valAddr, currentRewards) require.NoError(t, err) - err = f.distrKeeper.ValidatorOutstandingRewards.Set(f.sdkCtx, f.valAddr, distrtypes.ValidatorOutstandingRewards{Rewards: valCommission}) + err = f.distrKeeper.ValidatorOutstandingRewards.Set(f.ctx, f.valAddr, distrtypes.ValidatorOutstandingRewards{Rewards: valCommission}) require.NoError(t, err) testCases := []struct { @@ -320,12 +141,17 @@ func TestMsgWithdrawDelegatorReward(t *testing.T) { }, } height := f.app.LastBlockHeight() + msgServer := distrkeeper.NewMsgServerImpl(f.distrKeeper) for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { res, err := f.app.RunMsg( - tc.msg, - integration.WithAutomaticFinalizeBlock(), + t, + f.ctx, + func(ctx context.Context) (transaction.Msg, error) { + resp, e := msgServer.WithdrawDelegatorReward(ctx, tc.msg) + return resp, e + }, integration.WithAutomaticCommit(), ) @@ -341,17 +167,17 @@ func TestMsgWithdrawDelegatorReward(t *testing.T) { assert.Assert(t, res != nil) // check the result - result := distrtypes.MsgWithdrawDelegatorRewardResponse{} - err := f.cdc.Unmarshal(res.Value, &result) - assert.NilError(t, err) + _, ok := res.(*distrtypes.MsgWithdrawDelegatorRewardResponse) + assert.Assert(t, ok, true) // check current balance is greater than initial balance - curBalance := f.bankKeeper.GetAllBalances(f.sdkCtx, sdk.AccAddress(f.valAddr)) + curBalance := f.bankKeeper.GetAllBalances(f.ctx, sdk.AccAddress(f.valAddr)) assert.Assert(t, initBalance.IsAllLTE(curBalance)) } var previousTotalPower int64 - for _, vote := range f.sdkCtx.CometInfo().LastCommit.Votes { + cometInfo := f.ctx.Value(corecontext.CometInfoKey).(comet.Info) + for _, vote := range cometInfo.LastCommit.Votes { previousTotalPower += vote.Validator.Power } assert.Equal(t, previousTotalPower, int64(100)) @@ -361,9 +187,9 @@ func TestMsgWithdrawDelegatorReward(t *testing.T) { func TestMsgSetWithdrawAddress(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) - require.NoError(t, f.distrKeeper.Params.Set(f.sdkCtx, distrtypes.DefaultParams())) + require.NoError(t, f.distrKeeper.Params.Set(f.ctx, distrtypes.DefaultParams())) delAddr := sdk.AccAddress(PKS[0].Address()) withdrawAddr := sdk.AccAddress(PKS[1].Address()) @@ -378,9 +204,9 @@ func TestMsgSetWithdrawAddress(t *testing.T) { { name: "empty delegator address", preRun: func() { - params, _ := f.distrKeeper.Params.Get(f.sdkCtx) + params, _ := f.distrKeeper.Params.Get(f.ctx) params.WithdrawAddrEnabled = true - assert.NilError(t, f.distrKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.distrKeeper.Params.Set(f.ctx, params)) }, msg: &distrtypes.MsgSetWithdrawAddress{ DelegatorAddress: emptyDelAddr.String(), @@ -392,9 +218,9 @@ func TestMsgSetWithdrawAddress(t *testing.T) { { name: "empty withdraw address", preRun: func() { - params, _ := f.distrKeeper.Params.Get(f.sdkCtx) + params, _ := f.distrKeeper.Params.Get(f.ctx) params.WithdrawAddrEnabled = true - assert.NilError(t, f.distrKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.distrKeeper.Params.Set(f.ctx, params)) }, msg: &distrtypes.MsgSetWithdrawAddress{ DelegatorAddress: delAddr.String(), @@ -406,9 +232,9 @@ func TestMsgSetWithdrawAddress(t *testing.T) { { name: "both empty addresses", preRun: func() { - params, _ := f.distrKeeper.Params.Get(f.sdkCtx) + params, _ := f.distrKeeper.Params.Get(f.ctx) params.WithdrawAddrEnabled = true - assert.NilError(t, f.distrKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.distrKeeper.Params.Set(f.ctx, params)) }, msg: &distrtypes.MsgSetWithdrawAddress{ DelegatorAddress: emptyDelAddr.String(), @@ -420,9 +246,9 @@ func TestMsgSetWithdrawAddress(t *testing.T) { { name: "withdraw address disabled", preRun: func() { - params, _ := f.distrKeeper.Params.Get(f.sdkCtx) + params, _ := f.distrKeeper.Params.Get(f.ctx) params.WithdrawAddrEnabled = false - assert.NilError(t, f.distrKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.distrKeeper.Params.Set(f.ctx, params)) }, msg: &distrtypes.MsgSetWithdrawAddress{ DelegatorAddress: delAddr.String(), @@ -434,9 +260,9 @@ func TestMsgSetWithdrawAddress(t *testing.T) { { name: "valid msg with same delegator and withdraw address", preRun: func() { - params, _ := f.distrKeeper.Params.Get(f.sdkCtx) + params, _ := f.distrKeeper.Params.Get(f.ctx) params.WithdrawAddrEnabled = true - assert.NilError(t, f.distrKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.distrKeeper.Params.Set(f.ctx, params)) }, msg: &distrtypes.MsgSetWithdrawAddress{ DelegatorAddress: delAddr.String(), @@ -447,9 +273,9 @@ func TestMsgSetWithdrawAddress(t *testing.T) { { name: "valid msg", preRun: func() { - params, _ := f.distrKeeper.Params.Get(f.sdkCtx) + params, _ := f.distrKeeper.Params.Get(f.ctx) params.WithdrawAddrEnabled = true - assert.NilError(t, f.distrKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.distrKeeper.Params.Set(f.ctx, params)) }, msg: &distrtypes.MsgSetWithdrawAddress{ DelegatorAddress: delAddr.String(), @@ -458,31 +284,37 @@ func TestMsgSetWithdrawAddress(t *testing.T) { expErr: false, }, } + + msgServer := distrkeeper.NewMsgServerImpl(f.distrKeeper) + for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { tc.preRun() res, err := f.app.RunMsg( - tc.msg, - integration.WithAutomaticFinalizeBlock(), + t, + f.ctx, + func(ctx context.Context) (transaction.Msg, error) { + resp, e := msgServer.SetWithdrawAddress(ctx, tc.msg) + return resp, e + }, integration.WithAutomaticCommit(), ) if tc.expErr { assert.ErrorContains(t, err, tc.expErrMsg) // query the delegator withdraw address - addr, _ := f.distrKeeper.GetDelegatorWithdrawAddr(f.sdkCtx, delAddr) + addr, _ := f.distrKeeper.GetDelegatorWithdrawAddr(f.ctx, delAddr) assert.DeepEqual(t, addr, delAddr) } else { assert.NilError(t, err) assert.Assert(t, res != nil) // check the result - result := distrtypes.MsgSetWithdrawAddressResponse{} - err = f.cdc.Unmarshal(res.Value, &result) - assert.NilError(t, err) + _, ok := res.(*distrtypes.MsgSetWithdrawAddressResponse) + assert.Assert(t, ok, true) // query the delegator withdraw address - addr, _ := f.distrKeeper.GetDelegatorWithdrawAddr(f.sdkCtx, delAddr) + addr, _ := f.distrKeeper.GetDelegatorWithdrawAddr(f.ctx, delAddr) assert.DeepEqual(t, addr.String(), tc.msg.WithdrawAddress) } }) @@ -491,7 +323,7 @@ func TestMsgSetWithdrawAddress(t *testing.T) { func TestMsgWithdrawValidatorCommission(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) valCommission := sdk.DecCoins{ sdk.NewDecCoinFromDec("mytoken", math.LegacyNewDec(5).Quo(math.LegacyNewDec(4))), @@ -499,28 +331,28 @@ func TestMsgWithdrawValidatorCommission(t *testing.T) { } // set module account coins - initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) - err := f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + initTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, int64(1000)) + err := f.bankKeeper.MintCoins(f.ctx, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) require.NoError(t, err) // send funds to val addr - err = f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, distrtypes.ModuleName, sdk.AccAddress(f.valAddr), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + err = f.bankKeeper.SendCoinsFromModuleToAccount(f.ctx, distrtypes.ModuleName, sdk.AccAddress(f.valAddr), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) require.NoError(t, err) coins := sdk.NewCoins(sdk.NewCoin("mytoken", math.NewInt(2)), sdk.NewCoin("stake", math.NewInt(2))) - err = f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, coins) + err = f.bankKeeper.MintCoins(f.ctx, distrtypes.ModuleName, coins) require.NoError(t, err) // check initial balance - balance := f.bankKeeper.GetAllBalances(f.sdkCtx, sdk.AccAddress(f.valAddr)) - expTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 1000) + balance := f.bankKeeper.GetAllBalances(f.ctx, sdk.AccAddress(f.valAddr)) + expTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1000) expCoins := sdk.NewCoins(sdk.NewCoin("stake", expTokens)) assert.DeepEqual(t, expCoins, balance) // set outstanding rewards - err = f.distrKeeper.ValidatorOutstandingRewards.Set(f.sdkCtx, f.valAddr, distrtypes.ValidatorOutstandingRewards{Rewards: valCommission}) + err = f.distrKeeper.ValidatorOutstandingRewards.Set(f.ctx, f.valAddr, distrtypes.ValidatorOutstandingRewards{Rewards: valCommission}) require.NoError(t, err) // set commission - err = f.distrKeeper.ValidatorsAccumulatedCommission.Set(f.sdkCtx, f.valAddr, distrtypes.ValidatorAccumulatedCommission{Commission: valCommission}) + err = f.distrKeeper.ValidatorsAccumulatedCommission.Set(f.ctx, f.valAddr, distrtypes.ValidatorAccumulatedCommission{Commission: valCommission}) require.NoError(t, err) testCases := []struct { @@ -554,11 +386,17 @@ func TestMsgWithdrawValidatorCommission(t *testing.T) { }, } + msgServer := distrkeeper.NewMsgServerImpl(f.distrKeeper) + for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { res, err := f.app.RunMsg( - tc.msg, - integration.WithAutomaticFinalizeBlock(), + t, + f.ctx, + func(ctx context.Context) (transaction.Msg, error) { + resp, e := msgServer.WithdrawValidatorCommission(ctx, tc.msg) + return resp, e + }, integration.WithAutomaticCommit(), ) if tc.expErr { @@ -568,19 +406,18 @@ func TestMsgWithdrawValidatorCommission(t *testing.T) { assert.Assert(t, res != nil) // check the result - result := distrtypes.MsgWithdrawValidatorCommissionResponse{} - err = f.cdc.Unmarshal(res.Value, &result) - assert.NilError(t, err) + _, ok := res.(*distrtypes.MsgWithdrawValidatorCommissionResponse) + assert.Assert(t, ok, true) // check balance increase - balance = f.bankKeeper.GetAllBalances(f.sdkCtx, sdk.AccAddress(f.valAddr)) + balance = f.bankKeeper.GetAllBalances(f.ctx, sdk.AccAddress(f.valAddr)) assert.DeepEqual(t, sdk.NewCoins( sdk.NewCoin("mytoken", math.NewInt(1)), sdk.NewCoin("stake", expTokens.AddRaw(1)), ), balance) // check remainder - remainder, err := f.distrKeeper.ValidatorsAccumulatedCommission.Get(f.sdkCtx, f.valAddr) + remainder, err := f.distrKeeper.ValidatorsAccumulatedCommission.Get(f.ctx, f.valAddr) require.NoError(t, err) assert.DeepEqual(t, sdk.DecCoins{ sdk.NewDecCoinFromDec("mytoken", math.LegacyNewDec(1).Quo(math.LegacyNewDec(4))), @@ -593,21 +430,21 @@ func TestMsgWithdrawValidatorCommission(t *testing.T) { func TestMsgFundCommunityPool(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) addr := sdk.AccAddress(PKS[0].Address()) addr2 := sdk.AccAddress(PKS[1].Address()) amount := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - poolAcc := f.accountKeeper.GetModuleAccount(f.sdkCtx, pooltypes.ModuleName) + poolAcc := f.authKeeper.GetModuleAccount(f.ctx, pooltypes.ModuleName) // check that the pool account balance is empty - assert.Assert(t, f.bankKeeper.GetAllBalances(f.sdkCtx, poolAcc.GetAddress()).Empty()) + assert.Assert(t, f.bankKeeper.GetAllBalances(f.ctx, poolAcc.GetAddress()).Empty()) // fund the account by minting and sending amount from distribution module to addr - err := f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, amount) + err := f.bankKeeper.MintCoins(f.ctx, distrtypes.ModuleName, amount) assert.NilError(t, err) - err = f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, distrtypes.ModuleName, addr, amount) + err = f.bankKeeper.SendCoinsFromModuleToAccount(f.ctx, distrtypes.ModuleName, addr, amount) assert.NilError(t, err) testCases := []struct { @@ -652,11 +489,18 @@ func TestMsgFundCommunityPool(t *testing.T) { expErr: false, }, } + + msgServer := distrkeeper.NewMsgServerImpl(f.distrKeeper) + for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { res, err := f.app.RunMsg( - tc.msg, - integration.WithAutomaticFinalizeBlock(), + t, + f.ctx, + func(ctx context.Context) (transaction.Msg, error) { + res, err := msgServer.FundCommunityPool(ctx, tc.msg) //nolint:staticcheck // we're using a deprecated call + return res, err + }, integration.WithAutomaticCommit(), ) if tc.expErr { @@ -666,15 +510,14 @@ func TestMsgFundCommunityPool(t *testing.T) { assert.Assert(t, res != nil) // check the result - result := distrtypes.MsgFundCommunityPool{} //nolint:staticcheck // we're using a deprecated call - err = f.cdc.Unmarshal(res.Value, &result) - assert.NilError(t, err) + _, ok := res.(*distrtypes.MsgFundCommunityPoolResponse) //nolint:staticcheck // we're using a deprecated call + assert.Assert(t, ok, true) // query the community pool funds - poolBal := f.bankKeeper.GetAllBalances(f.sdkCtx, poolAcc.GetAddress()) + poolBal := f.bankKeeper.GetAllBalances(f.ctx, poolAcc.GetAddress()) assert.Assert(t, poolBal.Equal(amount)) - assert.Assert(t, f.bankKeeper.GetAllBalances(f.sdkCtx, addr).Empty()) + assert.Assert(t, f.bankKeeper.GetAllBalances(f.ctx, addr).Empty()) } }) } @@ -682,7 +525,7 @@ func TestMsgFundCommunityPool(t *testing.T) { func TestMsgUpdateParams(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) // default params communityTax := math.LegacyNewDecWithPrec(2, 2) // 2% @@ -793,11 +636,17 @@ func TestMsgUpdateParams(t *testing.T) { }, } + msgServer := distrkeeper.NewMsgServerImpl(f.distrKeeper) + for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { res, err := f.app.RunMsg( - tc.msg, - integration.WithAutomaticFinalizeBlock(), + t, + f.ctx, + func(ctx context.Context) (transaction.Msg, error) { + resp, e := msgServer.UpdateParams(ctx, tc.msg) + return resp, e + }, integration.WithAutomaticCommit(), ) if tc.expErr { @@ -807,12 +656,11 @@ func TestMsgUpdateParams(t *testing.T) { assert.Assert(t, res != nil) // check the result - result := distrtypes.MsgUpdateParams{} - err = f.cdc.Unmarshal(res.Value, &result) - assert.NilError(t, err) + _, ok := res.(*distrtypes.MsgUpdateParamsResponse) + assert.Assert(t, ok, true) // query the params and verify it has been updated - params, _ := f.distrKeeper.Params.Get(f.sdkCtx) + params, _ := f.distrKeeper.Params.Get(f.ctx) assert.DeepEqual(t, distrtypes.DefaultParams(), params) } }) @@ -821,20 +669,20 @@ func TestMsgUpdateParams(t *testing.T) { func TestMsgCommunityPoolSpend(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) - initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(100)) - err := f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + initTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, int64(100)) + err := f.bankKeeper.MintCoins(f.ctx, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) require.NoError(t, err) // fund pool module account amount := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - poolAcc := f.accountKeeper.GetModuleAccount(f.sdkCtx, pooltypes.ModuleName) - err = f.bankKeeper.SendCoinsFromModuleToModule(f.sdkCtx, distrtypes.ModuleName, poolAcc.GetName(), amount) + poolAcc := f.authKeeper.GetModuleAccount(f.ctx, pooltypes.ModuleName) + err = f.bankKeeper.SendCoinsFromModuleToModule(f.ctx, distrtypes.ModuleName, poolAcc.GetName(), amount) require.NoError(t, err) // query the community pool to verify it has been updated with balance - poolBal := f.bankKeeper.GetAllBalances(f.sdkCtx, poolAcc.GetAddress()) + poolBal := f.bankKeeper.GetAllBalances(f.ctx, poolAcc.GetAddress()) assert.Assert(t, poolBal.Equal(amount)) recipient := sdk.AccAddress([]byte("addr1")) @@ -875,11 +723,18 @@ func TestMsgCommunityPoolSpend(t *testing.T) { expErr: false, }, } + + msgServer := distrkeeper.NewMsgServerImpl(f.distrKeeper) + for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { res, err := f.app.RunMsg( - tc.msg, - integration.WithAutomaticFinalizeBlock(), + t, + f.ctx, + func(ctx context.Context) (transaction.Msg, error) { + res, e := msgServer.CommunityPoolSpend(ctx, tc.msg) //nolint:staticcheck // we're using a deprecated call + return res, e + }, integration.WithAutomaticCommit(), ) if tc.expErr { @@ -889,12 +744,11 @@ func TestMsgCommunityPoolSpend(t *testing.T) { assert.Assert(t, res != nil) // check the result - result := distrtypes.MsgCommunityPoolSpend{} //nolint:staticcheck // we're using a deprecated call - err = f.cdc.Unmarshal(res.Value, &result) - assert.NilError(t, err) + _, ok := res.(*distrtypes.MsgCommunityPoolSpendResponse) //nolint:staticcheck // we're using a deprecated call + assert.Assert(t, ok, true) // query the community pool to verify it has been updated - poolBal := f.bankKeeper.GetAllBalances(f.sdkCtx, poolAcc.GetAddress()) + poolBal := f.bankKeeper.GetAllBalances(f.ctx, poolAcc.GetAddress()) assert.Assert(t, poolBal.Empty()) } @@ -904,41 +758,42 @@ func TestMsgCommunityPoolSpend(t *testing.T) { func TestMsgDepositValidatorRewardsPool(t *testing.T) { t.Parallel() - f := initFixture(t) + f := createTestFixture(t) - require.NoError(t, f.distrKeeper.Params.Set(f.sdkCtx, distrtypes.DefaultParams())) - err := f.distrKeeper.FeePool.Set(f.sdkCtx, distrtypes.FeePool{ + require.NoError(t, f.distrKeeper.Params.Set(f.ctx, distrtypes.DefaultParams())) + err := f.distrKeeper.FeePool.Set(f.ctx, distrtypes.FeePool{ CommunityPool: sdk.NewDecCoins(sdk.DecCoin{Denom: "stake", Amount: math.LegacyNewDec(100)}), }) require.NoError(t, err) - initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(10000)) - require.NoError(t, f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens)))) + initTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, int64(10000)) + require.NoError(t, f.bankKeeper.MintCoins(f.ctx, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens)))) // Set default staking params - require.NoError(t, f.stakingKeeper.Params.Set(f.sdkCtx, stakingtypes.DefaultParams())) + require.NoError(t, f.stakingKeeper.Params.Set(f.ctx, stakingtypes.DefaultParams())) addr := sdk.AccAddress("addr") addr1 := sdk.AccAddress(PKS[0].Address()) valAddr1 := sdk.ValAddress(addr1) // send funds to val addr - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) - err = f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, distrtypes.ModuleName, sdk.AccAddress(valAddr1), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, tokens))) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, int64(1000)) + err = f.bankKeeper.SendCoinsFromModuleToAccount(f.ctx, distrtypes.ModuleName, sdk.AccAddress(valAddr1), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, tokens))) require.NoError(t, err) // send funds from module to addr to perform DepositValidatorRewardsPool - err = f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, distrtypes.ModuleName, addr, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, tokens))) - f.accountKeeper.SetAccount(f.sdkCtx, f.accountKeeper.NewAccountWithAddress(f.sdkCtx, sdk.AccAddress(valAddr1))) + err = f.bankKeeper.SendCoinsFromModuleToAccount(f.ctx, distrtypes.ModuleName, addr, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, tokens))) + f.authKeeper.SetAccount(f.ctx, f.authKeeper.NewAccountWithAddress(f.ctx, sdk.AccAddress(valAddr1))) require.NoError(t, err) - tstaking := stakingtestutil.NewHelper(t, f.sdkCtx, f.stakingKeeper) + + tstaking := stakingtestutil.NewHelper(t, f.ctx, f.stakingKeeper) tstaking.Commission = stakingtypes.NewCommissionRates(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) tstaking.CreateValidator(valAddr1, valConsPk0, math.NewInt(100), true) // mint a non-staking token and send to an account amt := sdk.NewCoins(sdk.NewInt64Coin("foo", 500)) - require.NoError(t, f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, amt)) - require.NoError(t, f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, distrtypes.ModuleName, addr, amt)) + require.NoError(t, f.bankKeeper.MintCoins(f.ctx, distrtypes.ModuleName, amt)) + require.NoError(t, f.bankKeeper.SendCoinsFromModuleToAccount(f.ctx, distrtypes.ModuleName, addr, amt)) - bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) + bondDenom, err := f.stakingKeeper.BondDenom(f.ctx) require.NoError(t, err) testCases := []struct { @@ -975,11 +830,17 @@ func TestMsgDepositValidatorRewardsPool(t *testing.T) { }, } + msgServer := distrkeeper.NewMsgServerImpl(f.distrKeeper) + for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { res, err := f.app.RunMsg( - tc.msg, - integration.WithAutomaticFinalizeBlock(), + t, + f.ctx, + func(ctx context.Context) (transaction.Msg, error) { + resp, e := msgServer.DepositValidatorRewardsPool(ctx, tc.msg) + return resp, e + }, integration.WithAutomaticCommit(), ) if tc.expErr { @@ -989,15 +850,14 @@ func TestMsgDepositValidatorRewardsPool(t *testing.T) { assert.Assert(t, res != nil) // check the result - result := distrtypes.MsgDepositValidatorRewardsPoolResponse{} - err = f.cdc.Unmarshal(res.Value, &result) - assert.NilError(t, err) + _, ok := res.(*distrtypes.MsgDepositValidatorRewardsPoolResponse) + assert.Assert(t, ok, true) val, err := sdk.ValAddressFromBech32(tc.msg.ValidatorAddress) assert.NilError(t, err) // check validator outstanding rewards - outstandingRewards, err := f.distrKeeper.ValidatorOutstandingRewards.Get(f.sdkCtx, val) + outstandingRewards, err := f.distrKeeper.ValidatorOutstandingRewards.Get(f.ctx, val) assert.NilError(t, err) for _, c := range tc.msg.Amount { x := outstandingRewards.Rewards.AmountOf(c.Denom) diff --git a/tests/integration/v2/services.go b/tests/integration/v2/services.go index 8cffbc0445ee..0773ecca3900 100644 --- a/tests/integration/v2/services.go +++ b/tests/integration/v2/services.go @@ -11,6 +11,7 @@ import ( "cosmossdk.io/core/comet" "cosmossdk.io/core/event" "cosmossdk.io/core/gas" + "cosmossdk.io/core/header" "cosmossdk.io/core/router" "cosmossdk.io/core/server" corestore "cosmossdk.io/core/store" @@ -69,6 +70,7 @@ var contextKey = contextKeyType{} type integrationContext struct { state corestore.WriterMap gasMeter gas.Meter + header header.Info } func GasMeterFromContext(ctx context.Context) gas.Meter { @@ -196,3 +198,15 @@ func (rs RouterService) Invoke(ctx context.Context, req transaction.Msg) (transa } return rs.handlers[typeUrl](ctx, req) } + +var _ header.Service = &HeaderService{} + +type HeaderService struct{} + +func (h *HeaderService) HeaderInfo(ctx context.Context) header.Info { + iCtx, ok := ctx.Value(contextKey).(*integrationContext) + if !ok { + return header.Info{} + } + return iCtx.header +} diff --git a/testutil/configurator/configurator.go b/testutil/configurator/configurator.go index 98b248cb361b..82399afa10bd 100644 --- a/testutil/configurator/configurator.go +++ b/testutil/configurator/configurator.go @@ -163,7 +163,7 @@ func AuthModule() ModuleOption { Bech32Prefix: "cosmos", ModuleAccountPermissions: []*authmodulev1.ModuleAccountPermission{ {Account: "fee_collector"}, - {Account: testutil.DistributionModuleName}, + {Account: testutil.DistributionModuleName, Permissions: []string{"minter"}}, {Account: testutil.MintModuleName, Permissions: []string{"minter"}}, {Account: "bonded_tokens_pool", Permissions: []string{"burner", testutil.StakingModuleName}}, {Account: "not_bonded_tokens_pool", Permissions: []string{"burner", testutil.StakingModuleName}}, @@ -178,6 +178,18 @@ func AuthModule() ModuleOption { } } +func AuthModuleWithMaccPerms(maccPerms []*authmodulev1.ModuleAccountPermission) ModuleOption { + return func(config *Config) { + config.ModuleConfigs[testutil.AuthModuleName] = &appv1alpha1.ModuleConfig{ + Name: testutil.AuthModuleName, + Config: appconfig.WrapAny(&authmodulev1.Module{ + Bech32Prefix: "cosmos", + ModuleAccountPermissions: maccPerms, + }), + } + } +} + func ParamsModule() ModuleOption { return func(config *Config) { config.ModuleConfigs[testutil.ParamsModuleName] = &appv1alpha1.ModuleConfig{ diff --git a/x/staking/testutil/helpers.go b/x/staking/testutil/helpers.go index 8976c6a684b5..65a95158d482 100644 --- a/x/staking/testutil/helpers.go +++ b/x/staking/testutil/helpers.go @@ -23,14 +23,14 @@ type Helper struct { msgSrvr stakingtypes.MsgServer k *keeper.Keeper - Ctx sdk.Context + Ctx context.Context Commission stakingtypes.CommissionRates // Coin Denomination Denom string } // NewHelper creates a new instance of Helper. -func NewHelper(t *testing.T, ctx sdk.Context, k *keeper.Keeper) *Helper { +func NewHelper(t *testing.T, ctx context.Context, k *keeper.Keeper) *Helper { t.Helper() return &Helper{t, keeper.NewMsgServerImpl(k), k, ctx, ZeroCommission(), sdk.DefaultBondDenom} } @@ -126,19 +126,21 @@ func (sh *Helper) CheckValidator(addr sdk.ValAddress, status stakingtypes.BondSt // TurnBlock calls EndBlocker and updates the block time func (sh *Helper) TurnBlock(newTime time.Time) sdk.Context { - sh.Ctx = sh.Ctx.WithHeaderInfo(header.Info{Time: newTime}) + sdkCtx := sdk.UnwrapSDKContext(sh.Ctx) + sh.Ctx = sdkCtx.WithHeaderInfo(header.Info{Time: newTime}) _, err := sh.k.EndBlocker(sh.Ctx) require.NoError(sh.t, err) - return sh.Ctx + return sdkCtx } // TurnBlockTimeDiff calls EndBlocker and updates the block time by adding the // duration to the current block time func (sh *Helper) TurnBlockTimeDiff(diff time.Duration) sdk.Context { - sh.Ctx = sh.Ctx.WithHeaderInfo(header.Info{Time: sh.Ctx.HeaderInfo().Time.Add(diff)}) + sdkCtx := sdk.UnwrapSDKContext(sh.Ctx) + sh.Ctx = sdkCtx.WithHeaderInfo(header.Info{Time: sdkCtx.HeaderInfo().Time.Add(diff)}) _, err := sh.k.EndBlocker(sh.Ctx) require.NoError(sh.t, err) - return sh.Ctx + return sdkCtx } // ZeroCommission constructs a commission rates with all zeros.