diff --git a/.github/.codespellignore b/.github/.codespellignore index 301cd418a1b00..e1e8758d0c306 100644 --- a/.github/.codespellignore +++ b/.github/.codespellignore @@ -3,4 +3,5 @@ pullrequest keypair pastTime hasTables -Nam \ No newline at end of file +Nam +EyT \ No newline at end of file diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 7c4a08af1730f..7af739bbcf302 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -106,6 +106,24 @@ updates: labels: - "A:automerge" - dependencies + - package-ecosystem: gomod + directory: "/indexer/postgres" + schedule: + interval: weekly + day: wednesday + time: "01:53" + labels: + - "A:automerge" + - dependencies + - package-ecosystem: gomod + directory: "/indexer/postgres/tests" + schedule: + interval: weekly + day: wednesday + time: "01:53" + labels: + - "A:automerge" + - dependencies - package-ecosystem: gomod directory: "/schema" schedule: diff --git a/.github/pr_labeler.yml b/.github/pr_labeler.yml index b935cf3195593..328bf07902ff8 100644 --- a/.github/pr_labeler.yml +++ b/.github/pr_labeler.yml @@ -24,6 +24,8 @@ - orm/**/* "C:schema": - schema/**/* +"C:indexer/postgres": + - indexer/postgres/**/* "C:x/accounts": - x/accounts/**/* "C:x/accounts/multisig": @@ -72,6 +74,16 @@ - x/upgrade/**/* "C:x/epochs": - x/epochs/**/* +"C:server/v2": + - server/v2/**/* +"C:server/v2 stf": + - server/v2/stf/**/* +"C:server/v2 appmanager": + - server/v2/appmanager/**/* +"C:server/v2 cometbft": + - server/v2/cometbft/**/* +"C:server/v2 api": + - server/v2/api/**/* "Type: ADR": - docs/architecture/**/* "Type: Build": diff --git a/.github/workflows/misspell.yml b/.github/workflows/misspell.yml index f524e88b2cb87..e4cff28364c19 100644 --- a/.github/workflows/misspell.yml +++ b/.github/workflows/misspell.yml @@ -15,7 +15,7 @@ jobs: continue-on-error: true run: | sudo apt-get install codespell -y - codespell -w --skip="*.pulsar.go,*.pb.go,*.pb.gw.go,*.cosmos_orm.go,*.json,*.git,*.js,crypto/keys,fuzz,*.h,proto/tendermint,*.bin" --ignore-words=.github/.codespellignore + codespell -w --skip="*.pulsar.go,*.pb.go,*.pb.gw.go,*.cosmos_orm.go,*.json,*.git,*.js,crypto/keys,fuzz,*.h,proto/tendermint,*.bin,go.sum,go.mod" --ignore-words=.github/.codespellignore - uses: peter-evans/create-pull-request@v6 if: github.event_name != 'pull_request' with: diff --git a/.github/workflows/proto.yml b/.github/workflows/proto.yml index 998b9ac993b11..3302e6edc82db 100644 --- a/.github/workflows/proto.yml +++ b/.github/workflows/proto.yml @@ -15,7 +15,7 @@ jobs: timeout-minutes: 5 steps: - uses: actions/checkout@v4 - - uses: bufbuild/buf-setup-action@v1.34.0 + - uses: bufbuild/buf-setup-action@v1.35.0 - uses: bufbuild/buf-lint-action@v1 with: input: "proto" @@ -24,7 +24,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: bufbuild/buf-setup-action@v1.34.0 + - uses: bufbuild/buf-setup-action@v1.35.0 - uses: bufbuild/buf-breaking-action@v1 with: input: "proto" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 9515c80f7b46f..6eea986e27b7d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -487,6 +487,42 @@ jobs: with: projectBaseDir: schema/ + test-indexer-postgres: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: "1.22" + cache: true + cache-dependency-path: indexer/postgres/tests/go.sum + - uses: technote-space/get-diff-action@v6.1.2 + id: git_diff + with: + PATTERNS: | + indexer/postgres/**/*.go + indexer/postgres/go.mod + indexer/postgres/go.sum + indexer/postgres/tests/go.mod + indexer/postgres/tests/go.sum + - name: tests + if: env.GIT_DIFF + run: | + cd indexer/postgres + go test -mod=readonly -timeout 30m -coverprofile=cov.out -covermode=atomic ./... + cd tests + go test -mod=readonly -timeout 30m -coverprofile=cov.out -covermode=atomic -coverpkg=cosmossdk.io/indexer/postgres ./... + cd .. + go run github.com/dylandreimerink/gocovmerge/cmd/gocovmerge@latest cov.out tests/cov.out > coverage.out + - name: sonarcloud + if: ${{ env.GIT_DIFF && !github.event.pull_request.draft && env.SONAR_TOKEN != null }} + uses: SonarSource/sonarcloud-github-action@master + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + with: + projectBaseDir: indexer/postgres/ + test-simapp: runs-on: ubuntu-latest steps: diff --git a/.github/workflows/v2-test.yml b/.github/workflows/v2-test.yml index 2cced36e47f35..7433a47a133e9 100644 --- a/.github/workflows/v2-test.yml +++ b/.github/workflows/v2-test.yml @@ -14,6 +14,30 @@ concurrency: cancel-in-progress: true jobs: + server-v2: + runs-on: ubuntu-latest + strategy: + fail-fast: false + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: "1.22" + check-latest: true + cache: true + cache-dependency-path: go.sum + - uses: technote-space/get-diff-action@v6.1.2 + id: git_diff + with: + PATTERNS: | + server/v2/*.go + server/v2/go.mod + server/v2/go.sum + server/v2/testdata/*.toml + - name: test & coverage report creation + if: env.GIT_DIFF + run: | + cd server/v2 && go test -mod=readonly -race -timeout 30m -covermode=atomic -tags='ledger test_ledger_mock' stf: runs-on: ubuntu-latest strategy: diff --git a/CHANGELOG.md b/CHANGELOG.md index 7288975cebf43..be30e89daadc0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -102,6 +102,7 @@ Every module contains its own CHANGELOG.md. Please refer to the module you are i * (baseapp) [#20208](https://github.com/cosmos/cosmos-sdk/pull/20208) Skip running validateBasic for rechecking txs. * (baseapp) [#20380](https://github.com/cosmos/cosmos-sdk/pull/20380) Enhanced OfferSnapshot documentation. * (client) [#20771](https://github.com/cosmos/cosmos-sdk/pull/20771) Remove `ReadDefaultValuesFromDefaultClientConfig` from `client` package. (It was introduced in `v0.50.6` as a quick fix). +* (grpcserver) [#20945](https://github.com/cosmos/cosmos-sdk/pull/20945) Adds error handling for out-of-gas panics in grpc query handlers. ### Bug Fixes @@ -115,9 +116,14 @@ Every module contains its own CHANGELOG.md. Please refer to the module you are i * [#19833](https://github.com/cosmos/cosmos-sdk/pull/19833) Fix some places in which we call Remove inside a Walk. * [#19851](https://github.com/cosmos/cosmos-sdk/pull/19851) Fix some places in which we call Remove inside a Walk (x/staking and x/gov). * [#20939](https://github.com/cosmos/cosmos-sdk/pull/20939) Fix collection reverse iterator to include `pagination.key` in the result. +* (client/grpc) [#20969](https://github.com/cosmos/cosmos-sdk/pull/20969) Fix `node.NewQueryServer` method not setting `cfg`. +* (testutil/integration) [#21006](https://github.com/cosmos/cosmos-sdk/pull/21006) Fix `NewIntegrationApp` method not writing default genesis to state ### API Breaking Changes +* (client) [#20976](https://github.com/cosmos/cosmos-sdk/pull/20976) Simplified command initialization by removing unnecessary parameters such as `txConfig` and `addressCodec`. + * Remove parameter `txConfig` from `genutilcli.Commands`,`genutilcli.CommandsWithCustomMigrationMap`,`genutilcli.GenTxCmd`. + * Remove parameter `addressCodec` from `genutilcli.GenTxCmd`,`genutilcli.AddGenesisAccountCmd`,`stakingcli.BuildCreateValidatorMsg`. * (x/genutil) [#20740](https://github.com/cosmos/cosmos-sdk/pull/20740) Update `genutilcli.Commands` and `genutilcli.CommandsWithCustomMigrationMap` to take the genesis module and abstract the module manager. * (server) [#20422](https://github.com/cosmos/cosmos-sdk/pull/20422) Deprecated `ServerContext`. To get `cmtcfg.Config` from cmd, use `client.GetCometConfigFromCmd(cmd)` instead of `server.GetServerContextFromCmd(cmd).Config` * (types)[#20369](https://github.com/cosmos/cosmos-sdk/pull/20369) The signature of `HasAminoCodec` has changed to accept a `core/legacy.Amino` interface instead of `codec.LegacyAmino`. diff --git a/Makefile b/Makefile index bf814eb5f5c77..2e760653bfc98 100644 --- a/Makefile +++ b/Makefile @@ -8,6 +8,8 @@ include scripts/build/testing.mk include scripts/build/documentation.mk include scripts/build/build.mk +.DEFAULT_GOAL := help + ############################################################################### ### Tools & Dependencies ### ############################################################################### diff --git a/UPGRADING.md b/UPGRADING.md index 887fb2a1e454e..5f96b53ed5351 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -170,7 +170,9 @@ There is no longer a need for the Cosmos SDK to host these protos for itself and That package containing proto v2 generated code, but the SDK now uses [buf generated go SDK instead](https://buf.build/docs/bsr/generated-sdks/go). If you were depending on `cosmossdk.io/api/tendermint`, please use the buf generated go SDK instead, or ask CometBFT host the generated proto v2 code. -The `codectypes.Any` has moved to `github.com/cosmos/gogoproto/types/any`. Module developers can update the `buf.gen.gogo.yaml` configuration files by adjusting the corresponding `opt` option to `Mgoogle/protobuf/any.proto=github.com/cosmos/gogoproto/types/any` for directly mapping the`Any` type to its new location. This change is optional as `codectypes.Any` is aliased to `gogoproto.Any` in the SDK. +The `codectypes.Any` has moved to `github.com/cosmos/gogoproto/types/any`. Module developers need to update the `buf.gen.gogo.yaml` configuration files by adjusting the corresponding `opt` option to `Mgoogle/protobuf/any.proto=github.com/cosmos/gogoproto/types/any` for directly mapping the`Any` type to its new location. This change is optional, but recommended, as `codectypes.Any` is aliased to `gogoproto.Any` in the SDK. + +Also, any usages of the interfaces `AnyUnpacker` and `UnpackInterfacesMessage` must be replaced with the interfaces of the same name in the `github.com/cosmos/gogoproto/types/any` package. ### Modules diff --git a/api/cosmos/base/node/v1beta1/query.pulsar.go b/api/cosmos/base/node/v1beta1/query.pulsar.go index f79e565e180b4..ae4e619147474 100644 --- a/api/cosmos/base/node/v1beta1/query.pulsar.go +++ b/api/cosmos/base/node/v1beta1/query.pulsar.go @@ -2086,7 +2086,7 @@ func (x *ConfigResponse) GetHaltHeight() uint64 { return 0 } -// StateRequest defines the request structure for the status of a node. +// StatusRequest defines the request structure for the status of a node. type StatusRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2113,7 +2113,7 @@ func (*StatusRequest) Descriptor() ([]byte, []int) { return file_cosmos_base_node_v1beta1_query_proto_rawDescGZIP(), []int{2} } -// StateResponse defines the response structure for the status of a node. +// StatusResponse defines the response structure for the status of a node. type StatusResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/api/cosmos/circuit/v1/query.pulsar.go b/api/cosmos/circuit/v1/query.pulsar.go index 20e472137296e..77fa017581890 100644 --- a/api/cosmos/circuit/v1/query.pulsar.go +++ b/api/cosmos/circuit/v1/query.pulsar.go @@ -2881,7 +2881,7 @@ func (x *AccountsResponse) GetPagination() *v1beta1.PageResponse { return nil } -// QueryDisableListRequest is the request type for the Query/DisabledList RPC method. +// QueryDisabledListRequest is the request type for the Query/DisabledList RPC method. type QueryDisabledListRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/api/cosmos/circuit/v1/query_grpc.pb.go b/api/cosmos/circuit/v1/query_grpc.pb.go index 6218b68d8bd19..06712054ae7ea 100644 --- a/api/cosmos/circuit/v1/query_grpc.pb.go +++ b/api/cosmos/circuit/v1/query_grpc.pb.go @@ -30,7 +30,7 @@ const ( type QueryClient interface { // Account returns account permissions. Account(ctx context.Context, in *QueryAccountRequest, opts ...grpc.CallOption) (*AccountResponse, error) - // Account returns account permissions. + // Accounts returns multiple accounts permissions. Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*AccountsResponse, error) // DisabledList returns a list of disabled message urls DisabledList(ctx context.Context, in *QueryDisabledListRequest, opts ...grpc.CallOption) (*DisabledListResponse, error) @@ -77,7 +77,7 @@ func (c *queryClient) DisabledList(ctx context.Context, in *QueryDisabledListReq type QueryServer interface { // Account returns account permissions. Account(context.Context, *QueryAccountRequest) (*AccountResponse, error) - // Account returns account permissions. + // Accounts returns multiple accounts permissions. Accounts(context.Context, *QueryAccountsRequest) (*AccountsResponse, error) // DisabledList returns a list of disabled message urls DisabledList(context.Context, *QueryDisabledListRequest) (*DisabledListResponse, error) diff --git a/api/cosmos/nft/v1beta1/query.pulsar.go b/api/cosmos/nft/v1beta1/query.pulsar.go index 156e61668db01..7c3cb4c065efd 100644 --- a/api/cosmos/nft/v1beta1/query.pulsar.go +++ b/api/cosmos/nft/v1beta1/query.pulsar.go @@ -11432,7 +11432,7 @@ func (x *QuerySupplyByQueryStringResponse) GetAmount() uint64 { return 0 } -// QueryNFTstRequest is the request type for the Query/NFTs RPC method +// QueryNFTsRequest is the request type for the Query/NFTs RPC method type QueryNFTsRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/api/cosmos/nft/v1beta1/query_grpc.pb.go b/api/cosmos/nft/v1beta1/query_grpc.pb.go index d25acc384af22..1f69c3c9643e9 100644 --- a/api/cosmos/nft/v1beta1/query_grpc.pb.go +++ b/api/cosmos/nft/v1beta1/query_grpc.pb.go @@ -39,7 +39,7 @@ const ( type QueryClient interface { // Balance queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 Balance(ctx context.Context, in *QueryBalanceRequest, opts ...grpc.CallOption) (*QueryBalanceResponse, error) - // BalancebyQueryString queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 + // BalanceByQueryString queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 BalanceByQueryString(ctx context.Context, in *QueryBalanceByQueryStringRequest, opts ...grpc.CallOption) (*QueryBalanceByQueryStringResponse, error) // Owner queries the owner of the NFT based on its class and id, same as ownerOf in ERC721 Owner(ctx context.Context, in *QueryOwnerRequest, opts ...grpc.CallOption) (*QueryOwnerResponse, error) @@ -186,7 +186,7 @@ func (c *queryClient) Classes(ctx context.Context, in *QueryClassesRequest, opts type QueryServer interface { // Balance queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 Balance(context.Context, *QueryBalanceRequest) (*QueryBalanceResponse, error) - // BalancebyQueryString queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 + // BalanceByQueryString queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 BalanceByQueryString(context.Context, *QueryBalanceByQueryStringRequest) (*QueryBalanceByQueryStringResponse, error) // Owner queries the owner of the NFT based on its class and id, same as ownerOf in ERC721 Owner(context.Context, *QueryOwnerRequest) (*QueryOwnerResponse, error) diff --git a/baseapp/abci_utils.go b/baseapp/abci_utils.go index 3372bf9e39d81..6da80906fab58 100644 --- a/baseapp/abci_utils.go +++ b/baseapp/abci_utils.go @@ -177,7 +177,7 @@ func validateExtendedCommitAgainstLastCommit(ec abci.ExtendedCommitInfo, lc come } return -int(vote1.Validator.Power - vote2.Validator.Power) // vp sorted in descending order }) { - return fmt.Errorf("extended commit votes are not sorted by voting power") + return errors.New("extended commit votes are not sorted by voting power") } addressCache := make(map[string]struct{}, len(ec.Votes)) diff --git a/baseapp/expected_keepers.go b/baseapp/expected_keepers.go deleted file mode 100644 index 26147f935ec92..0000000000000 --- a/baseapp/expected_keepers.go +++ /dev/null @@ -1,17 +0,0 @@ -package baseapp - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type BankKeeper interface { - MintCoins(ctx context.Context, moduleName string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - GetBalance(ctx context.Context, addr sdk.AccAddress, denom string) sdk.Coin -} - -type AuthKeeper interface { - GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI -} diff --git a/baseapp/grpcserver.go b/baseapp/grpcserver.go index b1befabe9e861..c162bebf1ee31 100644 --- a/baseapp/grpcserver.go +++ b/baseapp/grpcserver.go @@ -14,6 +14,7 @@ import ( "google.golang.org/grpc/status" errorsmod "cosmossdk.io/errors" + storetypes "cosmossdk.io/store/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -67,6 +68,18 @@ func (app *BaseApp) RegisterGRPCServer(server gogogrpc.Server) { app.logger.Debug("gRPC query received of type: " + fmt.Sprintf("%#v", req)) + // Catch an OutOfGasPanic caused in the query handlers + defer func() { + if r := recover(); r != nil { + switch rType := r.(type) { + case storetypes.ErrorOutOfGas: + err = errorsmod.Wrapf(sdkerrors.ErrOutOfGas, "Query gas limit exceeded: %v, out of gas in location: %v", sdkCtx.GasMeter().Limit(), rType.Descriptor) + default: + panic(r) + } + } + }() + return handler(grpcCtx, req) } diff --git a/baseapp/oe/optimistic_execution_test.go b/baseapp/oe/optimistic_execution_test.go index 726e971e4d84d..4afb16aaa795a 100644 --- a/baseapp/oe/optimistic_execution_test.go +++ b/baseapp/oe/optimistic_execution_test.go @@ -8,7 +8,7 @@ import ( abci "github.com/cometbft/cometbft/api/cometbft/abci/v1" "github.com/stretchr/testify/assert" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" ) func testFinalizeBlock(_ context.Context, _ *abci.FinalizeBlockRequest) (*abci.FinalizeBlockResponse, error) { @@ -16,7 +16,7 @@ func testFinalizeBlock(_ context.Context, _ *abci.FinalizeBlockRequest) (*abci.F } func TestOptimisticExecution(t *testing.T) { - oe := NewOptimisticExecution(log.NewNopLogger(), testFinalizeBlock) + oe := NewOptimisticExecution(coretesting.NewNopLogger(), testFinalizeBlock) assert.True(t, oe.Enabled()) oe.Execute(&abci.ProcessProposalRequest{ Hash: []byte("test"), diff --git a/client/config/config.go b/client/config/config.go index d850b04dc39b8..246ed98c7b9a4 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -2,6 +2,7 @@ package config import ( "crypto/tls" + "errors" "fmt" "os" "path/filepath" @@ -68,7 +69,7 @@ func CreateClientConfig(ctx client.Context, customClientTemplate string, customC } if (customClientTemplate != "" && customConfig == nil) || (customClientTemplate == "" && customConfig != nil) { - return ctx, fmt.Errorf("customClientTemplate and customConfig should be both nil or not nil") + return ctx, errors.New("customClientTemplate and customConfig should be both nil or not nil") } if customClientTemplate != "" { diff --git a/client/docs/swagger-ui/swagger.yaml b/client/docs/swagger-ui/swagger.yaml index f949019cfdd8f..c4352f47aec59 100644 --- a/client/docs/swagger-ui/swagger.yaml +++ b/client/docs/swagger-ui/swagger.yaml @@ -29831,7 +29831,7 @@ paths: /cosmos/nft/v1beta1/balance: get: summary: >- - BalancebyQueryString queries the number of NFTs of a given class owned + BalanceByQueryString queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 operationId: BalanceByQueryString responses: diff --git a/client/grpc/cmtservice/service.go b/client/grpc/cmtservice/service.go index ad307984c0e58..05eeeb6ecc432 100644 --- a/client/grpc/cmtservice/service.go +++ b/client/grpc/cmtservice/service.go @@ -5,6 +5,7 @@ import ( abci "github.com/cometbft/cometbft/api/cometbft/abci/v1" gogogrpc "github.com/cosmos/gogoproto/grpc" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -20,8 +21,8 @@ import ( ) var ( - _ ServiceServer = queryServer{} - _ codectypes.UnpackInterfacesMessage = &GetLatestValidatorSetResponse{} + _ ServiceServer = queryServer{} + _ gogoprotoany.UnpackInterfacesMessage = &GetLatestValidatorSetResponse{} ) type ( @@ -112,7 +113,7 @@ func (s queryServer) GetLatestValidatorSet(ctx context.Context, req *GetLatestVa return ValidatorsOutput(ctx, s.clientCtx, nil, page, limit) } -func (m *GetLatestValidatorSetResponse) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (m *GetLatestValidatorSetResponse) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var pubKey cryptotypes.PubKey for _, val := range m.Validators { err := unpacker.UnpackAny(val.PubKey, &pubKey) diff --git a/client/grpc/node/query.pb.go b/client/grpc/node/query.pb.go index a2c96dc1ec2fb..4fa49a40070e5 100644 --- a/client/grpc/node/query.pb.go +++ b/client/grpc/node/query.pb.go @@ -139,7 +139,7 @@ func (m *ConfigResponse) GetHaltHeight() uint64 { return 0 } -// StateRequest defines the request structure for the status of a node. +// StatusRequest defines the request structure for the status of a node. type StatusRequest struct { } @@ -176,7 +176,7 @@ func (m *StatusRequest) XXX_DiscardUnknown() { var xxx_messageInfo_StatusRequest proto.InternalMessageInfo -// StateResponse defines the response structure for the status of a node. +// StatusResponse defines the response structure for the status of a node. type StatusResponse struct { EarliestStoreHeight uint64 `protobuf:"varint,1,opt,name=earliest_store_height,json=earliestStoreHeight,proto3" json:"earliest_store_height,omitempty"` Height uint64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` diff --git a/client/grpc/node/service.go b/client/grpc/node/service.go index 5c9bb960025ef..f9fc13ea35df5 100644 --- a/client/grpc/node/service.go +++ b/client/grpc/node/service.go @@ -32,6 +32,7 @@ type queryServer struct { func NewQueryServer(clientCtx client.Context, cfg config.Config) ServiceServer { return queryServer{ clientCtx: clientCtx, + cfg: cfg, } } diff --git a/client/grpc/node/service_test.go b/client/grpc/node/service_test.go index 41ce2a2cc50cc..fc9ddbb5101e0 100644 --- a/client/grpc/node/service_test.go +++ b/client/grpc/node/service_test.go @@ -12,6 +12,9 @@ import ( func TestServiceServer_Config(t *testing.T) { defaultCfg := config.DefaultConfig() + defaultCfg.PruningKeepRecent = "2000" + defaultCfg.PruningInterval = "10" + defaultCfg.HaltHeight = 100 svr := NewQueryServer(client.Context{}, *defaultCfg) ctx := sdk.Context{}.WithMinGasPrices(sdk.NewDecCoins(sdk.NewInt64DecCoin("stake", 15))) @@ -19,5 +22,7 @@ func TestServiceServer_Config(t *testing.T) { require.NoError(t, err) require.NotNil(t, resp) require.Equal(t, ctx.MinGasPrices().String(), resp.MinimumGasPrice) + require.Equal(t, defaultCfg.PruningKeepRecent, resp.PruningKeepRecent) + require.Equal(t, defaultCfg.PruningInterval, resp.PruningInterval) require.Equal(t, defaultCfg.HaltHeight, resp.HaltHeight) } diff --git a/client/keys/output_test.go b/client/keys/output_test.go index c88f93b8752af..b56a30c7a083c 100644 --- a/client/keys/output_test.go +++ b/client/keys/output_test.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" addresscodec "github.com/cosmos/cosmos-sdk/codec/address" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -15,6 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" ) func generatePubKeys(n int) []types.PubKey { @@ -100,3 +102,24 @@ func TestProtoMarshalJSON(t *testing.T) { require.Equal(ko.Address, expectedOutput) require.Equal(ko.PubKey, string(bz)) } + +func TestNestedMultisigOutput(t *testing.T) { + cdc := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}).Codec + + sk := secp256k1.PrivKey{Key: []byte{154, 49, 3, 117, 55, 232, 249, 20, 205, 216, 102, 7, 136, 72, 177, 2, 131, 202, 234, 81, 31, 208, 46, 244, 179, 192, 167, 163, 142, 117, 246, 13}} + tmpKey := sk.PubKey() + multisigPk := kmultisig.NewLegacyAminoPubKey(1, []types.PubKey{tmpKey}) + multisigPk2 := kmultisig.NewLegacyAminoPubKey(1, []types.PubKey{tmpKey, multisigPk}) + + kb, err := keyring.New(t.Name(), keyring.BackendTest, t.TempDir(), nil, cdc) + require.NoError(t, err) + + _, err = kb.SaveMultisig("multisig", multisigPk2) + require.NoError(t, err) + + k, err := kb.Key("multisig") + require.NoError(t, err) + + _, err = MkAccKeyOutput(k, addresscodec.NewBech32Codec("cosmos")) + require.NoError(t, err) +} diff --git a/client/prompt_validation.go b/client/prompt_validation.go index 288a1c95ef72b..9d3af0d58f678 100644 --- a/client/prompt_validation.go +++ b/client/prompt_validation.go @@ -1,6 +1,7 @@ package client import ( + "errors" "fmt" "net/url" "unicode" @@ -11,7 +12,7 @@ import ( // ValidatePromptNotEmpty validates that the input is not empty. func ValidatePromptNotEmpty(input string) error { if input == "" { - return fmt.Errorf("input cannot be empty") + return errors.New("input cannot be empty") } return nil diff --git a/client/pruning/main.go b/client/pruning/main.go index 3db413b4c614e..9cb73a8cb9de3 100644 --- a/client/pruning/main.go +++ b/client/pruning/main.go @@ -1,6 +1,7 @@ package pruning import ( + "errors" "fmt" "path/filepath" @@ -76,7 +77,7 @@ Supported app-db-backend types include 'goleveldb', 'rocksdb', 'pebbledb'.`, rootMultiStore, ok := cms.(*rootmulti.Store) if !ok { - return fmt.Errorf("currently only support the pruning of rootmulti.Store type") + return errors.New("currently only support the pruning of rootmulti.Store type") } latestHeight := rootmulti.GetLatestVersion(db) // valid heights should be greater than 0. diff --git a/client/rpc/tx.go b/client/rpc/tx.go index 064859da8e671..cb5d6fd16a846 100644 --- a/client/rpc/tx.go +++ b/client/rpc/tx.go @@ -4,6 +4,7 @@ import ( "context" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "strings" @@ -17,7 +18,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/version" ) @@ -187,7 +188,7 @@ $ %[1]s tx [flags] | %[1]s q wait-tx return clientCtx.PrintProto(newResponseFormatBroadcastTxCommit(res)) } case <-ctx.Done(): - return errors.ErrLogic.Wrapf("timed out waiting for transaction %X to be included in a block", hash) + return sdkerrors.ErrLogic.Wrapf("timed out waiting for transaction %X to be included in a block", hash) } return nil }, @@ -222,5 +223,5 @@ func parseHashFromInput(in []byte) ([]byte, error) { return hex.DecodeString(hash) } } - return nil, fmt.Errorf("txhash not found") + return nil, errors.New("txhash not found") } diff --git a/client/v2/CHANGELOG.md b/client/v2/CHANGELOG.md index 335010baca5b5..5fae2c385bdc9 100644 --- a/client/v2/CHANGELOG.md +++ b/client/v2/CHANGELOG.md @@ -47,6 +47,10 @@ Ref: https://keepachangelog.com/en/1.0.0/ * [#17709](https://github.com/cosmos/cosmos-sdk/pull/17709) Address codecs have been removed from `autocli.AppOptions` and `flag.Builder`. Instead client/v2 uses the address codecs present in the context (introduced in [#17503](https://github.com/cosmos/cosmos-sdk/pull/17503)). +### Bug Fixes + +* [#20964](https://github.com/cosmos/cosmos-sdk/pull/20964) Fix `GetNodeHomeDirectory` helper in `client/v2/helpers` to respect the `(PREFIX)_HOME` environment variable. + ## [v2.0.0-beta.3] - 2024-07-15 ### Features diff --git a/client/v2/autocli/flag/pubkey.go b/client/v2/autocli/flag/pubkey.go index adc07956f6905..f91eab8f53359 100644 --- a/client/v2/autocli/flag/pubkey.go +++ b/client/v2/autocli/flag/pubkey.go @@ -2,6 +2,7 @@ package flag import ( "context" + "errors" "fmt" "google.golang.org/protobuf/reflect/protoreflect" @@ -47,7 +48,7 @@ func (a *pubkeyValue) Set(s string) error { any, err := types.NewAnyWithValue(pk) if err != nil { - return fmt.Errorf("error converting to any type") + return errors.New("error converting to any type") } a.value = any diff --git a/client/v2/autocli/query.go b/client/v2/autocli/query.go index 161abd75867ed..dc268b5736549 100644 --- a/client/v2/autocli/query.go +++ b/client/v2/autocli/query.go @@ -2,6 +2,7 @@ package autocli import ( "context" + "errors" "fmt" "io" "strings" @@ -176,14 +177,14 @@ func encoder(encoder aminojson.Encoder) aminojson.Encoder { fields := msg.Descriptor().Fields() secondsField := fields.ByName(secondsName) if secondsField == nil { - return fmt.Errorf("expected seconds field") + return errors.New("expected seconds field") } seconds := msg.Get(secondsField).Int() nanosField := fields.ByName(nanosName) if nanosField == nil { - return fmt.Errorf("expected nanos field") + return errors.New("expected nanos field") } nanos := msg.Get(nanosField).Int() @@ -199,14 +200,14 @@ func encoder(encoder aminojson.Encoder) aminojson.Encoder { fields := msg.Descriptor().Fields() denomField := fields.ByName(denomName) if denomField == nil { - return fmt.Errorf("expected denom field") + return errors.New("expected denom field") } denom := msg.Get(denomField).String() amountField := fields.ByName(amountName) if amountField == nil { - return fmt.Errorf("expected amount field") + return errors.New("expected amount field") } amount := msg.Get(amountField).String() diff --git a/client/v2/go.mod b/client/v2/go.mod index 565eddcc13568..d6e3d4e936805 100644 --- a/client/v2/go.mod +++ b/client/v2/go.mod @@ -5,7 +5,7 @@ go 1.22.2 require ( cosmossdk.io/api v0.7.5 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/x/bank v0.0.0-20240226161501-23359a0b6d91 cosmossdk.io/x/gov v0.0.0-20231113122742-912390d5fc4a cosmossdk.io/x/tx v0.13.3 @@ -51,7 +51,7 @@ require ( github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/gogoproto v1.5.0 @@ -171,6 +171,7 @@ require ( ) require ( + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/schema v0.1.1 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect ) @@ -182,7 +183,6 @@ replace ( cosmossdk.io/api => ./../../api cosmossdk.io/core => ./../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ./../../depinject cosmossdk.io/log => ./../../log cosmossdk.io/store => ./../../store cosmossdk.io/x/accounts => ./../../x/accounts diff --git a/client/v2/go.sum b/client/v2/go.sum index af5d9070de9ff..cd9dd4c5e9c8f 100644 --- a/client/v2/go.sum +++ b/client/v2/go.sum @@ -6,6 +6,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -106,8 +108,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/client/v2/helpers/home.go b/client/v2/helpers/home.go index f62ff30490e9a..af3fc28866732 100644 --- a/client/v2/helpers/home.go +++ b/client/v2/helpers/home.go @@ -6,8 +6,13 @@ import ( "strings" ) +// EnvPrefix is the prefix for environment variables that are used by the CLI. +// It should match the one used for viper in the CLI. +var EnvPrefix = "" + // GetNodeHomeDirectory gets the home directory of the node (where the config is located). -// It parses the home flag if set if the `NODE_HOME` environment variable if set (and ignores name). +// It parses the home flag if set if the `(PREFIX)_HOME` environment variable if set (and ignores name). +// When no prefix is set, it reads the `NODE_HOME` environment variable. // Otherwise, it returns the default home directory given its name. func GetNodeHomeDirectory(name string) (string, error) { // get the home directory from the flag @@ -21,12 +26,19 @@ func GetNodeHomeDirectory(name string) (string, error) { } // get the home directory from the environment variable - homeDir := os.Getenv("NODE_HOME") + // to not clash with the $HOME system variable, when no prefix is set + // we check the NODE_HOME environment variable + homeDir, envHome := "", "HOME" + if len(EnvPrefix) > 0 { + homeDir = os.Getenv(EnvPrefix + "_" + envHome) + } else { + homeDir = os.Getenv("NODE_" + envHome) + } if homeDir != "" { return filepath.Clean(homeDir), nil } - // return the default home directory + // get user home directory userHomeDir, err := os.UserHomeDir() if err != nil { return "", err diff --git a/codec/codec.go b/codec/codec.go index c8c5844ac04b8..3d9cfd771bc0d 100644 --- a/codec/codec.go +++ b/codec/codec.go @@ -2,6 +2,7 @@ package codec import ( "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "google.golang.org/grpc/encoding" "google.golang.org/protobuf/reflect/protoreflect" @@ -76,7 +77,7 @@ type ( // is not registered in codec, or is not compatible with the serialized data UnmarshalInterface(bz []byte, ptr interface{}) error - types.AnyUnpacker + gogoprotoany.AnyUnpacker } JSONCodec interface { diff --git a/codec/types/interface_registry.go b/codec/types/interface_registry.go index 63bcc8094b431..04c94c4394a98 100644 --- a/codec/types/interface_registry.go +++ b/codec/types/interface_registry.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/gogoproto/jsonpb" "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "google.golang.org/protobuf/reflect/protodesc" "google.golang.org/protobuf/reflect/protoreflect" @@ -14,47 +15,10 @@ import ( "cosmossdk.io/x/tx/signing" ) -// AnyUnpacker is an interface which allows safely unpacking types packed -// in Any's against a whitelist of registered types -type AnyUnpacker interface { - // UnpackAny unpacks the value in any to the interface pointer passed in as - // iface. Note that the type in any must have been registered in the - // underlying whitelist registry as a concrete type for that interface - // Ex: - // var msg sdk.Msg - // err := cdc.UnpackAny(any, &msg) - // ... - UnpackAny(any *Any, iface interface{}) error -} - -// UnpackInterfacesMessage is meant to extend protobuf types (which implement -// proto.Message) to support a post-deserialization phase which unpacks -// types packed within Any's using the whitelist provided by AnyUnpacker -type UnpackInterfacesMessage interface { - // UnpackInterfaces is implemented in order to unpack values packed within - // Any's using the AnyUnpacker. It should generally be implemented as - // follows: - // func (s *MyStruct) UnpackInterfaces(unpacker AnyUnpacker) error { - // var x AnyInterface - // // where X is an Any field on MyStruct - // err := unpacker.UnpackAny(s.X, &x) - // if err != nil { - // return nil - // } - // // where Y is a field on MyStruct that implements UnpackInterfacesMessage itself - // err = s.Y.UnpackInterfaces(unpacker) - // if err != nil { - // return nil - // } - // return nil - // } - UnpackInterfaces(unpacker AnyUnpacker) error -} - // UnpackInterfaces is a convenience function that calls UnpackInterfaces // on x if x implements UnpackInterfacesMessage -func UnpackInterfaces(x interface{}, unpacker AnyUnpacker) error { - if msg, ok := x.(UnpackInterfacesMessage); ok { +func UnpackInterfaces(x interface{}, unpacker gogoprotoany.AnyUnpacker) error { + if msg, ok := x.(gogoprotoany.UnpackInterfacesMessage); ok { return msg.UnpackInterfaces(unpacker) } return nil @@ -65,7 +29,7 @@ var protoMessageType = reflect.TypeOf((*proto.Message)(nil)).Elem() // InterfaceRegistry provides a mechanism for registering interfaces and // implementations that can be safely unpacked from Any type InterfaceRegistry interface { - AnyUnpacker + gogoprotoany.AnyUnpacker jsonpb.AnyResolver registry.InterfaceRegistrar diff --git a/collections/go.mod b/collections/go.mod index 63875a5552000..3aceac378f3e5 100644 --- a/collections/go.mod +++ b/collections/go.mod @@ -13,9 +13,7 @@ require ( github.com/cosmos/gogoproto v1.5.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/google/go-cmp v0.6.0 // indirect - github.com/kr/text v0.2.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/rogpeppe/go-internal v1.12.0 // indirect github.com/tidwall/btree v1.7.0 // indirect golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 // indirect golang.org/x/net v0.27.0 // indirect diff --git a/collections/go.sum b/collections/go.sum index b950887a563e1..0a20b8cfe165b 100644 --- a/collections/go.sum +++ b/collections/go.sum @@ -1,20 +1,13 @@ github.com/cosmos/gogoproto v1.5.0 h1:SDVwzEqZDDBoslaeZg+dGE55hdzHfgUA40pEanMh52o= github.com/cosmos/gogoproto v1.5.0/go.mod h1:iUM31aofn3ymidYG6bUR5ZFrk+Om8p5s754eMUcyp8I= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= -github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/tidwall/btree v1.7.0 h1:L1fkJH/AuEh5zBnnBbmTwQ5Lt+bRJ5A8EWecslvo9iI= @@ -33,9 +26,8 @@ google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA= google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0= google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw= diff --git a/core/appmodule/genesis.go b/core/appmodule/genesis.go index 981b933844d04..a7f1155a59ff2 100644 --- a/core/appmodule/genesis.go +++ b/core/appmodule/genesis.go @@ -8,9 +8,20 @@ import ( "cosmossdk.io/core/appmodule/v2" ) +// HasGenesisBasics is the legacy interface for stateless genesis methods. +type HasGenesisBasics interface { + DefaultGenesis() json.RawMessage + ValidateGenesis(json.RawMessage) error +} + // HasGenesis defines a custom genesis handling API implementation. type HasGenesis = appmodule.HasGenesis +// HasABCIGenesis defines a custom genesis handling API implementation for ABCI. +// (stateful genesis methods which returns validator updates) +// Most modules should not implement this interface. +type HasABCIGenesis = appmodule.HasABCIGenesis + // HasGenesisAuto is the extension interface that modules should implement to handle // genesis data and state initialization. // WARNING: This interface is experimental and may change at any time. @@ -30,14 +41,6 @@ type HasGenesisAuto interface { ExportGenesis(context.Context, GenesisTarget) error } -// HasGenesisBasics is the legacy interface for stateless genesis methods. -type HasGenesisBasics interface { - HasName - - DefaultGenesis() json.RawMessage - ValidateGenesis(json.RawMessage) error -} - // GenesisSource is a source for genesis data in JSON format. It may abstract over a // single JSON object or separate files for each field in a JSON object that can // be streamed over. Modules should open a separate io.ReadCloser for each field that diff --git a/core/appmodule/module.go b/core/appmodule/module.go index 8ce2b76a47dcb..7aef44a9b8acc 100644 --- a/core/appmodule/module.go +++ b/core/appmodule/module.go @@ -66,11 +66,6 @@ type HasPrecommit interface { Precommit(context.Context) error } -// HasName is an extension interface that must return the appmodule.AppModule's Name. -type HasName interface { - Name() string -} - // HasAminoCodec is an extension interface that module must implement to support JSON encoding and decoding of its types // through amino. This is used in genesis & the CLI client. type HasAminoCodec interface { diff --git a/core/appmodule/v2/genesis.go b/core/appmodule/v2/genesis.go index 4e7b78742df24..967618772f6ee 100644 --- a/core/appmodule/v2/genesis.go +++ b/core/appmodule/v2/genesis.go @@ -7,18 +7,27 @@ import ( // HasGenesis defines a custom genesis handling API implementation. // WARNING: this API is meant as a short-term solution to allow for the -// migration of existing modules to the new app module API. It is intended to be replaced by collections +// migration of existing modules to the new app module API. +// It is intended to be replaced by an automatic genesis with collections/orm. type HasGenesis interface { AppModule + DefaultGenesis() json.RawMessage ValidateGenesis(data json.RawMessage) error InitGenesis(ctx context.Context, data json.RawMessage) error ExportGenesis(ctx context.Context) (json.RawMessage, error) } +// HasABCIGenesis defines a custom genesis handling API implementation for ABCI. +// (stateful genesis methods which returns validator updates) +// Most modules should not implement this interface. type HasABCIGenesis interface { + AppModule + DefaultGenesis() json.RawMessage + ValidateGenesis(data json.RawMessage) error InitGenesis(ctx context.Context, data json.RawMessage) ([]ValidatorUpdate, error) + ExportGenesis(ctx context.Context) (json.RawMessage, error) } type GenesisDecoder interface { diff --git a/core/genesis/source_test.go b/core/genesis/source_test.go index cff1a3bde4673..ac8043d178793 100644 --- a/core/genesis/source_test.go +++ b/core/genesis/source_test.go @@ -5,31 +5,41 @@ import ( "io" "testing" - "github.com/stretchr/testify/require" - "cosmossdk.io/core/appmodule" ) func TestSource(t *testing.T) { source, err := SourceFromRawJSON(json.RawMessage(testJSON)) - require.NoError(t, err) + if err != nil { + t.Errorf("Error creating source: %s", err) + } expectJSON(t, source, "foo", fooContents) expectJSON(t, source, "bar", barContents) // missing fields just return nil, nil r, err := source("baz") - require.NoError(t, err) - require.Nil(t, r) + if err != nil { + t.Errorf("Error retrieving field: %s", err) + } + if r != nil { + t.Errorf("Expected nil result for missing field, got: %v", r) + } } func expectJSON(t *testing.T, source appmodule.GenesisSource, field, contents string) { t.Helper() r, err := source(field) - require.NoError(t, err) + if err != nil { + t.Errorf("Error retrieving field: %s", err) + } bz, err := io.ReadAll(r) - require.NoError(t, err) - require.Equal(t, contents, string(bz)) + if err != nil { + t.Errorf("Error reading contents: %s", err) + } + if string(bz) != contents { + t.Errorf("Expected contents: %s, got: %s", contents, string(bz)) + } } const ( diff --git a/core/genesis/target_test.go b/core/genesis/target_test.go index 31ce0812be016..4a506e66e126d 100644 --- a/core/genesis/target_test.go +++ b/core/genesis/target_test.go @@ -2,31 +2,45 @@ package genesis import ( "testing" - - "github.com/stretchr/testify/require" ) func TestTarget(t *testing.T) { target := &RawJSONTarget{} w, err := target.Target()("foo") - require.NoError(t, err) + if err != nil { + t.Errorf("Error creating target: %s", err) + } _, err = w.Write([]byte("1")) - require.NoError(t, err) - require.NoError(t, w.Close()) + if err != nil { + t.Errorf("Error writing to target: %s", err) + } + if err := w.Close(); err != nil { + t.Errorf("Error closing target: %s", err) + } w, err = target.Target()("bar") - require.NoError(t, err) + if err != nil { + t.Errorf("Error creating target: %s", err) + } _, err = w.Write([]byte(`"abc"`)) - require.NoError(t, err) - require.NoError(t, w.Close()) + if err != nil { + t.Errorf("Error writing to target: %s", err) + } + if err := w.Close(); err != nil { + t.Errorf("Error closing target: %s", err) + } bz, err := target.JSON() - require.NoError(t, err) + if err != nil { + t.Errorf("Error getting JSON: %s", err) + } // test that it's correct by reading back with a source source, err := SourceFromRawJSON(bz) - require.NoError(t, err) + if err != nil { + t.Errorf("Error creating source from JSON: %s", err) + } expectJSON(t, source, "foo", "1") expectJSON(t, source, "bar", `"abc"`) diff --git a/core/go.mod b/core/go.mod index 41972d62bbc52..640023bbfb5db 100644 --- a/core/go.mod +++ b/core/go.mod @@ -4,22 +4,15 @@ go 1.20 require ( github.com/cosmos/gogoproto v1.5.0 - github.com/stretchr/testify v1.9.0 google.golang.org/grpc v1.64.1 ) require ( - github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/google/go-cmp v0.6.0 // indirect - github.com/kr/pretty v0.3.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/rogpeppe/go-internal v1.11.0 // indirect golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect golang.org/x/net v0.27.0 // indirect golang.org/x/sys v0.22.0 // indirect golang.org/x/text v0.16.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20240709173604-40e1e62336c5 // indirect google.golang.org/protobuf v1.34.2 // indirect - gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/core/go.sum b/core/go.sum index 27572f4dd51be..d1734cd1d560c 100644 --- a/core/go.sum +++ b/core/go.sum @@ -1,26 +1,8 @@ github.com/cosmos/gogoproto v1.5.0 h1:SDVwzEqZDDBoslaeZg+dGE55hdzHfgUA40pEanMh52o= github.com/cosmos/gogoproto v1.5.0/go.mod h1:iUM31aofn3ymidYG6bUR5ZFrk+Om8p5s754eMUcyp8I= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= -github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys= @@ -35,8 +17,3 @@ google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA= google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0= google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/core/header/service_test.go b/core/header/service_test.go index c658de33ecfb3..7ac590a9fc7f7 100644 --- a/core/header/service_test.go +++ b/core/header/service_test.go @@ -4,8 +4,6 @@ import ( "crypto/sha256" "testing" "time" - - "github.com/stretchr/testify/require" ) func TestInfo_Bytes(t *testing.T) { @@ -28,8 +26,12 @@ func TestInfo_Bytes(t *testing.T) { } bytes, err := info.Bytes() - require.NoError(t, err) - require.Equal(t, expectedBytes, bytes) + if err != nil { + t.Errorf("unexpected error: %v", err) + } + if !bytesEqual(expectedBytes, bytes) { + t.Errorf("expected bytes %v, got %v", expectedBytes, bytes) + } } func TestInfo_FromBytes(t *testing.T) { @@ -46,10 +48,34 @@ func TestInfo_FromBytes(t *testing.T) { } err := info.FromBytes(bytes) - require.NoError(t, err) - require.Equal(t, int64(12345), info.Height) - require.Equal(t, []byte{0x26, 0xb0, 0xb8, 0x3e, 0x72, 0x81, 0xbe, 0x3b, 0x11, 0x76, 0x58, 0xb6, 0xf2, 0x63, 0x6d, 0x3, 0x68, 0xca, 0xd3, 0xd7, 0x4f, 0x22, 0x24, 0x34, 0x28, 0xf5, 0x40, 0x1a, 0x4b, 0x70, 0x89, 0x7e}, info.Hash) - require.Equal(t, time.Date(2024, time.January, 1, 0, 0, 0, 0, time.UTC), info.Time) - require.Equal(t, []byte{0x26, 0xb0, 0xb8, 0x3e, 0x72, 0x81, 0xbe, 0x3b, 0x11, 0x76, 0x58, 0xb6, 0xf2, 0x63, 0x6d, 0x3, 0x68, 0xca, 0xd3, 0xd7, 0x4f, 0x22, 0x24, 0x34, 0x28, 0xf5, 0x40, 0x1a, 0x4b, 0x70, 0x89, 0x7e}, info.AppHash) - require.Equal(t, "test-chain", info.ChainID) + if err != nil { + t.Errorf("unexpected error: %v", err) + } + if info.Height != 12345 { + t.Errorf("expected Height %d, got %d", 12345, info.Height) + } + if !bytesEqual([]byte{0x26, 0xb0, 0xb8, 0x3e, 0x72, 0x81, 0xbe, 0x3b, 0x11, 0x76, 0x58, 0xb6, 0xf2, 0x63, 0x6d, 0x3, 0x68, 0xca, 0xd3, 0xd7, 0x4f, 0x22, 0x24, 0x34, 0x28, 0xf5, 0x40, 0x1a, 0x4b, 0x70, 0x89, 0x7e}, info.Hash) { + t.Errorf("expected Hash %v, got %v", []byte{0x26, 0xb0, 0xb8, 0x3e, 0x72, 0x81, 0xbe, 0x3b, 0x11, 0x76, 0x58, 0xb6, 0xf2, 0x63, 0x6d, 0x3, 0x68, 0xca, 0xd3, 0xd7, 0x4f, 0x22, 0x24, 0x34, 0x28, 0xf5, 0x40, 0x1a, 0x4b, 0x70, 0x89, 0x7e}, info.Hash) + } + if info.Time != time.Date(2024, time.January, 1, 0, 0, 0, 0, time.UTC) { + t.Errorf("expected Time %v, got %v", time.Date(2024, time.January, 1, 0, 0, 0, 0, time.UTC), info.Time) + } + if !bytesEqual([]byte{0x26, 0xb0, 0xb8, 0x3e, 0x72, 0x81, 0xbe, 0x3b, 0x11, 0x76, 0x58, 0xb6, 0xf2, 0x63, 0x6d, 0x3, 0x68, 0xca, 0xd3, 0xd7, 0x4f, 0x22, 0x24, 0x34, 0x28, 0xf5, 0x40, 0x1a, 0x4b, 0x70, 0x89, 0x7e}, info.AppHash) { + t.Errorf("expected AppHash %v, got %v", []byte{0x26, 0xb0, 0xb8, 0x3e, 0x72, 0x81, 0xbe, 0x3b, 0x11, 0x76, 0x58, 0xb6, 0xf2, 0x63, 0x6d, 0x3, 0x68, 0xca, 0xd3, 0xd7, 0x4f, 0x22, 0x24, 0x34, 0x28, 0xf5, 0x40, 0x1a, 0x4b, 0x70, 0x89, 0x7e}, info.AppHash) + } + if info.ChainID != "test-chain" { + t.Errorf("expected ChainID %s, got %s", "test-chain", info.ChainID) + } +} + +func bytesEqual(a, b []byte) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true } diff --git a/core/log/noop.go b/core/testing/noop.go similarity index 50% rename from core/log/noop.go rename to core/testing/noop.go index 4a7a67af00711..94ea011b431bb 100644 --- a/core/log/noop.go +++ b/core/testing/noop.go @@ -1,7 +1,9 @@ -package log +package coretesting + +import "cosmossdk.io/core/log" // NewNopLogger returns a new logger that does nothing. -func NewNopLogger() Logger { +func NewNopLogger() log.Logger { // The custom nopLogger is about 3x faster than a zeroLogWrapper with zerolog.Nop(). return nopLogger{} } @@ -11,9 +13,9 @@ func NewNopLogger() Logger { // The custom implementation is about 3x faster. type nopLogger struct{} -func (nopLogger) Info(string, ...any) {} -func (nopLogger) Warn(string, ...any) {} -func (nopLogger) Error(string, ...any) {} -func (nopLogger) Debug(string, ...any) {} -func (nopLogger) With(...any) Logger { return nopLogger{} } -func (nopLogger) Impl() any { return nopLogger{} } +func (nopLogger) Info(string, ...any) {} +func (nopLogger) Warn(string, ...any) {} +func (nopLogger) Error(string, ...any) {} +func (nopLogger) Debug(string, ...any) {} +func (nopLogger) With(...any) log.Logger { return nopLogger{} } +func (nopLogger) Impl() any { return nopLogger{} } diff --git a/crypto/keyring/legacy_info.go b/crypto/keyring/legacy_info.go index 47cbe3e9a9202..48e5d664f11f4 100644 --- a/crypto/keyring/legacy_info.go +++ b/crypto/keyring/legacy_info.go @@ -4,6 +4,8 @@ import ( "errors" "fmt" + gogoprotoany "github.com/cosmos/gogoproto/types/any" + "github.com/cosmos/cosmos-sdk/codec/legacy" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/hd" @@ -218,7 +220,7 @@ func (i LegacyMultiInfo) GetPath() (*hd.BIP44Params, error) { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (i LegacyMultiInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (i LegacyMultiInfo) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { multiPK := i.PubKey.(*multisig.LegacyAminoPubKey) return codectypes.UnpackInterfaces(multiPK, unpacker) diff --git a/crypto/keyring/record.go b/crypto/keyring/record.go index 96141e4c906e4..2e19c5b91576e 100644 --- a/crypto/keyring/record.go +++ b/crypto/keyring/record.go @@ -3,6 +3,8 @@ package keyring import ( "errors" + gogoprotoany "github.com/cosmos/gogoproto/types/any" + errorsmod "cosmossdk.io/errors" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -103,7 +105,7 @@ func (k Record) GetType() KeyType { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (k *Record) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (k *Record) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var pk cryptotypes.PubKey if err := unpacker.UnpackAny(k.PubKey, &pk); err != nil { return err diff --git a/crypto/keys/multisig/multisig.go b/crypto/keys/multisig/multisig.go index 623f25516164d..1fc3f8e28098a 100644 --- a/crypto/keys/multisig/multisig.go +++ b/crypto/keys/multisig/multisig.go @@ -4,6 +4,7 @@ import ( "fmt" cmtcrypto "github.com/cometbft/cometbft/crypto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "github.com/cosmos/cosmos-sdk/codec/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -12,8 +13,8 @@ import ( ) var ( - _ multisigtypes.PubKey = &LegacyAminoPubKey{} - _ types.UnpackInterfacesMessage = &LegacyAminoPubKey{} + _ multisigtypes.PubKey = &LegacyAminoPubKey{} + _ gogoprotoany.UnpackInterfacesMessage = &LegacyAminoPubKey{} ) // NewLegacyAminoPubKey returns a new LegacyAminoPubKey. @@ -149,7 +150,7 @@ func (m *LegacyAminoPubKey) Type() string { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (m *LegacyAminoPubKey) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (m *LegacyAminoPubKey) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, any := range m.PubKeys { var pk cryptotypes.PubKey err := unpacker.UnpackAny(any, &pk) @@ -169,11 +170,6 @@ func packPubKeys(pubKeys []cryptotypes.PubKey) ([]*types.Any, error) { return nil, err } anyPubKeys[i] = any - - // sets the compat.aminoBz value - if err := anyPubKeys[i].UnmarshalAmino(pubKeys[i].Bytes()); err != nil { - return nil, err - } } return anyPubKeys, nil } diff --git a/depinject/CHANGELOG.md b/depinject/CHANGELOG.md index f386bd51196d5..4b308e63a3e98 100644 --- a/depinject/CHANGELOG.md +++ b/depinject/CHANGELOG.md @@ -22,9 +22,10 @@ Each entry must include the Github issue reference in the following format: ## [Unreleased] -### Features +## 1.0.0 -- [#20540](https://github.com/cosmos/cosmos-sdk/pull/20540) add support for defining `appconfig` module configuration types using `github.com/cosmos/gogoproto/proto` in addition to `google.golang.org/protobuf` so that users can use gogo proto across their stack. +* [#20540](https://github.com/cosmos/cosmos-sdk/pull/20540) Add support for defining `appconfig` module configuration types using `github.com/cosmos/gogoproto/proto` in addition to `google.golang.org/protobuf` so that users can use gogo proto across their stack. +* Move `cosmossdk.io/core/appconfig` to `cosmossdk.io/depinject/appconfig`. ## 1.0.0-alpha.x diff --git a/depinject/appconfig/config.go b/depinject/appconfig/config.go index 39a6c6c695fac..10e1d037386d9 100644 --- a/depinject/appconfig/config.go +++ b/depinject/appconfig/config.go @@ -5,23 +5,32 @@ import ( "reflect" "strings" - "github.com/cosmos/cosmos-proto/anyutil" gogoproto "github.com/cosmos/gogoproto/proto" "google.golang.org/protobuf/encoding/protojson" protov2 "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/types/dynamicpb" "google.golang.org/protobuf/types/known/anypb" "sigs.k8s.io/yaml" - appv1alpha1 "cosmossdk.io/api/cosmos/app/v1alpha1" "cosmossdk.io/depinject" + "cosmossdk.io/depinject/appconfig/v1alpha1" internal "cosmossdk.io/depinject/internal/appconfig" ) // LoadJSON loads an app config in JSON format. func LoadJSON(bz []byte) depinject.Config { - config := &appv1alpha1.Config{} - err := protojson.UnmarshalOptions{ + // in order to avoid a direct dependency on api types, but in order to also be able to support + // either gogo or google.golang.org/protobuf types, we use protojson and dynamicpb to unmarshal + // from JSON + resolver := gogoproto.HybridResolver + desc, err := resolver.FindDescriptorByName(protoreflect.FullName(gogoproto.MessageName(&v1alpha1.Config{}))) + if err != nil { + return depinject.Error(err) + } + + config := dynamicpb.NewMessage(desc.(protoreflect.MessageDescriptor)) + err = protojson.UnmarshalOptions{ Resolver: dynamicTypeResolver{resolver: gogoproto.HybridResolver}, }.Unmarshal(bz, config) if err != nil { @@ -42,18 +51,39 @@ func LoadYAML(bz []byte) depinject.Config { } // WrapAny marshals a proto message into a proto Any instance -func WrapAny(config protoreflect.ProtoMessage) *anypb.Any { - cfg, err := anyutil.New(config) +func WrapAny(config gogoproto.Message) *anypb.Any { + pbz, err := gogoproto.Marshal(config) if err != nil { panic(err) } - return cfg + return &anypb.Any{ + TypeUrl: "/" + gogoproto.MessageName(config), + Value: pbz, + } } -// Compose composes a v1alpha1 app config into a container option by resolving -// the required modules and composing their options. -func Compose(appConfig *appv1alpha1.Config) depinject.Config { +// Compose composes an app config into a container option by resolving +// the required modules and composing their options. appConfig should be an instance +// of cosmos.app.v1alpha1.Config (it doesn't matter whether you use gogo proto or +// google.golang.org/protobuf types). +func Compose(appConfig gogoproto.Message) depinject.Config { + appConfigConcrete, ok := appConfig.(*v1alpha1.Config) + if !ok { + // we convert any other proto type that was passed (such as an api module type) to the concrete + // type we're using here + appConfigConcrete = &v1alpha1.Config{} + bz, err := gogoproto.Marshal(appConfig) + if err != nil { + return depinject.Error(err) + } + + err = gogoproto.Unmarshal(bz, appConfigConcrete) + if err != nil { + return depinject.Error(err) + } + } + opts := []depinject.Config{ depinject.Supply(appConfig), } @@ -63,7 +93,7 @@ func Compose(appConfig *appv1alpha1.Config) depinject.Config { return depinject.Error(err) } - for _, module := range appConfig.Modules { + for _, module := range appConfigConcrete.Modules { if module.Name == "" { return depinject.Error(fmt.Errorf("module is missing name")) } @@ -84,10 +114,14 @@ func Compose(appConfig *appv1alpha1.Config) depinject.Config { init, ok := modules[msgName] if !ok { if msgDesc, err := gogoproto.HybridResolver.FindDescriptorByName(protoreflect.FullName(msgName)); err == nil { - modDesc := protov2.GetExtension(msgDesc.Options(), appv1alpha1.E_Module).(*appv1alpha1.ModuleDescriptor) + modDesc, err := internal.GetModuleDescriptor(msgDesc) + if err != nil { + return depinject.Error(err) + } + if modDesc == nil { return depinject.Error(fmt.Errorf("no module registered for type URL %s and that protobuf type does not have the option %s\n\n%s", - module.Config.TypeUrl, appv1alpha1.E_Module.TypeDescriptor().FullName(), dumpRegisteredModules(modules))) + module.Config.TypeUrl, v1alpha1.E_Module.Name, dumpRegisteredModules(modules))) } return depinject.Error(fmt.Errorf("no module registered for type URL %s, did you forget to import %s: find more information on how to make a module ready for app wiring: https://docs.cosmos.network/main/building-modules/depinject\n\n%s", @@ -122,7 +156,7 @@ func Compose(appConfig *appv1alpha1.Config) depinject.Config { } } - for _, binding := range appConfig.GolangBindings { + for _, binding := range appConfigConcrete.GolangBindings { opts = append(opts, depinject.BindInterface(binding.InterfaceType, binding.Implementation)) } diff --git a/depinject/appconfig/v1alpha1/config.pb.go b/depinject/appconfig/v1alpha1/config.pb.go new file mode 100644 index 0000000000000..838f6cf8fea37 --- /dev/null +++ b/depinject/appconfig/v1alpha1/config.pb.go @@ -0,0 +1,942 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/app/v1alpha1/config.proto + +package v1alpha1 + +import ( + fmt "fmt" + proto "github.com/cosmos/gogoproto/proto" + any "github.com/cosmos/gogoproto/types/any" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// Config represents the configuration for a Cosmos SDK ABCI app. +// It is intended that all state machine logic including the version of +// baseapp and tx handlers (and possibly even Tendermint) that an app needs +// can be described in a config object. For compatibility, the framework should +// allow a mixture of declarative and imperative app wiring, however, apps +// that strive for the maximum ease of maintainability should be able to describe +// their state machine with a config object alone. +type Config struct { + // modules are the module configurations for the app. + Modules []*ModuleConfig `protobuf:"bytes,1,rep,name=modules,proto3" json:"modules,omitempty"` + // golang_bindings specifies explicit interface to implementation type bindings which + // depinject uses to resolve interface inputs to provider functions. The scope of this + // field's configuration is global (not module specific). + GolangBindings []*GolangBinding `protobuf:"bytes,2,rep,name=golang_bindings,json=golangBindings,proto3" json:"golang_bindings,omitempty"` +} + +func (m *Config) Reset() { *m = Config{} } +func (m *Config) String() string { return proto.CompactTextString(m) } +func (*Config) ProtoMessage() {} +func (*Config) Descriptor() ([]byte, []int) { + return fileDescriptor_5af1d229673256fa, []int{0} +} +func (m *Config) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Config) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Config.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Config) XXX_Merge(src proto.Message) { + xxx_messageInfo_Config.Merge(m, src) +} +func (m *Config) XXX_Size() int { + return m.Size() +} +func (m *Config) XXX_DiscardUnknown() { + xxx_messageInfo_Config.DiscardUnknown(m) +} + +var xxx_messageInfo_Config proto.InternalMessageInfo + +func (m *Config) GetModules() []*ModuleConfig { + if m != nil { + return m.Modules + } + return nil +} + +func (m *Config) GetGolangBindings() []*GolangBinding { + if m != nil { + return m.GolangBindings + } + return nil +} + +// ModuleConfig is a module configuration for an app. +type ModuleConfig struct { + // name is the unique name of the module within the app. It should be a name + // that persists between different versions of a module so that modules + // can be smoothly upgraded to new versions. + // + // For example, for the module cosmos.bank.module.v1.Module, we may chose + // to simply name the module "bank" in the app. When we upgrade to + // cosmos.bank.module.v2.Module, the app-specific name "bank" stays the same + // and the framework knows that the v2 module should receive all the same state + // that the v1 module had. Note: modules should provide info on which versions + // they can migrate from in the ModuleDescriptor.can_migration_from field. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // config is the config object for the module. Module config messages should + // define a ModuleDescriptor using the cosmos.app.v1alpha1.is_module extension. + Config *any.Any `protobuf:"bytes,2,opt,name=config,proto3" json:"config,omitempty"` + // golang_bindings specifies explicit interface to implementation type bindings which + // depinject uses to resolve interface inputs to provider functions. The scope of this + // field's configuration is module specific. + GolangBindings []*GolangBinding `protobuf:"bytes,3,rep,name=golang_bindings,json=golangBindings,proto3" json:"golang_bindings,omitempty"` +} + +func (m *ModuleConfig) Reset() { *m = ModuleConfig{} } +func (m *ModuleConfig) String() string { return proto.CompactTextString(m) } +func (*ModuleConfig) ProtoMessage() {} +func (*ModuleConfig) Descriptor() ([]byte, []int) { + return fileDescriptor_5af1d229673256fa, []int{1} +} +func (m *ModuleConfig) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ModuleConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ModuleConfig.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ModuleConfig) XXX_Merge(src proto.Message) { + xxx_messageInfo_ModuleConfig.Merge(m, src) +} +func (m *ModuleConfig) XXX_Size() int { + return m.Size() +} +func (m *ModuleConfig) XXX_DiscardUnknown() { + xxx_messageInfo_ModuleConfig.DiscardUnknown(m) +} + +var xxx_messageInfo_ModuleConfig proto.InternalMessageInfo + +func (m *ModuleConfig) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *ModuleConfig) GetConfig() *any.Any { + if m != nil { + return m.Config + } + return nil +} + +func (m *ModuleConfig) GetGolangBindings() []*GolangBinding { + if m != nil { + return m.GolangBindings + } + return nil +} + +// GolangBinding is an explicit interface type to implementing type binding for dependency injection. +type GolangBinding struct { + // interface_type is the interface type which will be bound to a specific implementation type + InterfaceType string `protobuf:"bytes,1,opt,name=interface_type,json=interfaceType,proto3" json:"interface_type,omitempty"` + // implementation is the implementing type which will be supplied when an input of type interface is requested + Implementation string `protobuf:"bytes,2,opt,name=implementation,proto3" json:"implementation,omitempty"` +} + +func (m *GolangBinding) Reset() { *m = GolangBinding{} } +func (m *GolangBinding) String() string { return proto.CompactTextString(m) } +func (*GolangBinding) ProtoMessage() {} +func (*GolangBinding) Descriptor() ([]byte, []int) { + return fileDescriptor_5af1d229673256fa, []int{2} +} +func (m *GolangBinding) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GolangBinding) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GolangBinding.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *GolangBinding) XXX_Merge(src proto.Message) { + xxx_messageInfo_GolangBinding.Merge(m, src) +} +func (m *GolangBinding) XXX_Size() int { + return m.Size() +} +func (m *GolangBinding) XXX_DiscardUnknown() { + xxx_messageInfo_GolangBinding.DiscardUnknown(m) +} + +var xxx_messageInfo_GolangBinding proto.InternalMessageInfo + +func (m *GolangBinding) GetInterfaceType() string { + if m != nil { + return m.InterfaceType + } + return "" +} + +func (m *GolangBinding) GetImplementation() string { + if m != nil { + return m.Implementation + } + return "" +} + +func init() { + proto.RegisterType((*Config)(nil), "cosmos.app.v1alpha1.Config") + proto.RegisterType((*ModuleConfig)(nil), "cosmos.app.v1alpha1.ModuleConfig") + proto.RegisterType((*GolangBinding)(nil), "cosmos.app.v1alpha1.GolangBinding") +} + +func init() { proto.RegisterFile("cosmos/app/v1alpha1/config.proto", fileDescriptor_5af1d229673256fa) } + +var fileDescriptor_5af1d229673256fa = []byte{ + // 333 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x92, 0x31, 0x4f, 0x02, 0x31, + 0x1c, 0xc5, 0x29, 0x18, 0x0c, 0x45, 0x30, 0xa9, 0x0e, 0xa7, 0xc3, 0xe5, 0x24, 0xd1, 0x60, 0x62, + 0xda, 0x80, 0xa3, 0x93, 0x30, 0x38, 0x18, 0x97, 0x8b, 0x93, 0x83, 0xa4, 0xdc, 0x95, 0x5a, 0xbd, + 0x6b, 0x1b, 0x5a, 0x4c, 0xee, 0x5b, 0x18, 0x77, 0xbf, 0x8f, 0x23, 0xa3, 0xa3, 0x81, 0x2f, 0x62, + 0x6c, 0x3d, 0x82, 0x86, 0xc9, 0xad, 0xfd, 0xe7, 0xf7, 0x7f, 0x7d, 0xaf, 0x79, 0x30, 0x4a, 0x94, + 0xc9, 0x95, 0x21, 0x54, 0x6b, 0xf2, 0xdc, 0xa3, 0x99, 0x7e, 0xa0, 0x3d, 0x92, 0x28, 0x39, 0x11, + 0x1c, 0xeb, 0xa9, 0xb2, 0x0a, 0xed, 0x79, 0x02, 0x53, 0xad, 0x71, 0x49, 0x1c, 0x1e, 0x70, 0xa5, + 0x78, 0xc6, 0x88, 0x43, 0xc6, 0xb3, 0x09, 0xa1, 0xb2, 0xf0, 0x7c, 0xe7, 0x15, 0xc0, 0xfa, 0xd0, + 0x09, 0xa0, 0x0b, 0xb8, 0x9d, 0xab, 0x74, 0x96, 0x31, 0x13, 0x80, 0xa8, 0xd6, 0x6d, 0xf6, 0x8f, + 0xf0, 0x06, 0x31, 0x7c, 0xe3, 0x18, 0xbf, 0x13, 0x97, 0x1b, 0xe8, 0x1a, 0xee, 0x72, 0x95, 0x51, + 0xc9, 0x47, 0x63, 0x21, 0x53, 0x21, 0xb9, 0x09, 0xaa, 0x4e, 0xa4, 0xb3, 0x51, 0xe4, 0xca, 0xb1, + 0x03, 0x8f, 0xc6, 0x6d, 0xbe, 0x7e, 0x35, 0x9d, 0x37, 0x00, 0x77, 0xd6, 0x9f, 0x41, 0x08, 0x6e, + 0x49, 0x9a, 0xb3, 0x00, 0x44, 0xa0, 0xdb, 0x88, 0xdd, 0x19, 0x9d, 0xc1, 0xba, 0x4f, 0x1e, 0x54, + 0x23, 0xd0, 0x6d, 0xf6, 0xf7, 0xb1, 0x4f, 0x89, 0xcb, 0x94, 0xf8, 0x52, 0x16, 0xf1, 0x0f, 0xb3, + 0xc9, 0x5f, 0xed, 0xdf, 0xfe, 0xee, 0x61, 0xeb, 0x17, 0x80, 0x8e, 0x61, 0x5b, 0x48, 0xcb, 0xa6, + 0x13, 0x9a, 0xb0, 0x91, 0x2d, 0x74, 0xe9, 0xb4, 0xb5, 0x9a, 0xde, 0x16, 0x9a, 0xa1, 0x13, 0xd8, + 0x16, 0xb9, 0xce, 0x58, 0xce, 0xa4, 0xa5, 0x56, 0x28, 0xe9, 0xac, 0x37, 0xe2, 0x3f, 0xd3, 0xc1, + 0xf0, 0x7d, 0x11, 0x82, 0xf9, 0x22, 0x04, 0x9f, 0x8b, 0x10, 0xbc, 0x2c, 0xc3, 0xca, 0x7c, 0x19, + 0x56, 0x3e, 0x96, 0x61, 0xe5, 0xee, 0xd4, 0x9b, 0x35, 0xe9, 0x13, 0x16, 0x8a, 0xa4, 0x4c, 0x0b, + 0xf9, 0xc8, 0x12, 0xfb, 0x5d, 0x08, 0x1f, 0x74, 0x55, 0x8b, 0x71, 0xdd, 0xfd, 0xc3, 0xf9, 0x57, + 0x00, 0x00, 0x00, 0xff, 0xff, 0xd5, 0xfa, 0x9f, 0xcf, 0x34, 0x02, 0x00, 0x00, +} + +func (m *Config) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Config) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Config) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.GolangBindings) > 0 { + for iNdEx := len(m.GolangBindings) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.GolangBindings[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintConfig(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if len(m.Modules) > 0 { + for iNdEx := len(m.Modules) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Modules[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintConfig(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *ModuleConfig) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ModuleConfig) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ModuleConfig) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.GolangBindings) > 0 { + for iNdEx := len(m.GolangBindings) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.GolangBindings[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintConfig(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if m.Config != nil { + { + size, err := m.Config.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintConfig(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Name) > 0 { + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintConfig(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *GolangBinding) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GolangBinding) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GolangBinding) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Implementation) > 0 { + i -= len(m.Implementation) + copy(dAtA[i:], m.Implementation) + i = encodeVarintConfig(dAtA, i, uint64(len(m.Implementation))) + i-- + dAtA[i] = 0x12 + } + if len(m.InterfaceType) > 0 { + i -= len(m.InterfaceType) + copy(dAtA[i:], m.InterfaceType) + i = encodeVarintConfig(dAtA, i, uint64(len(m.InterfaceType))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintConfig(dAtA []byte, offset int, v uint64) int { + offset -= sovConfig(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Config) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Modules) > 0 { + for _, e := range m.Modules { + l = e.Size() + n += 1 + l + sovConfig(uint64(l)) + } + } + if len(m.GolangBindings) > 0 { + for _, e := range m.GolangBindings { + l = e.Size() + n += 1 + l + sovConfig(uint64(l)) + } + } + return n +} + +func (m *ModuleConfig) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovConfig(uint64(l)) + } + if m.Config != nil { + l = m.Config.Size() + n += 1 + l + sovConfig(uint64(l)) + } + if len(m.GolangBindings) > 0 { + for _, e := range m.GolangBindings { + l = e.Size() + n += 1 + l + sovConfig(uint64(l)) + } + } + return n +} + +func (m *GolangBinding) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.InterfaceType) + if l > 0 { + n += 1 + l + sovConfig(uint64(l)) + } + l = len(m.Implementation) + if l > 0 { + n += 1 + l + sovConfig(uint64(l)) + } + return n +} + +func sovConfig(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozConfig(x uint64) (n int) { + return sovConfig(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Config) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Config: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Config: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Modules", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthConfig + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Modules = append(m.Modules, &ModuleConfig{}) + if err := m.Modules[len(m.Modules)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field GolangBindings", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthConfig + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.GolangBindings = append(m.GolangBindings, &GolangBinding{}) + if err := m.GolangBindings[len(m.GolangBindings)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipConfig(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthConfig + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ModuleConfig) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ModuleConfig: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ModuleConfig: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthConfig + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthConfig + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Config == nil { + m.Config = &any.Any{} + } + if err := m.Config.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field GolangBindings", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthConfig + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.GolangBindings = append(m.GolangBindings, &GolangBinding{}) + if err := m.GolangBindings[len(m.GolangBindings)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipConfig(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthConfig + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GolangBinding) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GolangBinding: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GolangBinding: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InterfaceType", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthConfig + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.InterfaceType = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Implementation", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthConfig + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Implementation = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipConfig(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthConfig + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipConfig(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowConfig + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowConfig + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowConfig + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthConfig + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupConfig + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthConfig + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthConfig = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowConfig = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupConfig = fmt.Errorf("proto: unexpected end of group") +) diff --git a/depinject/appconfig/v1alpha1/module.pb.go b/depinject/appconfig/v1alpha1/module.pb.go new file mode 100644 index 0000000000000..67dde820c1ec9 --- /dev/null +++ b/depinject/appconfig/v1alpha1/module.pb.go @@ -0,0 +1,893 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/app/v1alpha1/module.proto + +package v1alpha1 + +import ( + fmt "fmt" + proto "github.com/cosmos/gogoproto/proto" + descriptorpb "google.golang.org/protobuf/types/descriptorpb" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// ModuleDescriptor describes an app module. +type ModuleDescriptor struct { + // go_import names the package that should be imported by an app to load the + // module in the runtime module registry. It is required to make debugging + // of configuration errors easier for users. + GoImport string `protobuf:"bytes,1,opt,name=go_import,json=goImport,proto3" json:"go_import,omitempty"` + // use_package refers to a protobuf package that this module + // uses and exposes to the world. In an app, only one module should "use" + // or own a single protobuf package. It is assumed that the module uses + // all of the .proto files in a single package. + UsePackage []*PackageReference `protobuf:"bytes,2,rep,name=use_package,json=usePackage,proto3" json:"use_package,omitempty"` + // can_migrate_from defines which module versions this module can migrate + // state from. The framework will check that one module version is able to + // migrate from a previous module version before attempting to update its + // config. It is assumed that modules can transitively migrate from earlier + // versions. For instance if v3 declares it can migrate from v2, and v2 + // declares it can migrate from v1, the framework knows how to migrate + // from v1 to v3, assuming all 3 module versions are registered at runtime. + CanMigrateFrom []*MigrateFromInfo `protobuf:"bytes,3,rep,name=can_migrate_from,json=canMigrateFrom,proto3" json:"can_migrate_from,omitempty"` +} + +func (m *ModuleDescriptor) Reset() { *m = ModuleDescriptor{} } +func (m *ModuleDescriptor) String() string { return proto.CompactTextString(m) } +func (*ModuleDescriptor) ProtoMessage() {} +func (*ModuleDescriptor) Descriptor() ([]byte, []int) { + return fileDescriptor_0e7eb8b9b8dcd164, []int{0} +} +func (m *ModuleDescriptor) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ModuleDescriptor) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ModuleDescriptor.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ModuleDescriptor) XXX_Merge(src proto.Message) { + xxx_messageInfo_ModuleDescriptor.Merge(m, src) +} +func (m *ModuleDescriptor) XXX_Size() int { + return m.Size() +} +func (m *ModuleDescriptor) XXX_DiscardUnknown() { + xxx_messageInfo_ModuleDescriptor.DiscardUnknown(m) +} + +var xxx_messageInfo_ModuleDescriptor proto.InternalMessageInfo + +func (m *ModuleDescriptor) GetGoImport() string { + if m != nil { + return m.GoImport + } + return "" +} + +func (m *ModuleDescriptor) GetUsePackage() []*PackageReference { + if m != nil { + return m.UsePackage + } + return nil +} + +func (m *ModuleDescriptor) GetCanMigrateFrom() []*MigrateFromInfo { + if m != nil { + return m.CanMigrateFrom + } + return nil +} + +// PackageReference is a reference to a protobuf package used by a module. +type PackageReference struct { + // name is the fully-qualified name of the package. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // revision is the optional revision of the package that is being used. + // Protobuf packages used in Cosmos should generally have a major version + // as the last part of the package name, ex. foo.bar.baz.v1. + // The revision of a package can be thought of as the minor version of a + // package which has additional backwards compatible definitions that weren't + // present in a previous version. + // + // A package should indicate its revision with a source code comment + // above the package declaration in one of its files containing the + // text "Revision N" where N is an integer revision. All packages start + // at revision 0 the first time they are released in a module. + // + // When a new version of a module is released and items are added to existing + // .proto files, these definitions should contain comments of the form + // "Since: Revision N" where N is an integer revision. + // + // When the module runtime starts up, it will check the pinned proto + // image and panic if there are runtime protobuf definitions that are not + // in the pinned descriptor which do not have + // a "Since Revision N" comment or have a "Since Revision N" comment where + // N is <= to the revision specified here. This indicates that the protobuf + // files have been updated, but the pinned file descriptor hasn't. + // + // If there are items in the pinned file descriptor with a revision + // greater than the value indicated here, this will also cause a panic + // as it may mean that the pinned descriptor for a legacy module has been + // improperly updated or that there is some other versioning discrepancy. + // Runtime protobuf definitions will also be checked for compatibility + // with pinned file descriptors to make sure there are no incompatible changes. + // + // This behavior ensures that: + // - pinned proto images are up-to-date + // - protobuf files are carefully annotated with revision comments which + // are important good client UX + // - protobuf files are changed in backwards and forwards compatible ways + Revision uint32 `protobuf:"varint,2,opt,name=revision,proto3" json:"revision,omitempty"` +} + +func (m *PackageReference) Reset() { *m = PackageReference{} } +func (m *PackageReference) String() string { return proto.CompactTextString(m) } +func (*PackageReference) ProtoMessage() {} +func (*PackageReference) Descriptor() ([]byte, []int) { + return fileDescriptor_0e7eb8b9b8dcd164, []int{1} +} +func (m *PackageReference) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PackageReference) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PackageReference.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PackageReference) XXX_Merge(src proto.Message) { + xxx_messageInfo_PackageReference.Merge(m, src) +} +func (m *PackageReference) XXX_Size() int { + return m.Size() +} +func (m *PackageReference) XXX_DiscardUnknown() { + xxx_messageInfo_PackageReference.DiscardUnknown(m) +} + +var xxx_messageInfo_PackageReference proto.InternalMessageInfo + +func (m *PackageReference) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *PackageReference) GetRevision() uint32 { + if m != nil { + return m.Revision + } + return 0 +} + +// MigrateFromInfo is information on a module version that a newer module +// can migrate from. +type MigrateFromInfo struct { + // module is the fully-qualified protobuf name of the module config object + // for the previous module version, ex: "cosmos.group.module.v1.Module". + Module string `protobuf:"bytes,1,opt,name=module,proto3" json:"module,omitempty"` +} + +func (m *MigrateFromInfo) Reset() { *m = MigrateFromInfo{} } +func (m *MigrateFromInfo) String() string { return proto.CompactTextString(m) } +func (*MigrateFromInfo) ProtoMessage() {} +func (*MigrateFromInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_0e7eb8b9b8dcd164, []int{2} +} +func (m *MigrateFromInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MigrateFromInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MigrateFromInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MigrateFromInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_MigrateFromInfo.Merge(m, src) +} +func (m *MigrateFromInfo) XXX_Size() int { + return m.Size() +} +func (m *MigrateFromInfo) XXX_DiscardUnknown() { + xxx_messageInfo_MigrateFromInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_MigrateFromInfo proto.InternalMessageInfo + +func (m *MigrateFromInfo) GetModule() string { + if m != nil { + return m.Module + } + return "" +} + +var E_Module = &proto.ExtensionDesc{ + ExtendedType: (*descriptorpb.MessageOptions)(nil), + ExtensionType: (*ModuleDescriptor)(nil), + Field: 57193479, + Name: "cosmos.app.v1alpha1.module", + Tag: "bytes,57193479,opt,name=module", + Filename: "cosmos/app/v1alpha1/module.proto", +} + +func init() { + proto.RegisterType((*ModuleDescriptor)(nil), "cosmos.app.v1alpha1.ModuleDescriptor") + proto.RegisterType((*PackageReference)(nil), "cosmos.app.v1alpha1.PackageReference") + proto.RegisterType((*MigrateFromInfo)(nil), "cosmos.app.v1alpha1.MigrateFromInfo") + proto.RegisterExtension(E_Module) +} + +func init() { proto.RegisterFile("cosmos/app/v1alpha1/module.proto", fileDescriptor_0e7eb8b9b8dcd164) } + +var fileDescriptor_0e7eb8b9b8dcd164 = []byte{ + // 368 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x52, 0xcd, 0xaa, 0x13, 0x31, + 0x18, 0x6d, 0xee, 0x95, 0xcb, 0x6d, 0x8a, 0x5a, 0x22, 0xc8, 0xd0, 0xc2, 0x38, 0x14, 0x85, 0x76, + 0x93, 0xa1, 0xba, 0x73, 0x59, 0xa5, 0xd0, 0x45, 0x55, 0x66, 0xe9, 0x66, 0x48, 0x33, 0xdf, 0xc4, + 0xd8, 0x4e, 0xbe, 0x90, 0xcc, 0xf4, 0x15, 0xdc, 0xfa, 0x0c, 0xbe, 0x8c, 0x2e, 0xbb, 0x74, 0x29, + 0xed, 0xc6, 0xc7, 0x10, 0xe7, 0xa7, 0x48, 0xa9, 0xbb, 0x9c, 0x93, 0x93, 0x73, 0xf2, 0x1d, 0x3e, + 0x1a, 0x49, 0xf4, 0x05, 0xfa, 0x58, 0x58, 0x1b, 0xef, 0xe7, 0x62, 0x67, 0x3f, 0x89, 0x79, 0x5c, + 0x60, 0x56, 0xed, 0x80, 0x5b, 0x87, 0x25, 0xb2, 0x27, 0x8d, 0x82, 0x0b, 0x6b, 0x79, 0xa7, 0x18, + 0x45, 0x0a, 0x51, 0xed, 0x20, 0xae, 0x25, 0x9b, 0x2a, 0x8f, 0x33, 0xf0, 0xd2, 0x69, 0x5b, 0xa2, + 0x6b, 0x9e, 0x4d, 0xbe, 0x13, 0x3a, 0x5c, 0xd7, 0x3e, 0x6f, 0xcf, 0x57, 0x6c, 0x4c, 0xfb, 0x0a, + 0x53, 0x5d, 0x58, 0x74, 0x65, 0x40, 0x22, 0x32, 0xed, 0x27, 0xf7, 0x0a, 0x57, 0x35, 0x66, 0x4b, + 0x3a, 0xa8, 0x3c, 0xa4, 0x56, 0xc8, 0xad, 0x50, 0x10, 0xdc, 0x44, 0xb7, 0xd3, 0xc1, 0xcb, 0x17, + 0xfc, 0x4a, 0x3c, 0xff, 0xd0, 0x68, 0x12, 0xc8, 0xc1, 0x81, 0x91, 0x90, 0xd0, 0xca, 0x43, 0x4b, + 0xb2, 0x77, 0x74, 0x28, 0x85, 0x49, 0x0b, 0xad, 0x9c, 0x28, 0x21, 0xcd, 0x1d, 0x16, 0xc1, 0x6d, + 0x6d, 0xf6, 0xfc, 0xaa, 0xd9, 0xba, 0x11, 0x2e, 0x1d, 0x16, 0x2b, 0x93, 0x63, 0xf2, 0x48, 0x0a, + 0xf3, 0x0f, 0x37, 0x59, 0xd0, 0xe1, 0x65, 0x1e, 0x63, 0xf4, 0x81, 0x11, 0x05, 0xb4, 0x33, 0xd4, + 0x67, 0x36, 0xa2, 0xf7, 0x0e, 0xf6, 0xda, 0x6b, 0x34, 0xc1, 0x4d, 0x44, 0xa6, 0x0f, 0x93, 0x33, + 0x9e, 0xcc, 0xe8, 0xe3, 0x8b, 0x18, 0xf6, 0x94, 0xde, 0x35, 0x3d, 0xb7, 0x26, 0x2d, 0x7a, 0x2d, + 0x3a, 0x9e, 0x3d, 0xe3, 0x4d, 0xcb, 0xbc, 0x6b, 0x99, 0xaf, 0xc1, 0x7b, 0xa1, 0xe0, 0xbd, 0x2d, + 0x35, 0x1a, 0x1f, 0x7c, 0xf9, 0xfd, 0x6d, 0x1c, 0x91, 0xff, 0xb6, 0x74, 0x59, 0x7f, 0x17, 0xb1, + 0x78, 0xf3, 0xe3, 0x18, 0x92, 0xc3, 0x31, 0x24, 0xbf, 0x8e, 0x21, 0xf9, 0x7a, 0x0a, 0x7b, 0x87, + 0x53, 0xd8, 0xfb, 0x79, 0x0a, 0x7b, 0x1f, 0x67, 0x8d, 0x8f, 0xcf, 0xb6, 0x5c, 0x63, 0x9c, 0x81, + 0xd5, 0xe6, 0x33, 0xc8, 0xf2, 0xef, 0x7a, 0x48, 0x34, 0xb9, 0x56, 0xe7, 0x25, 0xd9, 0xdc, 0xd5, + 0xbf, 0x7a, 0xf5, 0x27, 0x00, 0x00, 0xff, 0xff, 0xf5, 0x00, 0xca, 0xe6, 0x42, 0x02, 0x00, 0x00, +} + +func (m *ModuleDescriptor) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ModuleDescriptor) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ModuleDescriptor) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.CanMigrateFrom) > 0 { + for iNdEx := len(m.CanMigrateFrom) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.CanMigrateFrom[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintModule(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if len(m.UsePackage) > 0 { + for iNdEx := len(m.UsePackage) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.UsePackage[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintModule(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if len(m.GoImport) > 0 { + i -= len(m.GoImport) + copy(dAtA[i:], m.GoImport) + i = encodeVarintModule(dAtA, i, uint64(len(m.GoImport))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *PackageReference) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PackageReference) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PackageReference) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Revision != 0 { + i = encodeVarintModule(dAtA, i, uint64(m.Revision)) + i-- + dAtA[i] = 0x10 + } + if len(m.Name) > 0 { + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintModule(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MigrateFromInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MigrateFromInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MigrateFromInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Module) > 0 { + i -= len(m.Module) + copy(dAtA[i:], m.Module) + i = encodeVarintModule(dAtA, i, uint64(len(m.Module))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintModule(dAtA []byte, offset int, v uint64) int { + offset -= sovModule(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *ModuleDescriptor) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.GoImport) + if l > 0 { + n += 1 + l + sovModule(uint64(l)) + } + if len(m.UsePackage) > 0 { + for _, e := range m.UsePackage { + l = e.Size() + n += 1 + l + sovModule(uint64(l)) + } + } + if len(m.CanMigrateFrom) > 0 { + for _, e := range m.CanMigrateFrom { + l = e.Size() + n += 1 + l + sovModule(uint64(l)) + } + } + return n +} + +func (m *PackageReference) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovModule(uint64(l)) + } + if m.Revision != 0 { + n += 1 + sovModule(uint64(m.Revision)) + } + return n +} + +func (m *MigrateFromInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Module) + if l > 0 { + n += 1 + l + sovModule(uint64(l)) + } + return n +} + +func sovModule(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozModule(x uint64) (n int) { + return sovModule(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *ModuleDescriptor) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ModuleDescriptor: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ModuleDescriptor: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field GoImport", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthModule + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.GoImport = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field UsePackage", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthModule + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.UsePackage = append(m.UsePackage, &PackageReference{}) + if err := m.UsePackage[len(m.UsePackage)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CanMigrateFrom", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthModule + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CanMigrateFrom = append(m.CanMigrateFrom, &MigrateFromInfo{}) + if err := m.CanMigrateFrom[len(m.CanMigrateFrom)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PackageReference) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PackageReference: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PackageReference: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthModule + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Revision", wireType) + } + m.Revision = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Revision |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MigrateFromInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MigrateFromInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MigrateFromInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Module", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthModule + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Module = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipModule(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowModule + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowModule + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowModule + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthModule + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupModule + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthModule + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthModule = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowModule = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupModule = fmt.Errorf("proto: unexpected end of group") +) diff --git a/depinject/appconfig/v1alpha1/query.pb.go b/depinject/appconfig/v1alpha1/query.pb.go new file mode 100644 index 0000000000000..363c61fa9cd82 --- /dev/null +++ b/depinject/appconfig/v1alpha1/query.pb.go @@ -0,0 +1,537 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/app/v1alpha1/query.proto + +package v1alpha1 + +import ( + context "context" + fmt "fmt" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// QueryConfigRequest is the Query/Config request type. +type QueryConfigRequest struct { +} + +func (m *QueryConfigRequest) Reset() { *m = QueryConfigRequest{} } +func (m *QueryConfigRequest) String() string { return proto.CompactTextString(m) } +func (*QueryConfigRequest) ProtoMessage() {} +func (*QueryConfigRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_bd84655af543ba53, []int{0} +} +func (m *QueryConfigRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryConfigRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryConfigRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryConfigRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryConfigRequest.Merge(m, src) +} +func (m *QueryConfigRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryConfigRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryConfigRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryConfigRequest proto.InternalMessageInfo + +// QueryConfigResponse is the Query/Config response type. +type QueryConfigResponse struct { + // config is the current app config. + Config *Config `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` +} + +func (m *QueryConfigResponse) Reset() { *m = QueryConfigResponse{} } +func (m *QueryConfigResponse) String() string { return proto.CompactTextString(m) } +func (*QueryConfigResponse) ProtoMessage() {} +func (*QueryConfigResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_bd84655af543ba53, []int{1} +} +func (m *QueryConfigResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryConfigResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryConfigResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryConfigResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryConfigResponse.Merge(m, src) +} +func (m *QueryConfigResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryConfigResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryConfigResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryConfigResponse proto.InternalMessageInfo + +func (m *QueryConfigResponse) GetConfig() *Config { + if m != nil { + return m.Config + } + return nil +} + +func init() { + proto.RegisterType((*QueryConfigRequest)(nil), "cosmos.app.v1alpha1.QueryConfigRequest") + proto.RegisterType((*QueryConfigResponse)(nil), "cosmos.app.v1alpha1.QueryConfigResponse") +} + +func init() { proto.RegisterFile("cosmos/app/v1alpha1/query.proto", fileDescriptor_bd84655af543ba53) } + +var fileDescriptor_bd84655af543ba53 = []byte{ + // 222 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0x4f, 0x2c, 0x28, 0xd0, 0x2f, 0x33, 0x4c, 0xcc, 0x29, 0xc8, 0x48, 0x34, 0xd4, + 0x2f, 0x2c, 0x4d, 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x86, 0x28, 0xd0, + 0x4b, 0x2c, 0x28, 0xd0, 0x83, 0x29, 0x90, 0x52, 0xc0, 0xa6, 0x2b, 0x39, 0x3f, 0x2f, 0x2d, 0x33, + 0x1d, 0xa2, 0x4d, 0x49, 0x84, 0x4b, 0x28, 0x10, 0x64, 0x8a, 0x33, 0x58, 0x30, 0x28, 0xb5, 0xb0, + 0x34, 0xb5, 0xb8, 0x44, 0xc9, 0x8b, 0x4b, 0x18, 0x45, 0xb4, 0xb8, 0x20, 0x3f, 0xaf, 0x38, 0x55, + 0xc8, 0x98, 0x8b, 0x0d, 0xa2, 0x59, 0x82, 0x51, 0x81, 0x51, 0x83, 0xdb, 0x48, 0x5a, 0x0f, 0x8b, + 0xa5, 0x7a, 0x50, 0x4d, 0x50, 0xa5, 0x46, 0x99, 0x5c, 0xac, 0x60, 0xb3, 0x84, 0x12, 0xb8, 0xd8, + 0x20, 0x52, 0x42, 0xea, 0x58, 0xf5, 0x61, 0xba, 0x43, 0x4a, 0x83, 0xb0, 0x42, 0x88, 0xd3, 0x94, + 0x98, 0x3b, 0x98, 0x18, 0x9d, 0x9c, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, + 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, + 0x4a, 0x13, 0x62, 0x4e, 0x71, 0x4a, 0xb6, 0x5e, 0x66, 0xbe, 0x7e, 0x4a, 0x6a, 0x41, 0x66, 0x5e, + 0x56, 0x6a, 0x72, 0x09, 0x28, 0x60, 0x20, 0xce, 0x84, 0x07, 0x4f, 0x12, 0x1b, 0x38, 0x60, 0x8c, + 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x72, 0xe6, 0x07, 0x7f, 0x72, 0x01, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// QueryClient is the client API for Query service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type QueryClient interface { + // Config returns the current app config. + Config(ctx context.Context, in *QueryConfigRequest, opts ...grpc.CallOption) (*QueryConfigResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +// Deprecated: Do not use. +func (c *queryClient) Config(ctx context.Context, in *QueryConfigRequest, opts ...grpc.CallOption) (*QueryConfigResponse, error) { + out := new(QueryConfigResponse) + err := c.cc.Invoke(ctx, "/cosmos.app.v1alpha1.Query/Config", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // Config returns the current app config. + Config(context.Context, *QueryConfigRequest) (*QueryConfigResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) Config(ctx context.Context, req *QueryConfigRequest) (*QueryConfigResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Config not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_Config_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryConfigRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Config(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.app.v1alpha1.Query/Config", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Config(ctx, req.(*QueryConfigRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "cosmos.app.v1alpha1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Config", + Handler: _Query_Config_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "cosmos/app/v1alpha1/query.proto", +} + +func (m *QueryConfigRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryConfigRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryConfigRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryConfigResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryConfigResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryConfigResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Config != nil { + { + size, err := m.Config.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { + offset -= sovQuery(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *QueryConfigRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryConfigResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Config != nil { + l = m.Config.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func sovQuery(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozQuery(x uint64) (n int) { + return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *QueryConfigRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryConfigRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryConfigRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryConfigResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryConfigResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryConfigResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Config == nil { + m.Config = &Config{} + } + if err := m.Config.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipQuery(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthQuery + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupQuery + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthQuery + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") +) diff --git a/depinject/go.mod b/depinject/go.mod index 83f43fb81cf39..086dbfc14784e 100644 --- a/depinject/go.mod +++ b/depinject/go.mod @@ -3,11 +3,11 @@ module cosmossdk.io/depinject go 1.20 require ( - cosmossdk.io/api v0.7.5 github.com/cosmos/cosmos-proto v1.0.0-beta.5 github.com/cosmos/gogoproto v1.5.0 github.com/stretchr/testify v1.9.0 golang.org/x/exp v0.0.0-20231006140011-7918f672742d + google.golang.org/grpc v1.64.1 google.golang.org/protobuf v1.34.2 gotest.tools/v3 v3.5.1 sigs.k8s.io/yaml v1.4.0 @@ -19,11 +19,11 @@ require ( github.com/kr/pretty v0.3.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rogpeppe/go-internal v1.11.0 // indirect + github.com/tendermint/go-amino v0.16.0 // indirect golang.org/x/net v0.27.0 // indirect golang.org/x/sys v0.22.0 // indirect golang.org/x/text v0.16.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20240709173604-40e1e62336c5 // indirect - google.golang.org/grpc v1.64.1 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/depinject/go.sum b/depinject/go.sum index d45197eef76f7..aff372bf6fa8d 100644 --- a/depinject/go.sum +++ b/depinject/go.sum @@ -1,16 +1,18 @@ -cosmossdk.io/api v0.7.5 h1:eMPTReoNmGUm8DeiQL9DyM8sYDjEhWzL1+nLbI9DqtQ= -cosmossdk.io/api v0.7.5/go.mod h1:IcxpYS5fMemZGqyYtErK7OqvdM0C8kdW3dq8Q/XIG38= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= github.com/cosmos/gogoproto v1.5.0 h1:SDVwzEqZDDBoslaeZg+dGE55hdzHfgUA40pEanMh52o= github.com/cosmos/gogoproto v1.5.0/go.mod h1:iUM31aofn3ymidYG6bUR5ZFrk+Om8p5s754eMUcyp8I= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= @@ -24,16 +26,24 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/tendermint/go-amino v0.16.0 h1:GyhmgQKvqF82e2oZeuMSp9JTN0N09emoSZlb2lyGa2E= +github.com/tendermint/go-amino v0.16.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys= golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= +google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto/googleapis/rpc v0.0.0-20240709173604-40e1e62336c5 h1:SbSDUWW1PAO24TNpLdeheoYPd7kllICcLU52x6eD4kQ= google.golang.org/genproto/googleapis/rpc v0.0.0-20240709173604-40e1e62336c5/go.mod h1:Ue6ibwXGpU+dqIcODieyLOcgj7z8+IcskoNIgZxtrFY= google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA= diff --git a/depinject/internal/appconfig/buf.gen.pulsar.yaml b/depinject/internal/appconfig/buf.gen.pulsar.yaml new file mode 100644 index 0000000000000..1866261857af4 --- /dev/null +++ b/depinject/internal/appconfig/buf.gen.pulsar.yaml @@ -0,0 +1,5 @@ +version: v1 +plugins: + - name: go-pulsar + out: . + opt: paths=source_relative diff --git a/depinject/internal/appconfig/buf.gen.yaml b/depinject/internal/appconfig/buf.gen.yaml deleted file mode 100644 index 30a31e9678d3e..0000000000000 --- a/depinject/internal/appconfig/buf.gen.yaml +++ /dev/null @@ -1,11 +0,0 @@ -version: v1 -managed: - enabled: true - go_package_prefix: - default: cosmossdk.io/depinject/internal/appconfig - override: - buf.build/cosmos/cosmos-sdk: cosmossdk.io/api -plugins: - - name: go-pulsar - out: . - opt: paths=source_relative diff --git a/depinject/internal/appconfig/buf.yaml b/depinject/internal/appconfig/buf.yaml index ac1df238ebec9..fffe6eb932cf7 100644 --- a/depinject/internal/appconfig/buf.yaml +++ b/depinject/internal/appconfig/buf.yaml @@ -1,4 +1,6 @@ version: v1 +deps: + - buf.build/cosmos/cosmos-sdk lint: use: - DEFAULT diff --git a/depinject/internal/appconfig/registry.go b/depinject/internal/appconfig/registry.go index a03a3e859a43c..87161353b66ec 100644 --- a/depinject/internal/appconfig/registry.go +++ b/depinject/internal/appconfig/registry.go @@ -5,10 +5,13 @@ import ( "reflect" gogoproto "github.com/cosmos/gogoproto/proto" + "github.com/cosmos/gogoproto/protoc-gen-gogo/descriptor" + "google.golang.org/protobuf/encoding/protowire" protov2 "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protodesc" "google.golang.org/protobuf/reflect/protoreflect" - appv1alpha1 "cosmossdk.io/api/cosmos/app/v1alpha1" + "cosmossdk.io/depinject/appconfig/v1alpha1" ) // ModuleRegistry is the registry of module initializers indexed by their golang @@ -35,12 +38,16 @@ func ModulesByModuleTypeName() (map[string]*ModuleInitializer, error) { fullName := gogoproto.MessageName(initializer.ConfigProtoMessage) if desc, err := gogoproto.HybridResolver.FindDescriptorByName(protoreflect.FullName(fullName)); err == nil { - modDesc := protov2.GetExtension(desc.Options(), appv1alpha1.E_Module).(*appv1alpha1.ModuleDescriptor) + modDesc, err := GetModuleDescriptor(desc) + if err != nil { + return nil, err + } + if modDesc == nil { return nil, fmt.Errorf( "protobuf type %s registered as a module should have the option %s", - fullName, - appv1alpha1.E_Module.TypeDescriptor().FullName()) + desc.FullName(), + v1alpha1.E_Module.Name) } if modDesc.GoImport == "" { @@ -60,3 +67,47 @@ func ModulesByModuleTypeName() (map[string]*ModuleInitializer, error) { return res, nil } + +// GetModuleDescriptor returns the cosmos.app.v1alpha1.ModuleDescriptor or nil if one isn't found. +// Errors are returned in unexpected cases. +func GetModuleDescriptor(desc protoreflect.Descriptor) (*v1alpha1.ModuleDescriptor, error) { + // we need to take a somewhat round about way to get the extension here + // our most complete type registry has a mix of gogoproto and protoreflect types + // so we start with a protoreflect descriptor, convert it to a gogo descriptor + // and then get the extension by its raw field value to avoid any unmarshaling errors + + rawV2Desc := protodesc.ToDescriptorProto(desc.(protoreflect.MessageDescriptor)) + bz, err := protov2.Marshal(rawV2Desc) + if err != nil { + return nil, err + } + var gogoDesc descriptor.DescriptorProto + err = gogoproto.Unmarshal(bz, &gogoDesc) + if err != nil { + return nil, err + } + + opts := gogoDesc.Options + if !gogoproto.HasExtension(opts, v1alpha1.E_Module) { + return nil, nil + } + + bz, err = gogoproto.GetRawExtension(gogoproto.GetUnsafeExtensionsMap(opts), v1alpha1.E_Module.Field) + if err != nil { + return nil, err + } + + // we have to skip the field tag and length prefix itself to actually get the raw bytes we want + // this is really overly complex, but other methods caused runtime errors because of validation + // that gogo does that appears simply not necessary + _, _, n := protowire.ConsumeTag(bz) + bz, _ = protowire.ConsumeBytes(bz[n:]) + + var ext v1alpha1.ModuleDescriptor + err = gogoproto.Unmarshal(bz, &ext) + if err != nil { + return nil, err + } + + return &ext, nil +} diff --git a/depinject/internal/appconfig/testpb/test.proto b/depinject/internal/appconfig/testpb/test.proto index fe6535a2d44a3..ac1a8939e0ecb 100644 --- a/depinject/internal/appconfig/testpb/test.proto +++ b/depinject/internal/appconfig/testpb/test.proto @@ -4,6 +4,8 @@ package testpb; import "cosmos/app/v1alpha1/module.proto"; +option go_package = "cosmossdk.io/depinject/internal/appconfig/testpb"; + message TestRuntimeModule { option (cosmos.app.v1alpha1.module) = { go_import: "cosmossdk.io/core/internal/testpb" diff --git a/depinject/internal/appconfig/testpb/test.pulsar.go b/depinject/internal/appconfig/testpb/test.pulsar.go index 90dcab61cc2bb..2163a1fd63467 100644 --- a/depinject/internal/appconfig/testpb/test.pulsar.go +++ b/depinject/internal/appconfig/testpb/test.pulsar.go @@ -2,7 +2,7 @@ package testpb import ( - _ "cosmossdk.io/api/cosmos/app/v1alpha1" + _ "cosmossdk.io/depinject/appconfig/v1alpha1" fmt "fmt" runtime "github.com/cosmos/cosmos-proto/runtime" protoreflect "google.golang.org/protobuf/reflect/protoreflect" @@ -2344,14 +2344,10 @@ var file_testpb_test_proto_rawDesc = []byte{ 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x22, 0x1e, 0x0a, 0x14, 0x54, 0x65, 0x73, 0x74, 0x4e, 0x6f, 0x47, 0x6f, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x3a, 0x06, 0xba, 0xc0, 0x96, 0xda, - 0x01, 0x00, 0x42, 0x72, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, - 0x42, 0x09, 0x54, 0x65, 0x73, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x21, 0x63, - 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, - 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, - 0xa2, 0x02, 0x03, 0x54, 0x58, 0x58, 0xaa, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xca, - 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xe2, 0x02, 0x12, 0x54, 0x65, 0x73, 0x74, 0x70, - 0x62, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, - 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x01, 0x00, 0x42, 0x32, 0x5a, 0x30, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, + 0x69, 0x6f, 0x2f, 0x64, 0x65, 0x70, 0x69, 0x6e, 0x6a, 0x65, 0x63, 0x74, 0x2f, 0x69, 0x6e, 0x74, + 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x61, 0x70, 0x70, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/depinject/internal/appconfiggogo/buf.gen.gogo.yaml b/depinject/internal/appconfiggogo/buf.gen.gogo.yaml new file mode 100644 index 0000000000000..ca01a181525fe --- /dev/null +++ b/depinject/internal/appconfiggogo/buf.gen.gogo.yaml @@ -0,0 +1,5 @@ +version: v1 +plugins: + - name: gocosmos + out: . + opt: paths=source_relative diff --git a/depinject/internal/appconfiggogo/buf.gen.yaml b/depinject/internal/appconfiggogo/buf.gen.yaml deleted file mode 100644 index 48924f89b9548..0000000000000 --- a/depinject/internal/appconfiggogo/buf.gen.yaml +++ /dev/null @@ -1,11 +0,0 @@ -version: v1 -managed: - enabled: true - go_package_prefix: - default: cosmossdk.io/depinject/internal/appconfiggogo - override: - buf.build/cosmos/cosmos-sdk: cosmossdk.io/api -plugins: - - name: gocosmos - out: . - opt: paths=source_relative diff --git a/depinject/internal/appconfiggogo/buf.yaml b/depinject/internal/appconfiggogo/buf.yaml index ac1df238ebec9..fffe6eb932cf7 100644 --- a/depinject/internal/appconfiggogo/buf.yaml +++ b/depinject/internal/appconfiggogo/buf.yaml @@ -1,4 +1,6 @@ version: v1 +deps: + - buf.build/cosmos/cosmos-sdk lint: use: - DEFAULT diff --git a/depinject/internal/appconfiggogo/testpb/test.pb.go b/depinject/internal/appconfiggogo/testpb/test.pb.go index 583a24afe3eba..64cb974281dbc 100644 --- a/depinject/internal/appconfiggogo/testpb/test.pb.go +++ b/depinject/internal/appconfiggogo/testpb/test.pb.go @@ -4,7 +4,7 @@ package testpb import ( - _ "cosmossdk.io/api/cosmos/app/v1alpha1" + _ "cosmossdk.io/depinject/appconfig/v1alpha1" fmt "fmt" proto "github.com/cosmos/gogoproto/proto" io "io" @@ -66,22 +66,19 @@ func init() { func init() { proto.RegisterFile("testpb/test.proto", fileDescriptor_41c67e33ca9d1f26) } var fileDescriptor_41c67e33ca9d1f26 = []byte{ - // 240 bytes of a gzipped FileDescriptorProto + // 186 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x2c, 0x49, 0x2d, 0x2e, 0x29, 0x48, 0xd2, 0x07, 0x51, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x6c, 0x10, 0x21, 0x29, 0x85, 0xe4, 0xfc, 0xe2, 0xdc, 0xfc, 0x62, 0xfd, 0xc4, 0x82, 0x02, 0xfd, 0x32, 0xc3, 0xc4, 0x9c, - 0x82, 0x8c, 0x44, 0x43, 0xfd, 0xdc, 0xfc, 0x94, 0xd2, 0x9c, 0x54, 0x88, 0x4a, 0x25, 0x6b, 0x2e, - 0xbe, 0x90, 0xd4, 0xe2, 0x12, 0x5f, 0xb0, 0x98, 0x7b, 0x7e, 0x7a, 0xbe, 0x95, 0xe6, 0xae, 0x03, - 0xd3, 0x6e, 0x31, 0x2a, 0x73, 0x29, 0x42, 0xf4, 0x16, 0xa7, 0x64, 0xeb, 0x65, 0xe6, 0xeb, 0x27, - 0xe7, 0x17, 0xa5, 0xea, 0x67, 0xe6, 0x95, 0xa4, 0x16, 0xe5, 0x25, 0xe6, 0xe8, 0x43, 0x8c, 0x77, - 0x9a, 0xcb, 0x78, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, - 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x5c, 0x5c, 0xc9, 0xf9, - 0xb9, 0x7a, 0x50, 0x65, 0x9c, 0x20, 0x1b, 0x02, 0x40, 0xd6, 0x05, 0x30, 0x46, 0x99, 0xa0, 0x18, - 0x9b, 0x92, 0x5a, 0x90, 0x99, 0x97, 0x95, 0x9a, 0x5c, 0x82, 0x30, 0x3b, 0xb1, 0xa0, 0x20, 0x39, - 0x3f, 0x2f, 0x2d, 0x33, 0x3d, 0x3d, 0x3f, 0x3d, 0x1f, 0x6a, 0xd3, 0x22, 0x26, 0xe6, 0x90, 0x88, - 0x88, 0x55, 0x4c, 0x6c, 0x21, 0x60, 0xee, 0x29, 0x18, 0xe3, 0x11, 0x93, 0x10, 0x84, 0x11, 0xe3, - 0x1e, 0xe0, 0xe4, 0x9b, 0x5a, 0x92, 0x98, 0x92, 0x58, 0x92, 0xf8, 0x0a, 0x26, 0x9b, 0xc4, 0x06, - 0xf6, 0xa3, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x2e, 0x9f, 0x4d, 0x9e, 0x22, 0x01, 0x00, 0x00, + 0x82, 0x8c, 0x44, 0x43, 0xfd, 0xdc, 0xfc, 0x94, 0xd2, 0x9c, 0x54, 0x88, 0x4a, 0x25, 0x4f, 0x2e, + 0xbe, 0x90, 0xd4, 0xe2, 0x12, 0x5f, 0xb0, 0x98, 0x7b, 0x7e, 0x7a, 0xbe, 0x95, 0xf9, 0xae, 0x03, + 0xd3, 0x6e, 0x31, 0x1a, 0x72, 0xe9, 0x43, 0xf4, 0x16, 0xa7, 0x64, 0xeb, 0x65, 0xe6, 0xeb, 0x27, + 0xe7, 0x17, 0xa5, 0xea, 0x67, 0xe6, 0x95, 0xa4, 0x16, 0xe5, 0x25, 0xe6, 0x80, 0xcc, 0x4b, 0xce, + 0xcf, 0x4b, 0xcb, 0x4c, 0x4f, 0xcf, 0x4f, 0xcf, 0xd7, 0x87, 0x58, 0xe6, 0xe4, 0x77, 0xe2, 0x91, + 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, + 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x26, 0x28, 0x46, 0xa5, 0xa4, 0x16, 0x64, 0xe6, + 0x65, 0xa5, 0x26, 0x97, 0xe0, 0x37, 0x2f, 0x89, 0x0d, 0xec, 0x42, 0x63, 0x40, 0x00, 0x00, 0x00, + 0xff, 0xff, 0x1e, 0xdb, 0x22, 0xe2, 0xe0, 0x00, 0x00, 0x00, } func (m *TestModuleGogo) Marshal() (dAtA []byte, err error) { diff --git a/depinject/internal/appconfiggogo/testpb/test.proto b/depinject/internal/appconfiggogo/testpb/test.proto index 47294a53b4766..4b2154571d2e7 100644 --- a/depinject/internal/appconfiggogo/testpb/test.proto +++ b/depinject/internal/appconfiggogo/testpb/test.proto @@ -4,6 +4,8 @@ package testpb; import "cosmos/app/v1alpha1/module.proto"; +option go_package = "cosmossdk.io/depinject/internal/appconfiggogo/testpb"; + message TestModuleGogo { option (cosmos.app.v1alpha1.module) = { go_import: "cosmossdk.io/core/internal/appconfiggogo/testpb" diff --git a/docs/architecture/adr-043-nft-module.md b/docs/architecture/adr-043-nft-module.md index 85d439f7ef4d9..5968eb1305aa8 100644 --- a/docs/architecture/adr-043-nft-module.md +++ b/docs/architecture/adr-043-nft-module.md @@ -253,7 +253,7 @@ message QuerySupplyResponse { uint64 amount = 1; } -// QueryNFTstRequest is the request type for the Query/NFTs RPC method +// QueryNFTsRequest is the request type for the Query/NFTs RPC method message QueryNFTsRequest { string class_id = 1; string owner = 2; diff --git a/docs/build/building-apps/02-app-mempool.md b/docs/build/building-apps/02-app-mempool.md index d91593f2fbc99..a9a38fa6d0b38 100644 --- a/docs/build/building-apps/02-app-mempool.md +++ b/docs/build/building-apps/02-app-mempool.md @@ -42,7 +42,7 @@ baseAppOptions = append(baseAppOptions, mempoolOpt) ### No-op Mempool A no-op mempool is a mempool where transactions are completely discarded and ignored when BaseApp interacts with the mempool. -When this mempool is used, it assumed that an application will rely on CometBFT's transaction ordering defined in `RequestPrepareProposal`, +When this mempool is used, it is assumed that an application will rely on CometBFT's transaction ordering defined in `RequestPrepareProposal`, which is FIFO-ordered by default. > Note: If a NoOp mempool is used, PrepareProposal and ProcessProposal both should be aware of this as diff --git a/docs/build/building-apps/03-app-upgrade.md b/docs/build/building-apps/03-app-upgrade.md index 5276b00357628..a38644a40a442 100644 --- a/docs/build/building-apps/03-app-upgrade.md +++ b/docs/build/building-apps/03-app-upgrade.md @@ -22,7 +22,7 @@ This section is currently incomplete. Track the progress of this document [here] Let's assume we are running v0.38.0 of our software in our testnet and want to upgrade to v0.40.0. How would this look in practice? First of all, we want to finalize the v0.40.0 release candidate -and there install a specially named upgrade handler (eg. "testnet-v2" or even "v0.40.0"). An upgrade +and then install a specially named upgrade handler (eg. "testnet-v2" or even "v0.40.0"). An upgrade handler should be defined in a new version of the software to define what migrations to run to migrate from the older version of the software. Naturally, this is app-specific rather than module specific, and must be defined in `app.go`, even if it imports logic from various diff --git a/docs/build/building-modules/01-module-manager.md b/docs/build/building-modules/01-module-manager.md index ce9c229ce6d1c..5370ae41672f5 100644 --- a/docs/build/building-modules/01-module-manager.md +++ b/docs/build/building-modules/01-module-manager.md @@ -30,9 +30,8 @@ There are 2 main application module interfaces: The above interfaces are mostly embedding smaller interfaces (extension interfaces), that defines specific functionalities: - + -* (legacy) `module.HasName`: Allows the module to provide its own name for legacy purposes. * (legacy) [`module.HasGenesisBasics`](#modulehasgenesisbasics): The legacy interface for stateless genesis methods. * (legacy) [`module.HasGenesis`](#modulehasgenesis) for inter-dependent genesis-related module functionalities. * (legacy) [`module.HasABCIGenesis`](#modulehasabcigenesis) for inter-dependent genesis-related module functionalities. @@ -72,19 +71,10 @@ https://github.com/cosmos/cosmos-sdk/blob/eee5e21e1c8d0995b6d4f83b7f55ec0b58d27b * `RegisterGRPCGatewayRoutes(client.Context, *runtime.ServeMux)`: Registers gRPC routes for the module. - -### `HasName` - -```go reference -https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/types/module/module.go#L71-L73 -``` - -* `HasName` is an interface that has a method `Name()`. This method returns the name of the module as a `string`. - ### Genesis :::tip -For easily creating an `AppModule` that only has genesis functionalities, implement `module.HasGenesis/HasABCIGenesis` and `module.HasName`. +For easily creating an `AppModule` that only has genesis functionalities, implement `module.HasGenesis/HasABCIGenesis`. ::: #### `module.HasGenesisBasics` diff --git a/docs/learn/advanced/00-baseapp.md b/docs/learn/advanced/00-baseapp.md index e59eaf4e677f1..8a4fa12b3a15d 100644 --- a/docs/learn/advanced/00-baseapp.md +++ b/docs/learn/advanced/00-baseapp.md @@ -146,7 +146,7 @@ To avoid unnecessary roundtrip to the main state, all reads to the branched stor ### CheckTx State Updates -During `CheckTx`, the `checkState`, which is based off of the last committed state from the root +During `CheckTx`, the `checkState`, which is based on the last committed state from the root store, is used for any reads and writes. Here we only execute the `AnteHandler` and verify a service router exists for every message in the transaction. Note, when we execute the `AnteHandler`, we branch the already branched `checkState`. diff --git a/docs/learn/advanced/07-cli.md b/docs/learn/advanced/07-cli.md index b4932ad4c90df..409effef68019 100644 --- a/docs/learn/advanced/07-cli.md +++ b/docs/learn/advanced/07-cli.md @@ -182,7 +182,7 @@ this will be more convenient: ```shell # define env variables in .env, .envrc etc -NODE_HOME= +GAIA_HOME= GAIA_NODE= GAIA_CHAIN_ID="testchain-1" GAIA_KEYRING_BACKEND="test" diff --git a/docs/rfc/PROCESS.md b/docs/rfc/PROCESS.md index 9517868b55687..a4946cb2a218c 100644 --- a/docs/rfc/PROCESS.md +++ b/docs/rfc/PROCESS.md @@ -1,34 +1,34 @@ # RFC Creation Process 1. Copy the `rfc-template.md` file. Use the following filename pattern: `rfc-next_number-title.md` -2. Create a draft Pull Request if you want to get an early feedback. -3. Make sure the context and a solution is clear and well documented. -4. Add an entry to a list in the [README](./README.md) file. -5. Create a Pull Request to propose a new ADR. +2. Create a draft Pull Request if you want to get early feedback. +3. Make sure the context and solution are clear and well-documented. +4. Add an entry to the list in the [README](./README.md) file. +5. Create a Pull Request to propose a new RFC. ## What is an RFC? -An RFC is a sort of async whiteboarding session. It is meant to replace the need for a distributed team to come together to make a decision. Currently, the Cosmos SDK team and contributors are distributed around the world. The team conducts working groups to have a synchronous discussion and an RFC can be used to capture the discussion for a wider audience to better understand the changes that are coming to the software. +An RFC is a sort of async whiteboarding session. It is meant to replace the need for a distributed team to come together to decide. Currently, the Cosmos SDK team and contributors are distributed around the world. The team conducts working groups to have a synchronous discussion, and an RFC can be used to capture the discussion for a wider audience to better understand the changes that are coming to the software. -The main difference the Cosmos SDK is defining as a differentiation between RFC and ADRs is that one is to come to consensus and circulate information about a potential change or feature. An ADR is used if there is already consensus on a feature or change and there is not a need to articulate the change coming to the software. An ADR will articulate the changes and have a lower amount of communication . +The main difference the Cosmos SDK defines between RFCs and ADRs is that an RFC is to come to consensus and circulate information about a potential change or feature. An ADR is used if there is already consensus on a feature or change and there is no need to articulate the change coming to the software. An ADR will articulate the changes and require less communication. ## RFC life cycle -RFC creation is an **iterative** process. An RFC is meant as a distributed collaboration session, it may have many comments and is usually the bi-product of no working group or synchronous communication +RFC creation is an **iterative** process. An RFC is meant as a distributed collaboration session, it may have many comments and is usually the by-product of no working group or synchronous communication. -1. Proposals could start with a new GitHub Issue, be a result of existing Issues or a discussion. +1. Proposals could start with a new GitHub Issue, be a result of existing Issues or a discussion. 2. An RFC doesn't have to arrive to `main` with an _accepted_ status in a single PR. If the motivation is clear and the solution is sound, we SHOULD be able to merge it and keep a _proposed_ status. It's preferable to have an iterative approach rather than long, not merged Pull Requests. 3. If a _proposed_ RFC is merged, then it should clearly document outstanding issues either in the RFC document notes or in a GitHub Issue. -4. The PR SHOULD always be merged. In the case of a faulty RFC, we still prefer to merge it with a _rejected_ status. The only time the RFC SHOULD NOT be merged is if the author abandons it. +4. The PR SHOULD always be merged. In the case of a faulty RFC, we still prefer to merge it with a _rejected_ status. The only time the RFC SHOULD NOT be merged is if the author abandons it. 5. Merged RFCs SHOULD NOT be pruned. -6. If there is consensus and enough feedback then the RFC can be accepted. +6. If there is consensus and enough feedback then the RFC can be accepted. -> Note: An RFC is written when there is no working group or team session on the problem. RFC's are meant as a distributed white boarding session. If there is a working group on the proposal there is no need to have an RFC as there is synchronous whiteboarding going on. +> Note: An RFC is written when there is no working group or team session on the problem. RFCs are meant as a distributed whiteboarding session. If there is a working group on the proposal, there is no need to have an RFC as there is synchronous whiteboarding going on. ### RFC status @@ -41,22 +41,22 @@ Status has two components: #### Consensus Status ```text -DRAFT -> PROPOSED -> LAST CALL yyyy-mm-dd -> ACCEPTED | REJECTED -> SUPERSEDED by ADR-xxx +DRAFT -> PROPOSED -> LAST CALL yyyy-mm-dd -> ACCEPTED | REJECTED -> SUPERSEDED by RFC-xxx \ | \ | v v ABANDONED ``` -* `DRAFT`: [optional] an ADR which is work in progress, not being ready for a general review. This is to present an early work and get an early feedback in a Draft Pull Request form. -* `PROPOSED`: an ADR covering a full solution architecture and still in the review - project stakeholders haven't reached an agreed yet. -* `LAST CALL `: [optional] clear notify that we are close to accept updates. Changing a status to `LAST CALL` means that social consensus (of Cosmos SDK maintainers) has been reached and we still want to give it a time to let the community react or analyze. -* `ACCEPTED`: ADR which will represent a currently implemented or to be implemented architecture design. -* `REJECTED`: ADR can go from PROPOSED or ACCEPTED to rejected if the consensus among project stakeholders will decide so. -* `SUPERSEDED by ADR-xxx`: ADR which has been superseded by a new ADR. -* `ABANDONED`: the ADR is no longer pursued by the original authors. +* `DRAFT`: [optional] an RFC which is work in progress, not being ready for a general review. This is to present early work and get early feedback in a Draft Pull Request form. +* `PROPOSED`: an RFC covering a full solution architecture and still in review - project stakeholders haven't reached an agreement yet. +* `LAST CALL `: [optional] clearly notify that we are close to accepting updates. Changing a status to `LAST CALL` means that social consensus (of Cosmos SDK maintainers) has been reached, and we still want to give it time to let the community react or analyze. +* `ACCEPTED`: RFC which will represent a currently implemented or to be implemented architecture design. +* `REJECTED`: RFC can go from PROPOSED or ACCEPTED to rejected if the consensus among project stakeholders decides so. +* `SUPERSEDED by RFC-xxx`: RFC which has been superseded by a new RFC. +* `ABANDONED`: the RFC is no longer pursued by the original authors. ## Language used in RFC * The background/goal should be written in the present tense. -* Avoid using a first, personal form. +* Avoid using a first-person form. diff --git a/go.mod b/go.mod index 89281f6822463..00df79575de4c 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,7 @@ require ( cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/log v1.3.1 cosmossdk.io/math v1.3.0 @@ -25,7 +25,7 @@ require ( github.com/cosmos/btcutil v1.0.5 github.com/cosmos/cosmos-db v1.0.2 github.com/cosmos/cosmos-proto v1.0.0-beta.5 - github.com/cosmos/crypto v0.1.1 + github.com/cosmos/crypto v0.1.2 github.com/cosmos/go-bip39 v1.0.0 github.com/cosmos/gogogateway v1.2.0 github.com/cosmos/gogoproto v1.5.0 @@ -188,7 +188,6 @@ replace ( cosmossdk.io/collections => ./collections cosmossdk.io/core => ./core cosmossdk.io/core/testing => ./core/testing - cosmossdk.io/depinject => ./depinject cosmossdk.io/log => ./log cosmossdk.io/store => ./store cosmossdk.io/x/accounts => ./x/accounts diff --git a/go.sum b/go.sum index 9a6c9c5693486..d990868be5f00 100644 --- a/go.sum +++ b/go.sum @@ -4,6 +4,8 @@ buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88e buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2/go.mod h1:HqcXMSa5qnNuakaMUo+hWhF51mKbcrZxGl9Vp5EeJXc= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -95,8 +97,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/go.work.example b/go.work.example index 5e0f392aad4ef..035cbb3e34968 100644 --- a/go.work.example +++ b/go.work.example @@ -9,6 +9,7 @@ use ( ./core/testing ./depinject ./errors + ./indexer/postgres ./log ./math ./orm diff --git a/indexer/postgres/CHANGELOG.md b/indexer/postgres/CHANGELOG.md new file mode 100644 index 0000000000000..0c3c9d03857f6 --- /dev/null +++ b/indexer/postgres/CHANGELOG.md @@ -0,0 +1,37 @@ + + +# Changelog + +## [Unreleased] diff --git a/indexer/postgres/README.md b/indexer/postgres/README.md new file mode 100644 index 0000000000000..bb8c480f664ea --- /dev/null +++ b/indexer/postgres/README.md @@ -0,0 +1,41 @@ +# PostgreSQL Indexer + +The PostgreSQL indexer can fully index the current state for all modules that implement `cosmossdk.io/schema.HasModuleCodec`. +implement `cosmossdk.io/schema.HasModuleCodec`. + +## Table, Column and Enum Naming + +`ObjectType`s names are converted to table names prefixed with the module name and an underscore. i.e. the `ObjectType` `foo` in module `bar` will be stored in a table named `bar_foo`. + +Column names are identical to field names. All identifiers are quoted with double quotes so that they are case-sensitive and won't clash with any reserved names. + +Like, table names, enum types are prefixed with the module name and an underscore. + +## Schema Type Mapping + +The mapping of `cosmossdk.io/schema` `Kind`s to PostgreSQL types is as follows: + +| Kind | PostgreSQL Type | Notes | +|---------------------|----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `StringKind` | `TEXT` | | +| `BoolKind` | `BOOLEAN` | | +| `BytesKind` | `BYTEA` | | +| `Int8Kind` | `SMALLINT` | | +| `Int16Kind` | `SMALLINT` | | +| `Int32Kind` | `INTEGER` | | +| `Int64Kind` | `BIGINT` | | +| `Uint8Kind` | `SMALLINT` | | +| `Uint16Kind` | `INTEGER` | | +| `Uint32Kind` | `BIGINT` | | +| `Uint64Kind` | `NUMERIC` | | +| `Float32Kind` | `REAL` | | +| `Float64Kind` | `DOUBLE PRECISION` | | +| `IntegerStringKind` | `NUMERIC` | | +| `DecimalStringKind` | `NUMERIC` | | +| `JSONKind` | `JSONB` | | +| `Bech32AddressKind` | `TEXT` | addresses are converted to strings with the specified address prefix | +| `TimeKind` | `BIGINT` and `TIMESTAMPTZ` | time types are stored as two columns, one with the `_nanos` suffix with full nanoseconds precision, and another as a `TIMESTAMPTZ` generated column with microsecond precision | +| `DurationKind` | `BIGINT` | durations are stored as a single column in nanoseconds | +| `EnumKind` | `_` | a custom enum type is created for each module prefixed with the module name it pertains to | + + diff --git a/indexer/postgres/base_sql.go b/indexer/postgres/base_sql.go new file mode 100644 index 0000000000000..81e1ac704242a --- /dev/null +++ b/indexer/postgres/base_sql.go @@ -0,0 +1,8 @@ +package postgres + +// BaseSQL is the base SQL that is always included in the schema. +const BaseSQL = ` +CREATE OR REPLACE FUNCTION nanos_to_timestamptz(nanos bigint) RETURNS timestamptz AS $$ + SELECT to_timestamp(nanos / 1000000000) + (nanos / 1000000000) * INTERVAL '1 microsecond' +$$ LANGUAGE SQL IMMUTABLE; +` diff --git a/indexer/postgres/column.go b/indexer/postgres/column.go new file mode 100644 index 0000000000000..f9692af137117 --- /dev/null +++ b/indexer/postgres/column.go @@ -0,0 +1,120 @@ +package postgres + +import ( + "fmt" + "io" + + "cosmossdk.io/schema" +) + +// createColumnDefinition writes a column definition within a CREATE TABLE statement for the field. +func (tm *ObjectIndexer) createColumnDefinition(writer io.Writer, field schema.Field) error { + _, err := fmt.Fprintf(writer, "%q ", field.Name) + if err != nil { + return err + } + + simple := simpleColumnType(field.Kind) + if simple != "" { + _, err = fmt.Fprintf(writer, "%s", simple) + if err != nil { + return err + } + + return writeNullability(writer, field.Nullable) + } else { + switch field.Kind { + case schema.EnumKind: + _, err = fmt.Fprintf(writer, "%q", enumTypeName(tm.moduleName, field.EnumDefinition)) + if err != nil { + return err + } + case schema.TimeKind: + // for time fields, we generate two columns: + // - one with nanoseconds precision for lossless storage, suffixed with _nanos + // - one as a timestamptz (microsecond precision) for ease of use, that is GENERATED + nanosColName := fmt.Sprintf("%s_nanos", field.Name) + _, err = fmt.Fprintf(writer, "TIMESTAMPTZ GENERATED ALWAYS AS (nanos_to_timestamptz(%q)) STORED,\n\t", nanosColName) + if err != nil { + return err + } + + _, err = fmt.Fprintf(writer, `%q BIGINT`, nanosColName) + if err != nil { + return err + } + default: + return fmt.Errorf("unexpected kind: %v, this should have been handled earlier", field.Kind) + } + + return writeNullability(writer, field.Nullable) + } +} + +// writeNullability writes column nullability. +func writeNullability(writer io.Writer, nullable bool) error { + if nullable { + _, err := fmt.Fprintf(writer, " NULL,\n\t") + return err + } else { + _, err := fmt.Fprintf(writer, " NOT NULL,\n\t") + return err + } +} + +// simpleColumnType returns the postgres column type for the kind for simple types. +func simpleColumnType(kind schema.Kind) string { + //nolint:goconst // adding constants for these postgres type names would impede readability + switch kind { + case schema.StringKind: + return "TEXT" + case schema.BoolKind: + return "BOOLEAN" + case schema.BytesKind: + return "BYTEA" + case schema.Int8Kind: + return "SMALLINT" + case schema.Int16Kind: + return "SMALLINT" + case schema.Int32Kind: + return "INTEGER" + case schema.Int64Kind: + return "BIGINT" + case schema.Uint8Kind: + return "SMALLINT" + case schema.Uint16Kind: + return "INTEGER" + case schema.Uint32Kind: + return "BIGINT" + case schema.Uint64Kind: + return "NUMERIC" + case schema.IntegerStringKind: + return "NUMERIC" + case schema.DecimalStringKind: + return "NUMERIC" + case schema.Float32Kind: + return "REAL" + case schema.Float64Kind: + return "DOUBLE PRECISION" + case schema.JSONKind: + return "JSONB" + case schema.DurationKind: + return "BIGINT" + case schema.Bech32AddressKind: + return "TEXT" + default: + return "" + } +} + +// updatableColumnName is the name of the insertable/updatable column name for the field. +// This is the field name in most cases, except for time columns which are stored as nanos +// and then converted to timestamp generated columns. +func (tm *ObjectIndexer) updatableColumnName(field schema.Field) (name string, err error) { + name = field.Name + if field.Kind == schema.TimeKind { + name = fmt.Sprintf("%s_nanos", name) + } + name = fmt.Sprintf("%q", name) + return +} diff --git a/indexer/postgres/conn.go b/indexer/postgres/conn.go new file mode 100644 index 0000000000000..de8c1cac6b473 --- /dev/null +++ b/indexer/postgres/conn.go @@ -0,0 +1,14 @@ +package postgres + +import ( + "context" + "database/sql" +) + +// DBConn is an interface that abstracts the *sql.DB, *sql.Tx and *sql.Conn types. +type DBConn interface { + ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) + PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) + QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) + QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row +} diff --git a/indexer/postgres/create_table.go b/indexer/postgres/create_table.go new file mode 100644 index 0000000000000..8f5f0e6ca2069 --- /dev/null +++ b/indexer/postgres/create_table.go @@ -0,0 +1,96 @@ +package postgres + +import ( + "context" + "fmt" + "io" + "strings" +) + +// CreateTable creates the table for the object type. +func (tm *ObjectIndexer) CreateTable(ctx context.Context, conn DBConn) error { + buf := new(strings.Builder) + err := tm.CreateTableSql(buf) + if err != nil { + return err + } + + sqlStr := buf.String() + if tm.options.Logger != nil { + tm.options.Logger(fmt.Sprintf("Creating table %s", tm.TableName()), sqlStr) + } + _, err = conn.ExecContext(ctx, sqlStr) + return err +} + +// CreateTableSql generates a CREATE TABLE statement for the object type. +func (tm *ObjectIndexer) CreateTableSql(writer io.Writer) error { + _, err := fmt.Fprintf(writer, "CREATE TABLE IF NOT EXISTS %q (\n\t", tm.TableName()) + if err != nil { + return err + } + isSingleton := false + if len(tm.typ.KeyFields) == 0 { + isSingleton = true + _, err = fmt.Fprintf(writer, "_id INTEGER NOT NULL CHECK (_id = 1),\n\t") + if err != nil { + return err + } + } else { + for _, field := range tm.typ.KeyFields { + err = tm.createColumnDefinition(writer, field) + if err != nil { + return err + } + } + } + + for _, field := range tm.typ.ValueFields { + err = tm.createColumnDefinition(writer, field) + if err != nil { + return err + } + } + + // add _deleted column when we have RetainDeletions set and enabled + if !tm.options.DisableRetainDeletions && tm.typ.RetainDeletions { + _, err = fmt.Fprintf(writer, "_deleted BOOLEAN NOT NULL DEFAULT FALSE,\n\t") + if err != nil { + return err + } + } + + var pKeys []string + if !isSingleton { + for _, field := range tm.typ.KeyFields { + name, err := tm.updatableColumnName(field) + if err != nil { + return err + } + + pKeys = append(pKeys, name) + } + } else { + pKeys = []string{"_id"} + } + + _, err = fmt.Fprintf(writer, "PRIMARY KEY (%s)", strings.Join(pKeys, ", ")) + if err != nil { + return err + } + + _, err = fmt.Fprintf(writer, "\n);\n") + if err != nil { + return err + } + + // we GRANT SELECT on the table to PUBLIC so that the table is automatically available + // for querying using off-the-shelf tools like pg_graphql, Postgrest, Postgraphile, etc. + // without any login permissions + _, err = fmt.Fprintf(writer, "GRANT SELECT ON TABLE %q TO PUBLIC;", tm.TableName()) + if err != nil { + return err + } + + return nil +} diff --git a/indexer/postgres/create_table_test.go b/indexer/postgres/create_table_test.go new file mode 100644 index 0000000000000..dec09d7aed7af --- /dev/null +++ b/indexer/postgres/create_table_test.go @@ -0,0 +1,94 @@ +package postgres + +import ( + "os" + + "cosmossdk.io/indexer/postgres/internal/testdata" + "cosmossdk.io/schema" +) + +func ExampleObjectIndexer_CreateTableSql_allKinds() { + exampleCreateTable(testdata.AllKindsObject) + // Output: + // CREATE TABLE IF NOT EXISTS "test_all_kinds" ( + // "id" BIGINT NOT NULL, + // "ts" TIMESTAMPTZ GENERATED ALWAYS AS (nanos_to_timestamptz("ts_nanos")) STORED, + // "ts_nanos" BIGINT NOT NULL, + // "string" TEXT NOT NULL, + // "bytes" BYTEA NOT NULL, + // "int8" SMALLINT NOT NULL, + // "uint8" SMALLINT NOT NULL, + // "int16" SMALLINT NOT NULL, + // "uint16" INTEGER NOT NULL, + // "int32" INTEGER NOT NULL, + // "uint32" BIGINT NOT NULL, + // "int64" BIGINT NOT NULL, + // "uint64" NUMERIC NOT NULL, + // "integer" NUMERIC NOT NULL, + // "decimal" NUMERIC NOT NULL, + // "bool" BOOLEAN NOT NULL, + // "time" TIMESTAMPTZ GENERATED ALWAYS AS (nanos_to_timestamptz("time_nanos")) STORED, + // "time_nanos" BIGINT NOT NULL, + // "duration" BIGINT NOT NULL, + // "float32" REAL NOT NULL, + // "float64" DOUBLE PRECISION NOT NULL, + // "bech32address" TEXT NOT NULL, + // "enum" "test_my_enum" NOT NULL, + // "json" JSONB NOT NULL, + // PRIMARY KEY ("id", "ts_nanos") + // ); + // GRANT SELECT ON TABLE "test_all_kinds" TO PUBLIC; +} + +func ExampleObjectIndexer_CreateTableSql_singleton() { + exampleCreateTable(testdata.SingletonObject) + // Output: + // CREATE TABLE IF NOT EXISTS "test_singleton" ( + // _id INTEGER NOT NULL CHECK (_id = 1), + // "foo" TEXT NOT NULL, + // "bar" INTEGER NULL, + // "an_enum" "test_my_enum" NOT NULL, + // PRIMARY KEY (_id) + // ); + // GRANT SELECT ON TABLE "test_singleton" TO PUBLIC; +} + +func ExampleObjectIndexer_CreateTableSql_vote() { + exampleCreateTable(testdata.VoteObject) + // Output: + // CREATE TABLE IF NOT EXISTS "test_vote" ( + // "proposal" BIGINT NOT NULL, + // "address" TEXT NOT NULL, + // "vote" "test_vote_type" NOT NULL, + // _deleted BOOLEAN NOT NULL DEFAULT FALSE, + // PRIMARY KEY ("proposal", "address") + // ); + // GRANT SELECT ON TABLE "test_vote" TO PUBLIC; +} + +func ExampleObjectIndexer_CreateTableSql_vote_no_retain_delete() { + exampleCreateTableOpt(testdata.VoteObject, true) + // Output: + // CREATE TABLE IF NOT EXISTS "test_vote" ( + // "proposal" BIGINT NOT NULL, + // "address" TEXT NOT NULL, + // "vote" "test_vote_type" NOT NULL, + // PRIMARY KEY ("proposal", "address") + // ); + // GRANT SELECT ON TABLE "test_vote" TO PUBLIC; +} + +func exampleCreateTable(objectType schema.ObjectType) { + exampleCreateTableOpt(objectType, false) +} + +func exampleCreateTableOpt(objectType schema.ObjectType, noRetainDelete bool) { + tm := NewObjectIndexer("test", objectType, Options{ + Logger: func(msg, sql string, params ...interface{}) {}, + DisableRetainDeletions: noRetainDelete, + }) + err := tm.CreateTableSql(os.Stdout) + if err != nil { + panic(err) + } +} diff --git a/indexer/postgres/enum.go b/indexer/postgres/enum.go new file mode 100644 index 0000000000000..c438257d20205 --- /dev/null +++ b/indexer/postgres/enum.go @@ -0,0 +1,92 @@ +package postgres + +import ( + "context" + "database/sql" + "fmt" + "io" + "strings" + + "cosmossdk.io/schema" +) + +// CreateEnumType creates an enum type in the database. +func (m *ModuleIndexer) CreateEnumType(ctx context.Context, conn DBConn, enum schema.EnumDefinition) error { + typeName := enumTypeName(m.moduleName, enum) + row := conn.QueryRowContext(ctx, "SELECT 1 FROM pg_type WHERE typname = $1", typeName) + var res interface{} + if err := row.Scan(&res); err != nil { + if err != sql.ErrNoRows { + return fmt.Errorf("failed to check if enum type %q exists: %v", typeName, err) //nolint:errorlint // using %v for go 1.12 compat + } + } else { + // the enum type already exists + return nil + } + + buf := new(strings.Builder) + err := CreateEnumTypeSql(buf, m.moduleName, enum) + if err != nil { + return err + } + + sqlStr := buf.String() + if m.options.Logger != nil { + m.options.Logger("Creating enum type", sqlStr) + } + _, err = conn.ExecContext(ctx, sqlStr) + return err +} + +// CreateEnumTypeSql generates a CREATE TYPE statement for the enum definition. +func CreateEnumTypeSql(writer io.Writer, moduleName string, enum schema.EnumDefinition) error { + _, err := fmt.Fprintf(writer, "CREATE TYPE %q AS ENUM (", enumTypeName(moduleName, enum)) + if err != nil { + return err + } + + for i, value := range enum.Values { + if i > 0 { + _, err = fmt.Fprintf(writer, ", ") + if err != nil { + return err + } + } + _, err = fmt.Fprintf(writer, "'%s'", value) + if err != nil { + return err + } + } + + _, err = fmt.Fprintf(writer, ");") + return err +} + +// enumTypeName returns the name of the enum type scoped to the module. +func enumTypeName(moduleName string, enum schema.EnumDefinition) string { + return fmt.Sprintf("%s_%s", moduleName, enum.Name) +} + +// createEnumTypesForFields creates enum types for all the fields that have enum kind in the module schema. +func (m *ModuleIndexer) createEnumTypesForFields(ctx context.Context, conn DBConn, fields []schema.Field) error { + for _, field := range fields { + if field.Kind != schema.EnumKind { + continue + } + + if _, ok := m.definedEnums[field.EnumDefinition.Name]; ok { + // if the enum type is already defined, skip + // we assume validation already happened + continue + } + + err := m.CreateEnumType(ctx, conn, field.EnumDefinition) + if err != nil { + return err + } + + m.definedEnums[field.EnumDefinition.Name] = field.EnumDefinition + } + + return nil +} diff --git a/indexer/postgres/enum_test.go b/indexer/postgres/enum_test.go new file mode 100644 index 0000000000000..22d8870171c36 --- /dev/null +++ b/indexer/postgres/enum_test.go @@ -0,0 +1,16 @@ +package postgres + +import ( + "os" + + "cosmossdk.io/indexer/postgres/internal/testdata" +) + +func ExampleCreateEnumTypeSql() { + err := CreateEnumTypeSql(os.Stdout, "test", testdata.MyEnum) + if err != nil { + panic(err) + } + // Output: + // CREATE TYPE "test_my_enum" AS ENUM ('a', 'b', 'c'); +} diff --git a/indexer/postgres/go.mod b/indexer/postgres/go.mod new file mode 100644 index 0000000000000..d85dbc46718e5 --- /dev/null +++ b/indexer/postgres/go.mod @@ -0,0 +1,11 @@ +module cosmossdk.io/indexer/postgres + +// NOTE: we are staying on an earlier version of golang to avoid problems building +// with older codebases. +go 1.12 + +// NOTE: cosmossdk.io/schema should be the only dependency here +// so there are no problems building this with any version of the SDK. +// This module should only use the golang standard library (database/sql) +// and cosmossdk.io/indexer/base. +require cosmossdk.io/schema v0.1.1 diff --git a/indexer/postgres/go.sum b/indexer/postgres/go.sum new file mode 100644 index 0000000000000..6a92c3d3ec663 --- /dev/null +++ b/indexer/postgres/go.sum @@ -0,0 +1,2 @@ +cosmossdk.io/schema v0.1.1 h1:I0M6pgI7R10nq+/HCQfbO6BsGBZA8sQy+duR1Y3aKcA= +cosmossdk.io/schema v0.1.1/go.mod h1:RDAhxIeNB4bYqAlF4NBJwRrgtnciMcyyg0DOKnhNZQQ= diff --git a/indexer/postgres/indexer.go b/indexer/postgres/indexer.go new file mode 100644 index 0000000000000..afcd8e0d8dbfc --- /dev/null +++ b/indexer/postgres/indexer.go @@ -0,0 +1,80 @@ +package postgres + +import ( + "context" + "database/sql" + "fmt" + + "cosmossdk.io/schema/appdata" +) + +type Config struct { + // DatabaseURL is the PostgreSQL connection URL to use to connect to the database. + DatabaseURL string `json:"database_url"` + + // DatabaseDriver is the PostgreSQL database/sql driver to use. This defaults to "pgx". + DatabaseDriver string `json:"database_driver"` + + // DisableRetainDeletions disables the retain deletions functionality even if it is set in an object type schema. + DisableRetainDeletions bool `json:"disable_retain_deletions"` +} + +type SqlLogger = func(msg, sql string, params ...interface{}) + +func StartIndexer(ctx context.Context, logger SqlLogger, config Config) (appdata.Listener, error) { + if config.DatabaseURL == "" { + return appdata.Listener{}, fmt.Errorf("missing database URL") + } + + driver := config.DatabaseDriver + if driver == "" { + driver = "pgx" + } + + db, err := sql.Open(driver, config.DatabaseURL) + if err != nil { + return appdata.Listener{}, err + } + + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return appdata.Listener{}, err + } + + // commit base schema + _, err = tx.Exec(BaseSQL) + if err != nil { + return appdata.Listener{}, err + } + + moduleIndexers := map[string]*ModuleIndexer{} + opts := Options{ + DisableRetainDeletions: config.DisableRetainDeletions, + Logger: logger, + } + + return appdata.Listener{ + InitializeModuleData: func(data appdata.ModuleInitializationData) error { + moduleName := data.ModuleName + modSchema := data.Schema + _, ok := moduleIndexers[moduleName] + if ok { + return fmt.Errorf("module %s already initialized", moduleName) + } + + mm := NewModuleIndexer(moduleName, modSchema, opts) + moduleIndexers[moduleName] = mm + + return mm.InitializeSchema(ctx, tx) + }, + Commit: func(data appdata.CommitData) error { + err = tx.Commit() + if err != nil { + return err + } + + tx, err = db.BeginTx(ctx, nil) + return err + }, + }, nil +} diff --git a/indexer/postgres/internal/testdata/example_schema.go b/indexer/postgres/internal/testdata/example_schema.go new file mode 100644 index 0000000000000..ccdd39d96c35b --- /dev/null +++ b/indexer/postgres/internal/testdata/example_schema.go @@ -0,0 +1,98 @@ +package testdata + +import "cosmossdk.io/schema" + +var ExampleSchema schema.ModuleSchema + +var AllKindsObject schema.ObjectType + +func init() { + AllKindsObject = schema.ObjectType{ + Name: "all_kinds", + KeyFields: []schema.Field{ + { + Name: "id", + Kind: schema.Int64Kind, + }, + { + Name: "ts", + Kind: schema.TimeKind, + }, + }, + } + + for i := schema.InvalidKind + 1; i <= schema.MAX_VALID_KIND; i++ { + field := schema.Field{ + Name: i.String(), + Kind: i, + } + + switch i { + case schema.EnumKind: + field.EnumDefinition = MyEnum + case schema.Bech32AddressKind: + field.AddressPrefix = "foo" + default: + } + + AllKindsObject.ValueFields = append(AllKindsObject.ValueFields, field) + } + + ExampleSchema = schema.ModuleSchema{ + ObjectTypes: []schema.ObjectType{ + AllKindsObject, + SingletonObject, + VoteObject, + }, + } +} + +var SingletonObject = schema.ObjectType{ + Name: "singleton", + ValueFields: []schema.Field{ + { + Name: "foo", + Kind: schema.StringKind, + }, + { + Name: "bar", + Kind: schema.Int32Kind, + Nullable: true, + }, + { + Name: "an_enum", + Kind: schema.EnumKind, + EnumDefinition: MyEnum, + }, + }, +} + +var VoteObject = schema.ObjectType{ + Name: "vote", + KeyFields: []schema.Field{ + { + Name: "proposal", + Kind: schema.Int64Kind, + }, + { + Name: "address", + Kind: schema.Bech32AddressKind, + }, + }, + ValueFields: []schema.Field{ + { + Name: "vote", + Kind: schema.EnumKind, + EnumDefinition: schema.EnumDefinition{ + Name: "vote_type", + Values: []string{"yes", "no", "abstain"}, + }, + }, + }, + RetainDeletions: true, +} + +var MyEnum = schema.EnumDefinition{ + Name: "my_enum", + Values: []string{"a", "b", "c"}, +} diff --git a/indexer/postgres/module.go b/indexer/postgres/module.go new file mode 100644 index 0000000000000..57564700b78a6 --- /dev/null +++ b/indexer/postgres/module.go @@ -0,0 +1,61 @@ +package postgres + +import ( + "context" + "fmt" + + "cosmossdk.io/schema" +) + +// ModuleIndexer manages the tables for a module. +type ModuleIndexer struct { + moduleName string + schema schema.ModuleSchema + tables map[string]*ObjectIndexer + definedEnums map[string]schema.EnumDefinition + options Options +} + +// NewModuleIndexer creates a new ModuleIndexer for the given module schema. +func NewModuleIndexer(moduleName string, modSchema schema.ModuleSchema, options Options) *ModuleIndexer { + return &ModuleIndexer{ + moduleName: moduleName, + schema: modSchema, + tables: map[string]*ObjectIndexer{}, + definedEnums: map[string]schema.EnumDefinition{}, + options: options, + } +} + +// InitializeSchema creates tables for all object types in the module schema and creates enum types. +func (m *ModuleIndexer) InitializeSchema(ctx context.Context, conn DBConn) error { + // create enum types + for _, typ := range m.schema.ObjectTypes { + err := m.createEnumTypesForFields(ctx, conn, typ.KeyFields) + if err != nil { + return err + } + + err = m.createEnumTypesForFields(ctx, conn, typ.ValueFields) + if err != nil { + return err + } + } + + // create tables for all object types + for _, typ := range m.schema.ObjectTypes { + tm := NewObjectIndexer(m.moduleName, typ, m.options) + m.tables[typ.Name] = tm + err := tm.CreateTable(ctx, conn) + if err != nil { + return fmt.Errorf("failed to create table for %s in module %s: %v", typ.Name, m.moduleName, err) //nolint:errorlint // using %v for go 1.12 compat + } + } + + return nil +} + +// ObjectIndexers returns the object indexers for the module. +func (m *ModuleIndexer) ObjectIndexers() map[string]*ObjectIndexer { + return m.tables +} diff --git a/indexer/postgres/object.go b/indexer/postgres/object.go new file mode 100644 index 0000000000000..78bbfdf636b11 --- /dev/null +++ b/indexer/postgres/object.go @@ -0,0 +1,44 @@ +package postgres + +import ( + "fmt" + + "cosmossdk.io/schema" +) + +// ObjectIndexer is a helper struct that generates SQL for a given object type. +type ObjectIndexer struct { + moduleName string + typ schema.ObjectType + valueFields map[string]schema.Field + allFields map[string]schema.Field + options Options +} + +// NewObjectIndexer creates a new ObjectIndexer for the given object type. +func NewObjectIndexer(moduleName string, typ schema.ObjectType, options Options) *ObjectIndexer { + allFields := make(map[string]schema.Field) + valueFields := make(map[string]schema.Field) + + for _, field := range typ.KeyFields { + allFields[field.Name] = field + } + + for _, field := range typ.ValueFields { + valueFields[field.Name] = field + allFields[field.Name] = field + } + + return &ObjectIndexer{ + moduleName: moduleName, + typ: typ, + allFields: allFields, + valueFields: valueFields, + options: options, + } +} + +// TableName returns the name of the table for the object type scoped to its module. +func (tm *ObjectIndexer) TableName() string { + return fmt.Sprintf("%s_%s", tm.moduleName, tm.typ.Name) +} diff --git a/indexer/postgres/options.go b/indexer/postgres/options.go new file mode 100644 index 0000000000000..be93d43b6c76b --- /dev/null +++ b/indexer/postgres/options.go @@ -0,0 +1,10 @@ +package postgres + +// Options are the options for module and object indexers. +type Options struct { + // DisableRetainDeletions disables retain deletions functionality even on object types that have it set. + DisableRetainDeletions bool + + // Logger is the logger for the indexer to use. + Logger SqlLogger +} diff --git a/indexer/postgres/sonar-project.properties b/indexer/postgres/sonar-project.properties new file mode 100644 index 0000000000000..6d7366413a15d --- /dev/null +++ b/indexer/postgres/sonar-project.properties @@ -0,0 +1,16 @@ +sonar.projectKey=cosmos-sdk-indexer-postgres +sonar.organization=cosmos + +sonar.projectName=Cosmos SDK - Postgres Indexer +sonar.project.monorepo.enabled=true + +sonar.sources=. +sonar.exclusions=**/*_test.go,**/*.pb.go,**/*.pulsar.go,**/*.pb.gw.go +sonar.coverage.exclusions=**/*_test.go,**/testutil/**,**/*.pb.go,**/*.pb.gw.go,**/*.pulsar.go,test_helpers.go,docs/** +sonar.tests=. +sonar.test.inclusions=**/*_test.go +sonar.go.coverage.reportPaths=coverage.out + +sonar.sourceEncoding=UTF-8 +sonar.scm.provider=git +sonar.scm.forceReloadAll=true diff --git a/indexer/postgres/tests/README.md b/indexer/postgres/tests/README.md new file mode 100644 index 0000000000000..a57c861711046 --- /dev/null +++ b/indexer/postgres/tests/README.md @@ -0,0 +1,3 @@ +# PostgreSQL Indexer Tests + +The majority of tests for the PostgreSQL indexer are stored in this separate `tests` go module to keep the main indexer module free of dependencies on any particular PostgreSQL driver. This allows users to choose their own driver and integrate the indexer free of any dependency conflict concerns. \ No newline at end of file diff --git a/indexer/postgres/tests/go.mod b/indexer/postgres/tests/go.mod new file mode 100644 index 0000000000000..d5a29304251f1 --- /dev/null +++ b/indexer/postgres/tests/go.mod @@ -0,0 +1,33 @@ +module cosmossdk.io/indexer/postgres/testing + +require ( + cosmossdk.io/indexer/postgres v0.0.0-00010101000000-000000000000 + cosmossdk.io/schema v0.1.1 + github.com/fergusstrange/embedded-postgres v1.27.0 + github.com/hashicorp/consul/sdk v0.16.1 + github.com/jackc/pgx/v5 v5.6.0 + github.com/stretchr/testify v1.9.0 + gotest.tools/v3 v3.5.1 +) + +require ( + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/google/go-cmp v0.6.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect + github.com/jackc/puddle/v2 v2.2.1 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/lib/pq v1.10.4 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/rogpeppe/go-internal v1.12.0 // indirect + github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // indirect + golang.org/x/crypto v0.23.0 // indirect + golang.org/x/sync v0.1.0 // indirect + golang.org/x/sys v0.20.0 // indirect + golang.org/x/text v0.15.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) + +replace cosmossdk.io/indexer/postgres => ../. + +go 1.22 diff --git a/indexer/postgres/tests/go.sum b/indexer/postgres/tests/go.sum new file mode 100644 index 0000000000000..a4ba87b486c27 --- /dev/null +++ b/indexer/postgres/tests/go.sum @@ -0,0 +1,56 @@ +cosmossdk.io/schema v0.1.1 h1:I0M6pgI7R10nq+/HCQfbO6BsGBZA8sQy+duR1Y3aKcA= +cosmossdk.io/schema v0.1.1/go.mod h1:RDAhxIeNB4bYqAlF4NBJwRrgtnciMcyyg0DOKnhNZQQ= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fergusstrange/embedded-postgres v1.27.0 h1:RAlpWL194IhEpPgeJceTM0ifMJKhiSVxBVIDYB1Jee8= +github.com/fergusstrange/embedded-postgres v1.27.0/go.mod h1:t/MLs0h9ukYM6FSt99R7InCHs1nW0ordoVCcnzmpTYw= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/hashicorp/consul/sdk v0.16.1 h1:V8TxTnImoPD5cj0U9Spl0TUxcytjcbbJeADFF07KdHg= +github.com/hashicorp/consul/sdk v0.16.1/go.mod h1:fSXvwxB2hmh1FMZCNl6PwX0Q/1wdWtHJcZ7Ea5tns0s= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY= +github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw= +github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk= +github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/lib/pq v1.10.4 h1:SO9z7FRPzA03QhHKJrH5BXA6HU1rS4V2nIVrrNC1iYk= +github.com/lib/pq v1.10.4/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo= +github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos= +go.uber.org/goleak v1.1.12 h1:gZAh5/EyT/HQwlpkCy6wTpqfH9H8Lz8zbm3dZh+OyzA= +go.uber.org/goleak v1.1.12/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= +golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU= +gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU= diff --git a/indexer/postgres/tests/init_schema_test.go b/indexer/postgres/tests/init_schema_test.go new file mode 100644 index 0000000000000..8c4288ba344f6 --- /dev/null +++ b/indexer/postgres/tests/init_schema_test.go @@ -0,0 +1,87 @@ +package tests + +import ( + "context" + "fmt" + "os" + "strings" + "testing" + + embeddedpostgres "github.com/fergusstrange/embedded-postgres" + "github.com/hashicorp/consul/sdk/freeport" + _ "github.com/jackc/pgx/v5/stdlib" // this is where we get our pgx database driver from + "github.com/stretchr/testify/require" + "gotest.tools/v3/golden" + + "cosmossdk.io/indexer/postgres" + "cosmossdk.io/indexer/postgres/internal/testdata" + "cosmossdk.io/schema/appdata" +) + +func TestInitSchema(t *testing.T) { + t.Run("default", func(t *testing.T) { + testInitSchema(t, false, "init_schema.txt") + }) + + t.Run("retain deletions disabled", func(t *testing.T) { + testInitSchema(t, true, "init_schema_no_retain_delete.txt") + }) +} + +func testInitSchema(t *testing.T, disableRetainDeletions bool, goldenFileName string) { + t.Helper() + connectionUrl := createTestDB(t) + + buf := &strings.Builder{} + logger := func(msg, sql string, params ...interface{}) { + _, err := fmt.Fprintln(buf, msg) + require.NoError(t, err) + _, err = fmt.Fprintln(buf, sql) + require.NoError(t, err) + if len(params) != 0 { + _, err = fmt.Fprintln(buf, "Params:", params) + require.NoError(t, err) + } + _, err = fmt.Fprintln(buf) + require.NoError(t, err) + } + listener, err := postgres.StartIndexer(context.Background(), logger, postgres.Config{ + DatabaseURL: connectionUrl, + DisableRetainDeletions: disableRetainDeletions, + }) + require.NoError(t, err) + + require.NotNil(t, listener.InitializeModuleData) + require.NoError(t, listener.InitializeModuleData(appdata.ModuleInitializationData{ + ModuleName: "test", + Schema: testdata.ExampleSchema, + })) + + require.NotNil(t, listener.Commit) + require.NoError(t, listener.Commit(appdata.CommitData{})) + + golden.Assert(t, buf.String(), goldenFileName) +} + +func createTestDB(t *testing.T) (connectionUrl string) { + t.Helper() + tempDir, err := os.MkdirTemp("", "postgres-indexer-test") + require.NoError(t, err) + t.Cleanup(func() { + require.NoError(t, os.RemoveAll(tempDir)) + }) + + dbPort := freeport.GetOne(t) + pgConfig := embeddedpostgres.DefaultConfig(). + Port(uint32(dbPort)). + DataPath(tempDir) + + connectionUrl = pgConfig.GetConnectionURL() + pg := embeddedpostgres.NewDatabase(pgConfig) + require.NoError(t, pg.Start()) + t.Cleanup(func() { + require.NoError(t, pg.Stop()) + }) + + return +} diff --git a/indexer/postgres/tests/testdata/init_schema.txt b/indexer/postgres/tests/testdata/init_schema.txt new file mode 100644 index 0000000000000..e2a0a1730e35f --- /dev/null +++ b/indexer/postgres/tests/testdata/init_schema.txt @@ -0,0 +1,56 @@ +Creating enum type +CREATE TYPE "test_my_enum" AS ENUM ('a', 'b', 'c'); + +Creating enum type +CREATE TYPE "test_vote_type" AS ENUM ('yes', 'no', 'abstain'); + +Creating table test_all_kinds +CREATE TABLE IF NOT EXISTS "test_all_kinds" ( + "id" BIGINT NOT NULL, + "ts" TIMESTAMPTZ GENERATED ALWAYS AS (nanos_to_timestamptz("ts_nanos")) STORED, + "ts_nanos" BIGINT NOT NULL, + "string" TEXT NOT NULL, + "bytes" BYTEA NOT NULL, + "int8" SMALLINT NOT NULL, + "uint8" SMALLINT NOT NULL, + "int16" SMALLINT NOT NULL, + "uint16" INTEGER NOT NULL, + "int32" INTEGER NOT NULL, + "uint32" BIGINT NOT NULL, + "int64" BIGINT NOT NULL, + "uint64" NUMERIC NOT NULL, + "integer" NUMERIC NOT NULL, + "decimal" NUMERIC NOT NULL, + "bool" BOOLEAN NOT NULL, + "time" TIMESTAMPTZ GENERATED ALWAYS AS (nanos_to_timestamptz("time_nanos")) STORED, + "time_nanos" BIGINT NOT NULL, + "duration" BIGINT NOT NULL, + "float32" REAL NOT NULL, + "float64" DOUBLE PRECISION NOT NULL, + "bech32address" TEXT NOT NULL, + "enum" "test_my_enum" NOT NULL, + "json" JSONB NOT NULL, + PRIMARY KEY ("id", "ts_nanos") +); +GRANT SELECT ON TABLE "test_all_kinds" TO PUBLIC; + +Creating table test_singleton +CREATE TABLE IF NOT EXISTS "test_singleton" ( + _id INTEGER NOT NULL CHECK (_id = 1), + "foo" TEXT NOT NULL, + "bar" INTEGER NULL, + "an_enum" "test_my_enum" NOT NULL, + PRIMARY KEY (_id) +); +GRANT SELECT ON TABLE "test_singleton" TO PUBLIC; + +Creating table test_vote +CREATE TABLE IF NOT EXISTS "test_vote" ( + "proposal" BIGINT NOT NULL, + "address" TEXT NOT NULL, + "vote" "test_vote_type" NOT NULL, + _deleted BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY ("proposal", "address") +); +GRANT SELECT ON TABLE "test_vote" TO PUBLIC; + diff --git a/indexer/postgres/tests/testdata/init_schema_no_retain_delete.txt b/indexer/postgres/tests/testdata/init_schema_no_retain_delete.txt new file mode 100644 index 0000000000000..0d8cdad2cd243 --- /dev/null +++ b/indexer/postgres/tests/testdata/init_schema_no_retain_delete.txt @@ -0,0 +1,55 @@ +Creating enum type +CREATE TYPE "test_my_enum" AS ENUM ('a', 'b', 'c'); + +Creating enum type +CREATE TYPE "test_vote_type" AS ENUM ('yes', 'no', 'abstain'); + +Creating table test_all_kinds +CREATE TABLE IF NOT EXISTS "test_all_kinds" ( + "id" BIGINT NOT NULL, + "ts" TIMESTAMPTZ GENERATED ALWAYS AS (nanos_to_timestamptz("ts_nanos")) STORED, + "ts_nanos" BIGINT NOT NULL, + "string" TEXT NOT NULL, + "bytes" BYTEA NOT NULL, + "int8" SMALLINT NOT NULL, + "uint8" SMALLINT NOT NULL, + "int16" SMALLINT NOT NULL, + "uint16" INTEGER NOT NULL, + "int32" INTEGER NOT NULL, + "uint32" BIGINT NOT NULL, + "int64" BIGINT NOT NULL, + "uint64" NUMERIC NOT NULL, + "integer" NUMERIC NOT NULL, + "decimal" NUMERIC NOT NULL, + "bool" BOOLEAN NOT NULL, + "time" TIMESTAMPTZ GENERATED ALWAYS AS (nanos_to_timestamptz("time_nanos")) STORED, + "time_nanos" BIGINT NOT NULL, + "duration" BIGINT NOT NULL, + "float32" REAL NOT NULL, + "float64" DOUBLE PRECISION NOT NULL, + "bech32address" TEXT NOT NULL, + "enum" "test_my_enum" NOT NULL, + "json" JSONB NOT NULL, + PRIMARY KEY ("id", "ts_nanos") +); +GRANT SELECT ON TABLE "test_all_kinds" TO PUBLIC; + +Creating table test_singleton +CREATE TABLE IF NOT EXISTS "test_singleton" ( + _id INTEGER NOT NULL CHECK (_id = 1), + "foo" TEXT NOT NULL, + "bar" INTEGER NULL, + "an_enum" "test_my_enum" NOT NULL, + PRIMARY KEY (_id) +); +GRANT SELECT ON TABLE "test_singleton" TO PUBLIC; + +Creating table test_vote +CREATE TABLE IF NOT EXISTS "test_vote" ( + "proposal" BIGINT NOT NULL, + "address" TEXT NOT NULL, + "vote" "test_vote_type" NOT NULL, + PRIMARY KEY ("proposal", "address") +); +GRANT SELECT ON TABLE "test_vote" TO PUBLIC; + diff --git a/log/go.mod b/log/go.mod index 602e88b2ede66..da7c3d4d64a36 100644 --- a/log/go.mod +++ b/log/go.mod @@ -3,17 +3,24 @@ module cosmossdk.io/log go 1.20 require ( - cosmossdk.io/core v0.0.0-00010101000000-000000000000 + cosmossdk.io/core v0.12.0 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 github.com/pkg/errors v0.9.1 github.com/rs/zerolog v1.33.0 gotest.tools/v3 v3.5.1 ) require ( + github.com/cosmos/gogoproto v1.5.0 // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect + github.com/tidwall/btree v1.7.0 // indirect + golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect golang.org/x/sys v0.22.0 // indirect + google.golang.org/protobuf v1.34.2 // indirect ) replace cosmossdk.io/core => ../core + +replace cosmossdk.io/core/testing => ../core/testing diff --git a/log/go.sum b/log/go.sum index 12553f8dc11e2..c8715b25f5910 100644 --- a/log/go.sum +++ b/log/go.sum @@ -1,5 +1,8 @@ github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/cosmos/gogoproto v1.5.0 h1:SDVwzEqZDDBoslaeZg+dGE55hdzHfgUA40pEanMh52o= +github.com/cosmos/gogoproto v1.5.0/go.mod h1:iUM31aofn3ymidYG6bUR5ZFrk+Om8p5s754eMUcyp8I= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= @@ -13,10 +16,16 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8= github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= +github.com/tidwall/btree v1.7.0 h1:L1fkJH/AuEh5zBnnBbmTwQ5Lt+bRJ5A8EWecslvo9iI= +github.com/tidwall/btree v1.7.0/go.mod h1:twD9XRA5jj9VUQGELzDO4HPQTNJsoWWfYEL+EUQ2cKY= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU= gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU= diff --git a/log/logger.go b/log/logger.go index 685bcbba891c7..f57c7690b4140 100644 --- a/log/logger.go +++ b/log/logger.go @@ -11,6 +11,7 @@ import ( "github.com/rs/zerolog/pkgerrors" corelog "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" ) func init() { @@ -150,7 +151,7 @@ func (l zeroLogWrapper) Impl() interface{} { } // NewNopLogger returns a new logger that does nothing. -var NewNopLogger = corelog.NewNopLogger +var NewNopLogger = coretesting.NewNopLogger // LogWrapper wraps a Logger and implements the Logger interface. // it is only meant to avoid breakage of legacy versions of the Logger interface. diff --git a/orm/go.mod b/orm/go.mod index 6d94ca592acf8..7a290f798bff1 100644 --- a/orm/go.mod +++ b/orm/go.mod @@ -5,7 +5,7 @@ go 1.21 require ( cosmossdk.io/api v0.7.5 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 github.com/cosmos/cosmos-db v1.0.2 github.com/cosmos/cosmos-proto v1.0.0-beta.5 @@ -58,6 +58,7 @@ require ( github.com/rogpeppe/go-internal v1.12.0 // indirect github.com/spf13/cast v1.6.0 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect + github.com/tendermint/go-amino v0.16.0 // indirect golang.org/x/net v0.27.0 // indirect golang.org/x/sys v0.22.0 // indirect golang.org/x/text v0.16.0 // indirect @@ -67,7 +68,4 @@ require ( sigs.k8s.io/yaml v1.4.0 // indirect ) -replace ( - cosmossdk.io/core => ../core - cosmossdk.io/depinject => ../depinject -) +replace cosmossdk.io/core => ../core diff --git a/orm/go.sum b/orm/go.sum index b7d78aa2e5aac..4382ea973b422 100644 --- a/orm/go.sum +++ b/orm/go.sum @@ -1,5 +1,7 @@ cosmossdk.io/api v0.7.5 h1:eMPTReoNmGUm8DeiQL9DyM8sYDjEhWzL1+nLbI9DqtQ= cosmossdk.io/api v0.7.5/go.mod h1:IcxpYS5fMemZGqyYtErK7OqvdM0C8kdW3dq8Q/XIG38= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= github.com/DataDog/zstd v1.5.5 h1:oWf5W7GtOLgp6bciQYDmhHHjdhYkALu6S/5Ni9ZgSvQ= @@ -63,6 +65,7 @@ github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69 github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= @@ -84,6 +87,9 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= @@ -141,12 +147,15 @@ github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99 github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d h1:vfofYNRScrDdvS342BElfbETmL1Aiz3i2t0zfRj16Hs= github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d/go.mod h1:RRCYJbIwD5jmqPI9XoAFR0OcDxqUctll6zUj/+B4S48= +github.com/tendermint/go-amino v0.16.0 h1:GyhmgQKvqF82e2oZeuMSp9JTN0N09emoSZlb2lyGa2E= +github.com/tendermint/go-amino v0.16.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= @@ -171,6 +180,7 @@ golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys= golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -217,6 +227,7 @@ golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto/googleapis/api v0.0.0-20240318140521-94a12d6c2237 h1:RFiFrvy37/mpSpdySBDrUdipW/dHwsRwh3J3+A9VgT4= google.golang.org/genproto/googleapis/api v0.0.0-20240318140521-94a12d6c2237/go.mod h1:Z5Iiy3jtmioajWHDGFk7CeugTyHtPvMHA4UTmUkyalE= google.golang.org/genproto/googleapis/rpc v0.0.0-20240709173604-40e1e62336c5 h1:SbSDUWW1PAO24TNpLdeheoYPd7kllICcLU52x6eD4kQ= diff --git a/proto/cosmos/app/v1alpha1/config.proto b/proto/cosmos/app/v1alpha1/config.proto index f1993b82c1341..1aac4b4396f50 100644 --- a/proto/cosmos/app/v1alpha1/config.proto +++ b/proto/cosmos/app/v1alpha1/config.proto @@ -4,7 +4,7 @@ package cosmos.app.v1alpha1; import "google/protobuf/any.proto"; -option go_package = "cosmossdk.io/api/app/v1alpha1"; +option go_package = "cosmossdk.io/depinject/appconfig/v1alpha1"; // Config represents the configuration for a Cosmos SDK ABCI app. // It is intended that all state machine logic including the version of diff --git a/proto/cosmos/app/v1alpha1/module.proto b/proto/cosmos/app/v1alpha1/module.proto index 823dcb7d32593..ea475f35e17ee 100644 --- a/proto/cosmos/app/v1alpha1/module.proto +++ b/proto/cosmos/app/v1alpha1/module.proto @@ -4,7 +4,7 @@ package cosmos.app.v1alpha1; import "google/protobuf/descriptor.proto"; -option go_package = "cosmossdk.io/api/app/v1alpha1"; +option go_package = "cosmossdk.io/depinject/appconfig/v1alpha1"; extend google.protobuf.MessageOptions { // module indicates that this proto type is a config object for an app module diff --git a/proto/cosmos/app/v1alpha1/query.proto b/proto/cosmos/app/v1alpha1/query.proto index 2a854b18b2593..a51aea691db81 100644 --- a/proto/cosmos/app/v1alpha1/query.proto +++ b/proto/cosmos/app/v1alpha1/query.proto @@ -4,7 +4,7 @@ package cosmos.app.v1alpha1; import "cosmos/app/v1alpha1/config.proto"; -option go_package = "cosmossdk.io/api/app/v1alpha1"; +option go_package = "cosmossdk.io/depinject/appconfig/v1alpha1"; // Query is the app module query service. service Query { diff --git a/proto/cosmos/base/node/v1beta1/query.proto b/proto/cosmos/base/node/v1beta1/query.proto index 95df568f1175e..268c85b79d5e4 100644 --- a/proto/cosmos/base/node/v1beta1/query.proto +++ b/proto/cosmos/base/node/v1beta1/query.proto @@ -30,10 +30,10 @@ message ConfigResponse { uint64 halt_height = 4; } -// StateRequest defines the request structure for the status of a node. +// StatusRequest defines the request structure for the status of a node. message StatusRequest {} -// StateResponse defines the response structure for the status of a node. +// StatusResponse defines the response structure for the status of a node. message StatusResponse { uint64 earliest_store_height = 1; // earliest block height available in the store uint64 height = 2; // current block height diff --git a/runtime/router.go b/runtime/router.go index 928ef40cc5744..8c30f2a279298 100644 --- a/runtime/router.go +++ b/runtime/router.go @@ -2,6 +2,7 @@ package runtime import ( "context" + "errors" "fmt" "reflect" "strings" @@ -31,7 +32,7 @@ type msgRouterService struct { // CanInvoke returns an error if the given message cannot be invoked. func (m *msgRouterService) CanInvoke(ctx context.Context, typeURL string) error { if typeURL == "" { - return fmt.Errorf("missing type url") + return errors.New("missing type url") } typeURL = strings.TrimPrefix(typeURL, "/") @@ -94,7 +95,7 @@ type queryRouterService struct { // CanInvoke returns an error if the given request cannot be invoked. func (m *queryRouterService) CanInvoke(ctx context.Context, typeURL string) error { if typeURL == "" { - return fmt.Errorf("missing type url") + return errors.New("missing type url") } typeURL = strings.TrimPrefix(typeURL, "/") diff --git a/runtime/router_test.go b/runtime/router_test.go index 54b123fd04052..2eec2197a4dbf 100644 --- a/runtime/router_test.go +++ b/runtime/router_test.go @@ -7,7 +7,7 @@ import ( bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1" counterv1 "cosmossdk.io/api/cosmos/counter/v1" - "cosmossdk.io/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/baseapp" @@ -26,7 +26,7 @@ func TestRouterService(t *testing.T) { queryRouter.SetInterfaceRegistry(interfaceRegistry) key := storetypes.NewKVStoreKey(countertypes.StoreKey) storeService := runtime.NewKVStoreService(key) - counterKeeper := counterkeeper.NewKeeper(runtime.NewEnvironment(storeService, log.NewNopLogger())) + counterKeeper := counterkeeper.NewKeeper(runtime.NewEnvironment(storeService, coretesting.NewNopLogger())) countertypes.RegisterInterfaces(interfaceRegistry) countertypes.RegisterMsgServer(msgRouter, counterKeeper) countertypes.RegisterQueryServer(queryRouter, counterKeeper) diff --git a/runtime/v2/app.go b/runtime/v2/app.go index 8df0bdb7dedf5..89d6d0be24ba4 100644 --- a/runtime/v2/app.go +++ b/runtime/v2/app.go @@ -4,6 +4,7 @@ import ( "encoding/json" "errors" + gogoproto "github.com/cosmos/gogoproto/proto" "golang.org/x/exp/slices" runtimev2 "cosmossdk.io/api/cosmos/app/runtime/v2" @@ -44,6 +45,15 @@ type App[T transaction.Tx] struct { interfaceRegistrar registry.InterfaceRegistrar amino legacy.Amino moduleManager *MM[T] + + // GRPCQueryDecoders maps gRPC method name to a function that decodes the request + // bytes into a gogoproto.Message, which then can be passed to appmanager. + GRPCQueryDecoders map[string]func(requestBytes []byte) (gogoproto.Message, error) +} + +// Name returns the app name. +func (a *App[T]) Name() string { + return a.config.AppName } // Logger returns the app logger. @@ -109,3 +119,7 @@ func (a *App[T]) ExecuteGenesisTx(_ []byte) error { func (a *App[T]) GetAppManager() *appmanager.AppManager[T] { return a.AppManager } + +func (a *App[T]) GetGRPCQueryDecoders() map[string]func(requestBytes []byte) (gogoproto.Message, error) { + return a.GRPCQueryDecoders +} diff --git a/runtime/v2/builder.go b/runtime/v2/builder.go index 0bdf5992d6c52..82e418349d561 100644 --- a/runtime/v2/builder.go +++ b/runtime/v2/builder.go @@ -36,22 +36,26 @@ func (a *AppBuilder[T]) DefaultGenesis() map[string]json.RawMessage { // RegisterModules registers the provided modules with the module manager. // This is the primary hook for integrating with modules which are not registered using the app config. -func (a *AppBuilder[T]) RegisterModules(modules ...appmodulev2.AppModule) error { - for _, appModule := range modules { - if mod, ok := appModule.(appmodule.HasName); ok { - name := mod.Name() - if _, ok := a.app.moduleManager.modules[name]; ok { - return fmt.Errorf("module named %q already exists", name) +func (a *AppBuilder[T]) RegisterModules(modules map[string]appmodulev2.AppModule) error { + for name, appModule := range modules { + // if a (legacy) module implements the HasName interface, check that the name matches + if mod, ok := appModule.(interface{ Name() string }); ok { + if name != mod.Name() { + a.app.logger.Warn(fmt.Sprintf("module name %q does not match name returned by HasName: %q", name, mod.Name())) } - a.app.moduleManager.modules[name] = appModule + } - if mod, ok := appModule.(appmodulev2.HasRegisterInterfaces); ok { - mod.RegisterInterfaces(a.app.interfaceRegistrar) - } + if _, ok := a.app.moduleManager.modules[name]; ok { + return fmt.Errorf("module named %q already exists", name) + } + a.app.moduleManager.modules[name] = appModule - if mod, ok := appModule.(appmodule.HasAminoCodec); ok { - mod.RegisterLegacyAminoCodec(a.app.amino) - } + if mod, ok := appModule.(appmodulev2.HasRegisterInterfaces); ok { + mod.RegisterInterfaces(a.app.interfaceRegistrar) + } + + if mod, ok := appModule.(appmodule.HasAminoCodec); ok { + mod.RegisterLegacyAminoCodec(a.app.amino) } } @@ -113,7 +117,6 @@ func (a *AppBuilder[T]) Build(opts ...AppBuilderOption[T]) (*App[T], error) { if err != nil { return nil, fmt.Errorf("failed to create STF: %w", err) } - a.app.stf = stf rs, err := rootstore.CreateRootStore(a.storeOptions) diff --git a/runtime/v2/go.mod b/runtime/v2/go.mod index 1ae44abb4fe23..50c759c959b61 100644 --- a/runtime/v2/go.mod +++ b/runtime/v2/go.mod @@ -6,7 +6,7 @@ go 1.22.2 replace ( cosmossdk.io/api => ../../api cosmossdk.io/core => ../../core - cosmossdk.io/depinject => ../../depinject + cosmossdk.io/core/testing => ../../core/testing cosmossdk.io/log => ../../log cosmossdk.io/server/v2/appmanager => ../../server/v2/appmanager cosmossdk.io/server/v2/stf => ../../server/v2/stf @@ -24,7 +24,7 @@ replace ( require ( cosmossdk.io/api v0.7.5 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/server/v2/appmanager v0.0.0-00010101000000-000000000000 cosmossdk.io/server/v2/stf v0.0.0-00010101000000-000000000000 cosmossdk.io/store/v2 v2.0.0-00010101000000-000000000000 @@ -38,6 +38,7 @@ require ( require ( buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2 // indirect buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2 // indirect + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/errors v1.0.1 // indirect cosmossdk.io/log v1.3.1 // indirect github.com/DataDog/zstd v1.5.5 // indirect @@ -82,6 +83,7 @@ require ( github.com/spf13/cast v1.6.0 // indirect github.com/stretchr/testify v1.9.0 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect + github.com/tendermint/go-amino v0.16.0 // indirect github.com/tidwall/btree v1.7.0 // indirect golang.org/x/crypto v0.25.0 // indirect golang.org/x/net v0.27.0 // indirect diff --git a/runtime/v2/go.sum b/runtime/v2/go.sum index 5ffc4256a1909..3f00d777d26a9 100644 --- a/runtime/v2/go.sum +++ b/runtime/v2/go.sum @@ -2,6 +2,8 @@ buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fed buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2/go.mod h1:1+3gJj2NvZ1mTLAtHu+lMhOjGgQPiCKCeo+9MBww0Eo= buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2 h1:b7EEYTUHmWSBEyISHlHvXbJPqtKiHRuUignL1tsHnNQ= buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2/go.mod h1:HqcXMSa5qnNuakaMUo+hWhF51mKbcrZxGl9Vp5EeJXc= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= @@ -77,6 +79,7 @@ github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69 github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= @@ -100,7 +103,10 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= @@ -218,6 +224,8 @@ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsT github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d h1:vfofYNRScrDdvS342BElfbETmL1Aiz3i2t0zfRj16Hs= github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d/go.mod h1:RRCYJbIwD5jmqPI9XoAFR0OcDxqUctll6zUj/+B4S48= +github.com/tendermint/go-amino v0.16.0 h1:GyhmgQKvqF82e2oZeuMSp9JTN0N09emoSZlb2lyGa2E= +github.com/tendermint/go-amino v0.16.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= github.com/tidwall/btree v1.7.0 h1:L1fkJH/AuEh5zBnnBbmTwQ5Lt+bRJ5A8EWecslvo9iI= github.com/tidwall/btree v1.7.0/go.mod h1:twD9XRA5jj9VUQGELzDO4HPQTNJsoWWfYEL+EUQ2cKY= github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= @@ -249,6 +257,7 @@ golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -297,6 +306,7 @@ golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto/googleapis/api v0.0.0-20240318140521-94a12d6c2237 h1:RFiFrvy37/mpSpdySBDrUdipW/dHwsRwh3J3+A9VgT4= google.golang.org/genproto/googleapis/api v0.0.0-20240318140521-94a12d6c2237/go.mod h1:Z5Iiy3jtmioajWHDGFk7CeugTyHtPvMHA4UTmUkyalE= google.golang.org/genproto/googleapis/rpc v0.0.0-20240709173604-40e1e62336c5 h1:SbSDUWW1PAO24TNpLdeheoYPd7kllICcLU52x6eD4kQ= diff --git a/runtime/v2/manager.go b/runtime/v2/manager.go index 0b139c95bc356..c947e0b96581a 100644 --- a/runtime/v2/manager.go +++ b/runtime/v2/manager.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "reflect" "sort" gogoproto "github.com/cosmos/gogoproto/proto" @@ -105,7 +106,7 @@ func (m *MM[T]) DefaultGenesis() map[string]json.RawMessage { genesisData := make(map[string]json.RawMessage) for name, b := range m.modules { if mod, ok := b.(appmodule.HasGenesisBasics); ok { - genesisData[mod.Name()] = mod.DefaultGenesis() + genesisData[name] = mod.DefaultGenesis() } else if mod, ok := b.(appmodulev2.HasGenesis); ok { genesisData[name] = mod.DefaultGenesis() } else { @@ -120,7 +121,7 @@ func (m *MM[T]) DefaultGenesis() map[string]json.RawMessage { func (m *MM[T]) ValidateGenesis(genesisData map[string]json.RawMessage) error { for name, b := range m.modules { if mod, ok := b.(appmodule.HasGenesisBasics); ok { - if err := mod.ValidateGenesis(genesisData[mod.Name()]); err != nil { + if err := mod.ValidateGenesis(genesisData[name]); err != nil { return err } } else if mod, ok := b.(appmodulev2.HasGenesis); ok { @@ -555,17 +556,28 @@ func (m *MM[T]) assertNoForgottenModules( func registerServices[T transaction.Tx](s appmodule.HasServices, app *App[T], registry *protoregistry.Files) error { c := &configurator{ - stfQueryRouter: app.queryRouterBuilder, - stfMsgRouter: app.msgRouterBuilder, - registry: registry, - err: nil, + grpcQueryDecoders: map[string]func([]byte) (gogoproto.Message, error){}, + stfQueryRouter: app.queryRouterBuilder, + stfMsgRouter: app.msgRouterBuilder, + registry: registry, + err: nil, + } + + err := s.RegisterServices(c) + if err != nil { + return fmt.Errorf("unable to register services: %w", err) } - return s.RegisterServices(c) + app.GRPCQueryDecoders = c.grpcQueryDecoders + return nil } var _ grpc.ServiceRegistrar = (*configurator)(nil) type configurator struct { + // grpcQueryDecoders is required because module expose queries through gRPC + // this provides a way to route to modules using gRPC. + grpcQueryDecoders map[string]func([]byte) (gogoproto.Message, error) + stfQueryRouter *stf.MsgRouterBuilder stfMsgRouter *stf.MsgRouterBuilder registry *protoregistry.Files @@ -596,17 +608,28 @@ func (c *configurator) RegisterService(sd *grpc.ServiceDesc, ss interface{}) { func (c *configurator) registerQueryHandlers(sd *grpc.ServiceDesc, ss interface{}) error { for _, md := range sd.Methods { // TODO(tip): what if a query is not deterministic? - err := registerMethod(c.stfQueryRouter, sd, md, ss) + requestFullName, err := registerMethod(c.stfQueryRouter, sd, md, ss) if err != nil { return fmt.Errorf("unable to register query handler %s: %w", md.MethodName, err) } + + // register gRPC query method. + typ := gogoproto.MessageType(requestFullName) + if typ == nil { + return fmt.Errorf("unable to find message in gogotype registry: %w", err) + } + decoderFunc := func(bytes []byte) (gogoproto.Message, error) { + msg := reflect.New(typ.Elem()).Interface().(gogoproto.Message) + return msg, gogoproto.Unmarshal(bytes, msg) + } + c.grpcQueryDecoders[md.MethodName] = decoderFunc } return nil } func (c *configurator) registerMsgHandlers(sd *grpc.ServiceDesc, ss interface{}) error { for _, md := range sd.Methods { - err := registerMethod(c.stfMsgRouter, sd, md, ss) + _, err := registerMethod(c.stfMsgRouter, sd, md, ss) if err != nil { return fmt.Errorf("unable to register msg handler %s: %w", md.MethodName, err) } @@ -633,13 +656,13 @@ func registerMethod( sd *grpc.ServiceDesc, md grpc.MethodDesc, ss interface{}, -) error { +) (string, error) { requestName, err := requestFullNameFromMethodDesc(sd, md) if err != nil { - return err + return "", err } - return stfRouter.RegisterHandler(string(requestName), func( + return string(requestName), stfRouter.RegisterHandler(string(requestName), func( ctx context.Context, msg appmodulev2.Message, ) (resp appmodulev2.Message, err error) { diff --git a/schema/decoding/decoding_test.go b/schema/decoding/decoding_test.go new file mode 100644 index 0000000000000..d4308390d29c7 --- /dev/null +++ b/schema/decoding/decoding_test.go @@ -0,0 +1,458 @@ +package decoding + +import ( + "fmt" + "reflect" + "sort" + "strconv" + "strings" + "testing" + + "cosmossdk.io/schema" + "cosmossdk.io/schema/appdata" +) + +func TestMiddleware(t *testing.T) { + tl := newTestFixture(t) + listener, err := Middleware(tl.Listener, tl.resolver, MiddlewareOptions{}) + if err != nil { + t.Fatal("unexpected error", err) + } + tl.setListener(listener) + + tl.bankMod.Mint("bob", "foo", 100) + err = tl.bankMod.Send("bob", "alice", "foo", 50) + if err != nil { + t.Fatal("unexpected error", err) + } + + tl.oneMod.SetValue("abc") + + expectedBank := []schema.ObjectUpdate{ + { + TypeName: "supply", + Key: []interface{}{"foo"}, + Value: uint64(100), + }, + { + TypeName: "balances", + Key: []interface{}{"bob", "foo"}, + Value: uint64(100), + }, + { + TypeName: "balances", + Key: []interface{}{"bob", "foo"}, + Value: uint64(50), + }, + { + TypeName: "balances", + Key: []interface{}{"alice", "foo"}, + Value: uint64(50), + }, + } + + if !reflect.DeepEqual(tl.bankUpdates, expectedBank) { + t.Fatalf("expected %v, got %v", expectedBank, tl.bankUpdates) + } + + expectedOne := []schema.ObjectUpdate{ + {TypeName: "item", Value: "abc"}, + } + + if !reflect.DeepEqual(tl.oneValueUpdates, expectedOne) { + t.Fatalf("expected %v, got %v", expectedOne, tl.oneValueUpdates) + } +} + +func TestMiddleware_filtered(t *testing.T) { + tl := newTestFixture(t) + listener, err := Middleware(tl.Listener, tl.resolver, MiddlewareOptions{ + ModuleFilter: func(moduleName string) bool { + return moduleName == "one" //nolint:goconst // adding constants for this would impede readability + }, + }) + if err != nil { + t.Fatal("unexpected error", err) + } + tl.setListener(listener) + + tl.bankMod.Mint("bob", "foo", 100) + tl.oneMod.SetValue("abc") + + if len(tl.bankUpdates) != 0 { + t.Fatalf("expected no bank updates") + } + + expectedOne := []schema.ObjectUpdate{ + {TypeName: "item", Value: "abc"}, + } + + if !reflect.DeepEqual(tl.oneValueUpdates, expectedOne) { + t.Fatalf("expected %v, got %v", expectedOne, tl.oneValueUpdates) + } +} + +func TestSync(t *testing.T) { + tl := newTestFixture(t) + tl.bankMod.Mint("bob", "foo", 100) + err := tl.bankMod.Send("bob", "alice", "foo", 50) + if err != nil { + t.Fatal("unexpected error", err) + } + + tl.oneMod.SetValue("def") + + err = Sync(tl.Listener, tl.multiStore, tl.resolver, SyncOptions{}) + if err != nil { + t.Fatal("unexpected error", err) + } + + expected := []schema.ObjectUpdate{ + { + TypeName: "balances", + Key: []interface{}{"alice", "foo"}, + Value: uint64(50), + }, + { + TypeName: "balances", + Key: []interface{}{"bob", "foo"}, + Value: uint64(50), + }, + { + TypeName: "supply", + Key: []interface{}{"foo"}, + Value: uint64(100), + }, + } + + if !reflect.DeepEqual(tl.bankUpdates, expected) { + t.Fatalf("expected %v, got %v", expected, tl.bankUpdates) + } + + expectedOne := []schema.ObjectUpdate{ + {TypeName: "item", Value: "def"}, + } + + if !reflect.DeepEqual(tl.oneValueUpdates, expectedOne) { + t.Fatalf("expected %v, got %v", expectedOne, tl.oneValueUpdates) + } +} + +func TestSync_filtered(t *testing.T) { + tl := newTestFixture(t) + tl.bankMod.Mint("bob", "foo", 100) + tl.oneMod.SetValue("def") + + err := Sync(tl.Listener, tl.multiStore, tl.resolver, SyncOptions{ + ModuleFilter: func(moduleName string) bool { + return moduleName == "one" + }, + }) + if err != nil { + t.Fatal("unexpected error", err) + } + + if len(tl.bankUpdates) != 0 { + t.Fatalf("expected no bank updates") + } + + expectedOne := []schema.ObjectUpdate{ + {TypeName: "item", Value: "def"}, + } + + if !reflect.DeepEqual(tl.oneValueUpdates, expectedOne) { + t.Fatalf("expected %v, got %v", expectedOne, tl.oneValueUpdates) + } +} + +type testFixture struct { + appdata.Listener + bankUpdates []schema.ObjectUpdate + oneValueUpdates []schema.ObjectUpdate + resolver DecoderResolver + multiStore *testMultiStore + bankMod *exampleBankModule + oneMod *oneValueModule +} + +func newTestFixture(t *testing.T) *testFixture { + t.Helper() + res := &testFixture{} + res.Listener = appdata.Listener{ + InitializeModuleData: func(data appdata.ModuleInitializationData) error { + var expected schema.ModuleSchema + switch data.ModuleName { + case "bank": + expected = exampleBankSchema + case "one": + + expected = oneValueModSchema + default: + t.Fatalf("unexpected module %s", data.ModuleName) + } + + if !reflect.DeepEqual(data.Schema, expected) { + t.Errorf("expected %v, got %v", expected, data.Schema) + } + return nil + }, + OnObjectUpdate: func(data appdata.ObjectUpdateData) error { + switch data.ModuleName { + case "bank": + res.bankUpdates = append(res.bankUpdates, data.Updates...) + case "one": + res.oneValueUpdates = append(res.oneValueUpdates, data.Updates...) + default: + t.Errorf("unexpected module %s", data.ModuleName) + } + return nil + }, + } + res.multiStore = newTestMultiStore() + res.bankMod = &exampleBankModule{ + store: res.multiStore.newTestStore(t, "bank"), + } + res.oneMod = &oneValueModule{ + store: res.multiStore.newTestStore(t, "one"), + } + modSet := map[string]interface{}{ + "bank": res.bankMod, + "one": res.oneMod, + } + res.resolver = ModuleSetDecoderResolver(modSet) + return res +} + +func (f *testFixture) setListener(listener appdata.Listener) { + f.bankMod.store.listener = listener + f.oneMod.store.listener = listener +} + +type testMultiStore struct { + stores map[string]*testStore +} + +type testStore struct { + t *testing.T + modName string + store map[string][]byte + listener appdata.Listener +} + +func newTestMultiStore() *testMultiStore { + return &testMultiStore{ + stores: map[string]*testStore{}, + } +} + +var _ SyncSource = &testMultiStore{} + +func (ms *testMultiStore) IterateAllKVPairs(moduleName string, fn func(key, value []byte) error) error { + s, ok := ms.stores[moduleName] + if !ok { + return fmt.Errorf("don't have state for module %s", moduleName) + } + + var keys []string + for key := range s.store { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + err := fn([]byte(key), s.store[key]) + if err != nil { + return err + } + } + return nil +} + +func (ms *testMultiStore) newTestStore(t *testing.T, modName string) *testStore { + t.Helper() + s := &testStore{ + t: t, + modName: modName, + store: map[string][]byte{}, + } + ms.stores[modName] = s + return s +} + +func (t testStore) Get(key []byte) []byte { + return t.store[string(key)] +} + +func (t testStore) GetUInt64(key []byte) uint64 { + bz := t.store[string(key)] + if len(bz) == 0 { + return 0 + } + x, err := strconv.ParseUint(string(bz), 10, 64) + if err != nil { + t.t.Fatalf("unexpected error: %v", err) + } + return x +} + +func (t testStore) Set(key, value []byte) { + if t.listener.OnKVPair != nil { + err := t.listener.OnKVPair(appdata.KVPairData{Updates: []appdata.ModuleKVPairUpdate{ + { + ModuleName: t.modName, + Update: schema.KVPairUpdate{ + Key: key, + Value: value, + }, + }, + }}) + if err != nil { + t.t.Fatalf("unexpected error: %v", err) + } + } + t.store[string(key)] = value +} + +func (t testStore) SetUInt64(key []byte, value uint64) { + t.Set(key, []byte(strconv.FormatUint(value, 10))) +} + +type exampleBankModule struct { + store *testStore +} + +func (e exampleBankModule) Mint(acct, denom string, amount uint64) { + key := supplyKey(denom) + e.store.SetUInt64(key, e.store.GetUInt64(key)+amount) + e.addBalance(acct, denom, amount) +} + +func (e exampleBankModule) Send(from, to, denom string, amount uint64) error { + err := e.subBalance(from, denom, amount) + if err != nil { + return nil + } + e.addBalance(to, denom, amount) + return nil +} + +func (e exampleBankModule) GetBalance(acct, denom string) uint64 { + return e.store.GetUInt64(balanceKey(acct, denom)) +} + +func (e exampleBankModule) GetSupply(denom string) uint64 { + return e.store.GetUInt64(supplyKey(denom)) +} + +func balanceKey(acct, denom string) []byte { + return []byte(fmt.Sprintf("balance/%s/%s", acct, denom)) +} + +func supplyKey(denom string) []byte { + return []byte(fmt.Sprintf("supply/%s", denom)) +} + +func (e exampleBankModule) addBalance(acct, denom string, amount uint64) { + key := balanceKey(acct, denom) + e.store.SetUInt64(key, e.store.GetUInt64(key)+amount) +} + +func (e exampleBankModule) subBalance(acct, denom string, amount uint64) error { + key := balanceKey(acct, denom) + cur := e.store.GetUInt64(key) + if cur < amount { + return fmt.Errorf("insufficient balance") + } + e.store.SetUInt64(key, cur-amount) + return nil +} + +var exampleBankSchema = schema.ModuleSchema{ + ObjectTypes: []schema.ObjectType{ + { + Name: "balances", + KeyFields: []schema.Field{ + { + Name: "account", + Kind: schema.StringKind, + }, + { + Name: "denom", + Kind: schema.StringKind, + }, + }, + ValueFields: []schema.Field{ + { + Name: "amount", + Kind: schema.Uint64Kind, + }, + }, + }, + }, +} + +func (e exampleBankModule) ModuleCodec() (schema.ModuleCodec, error) { + return schema.ModuleCodec{ + Schema: exampleBankSchema, + KVDecoder: func(update schema.KVPairUpdate) ([]schema.ObjectUpdate, error) { + key := string(update.Key) + value, err := strconv.ParseUint(string(update.Value), 10, 64) + if err != nil { + return nil, err + } + if strings.HasPrefix(key, "balance/") { + parts := strings.Split(key, "/") + return []schema.ObjectUpdate{{ + TypeName: "balances", + Key: []interface{}{parts[1], parts[2]}, + Value: value, + }}, nil + } else if strings.HasPrefix(key, "supply/") { + parts := strings.Split(key, "/") + return []schema.ObjectUpdate{{ + TypeName: "supply", + Key: []interface{}{parts[1]}, + Value: value, + }}, nil + } else { + return nil, fmt.Errorf("unexpected key: %s", key) + } + }, + }, nil +} + +var _ schema.HasModuleCodec = exampleBankModule{} + +type oneValueModule struct { + store *testStore +} + +var oneValueModSchema = schema.ModuleSchema{ + ObjectTypes: []schema.ObjectType{ + { + Name: "item", + ValueFields: []schema.Field{ + {Name: "value", Kind: schema.StringKind}, + }, + }, + }, +} + +func (i oneValueModule) ModuleCodec() (schema.ModuleCodec, error) { + return schema.ModuleCodec{ + Schema: oneValueModSchema, + KVDecoder: func(update schema.KVPairUpdate) ([]schema.ObjectUpdate, error) { + if string(update.Key) != "key" { + return nil, fmt.Errorf("unexpected key: %v", update.Key) + } + return []schema.ObjectUpdate{ + {TypeName: "item", Value: string(update.Value)}, + }, nil + }, + }, nil +} + +func (i oneValueModule) SetValue(x string) { + i.store.Set([]byte("key"), []byte(x)) +} + +var _ schema.HasModuleCodec = oneValueModule{} diff --git a/schema/decoding/middleware.go b/schema/decoding/middleware.go new file mode 100644 index 0000000000000..57c0783c62818 --- /dev/null +++ b/schema/decoding/middleware.go @@ -0,0 +1,106 @@ +package decoding + +import ( + "cosmossdk.io/schema" + "cosmossdk.io/schema/appdata" +) + +type MiddlewareOptions struct { + ModuleFilter func(moduleName string) bool +} + +// Middleware decodes raw data passed to the listener as kv-updates into decoded object updates. Module initialization +// is done lazily as modules are encountered in the kv-update stream. +func Middleware(target appdata.Listener, resolver DecoderResolver, opts MiddlewareOptions) (appdata.Listener, error) { + initializeModuleData := target.InitializeModuleData + onObjectUpdate := target.OnObjectUpdate + + // no-op if not listening to decoded data + if initializeModuleData == nil && onObjectUpdate == nil { + return target, nil + } + + onKVPair := target.OnKVPair + + moduleCodecs := map[string]*schema.ModuleCodec{} + + target.OnKVPair = func(data appdata.KVPairData) error { + // first forward kv pair updates + if onKVPair != nil { + err := onKVPair(data) + if err != nil { + return err + } + } + + for _, kvUpdate := range data.Updates { + // look for an existing codec + pcdc, ok := moduleCodecs[kvUpdate.ModuleName] + if !ok { + if opts.ModuleFilter != nil && !opts.ModuleFilter(kvUpdate.ModuleName) { + // we don't care about this module so store nil and continue + moduleCodecs[kvUpdate.ModuleName] = nil + continue + } + + // look for a new codec + cdc, found, err := resolver.LookupDecoder(kvUpdate.ModuleName) + if err != nil { + return err + } + + if !found { + // store nil to indicate we've seen this module and don't have a codec + // and keep processing the kv updates + moduleCodecs[kvUpdate.ModuleName] = nil + continue + } + + pcdc = &cdc + moduleCodecs[kvUpdate.ModuleName] = pcdc + + if initializeModuleData != nil { + err = initializeModuleData(appdata.ModuleInitializationData{ + ModuleName: kvUpdate.ModuleName, + Schema: cdc.Schema, + }) + if err != nil { + return err + } + } + } + + if pcdc == nil { + // we've already seen this module and can't decode + continue + } + + if onObjectUpdate == nil || pcdc.KVDecoder == nil { + // not listening to updates or can't decode so continue + continue + } + + updates, err := pcdc.KVDecoder(kvUpdate.Update) + if err != nil { + return err + } + + if len(updates) == 0 { + // no updates + continue + } + + err = target.OnObjectUpdate(appdata.ObjectUpdateData{ + ModuleName: kvUpdate.ModuleName, + Updates: updates, + }) + if err != nil { + return err + } + } + + return nil + } + + return target, nil +} diff --git a/schema/decoding/resolver_test.go b/schema/decoding/resolver_test.go index ecea614d1999b..f5caf287ca5f2 100644 --- a/schema/decoding/resolver_test.go +++ b/schema/decoding/resolver_test.go @@ -1,7 +1,7 @@ package decoding import ( - "fmt" + "errors" "testing" "cosmossdk.io/schema" @@ -31,11 +31,11 @@ var moduleSet = map[string]interface{}{ "modC": modC{}, } -var resolver = ModuleSetDecoderResolver(moduleSet) +var testResolver = ModuleSetDecoderResolver(moduleSet) func TestModuleSetDecoderResolver_IterateAll(t *testing.T) { objectTypes := map[string]bool{} - err := resolver.IterateAll(func(moduleName string, cdc schema.ModuleCodec) error { + err := testResolver.IterateAll(func(moduleName string, cdc schema.ModuleCodec) error { objectTypes[cdc.Schema.ObjectTypes[0].Name] = true return nil }) @@ -57,7 +57,7 @@ func TestModuleSetDecoderResolver_IterateAll(t *testing.T) { } func TestModuleSetDecoderResolver_LookupDecoder(t *testing.T) { - decoder, found, err := resolver.LookupDecoder("modA") + decoder, found, err := testResolver.LookupDecoder("modA") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -70,7 +70,7 @@ func TestModuleSetDecoderResolver_LookupDecoder(t *testing.T) { t.Fatalf("expected object type A, got %s", decoder.Schema.ObjectTypes[0].Name) } - decoder, found, err = resolver.LookupDecoder("modB") + decoder, found, err = testResolver.LookupDecoder("modB") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -83,7 +83,7 @@ func TestModuleSetDecoderResolver_LookupDecoder(t *testing.T) { t.Fatalf("expected object type B, got %s", decoder.Schema.ObjectTypes[0].Name) } - decoder, found, err = resolver.LookupDecoder("modC") + decoder, found, err = testResolver.LookupDecoder("modC") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -92,7 +92,7 @@ func TestModuleSetDecoderResolver_LookupDecoder(t *testing.T) { t.Fatalf("expected not to find decoder") } - decoder, found, err = resolver.LookupDecoder("modD") + decoder, found, err = testResolver.LookupDecoder("modD") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -105,7 +105,7 @@ func TestModuleSetDecoderResolver_LookupDecoder(t *testing.T) { type modD struct{} func (m modD) ModuleCodec() (schema.ModuleCodec, error) { - return schema.ModuleCodec{}, fmt.Errorf("an error") + return schema.ModuleCodec{}, errors.New("an error") } func TestModuleSetDecoderResolver_IterateAll_Error(t *testing.T) { diff --git a/schema/decoding/sync.go b/schema/decoding/sync.go index 85e6b4d74ba02..d8aee9884c6a9 100644 --- a/schema/decoding/sync.go +++ b/schema/decoding/sync.go @@ -1,8 +1,63 @@ package decoding +import ( + "cosmossdk.io/schema" + "cosmossdk.io/schema/appdata" +) + // SyncSource is an interface that allows indexers to start indexing modules with pre-existing state. // It should generally be a wrapper around the key-value store. type SyncSource interface { // IterateAllKVPairs iterates over all key-value pairs for a given module. IterateAllKVPairs(moduleName string, fn func(key, value []byte) error) error } + +// SyncOptions are the options for Sync. +type SyncOptions struct { + ModuleFilter func(moduleName string) bool +} + +// Sync synchronizes existing state from the sync source to the listener using the resolver to decode data. +func Sync(listener appdata.Listener, source SyncSource, resolver DecoderResolver, opts SyncOptions) error { + initializeModuleData := listener.InitializeModuleData + onObjectUpdate := listener.OnObjectUpdate + + // no-op if not listening to decoded data + if initializeModuleData == nil && onObjectUpdate == nil { + return nil + } + + return resolver.IterateAll(func(moduleName string, cdc schema.ModuleCodec) error { + if opts.ModuleFilter != nil && !opts.ModuleFilter(moduleName) { + // ignore this module + return nil + } + + if initializeModuleData != nil { + err := initializeModuleData(appdata.ModuleInitializationData{ + ModuleName: moduleName, + Schema: cdc.Schema, + }) + if err != nil { + return err + } + } + + if onObjectUpdate == nil || cdc.KVDecoder == nil { + return nil + } + + return source.IterateAllKVPairs(moduleName, func(key, value []byte) error { + updates, err := cdc.KVDecoder(schema.KVPairUpdate{Key: key, Value: value}) + if err != nil { + return err + } + + if len(updates) == 0 { + return nil + } + + return onObjectUpdate(appdata.ObjectUpdateData{ModuleName: moduleName, Updates: updates}) + }) + }) +} diff --git a/schema/enum.go b/schema/enum.go index 6e0be7c615334..927cc827cb3ec 100644 --- a/schema/enum.go +++ b/schema/enum.go @@ -1,6 +1,9 @@ package schema -import "fmt" +import ( + "errors" + "fmt" +) // EnumDefinition represents the definition of an enum type. type EnumDefinition struct { @@ -22,7 +25,7 @@ func (e EnumDefinition) Validate() error { } if len(e.Values) == 0 { - return fmt.Errorf("enum definition values cannot be empty") + return errors.New("enum definition values cannot be empty") } seen := make(map[string]bool, len(e.Values)) for i, v := range e.Values { diff --git a/schema/field.go b/schema/field.go index 6a5df03a10ece..19a1b4085dd6a 100644 --- a/schema/field.go +++ b/schema/field.go @@ -33,7 +33,7 @@ func (c Field) Validate() error { // valid kind if err := c.Kind.Validate(); err != nil { - return fmt.Errorf("invalid field kind for %q: %v", c.Name, err) + return fmt.Errorf("invalid field kind for %q: %v", c.Name, err) //nolint:errorlint // false positive due to using go1.12 } // address prefix only valid with Bech32AddressKind @@ -46,7 +46,7 @@ func (c Field) Validate() error { // enum definition only valid with EnumKind if c.Kind == EnumKind { if err := c.EnumDefinition.Validate(); err != nil { - return fmt.Errorf("invalid enum definition for field %q: %v", c.Name, err) + return fmt.Errorf("invalid enum definition for field %q: %v", c.Name, err) //nolint:errorlint // false positive due to using go1.12 } } else if c.Kind != EnumKind && (c.EnumDefinition.Name != "" || c.EnumDefinition.Values != nil) { return fmt.Errorf("enum definition is only valid for field %q with type EnumKind", c.Name) @@ -67,7 +67,7 @@ func (c Field) ValidateValue(value interface{}) error { } err := c.Kind.ValidateValueType(value) if err != nil { - return fmt.Errorf("invalid value for field %q: %v", c.Name, err) + return fmt.Errorf("invalid value for field %q: %v", c.Name, err) //nolint:errorlint // false positive due to using go1.12 } if c.Kind == EnumKind { diff --git a/schema/object_type.go b/schema/object_type.go index 4189f88de82de..a8fa432d80329 100644 --- a/schema/object_type.go +++ b/schema/object_type.go @@ -43,7 +43,7 @@ func (o ObjectType) validate(enumValueMap map[string]map[string]bool) error { for _, field := range o.KeyFields { if err := field.Validate(); err != nil { - return fmt.Errorf("invalid key field %q: %v", field.Name, err) + return fmt.Errorf("invalid key field %q: %v", field.Name, err) //nolint:errorlint // false positive due to using go1.12 } if field.Nullable { @@ -62,7 +62,7 @@ func (o ObjectType) validate(enumValueMap map[string]map[string]bool) error { for _, field := range o.ValueFields { if err := field.Validate(); err != nil { - return fmt.Errorf("invalid value field %q: %v", field.Name, err) + return fmt.Errorf("invalid value field %q: %v", field.Name, err) //nolint:errorlint // false positive due to using go1.12 } if fieldNames[field.Name] { @@ -89,7 +89,7 @@ func (o ObjectType) ValidateObjectUpdate(update ObjectUpdate) error { } if err := ValidateObjectKey(o.KeyFields, update.Key); err != nil { - return fmt.Errorf("invalid key for object type %q: %v", update.TypeName, err) + return fmt.Errorf("invalid key for object type %q: %v", update.TypeName, err) //nolint:errorlint // false positive due to using go1.12 } if update.Delete { diff --git a/scripts/build/localnet.mk b/scripts/build/localnet.mk index 2bc94a7351d8d..931e8b421285c 100644 --- a/scripts/build/localnet.mk +++ b/scripts/build/localnet.mk @@ -27,7 +27,7 @@ localnet-debug: localnet-stop localnet-build-dlv localnet-build-nodes .PHONY: localnet-start localnet-stop localnet-debug localnet-build-env localnet-build-dlv localnet-build-nodes #? help: Get more info on make commands. -help: Makefile +help: @echo " Choose a command run in "$(PROJECT_NAME)":" - @sed -n 's/^#?//p' $< | column -t -s ':' | sort | sed -e 's/^/ /' + @cat $(MAKEFILE_LIST) | sed -n 's/^#?//p' | column -t -s ':' | sort | sed -e 's/^/ /' .PHONY: help diff --git a/scripts/mockgen.sh b/scripts/mockgen.sh index a82d6e99701e9..eef0730c881a4 100755 --- a/scripts/mockgen.sh +++ b/scripts/mockgen.sh @@ -12,7 +12,6 @@ $mockgen_cmd -source=orm/model/ormtable/hooks.go -package ormmocks -destination $mockgen_cmd -source=x/nft/expected_keepers.go -package testutil -destination x/nft/testutil/expected_keepers_mocks.go $mockgen_cmd -source=x/feegrant/expected_keepers.go -package testutil -destination x/feegrant/testutil/expected_keepers_mocks.go $mockgen_cmd -source=x/mint/types/expected_keepers.go -package testutil -destination x/mint/testutil/expected_keepers_mocks.go -$mockgen_cmd -source=x/crisis/types/expected_keepers.go -package testutil -destination x/crisis/testutil/expected_keepers_mocks.go $mockgen_cmd -source=x/auth/tx/config/expected_keepers.go -package testutil -destination x/auth/tx/testutil/expected_keepers_mocks.go $mockgen_cmd -source=x/auth/types/expected_keepers.go -package testutil -destination x/auth/testutil/expected_keepers_mocks.go $mockgen_cmd -source=x/auth/ante/expected_keepers.go -package testutil -destination x/auth/ante/testutil/expected_keepers_mocks.go diff --git a/server/util.go b/server/util.go index 74d3f3d47f50e..d84847ef27596 100644 --- a/server/util.go +++ b/server/util.go @@ -292,7 +292,7 @@ func interceptConfigs(rootViper *viper.Viper, customAppTemplate string, customCo appCfgFilePath := filepath.Join(configPath, "app.toml") if _, err := os.Stat(appCfgFilePath); os.IsNotExist(err) { if (customAppTemplate != "" && customConfig == nil) || (customAppTemplate == "" && customConfig != nil) { - return nil, fmt.Errorf("customAppTemplate and customConfig should be both nil or not nil") + return nil, errors.New("customAppTemplate and customConfig should be both nil or not nil") } if customAppTemplate != "" { diff --git a/server/v2/api/grpc/server.go b/server/v2/api/grpc/server.go index 20397ea7a89de..c5e31f5dfc717 100644 --- a/server/v2/api/grpc/server.go +++ b/server/v2/api/grpc/server.go @@ -14,7 +14,7 @@ import ( "cosmossdk.io/server/v2/api/grpc/gogoreflection" ) -type GRPCServer[AppT serverv2.AppI[T], T transaction.Tx] struct { +type GRPCServer[T transaction.Tx] struct { logger log.Logger config *Config cfgOptions []CfgOption @@ -23,18 +23,18 @@ type GRPCServer[AppT serverv2.AppI[T], T transaction.Tx] struct { } // New creates a new grpc server. -func New[AppT serverv2.AppI[T], T transaction.Tx](cfgOptions ...CfgOption) *GRPCServer[AppT, T] { - return &GRPCServer[AppT, T]{ +func New[T transaction.Tx](cfgOptions ...CfgOption) *GRPCServer[T] { + return &GRPCServer[T]{ cfgOptions: cfgOptions, } } // Init returns a correctly configured and initialized gRPC server. // Note, the caller is responsible for starting the server. -func (s *GRPCServer[AppT, T]) Init(appI AppT, v *viper.Viper, logger log.Logger) error { +func (s *GRPCServer[T]) Init(appI serverv2.AppI[T], v *viper.Viper, logger log.Logger) error { cfg := s.Config().(*Config) if v != nil { - if err := v.Sub(s.Name()).Unmarshal(&cfg); err != nil { + if err := serverv2.UnmarshalSubConfig(v, s.Name(), &cfg); err != nil { return fmt.Errorf("failed to unmarshal config: %w", err) } } @@ -57,11 +57,11 @@ func (s *GRPCServer[AppT, T]) Init(appI AppT, v *viper.Viper, logger log.Logger) return nil } -func (s *GRPCServer[AppT, T]) Name() string { +func (s *GRPCServer[T]) Name() string { return "grpc" } -func (s *GRPCServer[AppT, T]) Config() any { +func (s *GRPCServer[T]) Config() any { if s.config == nil || s.config == (&Config{}) { cfg := DefaultConfig() // overwrite the default config with the provided options @@ -75,7 +75,7 @@ func (s *GRPCServer[AppT, T]) Config() any { return s.config } -func (s *GRPCServer[AppT, T]) Start(ctx context.Context) error { +func (s *GRPCServer[T]) Start(ctx context.Context) error { if !s.config.Enable { return nil } @@ -102,7 +102,7 @@ func (s *GRPCServer[AppT, T]) Start(ctx context.Context) error { return err } -func (s *GRPCServer[AppT, T]) Stop(ctx context.Context) error { +func (s *GRPCServer[T]) Stop(ctx context.Context) error { if !s.config.Enable { return nil } diff --git a/server/v2/api/grpcgateway/server.go b/server/v2/api/grpcgateway/server.go index 220e8b32f617a..a8a67590df20e 100644 --- a/server/v2/api/grpcgateway/server.go +++ b/server/v2/api/grpcgateway/server.go @@ -18,16 +18,14 @@ import ( serverv2 "cosmossdk.io/server/v2" ) -var _ serverv2.ServerComponent[ - serverv2.AppI[transaction.Tx], transaction.Tx, -] = (*GRPCGatewayServer[serverv2.AppI[transaction.Tx], transaction.Tx])(nil) +var _ serverv2.ServerComponent[transaction.Tx] = (*GRPCGatewayServer[transaction.Tx])(nil) const ( // GRPCBlockHeightHeader is the gRPC header for block height. GRPCBlockHeightHeader = "x-cosmos-block-height" ) -type GRPCGatewayServer[AppT serverv2.AppI[T], T transaction.Tx] struct { +type GRPCGatewayServer[T transaction.Tx] struct { logger log.Logger config *Config cfgOptions []CfgOption @@ -37,7 +35,7 @@ type GRPCGatewayServer[AppT serverv2.AppI[T], T transaction.Tx] struct { } // New creates a new gRPC-gateway server. -func New[AppT serverv2.AppI[T], T transaction.Tx](grpcSrv *grpc.Server, ir jsonpb.AnyResolver, cfgOptions ...CfgOption) *GRPCGatewayServer[AppT, T] { +func New[T transaction.Tx](grpcSrv *grpc.Server, ir jsonpb.AnyResolver, cfgOptions ...CfgOption) *GRPCGatewayServer[T] { // The default JSON marshaller used by the gRPC-Gateway is unable to marshal non-nullable non-scalar fields. // Using the gogo/gateway package with the gRPC-Gateway WithMarshaler option fixes the scalar field marshaling issue. marshalerOption := &gateway.JSONPb{ @@ -47,7 +45,7 @@ func New[AppT serverv2.AppI[T], T transaction.Tx](grpcSrv *grpc.Server, ir jsonp AnyResolver: ir, } - return &GRPCGatewayServer[AppT, T]{ + return &GRPCGatewayServer[T]{ GRPCSrv: grpcSrv, GRPCGatewayRouter: runtime.NewServeMux( // Custom marshaler option is required for gogo proto @@ -65,11 +63,11 @@ func New[AppT serverv2.AppI[T], T transaction.Tx](grpcSrv *grpc.Server, ir jsonp } } -func (g *GRPCGatewayServer[AppT, T]) Name() string { +func (g *GRPCGatewayServer[T]) Name() string { return "grpc-gateway" } -func (s *GRPCGatewayServer[AppT, T]) Config() any { +func (s *GRPCGatewayServer[T]) Config() any { if s.config == nil || s.config == (&Config{}) { cfg := DefaultConfig() // overwrite the default config with the provided options @@ -83,10 +81,10 @@ func (s *GRPCGatewayServer[AppT, T]) Config() any { return s.config } -func (s *GRPCGatewayServer[AppT, T]) Init(appI AppT, v *viper.Viper, logger log.Logger) error { +func (s *GRPCGatewayServer[T]) Init(appI serverv2.AppI[transaction.Tx], v *viper.Viper, logger log.Logger) error { cfg := s.Config().(*Config) if v != nil { - if err := v.Sub(s.Name()).Unmarshal(&cfg); err != nil { + if err := serverv2.UnmarshalSubConfig(v, s.Name(), &cfg); err != nil { return fmt.Errorf("failed to unmarshal config: %w", err) } } @@ -100,7 +98,7 @@ func (s *GRPCGatewayServer[AppT, T]) Init(appI AppT, v *viper.Viper, logger log. return nil } -func (s *GRPCGatewayServer[AppT, T]) Start(ctx context.Context) error { +func (s *GRPCGatewayServer[T]) Start(ctx context.Context) error { if !s.config.Enable { return nil } @@ -110,7 +108,7 @@ func (s *GRPCGatewayServer[AppT, T]) Start(ctx context.Context) error { return nil } -func (s *GRPCGatewayServer[AppT, T]) Stop(ctx context.Context) error { +func (s *GRPCGatewayServer[T]) Stop(ctx context.Context) error { if !s.config.Enable { return nil } @@ -119,7 +117,7 @@ func (s *GRPCGatewayServer[AppT, T]) Stop(ctx context.Context) error { } // Register implements registers a grpc-gateway server -func (s *GRPCGatewayServer[AppT, T]) Register(r mux.Router) error { +func (s *GRPCGatewayServer[T]) Register(r mux.Router) error { // configure grpc-gatway server r.PathPrefix("/").Handler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { // Fall back to grpc gateway server. diff --git a/server/v2/appmanager/appmanager.go b/server/v2/appmanager/appmanager.go index f20abad5567cc..d9c84c5035d71 100644 --- a/server/v2/appmanager/appmanager.go +++ b/server/v2/appmanager/appmanager.go @@ -9,15 +9,25 @@ import ( appmanager "cosmossdk.io/core/app" corestore "cosmossdk.io/core/store" "cosmossdk.io/core/transaction" - "cosmossdk.io/server/v2/appmanager/store" ) +// Store defines the underlying storage behavior needed by AppManager. +type Store interface { + // StateLatest returns a readonly view over the latest + // committed state of the store. Alongside the version + // associated with it. + StateLatest() (uint64, corestore.ReaderMap, error) + + // StateAt returns a readonly view over the provided + // state. Must error when the version does not exist. + StateAt(version uint64) (corestore.ReaderMap, error) +} + // AppManager is a coordinator for all things related to an application -// TODO: add exportGenesis function type AppManager[T transaction.Tx] struct { config Config - db store.Store + db Store initGenesis InitGenesis exportGenesis ExportGenesis @@ -40,7 +50,7 @@ func (a AppManager[T]) InitGenesis( } var genTxs []T - zeroState, err = a.stf.RunWithCtx(ctx, zeroState, func(ctx context.Context) error { + genesisState, err := a.stf.RunWithCtx(ctx, zeroState, func(ctx context.Context) error { return a.initGenesis(ctx, bytes.NewBuffer(initGenesisJSON), func(jsonTx json.RawMessage) error { genTx, err := txDecoder.DecodeJSON(jsonTx) if err != nil { @@ -55,16 +65,26 @@ func (a AppManager[T]) InitGenesis( } // run block // TODO: in an ideal world, genesis state is simply an initial state being applied - // unaware of what that state means in relation to every other, so here we can - // chain genesis + // unaware of what that state means in relation to every other blockRequest.Txs = genTxs - blockresponse, genesisState, err := a.stf.DeliverBlock(ctx, blockRequest, zeroState) + blockResponse, blockZeroState, err := a.stf.DeliverBlock(ctx, blockRequest, genesisState) + if err != nil { + return blockResponse, nil, fmt.Errorf("failed to deliver block %d: %w", blockRequest.Height, err) + } + + // after executing block 0, we extract the changes and apply them to the genesis state. + blockZeroStateChanges, err := blockZeroState.GetStateChanges() + if err != nil { + return nil, nil, fmt.Errorf("failed to get block zero state changes: %w", err) + } + + err = genesisState.ApplyStateChanges(blockZeroStateChanges) if err != nil { - return blockresponse, nil, fmt.Errorf("failed to deliver block %d: %w", blockRequest.Height, err) + return nil, nil, fmt.Errorf("failed to apply block zero state changes to genesis state: %w", err) } - return blockresponse, genesisState, err + return blockResponse, genesisState, err // consensus server will need to set the version of the store } diff --git a/server/v2/appmanager/appmanager_builder.go b/server/v2/appmanager/appmanager_builder.go index 7b952c92e982e..b3671706c7f2d 100644 --- a/server/v2/appmanager/appmanager_builder.go +++ b/server/v2/appmanager/appmanager_builder.go @@ -2,14 +2,13 @@ package appmanager import ( "cosmossdk.io/core/transaction" - "cosmossdk.io/server/v2/appmanager/store" ) // Builder is a struct that represents the application builder for managing transactions. // It contains various fields and methods for initializing the application and handling transactions. type Builder[T transaction.Tx] struct { STF StateTransitionFunction[T] // The state transition function for processing transactions. - DB store.Store // The database for storing application data. + DB Store // The database for storing application data. // Gas limits for validating, querying, and simulating transactions. ValidateTxGasLimit uint64 diff --git a/server/v2/appmanager/go.mod b/server/v2/appmanager/go.mod index 1a68cf3957149..266c4eb8c4317 100644 --- a/server/v2/appmanager/go.mod +++ b/server/v2/appmanager/go.mod @@ -9,7 +9,6 @@ require cosmossdk.io/core v0.12.0 require ( github.com/cosmos/gogoproto v1.5.0 // indirect github.com/google/go-cmp v0.6.0 // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect golang.org/x/exp v0.0.0-20240314144324-c7f7c6466f7f // indirect google.golang.org/protobuf v1.34.2 // indirect ) diff --git a/server/v2/appmanager/go.sum b/server/v2/appmanager/go.sum index 174f840d47d06..f9ca7916a774a 100644 --- a/server/v2/appmanager/go.sum +++ b/server/v2/appmanager/go.sum @@ -1,18 +1,10 @@ github.com/cosmos/gogoproto v1.5.0 h1:SDVwzEqZDDBoslaeZg+dGE55hdzHfgUA40pEanMh52o= github.com/cosmos/gogoproto v1.5.0/go.mod h1:iUM31aofn3ymidYG6bUR5ZFrk+Om8p5s754eMUcyp8I= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= golang.org/x/exp v0.0.0-20240314144324-c7f7c6466f7f h1:3CW0unweImhOzd5FmYuRsD4Y4oQFKZIjAnKbjV4WIrw= golang.org/x/exp v0.0.0-20240314144324-c7f7c6466f7f/go.mod h1:CxmFvTBINI24O/j8iY7H1xHzx2i4OsyguNBmN/uPtqc= google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/server/v2/appmanager/store/types.go b/server/v2/appmanager/store/types.go deleted file mode 100644 index 1993df517451d..0000000000000 --- a/server/v2/appmanager/store/types.go +++ /dev/null @@ -1,17 +0,0 @@ -package store - -import ( - "cosmossdk.io/core/store" -) - -// Store defines the underlying storage engine of an app. -type Store interface { - // StateLatest returns a readonly view over the latest - // committed state of the store. Alongside the version - // associated with it. - StateLatest() (uint64, store.ReaderMap, error) - - // StateAt returns a readonly view over the provided - // state. Must error when the version does not exist. - StateAt(version uint64) (store.ReaderMap, error) -} diff --git a/server/v2/cometbft/abci.go b/server/v2/cometbft/abci.go index c500d47e1edb6..b0c1a8452a134 100644 --- a/server/v2/cometbft/abci.go +++ b/server/v2/cometbft/abci.go @@ -9,6 +9,7 @@ import ( abci "github.com/cometbft/cometbft/abci/types" abciproto "github.com/cometbft/cometbft/api/cometbft/abci/v1" + gogoproto "github.com/cosmos/gogoproto/proto" coreappmgr "cosmossdk.io/core/app" "cosmossdk.io/core/comet" @@ -31,15 +32,22 @@ import ( var _ abci.Application = (*Consensus[transaction.Tx])(nil) type Consensus[T transaction.Tx] struct { - app *appmanager.AppManager[T] - cfg Config - store types.Store - logger log.Logger - txCodec transaction.Codec[T] - streaming streaming.Manager - snapshotManager *snapshots.Manager - mempool mempool.Mempool[T] - + logger log.Logger + appName, version string + consensusAuthority string // Set by the application to grant authority to the consensus engine to send messages to the consensus module + app *appmanager.AppManager[T] + txCodec transaction.Codec[T] + store types.Store + streaming streaming.Manager + snapshotManager *snapshots.Manager + mempool mempool.Mempool[T] + grpcQueryDecoders map[string]func(requestBytes []byte) (gogoproto.Message, error) // legacy support for gRPC + + cfg Config + indexedEvents map[string]struct{} + chainID string + + initialHeight uint64 // this is only available after this node has committed a block (in FinalizeBlock), // otherwise it will be empty and we will need to query the app for the last // committed block. @@ -50,45 +58,59 @@ type Consensus[T transaction.Tx] struct { verifyVoteExt handlers.VerifyVoteExtensionhandler extendVote handlers.ExtendVoteHandler - chainID string + addrPeerFilter types.PeerFilter // filter peers by address and port + idPeerFilter types.PeerFilter // filter peers by node ID } func NewConsensus[T transaction.Tx]( + logger log.Logger, + appName string, + consensusAuthority string, app *appmanager.AppManager[T], mp mempool.Mempool[T], + indexedEvents map[string]struct{}, + grpcQueryDecoders map[string]func(requestBytes []byte) (gogoproto.Message, error), store types.Store, cfg Config, txCodec transaction.Codec[T], - logger log.Logger, ) *Consensus[T] { return &Consensus[T]{ - mempool: mp, - store: store, - app: app, - cfg: cfg, - txCodec: txCodec, - logger: logger, + appName: appName, + version: getCometBFTServerVersion(), + consensusAuthority: consensusAuthority, + grpcQueryDecoders: grpcQueryDecoders, + app: app, + cfg: cfg, + store: store, + logger: logger, + txCodec: txCodec, + streaming: streaming.Manager{}, + snapshotManager: nil, + mempool: mp, + lastCommittedHeight: atomic.Int64{}, + prepareProposalHandler: nil, + processProposalHandler: nil, + verifyVoteExt: nil, + extendVote: nil, + chainID: "", + indexedEvents: indexedEvents, + initialHeight: 0, } } +// SetStreamingManager sets the streaming manager for the consensus module. func (c *Consensus[T]) SetStreamingManager(sm streaming.Manager) { c.streaming = sm } -// SetSnapshotManager sets the snapshot manager for the Consensus. -// The snapshot manager is responsible for managing snapshots of the Consensus state. -// It allows for creating, storing, and restoring snapshots of the Consensus state. -// The provided snapshot manager will be used by the Consensus to handle snapshots. -func (c *Consensus[T]) SetSnapshotManager(sm *snapshots.Manager) { - c.snapshotManager = sm -} - -// RegisterExtensions registers the given extensions with the consensus module's snapshot manager. +// RegisterSnapshotExtensions registers the given extensions with the consensus module's snapshot manager. // It allows additional snapshotter implementations to be used for creating and restoring snapshots. -func (c *Consensus[T]) RegisterExtensions(extensions ...snapshots.ExtensionSnapshotter) { +func (c *Consensus[T]) RegisterSnapshotExtensions(extensions ...snapshots.ExtensionSnapshotter) error { if err := c.snapshotManager.RegisterExtensions(extensions...); err != nil { - panic(fmt.Errorf("failed to register snapshot extensions: %w", err)) + return fmt.Errorf("failed to register snapshot extensions: %w", err) } + + return nil } // CheckTx implements types.Application. @@ -108,7 +130,7 @@ func (c *Consensus[T]) CheckTx(ctx context.Context, req *abciproto.CheckTxReques Code: resp.Code, GasWanted: uint64ToInt64(resp.GasWanted), GasUsed: uint64ToInt64(resp.GasUsed), - Events: intoABCIEvents(resp.Events, c.cfg.IndexEvents), + Events: intoABCIEvents(resp.Events, c.indexedEvents), Info: resp.Info, Data: resp.Data, Log: resp.Log, @@ -130,7 +152,7 @@ func (c *Consensus[T]) Info(ctx context.Context, _ *abciproto.InfoRequest) (*abc // cp, err := c.GetConsensusParams(ctx) // if err != nil { - // return nil, err + // return nil, err // } cid, err := c.store.LastCommitID() @@ -139,10 +161,9 @@ func (c *Consensus[T]) Info(ctx context.Context, _ *abciproto.InfoRequest) (*abc } return &abciproto.InfoResponse{ - Data: c.cfg.Name, - Version: c.cfg.Version, - // AppVersion: cp.GetVersion().App, - AppVersion: 0, // TODO fetch from store? + Data: c.appName, + Version: c.version, + AppVersion: 0, // TODO fetch consensus params? LastBlockHeight: int64(version), LastBlockAppHash: cid.Hash, }, nil @@ -150,18 +171,15 @@ func (c *Consensus[T]) Info(ctx context.Context, _ *abciproto.InfoRequest) (*abc // Query implements types.Application. // It is called by cometbft to query application state. -func (c *Consensus[T]) Query(ctx context.Context, req *abciproto.QueryRequest) (*abciproto.QueryResponse, error) { - // follow the query path from here - decodedMsg, err := c.txCodec.Decode(req.Data) - protoMsg, ok := any(decodedMsg).(transaction.Msg) - if !ok { - return nil, fmt.Errorf("decoded type T %T must implement core/transaction.Msg", decodedMsg) - } - - // if no error is returned then we can handle the query with the appmanager - // otherwise it is a KV store query - if err == nil { - res, err := c.app.Query(ctx, uint64(req.Height), protoMsg) +func (c *Consensus[T]) Query(ctx context.Context, req *abciproto.QueryRequest) (resp *abciproto.QueryResponse, err error) { + // check if it's a gRPC method + grpcQueryDecoder, isGRPC := c.grpcQueryDecoders[req.Path] + if isGRPC { + protoRequest, err := grpcQueryDecoder(req.Data) + if err != nil { + return nil, fmt.Errorf("unable to decode gRPC request with path %s from ABCI.Query: %w", req.Path, err) + } + res, err := c.app.Query(ctx, uint64(req.Height), protoRequest) if err != nil { resp := queryResult(err) resp.Height = req.Height @@ -176,11 +194,9 @@ func (c *Consensus[T]) Query(ctx context.Context, req *abciproto.QueryRequest) ( // it must be an app/p2p/store query path := splitABCIQueryPath(req.Path) if len(path) == 0 { - return QueryResult(errorsmod.Wrap(cometerrors.ErrUnknownRequest, "no query path provided"), c.cfg.Trace), nil + return QueryResult(errorsmod.Wrap(cometerrors.ErrUnknownRequest, "no query path provided"), c.cfg.AppTomlConfig.Trace), nil } - var resp *abciproto.QueryResponse - switch path[0] { case cmtservice.QueryPathApp: resp, err = c.handlerQueryApp(ctx, path, req) @@ -192,11 +208,11 @@ func (c *Consensus[T]) Query(ctx context.Context, req *abciproto.QueryRequest) ( resp, err = c.handleQueryP2P(path) default: - resp = QueryResult(errorsmod.Wrap(cometerrors.ErrUnknownRequest, "unknown query path"), c.cfg.Trace) + resp = QueryResult(errorsmod.Wrap(cometerrors.ErrUnknownRequest, "unknown query path"), c.cfg.AppTomlConfig.Trace) } if err != nil { - return QueryResult(err, c.cfg.Trace), nil + return QueryResult(err, c.cfg.AppTomlConfig.Trace), nil } return resp, nil @@ -208,17 +224,17 @@ func (c *Consensus[T]) InitChain(ctx context.Context, req *abciproto.InitChainRe // store chainID to be used later on in execution c.chainID = req.ChainId - // TODO: check if we need to load the config from genesis.json or config.toml - c.cfg.InitialHeight = uint64(req.InitialHeight) - // On a new chain, we consider the init chain block height as 0, even though - // req.InitialHeight is 1 by default. - // TODO + // TODO: check if we need to load the config from genesis.json or config.toml + c.initialHeight = uint64(req.InitialHeight) + if c.initialHeight == 0 { // If initial height is 0, set it to 1 + c.initialHeight = 1 + } var consMessages []transaction.Msg if req.ConsensusParams != nil { consMessages = append(consMessages, &consensustypes.MsgUpdateParams{ - Authority: c.cfg.ConsensusAuthority, + Authority: c.consensusAuthority, Block: req.ConsensusParams.Block, Evidence: req.ConsensusParams.Evidence, Validator: req.ConsensusParams.Validator, @@ -384,14 +400,14 @@ func (c *Consensus[T]) FinalizeBlock( // TODO evaluate this approach vs. service using context. // cometInfo := &consensustypes.MsgUpdateCometInfo{ - // Authority: c.cfg.ConsensusAuthority, + // Authority: c.consensusAuthority, // CometInfo: &consensustypes.CometInfo{ // Evidence: req.Misbehavior, // ValidatorsHash: req.NextValidatorsHash, // ProposerAddress: req.ProposerAddress, // LastCommit: req.DecidedLastCommit, // }, - //} + // } // // ctx = context.WithValue(ctx, corecontext.CometInfoKey, &comet.Info{ // Evidence: sdktypes.ToSDKEvidence(req.Misbehavior), @@ -401,7 +417,7 @@ func (c *Consensus[T]) FinalizeBlock( // }) // we don't need to deliver the block in the genesis block - if req.Height == int64(c.cfg.InitialHeight) { + if req.Height == int64(c.initialHeight) { appHash, err := c.store.Commit(store.NewChangeset()) if err != nil { return nil, fmt.Errorf("unable to commit the changeset: %w", err) @@ -485,7 +501,7 @@ func (c *Consensus[T]) FinalizeBlock( return nil, err } - return finalizeBlockResponse(resp, cp, appHash, c.cfg.IndexEvents) + return finalizeBlockResponse(resp, cp, appHash, c.indexedEvents) } // Commit implements types.Application. diff --git a/server/v2/cometbft/client/grpc/cmtservice/service.go b/server/v2/cometbft/client/grpc/cmtservice/service.go index 426b32aa45d42..3e0188c2a7e91 100644 --- a/server/v2/cometbft/client/grpc/cmtservice/service.go +++ b/server/v2/cometbft/client/grpc/cmtservice/service.go @@ -4,15 +4,15 @@ import ( "context" "strings" + "cosmossdk.io/server/v2/cometbft/client/rpc" abci "github.com/cometbft/cometbft/api/cometbft/abci/v1" coretypes "github.com/cometbft/cometbft/rpc/core/types" gogogrpc "github.com/cosmos/gogoproto/grpc" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "cosmossdk.io/server/v2/cometbft/client/rpc" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -22,8 +22,8 @@ import ( ) var ( - _ ServiceServer = queryServer{} - _ codectypes.UnpackInterfacesMessage = &GetLatestValidatorSetResponse{} + _ ServiceServer = queryServer{} + _ gogoprotoany.UnpackInterfacesMessage = &GetLatestValidatorSetResponse{} ) const ( @@ -136,7 +136,7 @@ func (s queryServer) GetLatestValidatorSet( return ValidatorsOutput(ctx, s.client, nil, page, limit) } -func (m *GetLatestValidatorSetResponse) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (m *GetLatestValidatorSetResponse) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var pubKey cryptotypes.PubKey for _, val := range m.Validators { err := unpacker.UnpackAny(val.PubKey, &pubKey) diff --git a/server/v2/cometbft/commands.go b/server/v2/cometbft/commands.go index 982eff6ae4c1b..16c1e30905eb1 100644 --- a/server/v2/cometbft/commands.go +++ b/server/v2/cometbft/commands.go @@ -19,7 +19,6 @@ import ( "sigs.k8s.io/yaml" "cosmossdk.io/server/v2/cometbft/client/rpc" - auth "cosmossdk.io/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/client" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" @@ -28,8 +27,8 @@ import ( "github.com/cosmos/cosmos-sdk/version" ) -func (s *CometBFTServer[AppT, T]) rpcClient(cmd *cobra.Command) (rpc.CometRPC, error) { - if s.config.Standalone { +func (s *CometBFTServer[T]) rpcClient(cmd *cobra.Command) (rpc.CometRPC, error) { + if s.config.AppTomlConfig.Standalone { client, err := rpchttp.New(client.GetConfigFromCmd(cmd).RPC.ListenAddress) if err != nil { return nil, err @@ -51,7 +50,7 @@ func (s *CometBFTServer[AppT, T]) rpcClient(cmd *cobra.Command) (rpc.CometRPC, e } // StatusCommand returns the command to return the status of the network. -func (s *CometBFTServer[AppT, T]) StatusCommand() *cobra.Command { +func (s *CometBFTServer[T]) StatusCommand() *cobra.Command { cmd := &cobra.Command{ Use: "status", Short: "Query remote node for status", @@ -82,7 +81,7 @@ func (s *CometBFTServer[AppT, T]) StatusCommand() *cobra.Command { } // ShowNodeIDCmd - ported from CometBFT, dump node ID to stdout -func (s *CometBFTServer[AppT, T]) ShowNodeIDCmd() *cobra.Command { +func (s *CometBFTServer[T]) ShowNodeIDCmd() *cobra.Command { return &cobra.Command{ Use: "show-node-id", Short: "Show this node's ID", @@ -100,7 +99,7 @@ func (s *CometBFTServer[AppT, T]) ShowNodeIDCmd() *cobra.Command { } // ShowValidatorCmd - ported from CometBFT, show this node's validator info -func (s *CometBFTServer[AppT, T]) ShowValidatorCmd() *cobra.Command { +func (s *CometBFTServer[T]) ShowValidatorCmd() *cobra.Command { cmd := cobra.Command{ Use: "show-validator", Short: "Show this node's CometBFT validator info", @@ -134,7 +133,7 @@ func (s *CometBFTServer[AppT, T]) ShowValidatorCmd() *cobra.Command { } // ShowAddressCmd - show this node's validator address -func (s *CometBFTServer[AppT, T]) ShowAddressCmd() *cobra.Command { +func (s *CometBFTServer[T]) ShowAddressCmd() *cobra.Command { cmd := &cobra.Command{ Use: "show-address", Short: "Shows this node's CometBFT validator consensus address", @@ -153,7 +152,7 @@ func (s *CometBFTServer[AppT, T]) ShowAddressCmd() *cobra.Command { } // VersionCmd prints CometBFT and ABCI version numbers. -func (s *CometBFTServer[AppT, T]) VersionCmd() *cobra.Command { +func (s *CometBFTServer[T]) VersionCmd() *cobra.Command { return &cobra.Command{ Use: "version", Short: "Print CometBFT libraries' version", @@ -181,7 +180,7 @@ func (s *CometBFTServer[AppT, T]) VersionCmd() *cobra.Command { } // QueryBlocksCmd returns a command to search through blocks by events. -func (s *CometBFTServer[AppT, T]) QueryBlocksCmd() *cobra.Command { +func (s *CometBFTServer[T]) QueryBlocksCmd() *cobra.Command { cmd := &cobra.Command{ Use: "blocks", Short: "Query for paginated blocks that match a set of events", @@ -201,10 +200,10 @@ for. Each module documents its respective events under 'xx_events.md'. return err } - query, _ := cmd.Flags().GetString(auth.FlagQuery) + query, _ := cmd.Flags().GetString(FlagQuery) page, _ := cmd.Flags().GetInt(FlagPage) limit, _ := cmd.Flags().GetInt(FlagLimit) - orderBy, _ := cmd.Flags().GetString(auth.FlagOrderBy) + orderBy, _ := cmd.Flags().GetString(FlagOrderBy) blocks, err := rpc.QueryBlocks(cmd.Context(), rpcclient, page, limit, query, orderBy) if err != nil { @@ -223,15 +222,15 @@ for. Each module documents its respective events under 'xx_events.md'. AddQueryFlagsToCmd(cmd) cmd.Flags().Int(FlagPage, query.DefaultPage, "Query a specific page of paginated results") cmd.Flags().Int(FlagLimit, query.DefaultLimit, "Query number of transactions results per page returned") - cmd.Flags().String(auth.FlagQuery, "", "The blocks events query per CometBFT's query semantics") - cmd.Flags().String(auth.FlagOrderBy, "", "The ordering semantics (asc|dsc)") - _ = cmd.MarkFlagRequired(auth.FlagQuery) + cmd.Flags().String(FlagQuery, "", "The blocks events query per CometBFT's query semantics") + cmd.Flags().String(FlagOrderBy, "", "The ordering semantics (asc|dsc)") + _ = cmd.MarkFlagRequired(FlagQuery) return cmd } // QueryBlockCmd implements the default command for a Block query. -func (s *CometBFTServer[AppT, T]) QueryBlockCmd() *cobra.Command { +func (s *CometBFTServer[T]) QueryBlockCmd() *cobra.Command { cmd := &cobra.Command{ Use: "block --type=[height|hash] [height|hash]", Short: "Query for a committed block by height, hash, or event(s)", @@ -240,11 +239,11 @@ func (s *CometBFTServer[AppT, T]) QueryBlockCmd() *cobra.Command { $ %s query block --%s=%s $ %s query block --%s=%s `, - version.AppName, auth.FlagType, auth.TypeHeight, - version.AppName, auth.FlagType, auth.TypeHash)), + version.AppName, FlagType, TypeHeight, + version.AppName, FlagType, TypeHash)), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - typ, _ := cmd.Flags().GetString(auth.FlagType) + typ, _ := cmd.Flags().GetString(FlagType) rpcclient, err := s.rpcClient(cmd) if err != nil { @@ -252,7 +251,7 @@ $ %s query block --%s=%s } switch typ { - case auth.TypeHeight: + case TypeHeight: if args[0] == "" { return fmt.Errorf("argument should be a block height") } @@ -282,7 +281,7 @@ $ %s query block --%s=%s return printOutput(cmd, bz) - case auth.TypeHash: + case TypeHash: if args[0] == "" { return fmt.Errorf("argument should be a tx hash") @@ -306,19 +305,19 @@ $ %s query block --%s=%s return printOutput(cmd, bz) default: - return fmt.Errorf("unknown --%s value %s", auth.FlagType, typ) + return fmt.Errorf("unknown --%s value %s", FlagType, typ) } }, } AddQueryFlagsToCmd(cmd) - cmd.Flags().String(auth.FlagType, auth.TypeHash, fmt.Sprintf("The type to be used when querying tx, can be one of \"%s\", \"%s\"", auth.TypeHeight, auth.TypeHash)) + cmd.Flags().String(FlagType, TypeHash, fmt.Sprintf("The type to be used when querying tx, can be one of \"%s\", \"%s\"", TypeHeight, TypeHash)) return cmd } // QueryBlockResultsCmd implements the default command for a BlockResults query. -func (s *CometBFTServer[AppT, T]) QueryBlockResultsCmd() *cobra.Command { +func (s *CometBFTServer[T]) QueryBlockResultsCmd() *cobra.Command { cmd := &cobra.Command{ Use: "block-results [height]", Short: "Query for a committed block's results by height", @@ -383,7 +382,7 @@ func parseOptionalHeight(heightStr string) (*int64, error) { return &tmp, nil } -func (s *CometBFTServer[AppT, T]) BootstrapStateCmd() *cobra.Command { +func (s *CometBFTServer[T]) BootstrapStateCmd() *cobra.Command { cmd := &cobra.Command{ Use: "bootstrap-state", Short: "Bootstrap CometBFT state at an arbitrary block height using a light client", diff --git a/server/v2/cometbft/config.go b/server/v2/cometbft/config.go index e349cf6dc5631..3f03e383c6016 100644 --- a/server/v2/cometbft/config.go +++ b/server/v2/cometbft/config.go @@ -5,54 +5,62 @@ import ( "github.com/spf13/viper" serverv2 "cosmossdk.io/server/v2" - "cosmossdk.io/server/v2/cometbft/types" ) -// TODO REDO/VERIFY THIS +// Config is the configuration for the CometBFT application +type Config struct { + AppTomlConfig *AppTomlConfig + ConfigTomlConfig *cmtcfg.Config +} -func GetConfigFromViper(v *viper.Viper) *cmtcfg.Config { - conf := cmtcfg.DefaultConfig() - err := v.Unmarshal(conf) - rootDir := v.GetString(serverv2.FlagHome) - if err != nil { - return cmtcfg.DefaultConfig().SetRoot(rootDir) +func DefaultAppTomlConfig() *AppTomlConfig { + return &AppTomlConfig{ + MinRetainBlocks: 0, + IndexEvents: make([]string, 0), + HaltHeight: 0, + HaltTime: 0, + Address: "tcp://127.0.0.1:26658", + Transport: "socket", + Trace: false, + Standalone: false, } +} - return conf.SetRoot(rootDir) +type AppTomlConfig struct { + MinRetainBlocks uint64 `mapstructure:"min-retain-blocks" toml:"min-retain-blocks" comment:"min-retain-blocks defines the minimum block height offset from the current block being committed, such that all blocks past this offset are pruned from CometBFT. A value of 0 indicates that no blocks should be pruned."` + IndexEvents []string `mapstructure:"index-events" toml:"index-events" comment:"index-events defines the set of events in the form {eventType}.{attributeKey}, which informs CometBFT what to index. If empty, all events will be indexed."` + HaltHeight uint64 `mapstructure:"halt-height" toml:"halt-height" comment:"halt-height contains a non-zero block height at which a node will gracefully halt and shutdown that can be used to assist upgrades and testing."` + HaltTime uint64 `mapstructure:"halt-time" toml:"halt-time" comment:"halt-time contains a non-zero minimum block time (in Unix seconds) at which a node will gracefully halt and shutdown that can be used to assist upgrades and testing."` + Address string `mapstructure:"address" toml:"address" comment:"address defines the CometBFT RPC server address to bind to."` + Transport string `mapstructure:"transport" toml:"transport" comment:"transport defines the CometBFT RPC server transport protocol: socket, grpc"` + Trace bool `mapstructure:"trace" toml:"trace" comment:"trace enables the CometBFT RPC server to output trace information about its internal operations."` + Standalone bool `mapstructure:"standalone" toml:"standalone" comment:"standalone starts the application without the CometBFT node. The node should be started separately."` } -// Config is the configuration for the CometBFT application -type Config struct { - // app.toml config options - Name string `mapstructure:"name" toml:"name"` - Version string `mapstructure:"version" toml:"version"` - InitialHeight uint64 `mapstructure:"initial_height" toml:"initial_height"` - MinRetainBlocks uint64 `mapstructure:"min_retain_blocks" toml:"min_retain_blocks"` - IndexEvents map[string]struct{} `mapstructure:"index_events" toml:"index_events"` - HaltHeight uint64 `mapstructure:"halt_height" toml:"halt_height"` - HaltTime uint64 `mapstructure:"halt_time" toml:"halt_time"` - // end of app.toml config options - - AddrPeerFilter types.PeerFilter // filter peers by address and port - IdPeerFilter types.PeerFilter // filter peers by node ID - - Transport string `mapstructure:"transport" toml:"transport"` - Addr string `mapstructure:"addr" toml:"addr"` - Standalone bool `mapstructure:"standalone" toml:"standalone"` - Trace bool `mapstructure:"trace" toml:"trace"` - // Must be set by the application to grant authority to the consensus engine to send messages to the consensus module - ConsensusAuthority string - - // config.toml - CmtConfig *cmtcfg.Config +// CfgOption is a function that allows to overwrite the default server configuration. +type CfgOption func(*Config) + +// OverwriteDefaultConfigTomlConfig overwrites the default comet config with the new config. +func OverwriteDefaultConfigTomlConfig(newCfg *cmtcfg.Config) CfgOption { + return func(cfg *Config) { + cfg.ConfigTomlConfig = newCfg // nolint:ineffassign,staticcheck // We want to overwrite everything + } +} + +// OverwriteDefaultAppTomlConfig overwrites the default comet config with the new config. +func OverwriteDefaultAppTomlConfig(newCfg *AppTomlConfig) CfgOption { + return func(cfg *Config) { + cfg.AppTomlConfig = newCfg // nolint:ineffassign,staticcheck // We want to overwrite everything + } } -// CmtCfgOption is a function that allows to overwrite the default server configuration. -type CmtCfgOption func(*cmtcfg.Config) +func getConfigTomlFromViper(v *viper.Viper) *cmtcfg.Config { + rootDir := v.GetString(serverv2.FlagHome) -// OverwriteDefaultCometConfig overwrites the default comet config with the new config. -func OverwriteDefaultCometConfig(newCfg *cmtcfg.Config) CmtCfgOption { - return func(cfg *cmtcfg.Config) { // nolint:staticcheck // We want to overwrite everything - cfg = newCfg // nolint:ineffassign,staticcheck // We want to overwrite everything + conf := cmtcfg.DefaultConfig() + if err := v.Unmarshal(conf); err != nil { + return cmtcfg.DefaultConfig().SetRoot(rootDir) } + + return conf.SetRoot(rootDir) } diff --git a/server/v2/cometbft/flags.go b/server/v2/cometbft/flags.go index fe1442edf6c55..00d57b81fb782 100644 --- a/server/v2/cometbft/flags.go +++ b/server/v2/cometbft/flags.go @@ -2,26 +2,11 @@ package cometbft import "github.com/spf13/cobra" +// Query flags const ( - FlagQuery = "query" - FlagType = "type" - FlagOrderBy = "order_by" -) - -const ( - FlagWithComet = "with-comet" - FlagAddress = "address" - FlagTransport = "transport" - FlagTraceStore = "trace-store" - FlagCPUProfile = "cpu-profile" - FlagMinGasPrices = "minimum-gas-prices" - FlagQueryGasLimit = "query-gas-limit" - FlagHaltHeight = "halt-height" - FlagHaltTime = "halt-time" - FlagTrace = "trace" -) - -const ( + FlagQuery = "query" + FlagType = "type" + FlagOrderBy = "order_by" FlagChainID = "chain-id" FlagNode = "node" FlagGRPC = "grpc-addr" @@ -30,6 +15,8 @@ const ( FlagPage = "page" FlagLimit = "limit" FlagOutput = "output" + TypeHash = "hash" + TypeHeight = "height" ) // List of supported output formats @@ -50,3 +37,13 @@ func AddQueryFlagsToCmd(cmd *cobra.Command) { // hence the flag should not be required for those commands _ = cmd.MarkFlagRequired(FlagChainID) } + +// Server flags +const ( + Standalone = "standalone" + FlagAddress = "address" + FlagTransport = "transport" + FlagHaltHeight = "halt-height" + FlagHaltTime = "halt-time" + FlagTrace = "trace" +) diff --git a/server/v2/cometbft/go.mod b/server/v2/cometbft/go.mod index 65f06e4b07c77..b33ca719aef4c 100644 --- a/server/v2/cometbft/go.mod +++ b/server/v2/cometbft/go.mod @@ -6,7 +6,6 @@ replace ( cosmossdk.io/api => ../../../api cosmossdk.io/core => ../../../core cosmossdk.io/core/testing => ../../../core/testing - cosmossdk.io/depinject => ../../../depinject cosmossdk.io/log => ../../../log cosmossdk.io/server/v2 => ../ cosmossdk.io/server/v2/appmanager => ../appmanager @@ -29,7 +28,6 @@ require ( cosmossdk.io/server/v2 v2.0.0-00010101000000-000000000000 cosmossdk.io/server/v2/appmanager v0.0.0-00010101000000-000000000000 cosmossdk.io/store/v2 v2.0.0-00010101000000-000000000000 - cosmossdk.io/x/auth v0.0.0-00010101000000-000000000000 cosmossdk.io/x/consensus v0.0.0-00010101000000-000000000000 github.com/cometbft/cometbft v1.0.0-rc1 github.com/cometbft/cometbft/api v1.0.0-rc.1 @@ -50,11 +48,13 @@ require ( require ( buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2 // indirect cosmossdk.io/collections v0.4.0 // indirect - cosmossdk.io/depinject v1.0.0-alpha.4 // indirect + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 // indirect + cosmossdk.io/depinject v1.0.0 // indirect cosmossdk.io/log v1.3.1 // indirect cosmossdk.io/math v1.3.0 // indirect cosmossdk.io/schema v0.1.1 // indirect cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc // indirect + cosmossdk.io/x/auth v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/x/bank v0.0.0-20240226161501-23359a0b6d91 // indirect cosmossdk.io/x/staking v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/x/tx v0.13.3 // indirect @@ -76,7 +76,7 @@ require ( github.com/cometbft/cometbft-db v0.12.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect diff --git a/server/v2/cometbft/go.sum b/server/v2/cometbft/go.sum index 9dce66617cae0..7ba20e510178a 100644 --- a/server/v2/cometbft/go.sum +++ b/server/v2/cometbft/go.sum @@ -6,6 +6,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -100,8 +102,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/server/v2/cometbft/options.go b/server/v2/cometbft/options.go index 0950609f7da9b..1e0a389882e04 100644 --- a/server/v2/cometbft/options.go +++ b/server/v2/cometbft/options.go @@ -4,6 +4,7 @@ import ( "cosmossdk.io/core/transaction" "cosmossdk.io/server/v2/cometbft/handlers" "cosmossdk.io/server/v2/cometbft/mempool" + "cosmossdk.io/server/v2/cometbft/types" "cosmossdk.io/store/v2/snapshots" ) @@ -16,6 +17,9 @@ type ServerOptions[T transaction.Tx] struct { ExtendVoteHandler handlers.ExtendVoteHandler SnapshotOptions snapshots.SnapshotOptions + + AddrPeerFilter types.PeerFilter // filter peers by address and port + IdPeerFilter types.PeerFilter // filter peers by node ID } // DefaultServerOptions returns the default server options. @@ -28,5 +32,7 @@ func DefaultServerOptions[T transaction.Tx]() ServerOptions[T] { VerifyVoteExtensionHandler: handlers.NoOpVerifyVoteExtensionHandler(), ExtendVoteHandler: handlers.NoOpExtendVote(), SnapshotOptions: snapshots.NewSnapshotOptions(0, 0), + AddrPeerFilter: nil, + IdPeerFilter: nil, } } diff --git a/server/v2/cometbft/query.go b/server/v2/cometbft/query.go index d45c97cd078b0..912338ff79f35 100644 --- a/server/v2/cometbft/query.go +++ b/server/v2/cometbft/query.go @@ -20,13 +20,14 @@ func (c *Consensus[T]) handleQueryP2P(path []string) (*abci.QueryResponse, error cmd, typ, arg := path[1], path[2], path[3] if cmd == "filter" { - if typ == "addr" { - if c.cfg.AddrPeerFilter != nil { - return c.cfg.AddrPeerFilter(arg) + switch typ { + case "addr": + if c.addrPeerFilter != nil { + return c.addrPeerFilter(arg) } - } else if typ == "id" { - if c.cfg.IdPeerFilter != nil { - return c.cfg.IdPeerFilter(arg) + case "id": + if c.idPeerFilter != nil { + return c.idPeerFilter(arg) } } } @@ -61,7 +62,7 @@ func (c *Consensus[T]) handlerQueryApp(ctx context.Context, path []string, req * return nil, errorsmod.Wrap(err, "failed to simulate tx") } - bz, err := intoABCISimulationResponse(txResult, c.cfg.IndexEvents) + bz, err := intoABCISimulationResponse(txResult, c.indexedEvents) if err != nil { return nil, errorsmod.Wrap(err, "failed to marshal txResult") } @@ -75,7 +76,7 @@ func (c *Consensus[T]) handlerQueryApp(ctx context.Context, path []string, req * case "version": return &abci.QueryResponse{ Codespace: cometerrors.RootCodespace, - Value: []byte(c.cfg.Version), + Value: []byte(c.version), Height: req.Height, }, nil } diff --git a/server/v2/cometbft/server.go b/server/v2/cometbft/server.go index 1b1f0ff6637ee..1553a5c9a5929 100644 --- a/server/v2/cometbft/server.go +++ b/server/v2/cometbft/server.go @@ -18,7 +18,6 @@ import ( "github.com/spf13/pflag" "github.com/spf13/viper" - corectx "cosmossdk.io/core/context" "cosmossdk.io/core/log" "cosmossdk.io/core/transaction" serverv2 "cosmossdk.io/server/v2" @@ -30,72 +29,91 @@ import ( ) var ( - _ serverv2.ServerComponent[ - serverv2.AppI[transaction.Tx], transaction.Tx, - ] = (*CometBFTServer[serverv2.AppI[transaction.Tx], transaction.Tx])(nil) - _ serverv2.HasCLICommands = (*CometBFTServer[serverv2.AppI[transaction.Tx], transaction.Tx])(nil) - _ serverv2.HasStartFlags = (*CometBFTServer[serverv2.AppI[transaction.Tx], transaction.Tx])(nil) + _ serverv2.ServerComponent[transaction.Tx] = (*CometBFTServer[transaction.Tx])(nil) + _ serverv2.HasCLICommands = (*CometBFTServer[transaction.Tx])(nil) + _ serverv2.HasStartFlags = (*CometBFTServer[transaction.Tx])(nil) ) -type CometBFTServer[AppT serverv2.AppI[T], T transaction.Tx] struct { +type CometBFTServer[T transaction.Tx] struct { Node *node.Node Consensus *Consensus[T] - initTxCodec transaction.Codec[T] - logger log.Logger - config Config - options ServerOptions[T] - cmtConfigOptions []CmtCfgOption + initTxCodec transaction.Codec[T] + logger log.Logger + serverOptions ServerOptions[T] + config Config + cfgOptions []CfgOption } -func New[AppT serverv2.AppI[T], T transaction.Tx](txCodec transaction.Codec[T], options ServerOptions[T], cfgOptions ...CmtCfgOption) *CometBFTServer[AppT, T] { - return &CometBFTServer[AppT, T]{ - initTxCodec: txCodec, - options: options, - cmtConfigOptions: cfgOptions, +func New[T transaction.Tx](txCodec transaction.Codec[T], serverOptions ServerOptions[T], cfgOptions ...CfgOption) *CometBFTServer[T] { + return &CometBFTServer[T]{ + initTxCodec: txCodec, + serverOptions: serverOptions, + cfgOptions: cfgOptions, } } -func (s *CometBFTServer[AppT, T]) Init(appI AppT, v *viper.Viper, logger log.Logger) error { - s.config = Config{CmtConfig: GetConfigFromViper(v), ConsensusAuthority: appI.GetConsensusAuthority()} - s.logger = logger.With(log.ModuleKey, s.Name()) +func (s *CometBFTServer[T]) Init(appI serverv2.AppI[T], v *viper.Viper, logger log.Logger) error { + // get configs (app.toml + config.toml) from viper + appTomlConfig := s.Config().(*AppTomlConfig) + if v != nil { + if err := serverv2.UnmarshalSubConfig(v, s.Name(), &appTomlConfig); err != nil { + return fmt.Errorf("failed to unmarshal config: %w", err) + } + } + s.config = Config{ + ConfigTomlConfig: getConfigTomlFromViper(v), + AppTomlConfig: appTomlConfig, + } - // create consensus - store := appI.GetStore().(types.Store) - consensus := NewConsensus[T](appI.GetAppManager(), s.options.Mempool, store, s.config, s.initTxCodec, s.logger) + indexEvents := make(map[string]struct{}, len(s.config.AppTomlConfig.IndexEvents)) + for _, e := range s.config.AppTomlConfig.IndexEvents { + indexEvents[e] = struct{}{} + } - consensus.prepareProposalHandler = s.options.PrepareProposalHandler - consensus.processProposalHandler = s.options.ProcessProposalHandler - consensus.verifyVoteExt = s.options.VerifyVoteExtensionHandler - consensus.extendVote = s.options.ExtendVoteHandler + s.logger = logger.With(log.ModuleKey, s.Name()) + consensus := NewConsensus( + s.logger, + appI.Name(), + appI.GetConsensusAuthority(), + appI.GetAppManager(), + s.serverOptions.Mempool, + indexEvents, + appI.GetGRPCQueryDecoders(), + appI.GetStore().(types.Store), + s.config, + s.initTxCodec, + ) + consensus.prepareProposalHandler = s.serverOptions.PrepareProposalHandler + consensus.processProposalHandler = s.serverOptions.ProcessProposalHandler + consensus.verifyVoteExt = s.serverOptions.VerifyVoteExtensionHandler + consensus.extendVote = s.serverOptions.ExtendVoteHandler + consensus.addrPeerFilter = s.serverOptions.AddrPeerFilter + consensus.idPeerFilter = s.serverOptions.IdPeerFilter // TODO: set these; what is the appropriate presence of the Store interface here? var ss snapshots.StorageSnapshotter var sc snapshots.CommitSnapshotter - snapshotStore, err := GetSnapshotStore(s.config.CmtConfig.RootDir) + snapshotStore, err := GetSnapshotStore(s.config.ConfigTomlConfig.RootDir) if err != nil { return err } - - sm := snapshots.NewManager(snapshotStore, s.options.SnapshotOptions, sc, ss, nil, s.logger) - consensus.SetSnapshotManager(sm) + consensus.snapshotManager = snapshots.NewManager(snapshotStore, s.serverOptions.SnapshotOptions, sc, ss, nil, s.logger) s.Consensus = consensus + return nil } -func (s *CometBFTServer[AppT, T]) Name() string { +func (s *CometBFTServer[T]) Name() string { return "comet" } -func (s *CometBFTServer[AppT, T]) Start(ctx context.Context) error { - viper := ctx.Value(corectx.ViperContextKey).(*viper.Viper) - cometConfig := GetConfigFromViper(viper) - +func (s *CometBFTServer[T]) Start(ctx context.Context) error { wrappedLogger := cometlog.CometLoggerWrapper{Logger: s.logger} - if s.config.Standalone { - svr, err := abciserver.NewServer(s.config.Addr, s.config.Transport, s.Consensus) + if s.config.AppTomlConfig.Standalone { + svr, err := abciserver.NewServer(s.config.AppTomlConfig.Address, s.config.AppTomlConfig.Transport, s.Consensus) if err != nil { return fmt.Errorf("error creating listener: %w", err) } @@ -105,20 +123,20 @@ func (s *CometBFTServer[AppT, T]) Start(ctx context.Context) error { return svr.Start() } - nodeKey, err := p2p.LoadOrGenNodeKey(cometConfig.NodeKeyFile()) + nodeKey, err := p2p.LoadOrGenNodeKey(s.config.ConfigTomlConfig.NodeKeyFile()) if err != nil { return err } s.Node, err = node.NewNode( ctx, - cometConfig, - pvm.LoadOrGenFilePV(cometConfig.PrivValidatorKeyFile(), cometConfig.PrivValidatorStateFile()), + s.config.ConfigTomlConfig, + pvm.LoadOrGenFilePV(s.config.ConfigTomlConfig.PrivValidatorKeyFile(), s.config.ConfigTomlConfig.PrivValidatorStateFile()), nodeKey, proxy.NewConsensusSyncLocalClientCreator(s.Consensus), - getGenDocProvider(cometConfig), + getGenDocProvider(s.config.ConfigTomlConfig), cmtcfg.DefaultDBProvider, - node.DefaultMetricsProvider(cometConfig.Instrumentation), + node.DefaultMetricsProvider(s.config.ConfigTomlConfig.Instrumentation), wrappedLogger, ) if err != nil { @@ -128,7 +146,7 @@ func (s *CometBFTServer[AppT, T]) Start(ctx context.Context) error { return s.Node.Start() } -func (s *CometBFTServer[AppT, T]) Stop(context.Context) error { +func (s *CometBFTServer[T]) Stop(context.Context) error { if s.Node != nil && s.Node.IsRunning() { return s.Node.Stop() } @@ -174,22 +192,26 @@ func getGenDocProvider(cfg *cmtcfg.Config) func() (node.ChecksummedGenesisDoc, e } } -func (s *CometBFTServer[AppT, T]) StartCmdFlags() *pflag.FlagSet { +func (s *CometBFTServer[T]) StartCmdFlags() *pflag.FlagSet { flags := pflag.NewFlagSet("cometbft", pflag.ExitOnError) - flags.Bool(FlagWithComet, true, "Run abci app embedded in-process with CometBFT") - flags.String(FlagAddress, "tcp://127.0.0.1:26658", "Listen address") - flags.String(FlagTransport, "socket", "Transport protocol: socket, grpc") - flags.String(FlagTraceStore, "", "Enable KVStore tracing to an output file") - flags.String(FlagMinGasPrices, "", "Minimum gas prices to accept for transactions; Any fee in a tx must meet this minimum (e.g. 0.01photino;0.0001stake)") - flags.Uint64(FlagQueryGasLimit, 0, "Maximum gas a Rest/Grpc query can consume. Blank and 0 imply unbounded.") - flags.Uint64(FlagHaltHeight, 0, "Block height at which to gracefully halt the chain and shutdown the node") - flags.Uint64(FlagHaltTime, 0, "Minimum block time (in Unix seconds) at which to gracefully halt the chain and shutdown the node") - flags.String(FlagCPUProfile, "", "Enable CPU profiling and write to the provided file") - flags.Bool(FlagTrace, false, "Provide full stack traces for errors in ABCI Log") + + // start flags are prefixed with the server name + // as the config in prefixed with the server name + // this allows viper to properly bind the flags + prefix := func(f string) string { + return fmt.Sprintf("%s.%s", s.Name(), f) + } + + flags.String(prefix(FlagAddress), "tcp://127.0.0.1:26658", "Listen address") + flags.String(prefix(FlagTransport), "socket", "Transport protocol: socket, grpc") + flags.Uint64(prefix(FlagHaltHeight), 0, "Block height at which to gracefully halt the chain and shutdown the node") + flags.Uint64(prefix(FlagHaltTime), 0, "Minimum block time (in Unix seconds) at which to gracefully halt the chain and shutdown the node") + flags.Bool(prefix(FlagTrace), false, "Provide full stack traces for errors in ABCI Log") + flags.Bool(prefix(Standalone), false, "Run app without CometBFT") return flags } -func (s *CometBFTServer[AppT, T]) CLICommands() serverv2.CLIConfig { +func (s *CometBFTServer[T]) CLICommands() serverv2.CLIConfig { return serverv2.CLIConfig{ Commands: []*cobra.Command{ s.StatusCommand(), @@ -208,12 +230,30 @@ func (s *CometBFTServer[AppT, T]) CLICommands() serverv2.CLIConfig { } } -func (s *CometBFTServer[AppT, T]) WriteDefaultConfigAt(configPath string) error { - cometConfig := cmtcfg.DefaultConfig() - for _, opt := range s.cmtConfigOptions { - opt(cometConfig) +// CometBFT is a special server, it has config in config.toml and app.toml + +// Config returns the (app.toml) server configuration. +func (s *CometBFTServer[T]) Config() any { + if s.config.AppTomlConfig == nil || s.config.AppTomlConfig == (&AppTomlConfig{}) { + cfg := &Config{AppTomlConfig: DefaultAppTomlConfig()} + // overwrite the default config with the provided options + for _, opt := range s.cfgOptions { + opt(cfg) + } + + return cfg.AppTomlConfig + } + + return s.config.AppTomlConfig +} + +// WriteCustomConfigAt writes the default cometbft config.toml +func (s *CometBFTServer[T]) WriteCustomConfigAt(configPath string) error { + cfg := &Config{ConfigTomlConfig: cmtcfg.DefaultConfig()} + for _, opt := range s.cfgOptions { + opt(cfg) } - cmtcfg.WriteConfigFile(filepath.Join(configPath, "config.toml"), cometConfig) + cmtcfg.WriteConfigFile(filepath.Join(configPath, "config.toml"), cfg.ConfigTomlConfig) return nil } diff --git a/server/v2/cometbft/utils.go b/server/v2/cometbft/utils.go index b302e90c78c35..b4bfb5a6dd30e 100644 --- a/server/v2/cometbft/utils.go +++ b/server/v2/cometbft/utils.go @@ -262,10 +262,10 @@ func (c *Consensus[T]) validateFinalizeBlockHeight(req *abci.FinalizeBlockReques // expectedHeight holds the expected height to validate var expectedHeight uint64 - if lastBlockHeight == 0 && c.cfg.InitialHeight > 1 { + if lastBlockHeight == 0 && c.initialHeight > 1 { // In this case, we're validating the first block of the chain, i.e no // previous commit. The height we're expecting is the initial height. - expectedHeight = c.cfg.InitialHeight + expectedHeight = c.initialHeight } else { // This case can mean two things: // @@ -327,7 +327,7 @@ func (c *Consensus[T]) GetConsensusParams(ctx context.Context) (*cmtproto.Consen func (c *Consensus[T]) GetBlockRetentionHeight(cp *cmtproto.ConsensusParams, commitHeight int64) int64 { // pruning is disabled if minRetainBlocks is zero - if c.cfg.MinRetainBlocks == 0 { + if c.cfg.AppTomlConfig.MinRetainBlocks == 0 { return 0 } @@ -368,7 +368,7 @@ func (c *Consensus[T]) GetBlockRetentionHeight(cp *cmtproto.ConsensusParams, com } } - v := commitHeight - int64(c.cfg.MinRetainBlocks) + v := commitHeight - int64(c.cfg.AppTomlConfig.MinRetainBlocks) retentionHeight = minNonZero(retentionHeight, v) if retentionHeight <= 0 { @@ -383,15 +383,15 @@ func (c *Consensus[T]) GetBlockRetentionHeight(cp *cmtproto.ConsensusParams, com func (c *Consensus[T]) checkHalt(height int64, time time.Time) error { var halt bool switch { - case c.cfg.HaltHeight > 0 && uint64(height) > c.cfg.HaltHeight: + case c.cfg.AppTomlConfig.HaltHeight > 0 && uint64(height) > c.cfg.AppTomlConfig.HaltHeight: halt = true - case c.cfg.HaltTime > 0 && time.Unix() > int64(c.cfg.HaltTime): + case c.cfg.AppTomlConfig.HaltTime > 0 && time.Unix() > int64(c.cfg.AppTomlConfig.HaltTime): halt = true } if halt { - return fmt.Errorf("halt per configuration height %d time %d", c.cfg.HaltHeight, c.cfg.HaltTime) + return fmt.Errorf("halt per configuration height %d time %d", c.cfg.AppTomlConfig.HaltHeight, c.cfg.AppTomlConfig.HaltTime) } return nil diff --git a/server/v2/cometbft/version.go b/server/v2/cometbft/version.go new file mode 100644 index 0000000000000..1151f819ac39d --- /dev/null +++ b/server/v2/cometbft/version.go @@ -0,0 +1,26 @@ +package cometbft + +import "runtime/debug" + +var Version = "" + +func getCometBFTServerVersion() string { + deps, ok := debug.ReadBuildInfo() + if !ok { + return Version + } + + var serverVersion string + for _, dep := range deps.Deps { + if dep.Path == "cosmossdk.io/server/v2/cometbft" { + if dep.Replace != nil && dep.Replace.Version != "(devel)" { + serverVersion = dep.Replace.Version + } else { + serverVersion = dep.Version + } + } + } + + Version = serverVersion + return serverVersion +} diff --git a/server/v2/commands.go b/server/v2/commands.go index db385a832d818..a0b2b05ae9028 100644 --- a/server/v2/commands.go +++ b/server/v2/commands.go @@ -3,7 +3,6 @@ package serverv2 import ( "context" "errors" - "fmt" "os" "os/signal" "path/filepath" @@ -35,11 +34,11 @@ func Execute(rootCmd *cobra.Command, envPrefix, defaultHome string) error { // AddCommands add the server commands to the root command // It configure the config handling and the logger handling -func AddCommands[AppT AppI[T], T transaction.Tx]( +func AddCommands[T transaction.Tx]( rootCmd *cobra.Command, - newApp AppCreator[AppT, T], + newApp AppCreator[T], logger log.Logger, - components ...ServerComponent[AppT, T], + components ...ServerComponent[T], ) error { if len(components) == 0 { return errors.New("no components provided") @@ -96,25 +95,18 @@ func AddCommands[AppT AppI[T], T transaction.Tx]( } // createStartCommand creates the start command for the application. -func createStartCommand[AppT AppI[T], T transaction.Tx]( - server *Server[AppT, T], - newApp AppCreator[AppT, T], +func createStartCommand[T transaction.Tx]( + server *Server[T], + newApp AppCreator[T], ) *cobra.Command { flags := server.StartFlags() - return &cobra.Command{ + cmd := &cobra.Command{ Use: "start", Short: "Run the application", RunE: func(cmd *cobra.Command, args []string) error { v := GetViperFromCmd(cmd) l := GetLoggerFromCmd(cmd) - - for _, startFlags := range flags { - if err := v.BindPFlags(startFlags); err != nil { - return err - } - } - if err := v.BindPFlags(cmd.Flags()); err != nil { return err } @@ -137,16 +129,23 @@ func createStartCommand[AppT AppI[T], T transaction.Tx]( }() if err := server.Start(ctx); err != nil { - return fmt.Errorf("failed to start servers: %w", err) + return err } return nil }, } + + // add the start flags to the command + for _, startFlags := range flags { + cmd.Flags().AddFlagSet(startFlags) + } + + return cmd } // configHandle writes the default config to the home directory if it does not exist and sets the server context -func configHandle[AppT AppI[T], T transaction.Tx](s *Server[AppT, T], cmd *cobra.Command) error { +func configHandle[T transaction.Tx](s *Server[T], cmd *cobra.Command) error { home, err := cmd.Flags().GetString(FlagHome) if err != nil { return err diff --git a/server/v2/config.go b/server/v2/config.go index cb5fbeae7cb53..57cce302bd743 100644 --- a/server/v2/config.go +++ b/server/v2/config.go @@ -1,15 +1,61 @@ package serverv2 -import "github.com/spf13/cobra" - -// CLIConfig defines the CLI configuration for a module server. -type CLIConfig struct { - // Commands defines the main command of a module server. - Commands []*cobra.Command - // Queries defines the query commands of a module server. - // Those commands are meant to be added in the root query command. - Queries []*cobra.Command - // Txs defines the tx commands of a module server. - // Those commands are meant to be added in the root tx command. - Txs []*cobra.Command +import ( + "fmt" + "strings" + + "github.com/mitchellh/mapstructure" + "github.com/spf13/viper" +) + +// ReadConfig returns a viper instance of the config file +func ReadConfig(configPath string) (*viper.Viper, error) { + v := viper.New() + v.SetConfigType("toml") + v.SetConfigName("config") + v.AddConfigPath(configPath) + if err := v.ReadInConfig(); err != nil { + return nil, fmt.Errorf("failed to read config: %s: %w", configPath, err) + } + + v.SetConfigName("app") + if err := v.MergeInConfig(); err != nil { + return nil, fmt.Errorf("failed to merge configuration: %w", err) + } + + v.WatchConfig() + + return v, nil +} + +// UnmarshalSubConfig unmarshals the given subconfig from the viper instance. +// It unmarshals the config, env, flags into the target struct. +// Use this instead of viper.Sub because viper does not unmarshal flags. +func UnmarshalSubConfig(v *viper.Viper, subName string, target any) error { + var sub any + for k, val := range v.AllSettings() { + if strings.HasPrefix(k, subName) { + sub = val + } + } + + // Create a new decoder with custom decoding options + decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ + DecodeHook: mapstructure.ComposeDecodeHookFunc( + mapstructure.StringToTimeDurationHookFunc(), + mapstructure.StringToSliceHookFunc(","), + ), + Result: target, + WeaklyTypedInput: true, + }) + if err != nil { + return fmt.Errorf("failed to create decoder: %w", err) + } + + // Decode the sub-configuration + if err := decoder.Decode(sub); err != nil { + return fmt.Errorf("failed to decode sub-configuration: %w", err) + } + + return nil } diff --git a/server/v2/config_test.go b/server/v2/config_test.go new file mode 100644 index 0000000000000..24eb28bb7522e --- /dev/null +++ b/server/v2/config_test.go @@ -0,0 +1,39 @@ +package serverv2_test + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" + + serverv2 "cosmossdk.io/server/v2" + grpc "cosmossdk.io/server/v2/api/grpc" +) + +func TestReadConfig(t *testing.T) { + currentDir, err := os.Getwd() + require.NoError(t, err) + configPath := filepath.Join(currentDir, "testdata") + + v, err := serverv2.ReadConfig(configPath) + require.NoError(t, err) + + require.Equal(t, v.GetString("grpc.address"), grpc.DefaultConfig().Address) +} + +func TestUnmarshalSubConfig(t *testing.T) { + currentDir, err := os.Getwd() + require.NoError(t, err) + configPath := filepath.Join(currentDir, "testdata") + + v, err := serverv2.ReadConfig(configPath) + require.NoError(t, err) + + grpcConfig := grpc.DefaultConfig() + err = serverv2.UnmarshalSubConfig(v, "grpc", &grpcConfig) + require.NoError(t, err) + + require.True(t, grpc.DefaultConfig().Enable) + require.False(t, grpcConfig.Enable) +} diff --git a/server/v2/go.mod b/server/v2/go.mod index 9bd01b72a7d1b..31e857839fa94 100644 --- a/server/v2/go.mod +++ b/server/v2/go.mod @@ -5,7 +5,7 @@ go 1.21 replace ( cosmossdk.io/api => ../../api cosmossdk.io/core => ../../core - cosmossdk.io/depinject => ../../depinject + cosmossdk.io/core/testing => ../../core/testing cosmossdk.io/log => ../../log cosmossdk.io/server/v2/appmanager => ./appmanager cosmossdk.io/server/v2/stf => ./stf @@ -15,6 +15,7 @@ replace ( require ( cosmossdk.io/api v0.7.5 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 cosmossdk.io/log v1.3.1 cosmossdk.io/server/v2/appmanager v0.0.0-00010101000000-000000000000 github.com/cosmos/cosmos-proto v1.0.0-beta.5 @@ -26,6 +27,7 @@ require ( github.com/hashicorp/go-hclog v1.6.2 github.com/hashicorp/go-metrics v0.5.3 github.com/hashicorp/go-plugin v1.6.0 + github.com/mitchellh/mapstructure v1.5.0 github.com/pelletier/go-toml/v2 v2.2.2 github.com/prometheus/client_golang v1.19.1 github.com/prometheus/common v0.55.0 @@ -60,7 +62,6 @@ require ( github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mitchellh/go-testing-interface v1.14.1 // indirect - github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/oklog/run v1.1.0 // indirect github.com/pkg/errors v0.9.1 // indirect @@ -74,6 +75,7 @@ require ( github.com/spf13/afero v1.11.0 // indirect github.com/spf13/cast v1.6.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect + github.com/tidwall/btree v1.7.0 // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc // indirect golang.org/x/net v0.27.0 // indirect diff --git a/server/v2/go.sum b/server/v2/go.sum index 14f585a6b8c5d..247c43d719ec9 100644 --- a/server/v2/go.sum +++ b/server/v2/go.sum @@ -243,6 +243,8 @@ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsT github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/tidwall/btree v1.7.0 h1:L1fkJH/AuEh5zBnnBbmTwQ5Lt+bRJ5A8EWecslvo9iI= +github.com/tidwall/btree v1.7.0/go.mod h1:twD9XRA5jj9VUQGELzDO4HPQTNJsoWWfYEL+EUQ2cKY= github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= diff --git a/server/v2/server.go b/server/v2/server.go index c8db2773bdbbf..6e1a4e7114dbb 100644 --- a/server/v2/server.go +++ b/server/v2/server.go @@ -18,17 +18,20 @@ import ( ) // ServerComponent is a server module that can be started and stopped. -type ServerComponent[AppT AppI[T], T transaction.Tx] interface { +type ServerComponent[T transaction.Tx] interface { Name() string Start(context.Context) error Stop(context.Context) error - Init(AppT, *viper.Viper, log.Logger) error + Init(AppI[T], *viper.Viper, log.Logger) error } -// HasCLICommands is a server module that has CLI commands. -type HasCLICommands interface { - CLICommands() CLIConfig +// HasStartFlags is a server module that has start flags. +type HasStartFlags interface { + // StartCmdFlags returns server start flags. + // Those flags should be prefixed with the server name. + // They are then merged with the server config in one viper instance. + StartCmdFlags() *pflag.FlagSet } // HasConfig is a server module that has a config. @@ -36,53 +39,46 @@ type HasConfig interface { Config() any } -// HasStartFlags is a server module that has start flags. -type HasStartFlags interface { - StartCmdFlags() *pflag.FlagSet +// HasCLICommands is a server module that has CLI commands. +type HasCLICommands interface { + CLICommands() CLIConfig } -var _ ServerComponent[AppI[transaction.Tx], transaction.Tx] = (*Server[AppI[transaction.Tx], transaction.Tx])(nil) - -// ReadConfig returns a viper instance of the config file -func ReadConfig(configPath string) (*viper.Viper, error) { - v := viper.New() - v.SetConfigType("toml") - v.SetConfigName("config") - v.AddConfigPath(configPath) - if err := v.ReadInConfig(); err != nil { - return nil, fmt.Errorf("failed to read config: %s: %w", configPath, err) - } - - v.SetConfigName("app") - if err := v.MergeInConfig(); err != nil { - return nil, fmt.Errorf("failed to merge configuration: %w", err) - } - - v.WatchConfig() - - return v, nil +// CLIConfig defines the CLI configuration for a module server. +type CLIConfig struct { + // Commands defines the main command of a module server. + Commands []*cobra.Command + // Queries defines the query commands of a module server. + // Those commands are meant to be added in the root query command. + Queries []*cobra.Command + // Txs defines the tx commands of a module server. + // Those commands are meant to be added in the root tx command. + Txs []*cobra.Command } -type Server[AppT AppI[T], T transaction.Tx] struct { +var _ ServerComponent[transaction.Tx] = (*Server[transaction.Tx])(nil) + +type Server[T transaction.Tx] struct { logger log.Logger - components []ServerComponent[AppT, T] + components []ServerComponent[T] } -func NewServer[AppT AppI[T], T transaction.Tx]( - logger log.Logger, components ...ServerComponent[AppT, T], -) *Server[AppT, T] { - return &Server[AppT, T]{ +func NewServer[T transaction.Tx]( + logger log.Logger, + components ...ServerComponent[T], +) *Server[T] { + return &Server[T]{ logger: logger, components: components, } } -func (s *Server[AppT, T]) Name() string { +func (s *Server[T]) Name() string { return "server" } // Start starts all components concurrently. -func (s *Server[AppT, T]) Start(ctx context.Context) error { +func (s *Server[T]) Start(ctx context.Context) error { s.logger.Info("starting servers...") g, ctx := errgroup.WithContext(ctx) @@ -103,7 +99,7 @@ func (s *Server[AppT, T]) Start(ctx context.Context) error { } // Stop stops all components concurrently. -func (s *Server[AppT, T]) Stop(ctx context.Context) error { +func (s *Server[T]) Stop(ctx context.Context) error { s.logger.Info("stopping servers...") g, ctx := errgroup.WithContext(ctx) @@ -118,7 +114,7 @@ func (s *Server[AppT, T]) Stop(ctx context.Context) error { } // CLICommands returns all CLI commands of all components. -func (s *Server[AppT, T]) CLICommands() CLIConfig { +func (s *Server[T]) CLICommands() CLIConfig { compart := func(name string, cmds ...*cobra.Command) *cobra.Command { if len(cmds) == 1 && strings.HasPrefix(cmds[0].Use, name) { return cmds[0] @@ -156,7 +152,7 @@ func (s *Server[AppT, T]) CLICommands() CLIConfig { } // Configs returns all configs of all server components. -func (s *Server[AppT, T]) Configs() map[string]any { +func (s *Server[T]) Configs() map[string]any { cfgs := make(map[string]any) for _, mod := range s.components { if configmod, ok := mod.(HasConfig); ok { @@ -170,8 +166,8 @@ func (s *Server[AppT, T]) Configs() map[string]any { // Init initializes all server components with the provided application, configuration, and logger. // It returns an error if any component fails to initialize. -func (s *Server[AppT, T]) Init(appI AppT, v *viper.Viper, logger log.Logger) error { - var components []ServerComponent[AppT, T] +func (s *Server[T]) Init(appI AppI[T], v *viper.Viper, logger log.Logger) error { + var components []ServerComponent[T] for _, mod := range s.components { mod := mod if err := mod.Init(appI, v, logger); err != nil { @@ -187,7 +183,7 @@ func (s *Server[AppT, T]) Init(appI AppT, v *viper.Viper, logger log.Logger) err // WriteConfig writes the config to the given path. // Note: it does not use viper.WriteConfigAs because we do not want to store flag values in the config. -func (s *Server[AppT, T]) WriteConfig(configPath string) error { +func (s *Server[T]) WriteConfig(configPath string) error { cfgs := s.Configs() b, err := toml.Marshal(cfgs) if err != nil { @@ -208,8 +204,8 @@ func (s *Server[AppT, T]) WriteConfig(configPath string) error { // undocumented interface to write the component default config in another file than app.toml // it is used by cometbft for backward compatibility // it should not be used by other components - if mod, ok := component.(interface{ WriteDefaultConfigAt(string) error }); ok { - if err := mod.WriteDefaultConfigAt(configPath); err != nil { + if mod, ok := component.(interface{ WriteCustomConfigAt(string) error }); ok { + if err := mod.WriteCustomConfigAt(configPath); err != nil { return err } } @@ -219,7 +215,7 @@ func (s *Server[AppT, T]) WriteConfig(configPath string) error { } // StartFlags returns all flags of all server components. -func (s *Server[AppT, T]) StartFlags() []*pflag.FlagSet { +func (s *Server[T]) StartFlags() []*pflag.FlagSet { flags := []*pflag.FlagSet{} for _, mod := range s.components { if startmod, ok := mod.(HasStartFlags); ok { diff --git a/server/v2/server_test.go b/server/v2/server_test.go index 2155e0e1af8ea..3faef417757b9 100644 --- a/server/v2/server_test.go +++ b/server/v2/server_test.go @@ -37,19 +37,9 @@ func (*mockApp[T]) InterfaceRegistry() coreapp.InterfaceRegistry { return &mockInterfaceRegistry{} } -// TODO split this test into multiple tests -// test read config -// test write config -// test server configs -// test start empty -// test start config exists -// test stop func TestServer(t *testing.T) { currentDir, err := os.Getwd() - if err != nil { - t.Log(err) - t.Fail() - } + require.NoError(t, err) configPath := filepath.Join(currentDir, "testdata") v, err := serverv2.ReadConfig(configPath) @@ -58,11 +48,9 @@ func TestServer(t *testing.T) { } logger := log.NewLogger(os.Stdout) - grpcServer := grpc.New[serverv2.AppI[transaction.Tx], transaction.Tx]() - if err := grpcServer.Init(&mockApp[transaction.Tx]{}, v, logger); err != nil { - t.Log(err) - t.Fail() - } + grpcServer := grpc.New[transaction.Tx]() + err = grpcServer.Init(&mockApp[transaction.Tx]{}, v, logger) + require.NoError(t, err) mockServer := &mockServer{name: "mock-server-1", ch: make(chan string, 100)} @@ -73,30 +61,17 @@ func TestServer(t *testing.T) { ) serverCfgs := server.Configs() - if serverCfgs[grpcServer.Name()].(*grpc.Config).Address != grpc.DefaultConfig().Address { - t.Logf("config is not equal: %v", serverCfgs[grpcServer.Name()]) - t.Fail() - } - if serverCfgs[mockServer.Name()].(*mockServerConfig).MockFieldOne != MockServerDefaultConfig().MockFieldOne { - t.Logf("config is not equal: %v", serverCfgs[mockServer.Name()]) - t.Fail() - } + require.Equal(t, serverCfgs[grpcServer.Name()].(*grpc.Config).Address, grpc.DefaultConfig().Address) + require.Equal(t, serverCfgs[mockServer.Name()].(*mockServerConfig).MockFieldOne, MockServerDefaultConfig().MockFieldOne) // write config - if err := server.WriteConfig(configPath); err != nil { - t.Log(err) - t.Fail() - } + err = server.WriteConfig(configPath) + require.NoError(t, err) v, err = serverv2.ReadConfig(configPath) - if err != nil { - t.Log(err) // config should be created by WriteConfig - t.FailNow() - } - if v.GetString(grpcServer.Name()+".address") != grpc.DefaultConfig().Address { - t.Logf("config is not equal: %v", v) - t.Fail() - } + require.NoError(t, err) + + require.Equal(t, v.GetString(grpcServer.Name()+".address"), grpc.DefaultConfig().Address) // start empty ctx, cancelFn := context.WithCancel(context.TODO()) @@ -105,30 +80,10 @@ func TestServer(t *testing.T) { <-time.After(5 * time.Second) cancelFn() - if err := server.Stop(ctx); err != nil { - t.Logf("failed to stop servers: %s", err) - t.Fail() - } + err = server.Stop(ctx) + require.NoError(t, err) }() - if err := server.Start(ctx); err != nil { - t.Log(err) - t.Fail() - } -} - -func TestReadConfig(t *testing.T) { - currentDir, err := os.Getwd() - if err != nil { - t.Log(err) - t.Fail() - } - configPath := filepath.Join(currentDir, "testdata") - - v, err := serverv2.ReadConfig(configPath) - require.NoError(t, err) - - grpcConfig := grpc.DefaultConfig() - err = v.Sub("grpc-server").Unmarshal(&grpcConfig) + err = server.Start(ctx) require.NoError(t, err) } diff --git a/server/v2/stf/branch/writer_map.go b/server/v2/stf/branch/writer_map.go index ebe02f4e7b0b4..244b51b3e7897 100644 --- a/server/v2/stf/branch/writer_map.go +++ b/server/v2/stf/branch/writer_map.go @@ -53,47 +53,22 @@ func (b WriterMap) ApplyStateChanges(stateChanges []store.StateChanges) error { return nil } -// GetStateChanges returns the state changes for all actors in the WriterMap, including all direct -// ancesotors from which this WriterMap was derived. -// See WriterMap.recurseStateChanges for more details. -// Subject to possible renaming to ensure a developer can retrieve only changes in *this* branch -// context (not ancestors) if that is desired. -// see: https://github.com/cosmos/cosmos-sdk/pull/20412#discussion_r1618771230 +// GetStateChanges returns the state changes for all actors in the WriterMap. func (b WriterMap) GetStateChanges() ([]store.StateChanges, error) { - var ( - changes = make(map[string][]store.KVPair) - sc []store.StateChanges - ) - if err := b.recurseStateChanges(changes); err != nil { - return nil, err - } - - for account, kvPairs := range changes { + sc := make([]store.StateChanges, 0, len(b.branchedWriterState)) + for acc, w := range b.branchedWriterState { + accBytes := []byte(acc) + kvChanges, err := w.ChangeSets() + if err != nil { + return nil, fmt.Errorf("unable to get actor writer changes %x: %w", accBytes, err) + } sc = append(sc, store.StateChanges{ - Actor: []byte(account), - StateChanges: kvPairs, + Actor: accBytes, + StateChanges: kvChanges, }) } - return sc, nil -} -// recurseStateChanges will recursively collect state changes from the tree of -// WriterMap's and write them to the `changes` map. -func (b WriterMap) recurseStateChanges(changes map[string][]store.KVPair) error { - // depth first - if wr, ok := b.state.(WriterMap); ok { - if err := wr.recurseStateChanges(changes); err != nil { - return err - } - } - for account, stateChange := range b.branchedWriterState { - kvChanges, err := stateChange.ChangeSets() - if err != nil { - return err - } - changes[account] = append(changes[account], kvChanges...) - } - return nil + return sc, nil } func (b WriterMap) applyStateChange(sc store.StateChanges) error { diff --git a/server/v2/stf/go.mod b/server/v2/stf/go.mod index fde2f7501ae60..59c6888ecb4cd 100644 --- a/server/v2/stf/go.mod +++ b/server/v2/stf/go.mod @@ -15,7 +15,6 @@ require ( require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/google/go-cmp v0.6.0 // indirect - github.com/kr/text v0.1.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect google.golang.org/protobuf v1.34.2 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/server/v2/stf/go.sum b/server/v2/stf/go.sum index 00afeef4cfd9c..fe0851fd94014 100644 --- a/server/v2/stf/go.sum +++ b/server/v2/stf/go.sum @@ -6,15 +6,8 @@ github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= -github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/tidwall/btree v1.7.0 h1:L1fkJH/AuEh5zBnnBbmTwQ5Lt+bRJ5A8EWecslvo9iI= @@ -23,8 +16,7 @@ golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/server/v2/streaming/streaming_test.go b/server/v2/streaming/streaming_test.go index 86ff7fd0719a9..0a590c951177d 100644 --- a/server/v2/streaming/streaming_test.go +++ b/server/v2/streaming/streaming_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/suite" "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" ) type PluginTestSuite struct { @@ -52,7 +53,7 @@ func (s *PluginTestSuite) SetupTest() { abciListener, ok := raw.(Listener) require.True(s.T(), ok, "should pass type check") - logger := log.NewNopLogger() + logger := coretesting.NewNopLogger() streamingService := Manager{ Listeners: []Listener{abciListener}, StopNodeOnErr: true, diff --git a/server/v2/testdata/app.toml b/server/v2/testdata/app.toml index 34fb5b0b02393..20482ac442820 100644 --- a/server/v2/testdata/app.toml +++ b/server/v2/testdata/app.toml @@ -1,6 +1,6 @@ [grpc] # Enable defines if the gRPC server should be enabled. -enable = true +enable = false # Address defines the gRPC server address to bind to. address = 'localhost:9090' # MaxRecvMsgSize defines the max message size in bytes the server can receive. diff --git a/server/v2/types.go b/server/v2/types.go index 1a22abf8e16f7..fc6caaaeb7350 100644 --- a/server/v2/types.go +++ b/server/v2/types.go @@ -1,6 +1,7 @@ package serverv2 import ( + gogoproto "github.com/cosmos/gogoproto/proto" "github.com/spf13/viper" coreapp "cosmossdk.io/core/app" @@ -9,11 +10,13 @@ import ( "cosmossdk.io/server/v2/appmanager" ) -type AppCreator[AppT AppI[T], T transaction.Tx] func(log.Logger, *viper.Viper) AppT +type AppCreator[T transaction.Tx] func(log.Logger, *viper.Viper) AppI[T] type AppI[T transaction.Tx] interface { + Name() string + InterfaceRegistry() coreapp.InterfaceRegistry GetAppManager() *appmanager.AppManager[T] GetConsensusAuthority() string - InterfaceRegistry() coreapp.InterfaceRegistry + GetGRPCQueryDecoders() map[string]func(requestBytes []byte) (gogoproto.Message, error) GetStore() any } diff --git a/simapp/app.go b/simapp/app.go index 4eecb39e8208a..70891d8a1626c 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -19,6 +19,7 @@ import ( reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1" "cosmossdk.io/client/v2/autocli" clienthelpers "cosmossdk.io/client/v2/helpers" + "cosmossdk.io/core/appmodule" "cosmossdk.io/core/log" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/accounts" @@ -436,28 +437,29 @@ func NewSimApp( // NOTE: Any module instantiated in the module manager that is later modified // must be passed by reference here. - app.ModuleManager = module.NewManager( - genutil.NewAppModule(appCodec, app.AuthKeeper, app.StakingKeeper, app, txConfig, genutiltypes.DefaultMessageValidator), - accounts.NewAppModule(appCodec, app.AccountsKeeper), - auth.NewAppModule(appCodec, app.AuthKeeper, app.AccountsKeeper, authsims.RandomGenesisAccounts), - vesting.NewAppModule(app.AuthKeeper, app.BankKeeper), - bank.NewAppModule(appCodec, app.BankKeeper, app.AuthKeeper), - feegrantmodule.NewAppModule(appCodec, app.FeeGrantKeeper, app.interfaceRegistry), - gov.NewAppModule(appCodec, &app.GovKeeper, app.AuthKeeper, app.BankKeeper, app.PoolKeeper), - mint.NewAppModule(appCodec, app.MintKeeper, app.AuthKeeper, nil), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AuthKeeper, app.BankKeeper, app.StakingKeeper, app.interfaceRegistry, cometService), - distr.NewAppModule(appCodec, app.DistrKeeper, app.StakingKeeper), - staking.NewAppModule(appCodec, app.StakingKeeper), - upgrade.NewAppModule(app.UpgradeKeeper), - evidence.NewAppModule(appCodec, app.EvidenceKeeper, cometService), - authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.interfaceRegistry), - groupmodule.NewAppModule(appCodec, app.GroupKeeper, app.AuthKeeper, app.BankKeeper, app.interfaceRegistry), - nftmodule.NewAppModule(appCodec, app.NFTKeeper, app.AuthKeeper, app.BankKeeper, app.interfaceRegistry), - consensus.NewAppModule(appCodec, app.ConsensusParamsKeeper), - circuit.NewAppModule(appCodec, app.CircuitKeeper), - protocolpool.NewAppModule(appCodec, app.PoolKeeper, app.AuthKeeper, app.BankKeeper), - epochs.NewAppModule(appCodec, app.EpochsKeeper), - ) + app.ModuleManager = module.NewManagerFromMap(map[string]appmodule.AppModule{ + genutiltypes.ModuleName: genutil.NewAppModule(appCodec, app.AuthKeeper, app.StakingKeeper, app, txConfig, genutiltypes.DefaultMessageValidator), + accounts.ModuleName: accounts.NewAppModule(appCodec, app.AccountsKeeper), + authtypes.ModuleName: auth.NewAppModule(appCodec, app.AuthKeeper, app.AccountsKeeper, authsims.RandomGenesisAccounts), + vestingtypes.ModuleName: vesting.NewAppModule(app.AuthKeeper, app.BankKeeper), + banktypes.ModuleName: bank.NewAppModule(appCodec, app.BankKeeper, app.AuthKeeper), + feegrant.ModuleName: feegrantmodule.NewAppModule(appCodec, app.AuthKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), + govtypes.ModuleName: gov.NewAppModule(appCodec, &app.GovKeeper, app.AuthKeeper, app.BankKeeper, app.PoolKeeper), + minttypes.ModuleName: mint.NewAppModule(appCodec, app.MintKeeper, app.AuthKeeper, nil), + slashingtypes.ModuleName: slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AuthKeeper, app.BankKeeper, app.StakingKeeper, app.interfaceRegistry, cometService), + distrtypes.ModuleName: distr.NewAppModule(appCodec, app.DistrKeeper, app.AuthKeeper, app.BankKeeper, app.StakingKeeper, app.PoolKeeper), + stakingtypes.ModuleName: staking.NewAppModule(appCodec, app.StakingKeeper, app.AuthKeeper, app.BankKeeper), + upgradetypes.ModuleName: upgrade.NewAppModule(app.UpgradeKeeper), + evidencetypes.ModuleName: evidence.NewAppModule(appCodec, app.EvidenceKeeper, cometService), + authz.ModuleName: authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AuthKeeper, app.BankKeeper, app.interfaceRegistry), + group.ModuleName: groupmodule.NewAppModule(appCodec, app.GroupKeeper, app.AuthKeeper, app.BankKeeper, app.interfaceRegistry), + nft.ModuleName: nftmodule.NewAppModule(appCodec, app.NFTKeeper, app.AuthKeeper, app.BankKeeper, app.interfaceRegistry), + consensusparamtypes.ModuleName: consensus.NewAppModule(appCodec, app.ConsensusParamsKeeper), + circuittypes.ModuleName: circuit.NewAppModule(appCodec, app.CircuitKeeper), + pooltypes.ModuleName: protocolpool.NewAppModule(appCodec, app.PoolKeeper, app.AuthKeeper, app.BankKeeper), + epochstypes.ModuleName: epochs.NewAppModule(appCodec, app.EpochsKeeper), + }) + app.ModuleManager.RegisterLegacyAminoCodec(legacyAmino) app.ModuleManager.RegisterInterfaces(interfaceRegistry) diff --git a/simapp/app_config.go b/simapp/app_config.go index f7f924825b05e..4eb39f1766c75 100644 --- a/simapp/app_config.go +++ b/simapp/app_config.go @@ -69,6 +69,8 @@ import ( upgradetypes "cosmossdk.io/x/upgrade/types" "github.com/cosmos/cosmos-sdk/runtime" + _ "github.com/cosmos/cosmos-sdk/testutil/x/counter" // import for side-effects + countertypes "github.com/cosmos/cosmos-sdk/testutil/x/counter/types" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" ) @@ -279,6 +281,11 @@ var ( Name: epochstypes.ModuleName, Config: appconfig.WrapAny(&epochsmodulev1.Module{}), }, + // This module is used for testing the depinject gogo x pulsar module registration. + { + Name: countertypes.ModuleName, + Config: appconfig.WrapAny(&countertypes.Module{}), + }, }, }) ) diff --git a/simapp/go.mod b/simapp/go.mod index 7683633a981c4..5d67518fce5a4 100644 --- a/simapp/go.mod +++ b/simapp/go.mod @@ -7,7 +7,8 @@ require ( cosmossdk.io/client/v2 v2.0.0-20230630094428-02b760776860 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/log v1.3.1 cosmossdk.io/math v1.3.0 cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc @@ -18,6 +19,7 @@ require ( cosmossdk.io/x/authz v0.0.0-00010101000000-000000000000 cosmossdk.io/x/bank v0.0.0-20240226161501-23359a0b6d91 cosmossdk.io/x/circuit v0.0.0-20230613133644-0a778132a60f + cosmossdk.io/x/consensus v0.0.0-00010101000000-000000000000 cosmossdk.io/x/distribution v0.0.0-20240227221813-a248d05f70f4 cosmossdk.io/x/epochs v0.0.0-20240522060652-a1ae4c3e0337 cosmossdk.io/x/evidence v0.0.0-20230613133644-0a778132a60f @@ -32,6 +34,7 @@ require ( cosmossdk.io/x/tx v0.13.3 cosmossdk.io/x/upgrade v0.0.0-20230613133644-0a778132a60f github.com/cometbft/cometbft v1.0.0-rc1 + github.com/cometbft/cometbft/api v1.0.0-rc.1 github.com/cosmos/cosmos-db v1.0.2 // this version is not used as it is always replaced by the latest Cosmos SDK version github.com/cosmos/cosmos-sdk v0.51.0 @@ -45,10 +48,6 @@ require ( google.golang.org/protobuf v1.34.2 ) -require github.com/cometbft/cometbft/api v1.0.0-rc.1 - -require cosmossdk.io/x/consensus v0.0.0-00010101000000-000000000000 - require ( buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2 // indirect buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2 // indirect @@ -58,7 +57,6 @@ require ( cloud.google.com/go/compute/metadata v0.3.0 // indirect cloud.google.com/go/iam v1.1.8 // indirect cloud.google.com/go/storage v1.42.0 // indirect - cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/errors v1.0.1 // indirect cosmossdk.io/schema v0.1.1 // indirect cosmossdk.io/x/accounts/defaults/multisig v0.0.0-00010101000000-000000000000 // indirect @@ -86,7 +84,7 @@ require ( github.com/cometbft/cometbft-db v0.12.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-proto v1.0.0-beta.5 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -246,7 +244,6 @@ replace ( cosmossdk.io/collections => ../collections cosmossdk.io/core => ../core cosmossdk.io/core/testing => ../core/testing - cosmossdk.io/depinject => ../depinject cosmossdk.io/log => ../log cosmossdk.io/store => ../store cosmossdk.io/tools/confix => ../tools/confix diff --git a/simapp/go.sum b/simapp/go.sum index 8770d143018f5..33e6ee51d3b24 100644 --- a/simapp/go.sum +++ b/simapp/go.sum @@ -192,6 +192,8 @@ cloud.google.com/go/webrisk v1.4.0/go.mod h1:Hn8X6Zr+ziE2aNd8SliSDWpEnSS1u4R9+xX cloud.google.com/go/webrisk v1.5.0/go.mod h1:iPG6fr52Tv7sGk0H6qUFzmL3HHZev1htXuWDEEsqMTg= cloud.google.com/go/workflows v1.6.0/go.mod h1:6t9F5h/unJz41YqfBmqSASJSXccBLtD1Vwf+KmJENM0= cloud.google.com/go/workflows v1.7.0/go.mod h1:JhSrZuVZWuiDfKEFxU0/F1PQjmpnpcoISEXH2bcHC3M= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -308,8 +310,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/simapp/sim_bench_test.go b/simapp/sim_bench_test.go index af3020a908391..914e7a40c5cef 100644 --- a/simapp/sim_bench_test.go +++ b/simapp/sim_bench_test.go @@ -3,13 +3,32 @@ package simapp import ( + "os" "testing" + coretesting "cosmossdk.io/core/testing" "github.com/cosmos/cosmos-sdk/testutils/sims" + flag "github.com/spf13/pflag" + "github.com/spf13/viper" + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/server" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" simcli "github.com/cosmos/cosmos-sdk/x/simulation/client/cli" ) +var FlagEnableBenchStreamingValue bool + +// Get flags every time the simulator is run +func init() { + flag.BoolVar(&FlagEnableBenchStreamingValue, "EnableStreaming", false, "Enable streaming service") +} + // Profile with: // /usr/local/go/bin/go test -benchmem -run=^$ cosmossdk.io/simapp -bench ^BenchmarkFullAppSimulation$ -Commit=true -cpuprofile cpu.out func BenchmarkFullAppSimulation(b *testing.B) { @@ -18,5 +37,52 @@ func BenchmarkFullAppSimulation(b *testing.B) { config := simcli.NewConfigFromFlags() config.ChainID = sims.SimAppChainID - sims.RunWithSeed(b, config, NewSimApp, setupStateFactory, 1, nil) + db, dir, logger, skip, err := simtestutil.SetupSimulation(config, "goleveldb-app-sim", "Simulation", simcli.FlagVerboseValue, simcli.FlagEnabledValue) + if err != nil { + b.Fatalf("simulation setup failed: %s", err.Error()) + } + + if skip { + b.Skip("skipping benchmark application simulation") + } + + defer func() { + require.NoError(b, db.Close()) + require.NoError(b, os.RemoveAll(dir)) + }() + + appOptions := viper.New() + appOptions.SetDefault(flags.FlagHome, DefaultNodeHome) + appOptions.SetDefault(server.FlagInvCheckPeriod, simcli.FlagPeriodValue) + + app := NewSimApp(logger, db, nil, true, appOptions, interBlockCacheOpt(), baseapp.SetChainID(sims.SimAppChainID)) + + // run randomized simulation + simParams, simErr := simulation.SimulateFromSeedX( + b, + coretesting.NewNopLogger(), + os.Stdout, + app.BaseApp, + simtestutil.AppStateFn(app.AppCodec(), app.AuthKeeper.AddressCodec(), app.StakingKeeper.ValidatorAddressCodec(), app.SimulationManager(), app.DefaultGenesis()), + simtypes.RandomAccounts, + simtestutil.SimulationOperations(app, app.AppCodec(), config, app.txConfig), + BlockedAddresses(), + config, + app.AppCodec(), + app.txConfig.SigningContext().AddressCodec(), + &simulation.DummyLogWriter{}, + ) + + // export state and simParams before the simulation error is checked + if err = simtestutil.CheckExportSimulation(app, config, simParams); err != nil { + b.Fatal(err) + } + + if simErr != nil { + b.Fatal(simErr) + } + + if config.Commit { + simtestutil.PrintStats(db) + } } diff --git a/simapp/simd/cmd/commands.go b/simapp/simd/cmd/commands.go index 60c5808f25bbd..67175d3ee31d3 100644 --- a/simapp/simd/cmd/commands.go +++ b/simapp/simd/cmd/commands.go @@ -31,7 +31,6 @@ import ( func initRootCmd( rootCmd *cobra.Command, - txConfig client.TxConfig, moduleManager *module.Manager, ) { cfg := sdk.GetConfig() @@ -51,7 +50,7 @@ func initRootCmd( // add keybase, auxiliary RPC, query, genesis, and tx child commands rootCmd.AddCommand( server.StatusCommand(), - genesisCommand(txConfig, moduleManager, appExport), + genesisCommand(moduleManager, appExport), queryCommand(), txCommand(), keys.Commands(), @@ -60,8 +59,8 @@ func initRootCmd( } // genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter -func genesisCommand(txConfig client.TxConfig, moduleManager *module.Manager, appExport servertypes.AppExporter, cmds ...*cobra.Command) *cobra.Command { - cmd := genutilcli.Commands(txConfig, moduleManager.Modules[genutiltypes.ModuleName].(genutil.AppModule), moduleManager, appExport) +func genesisCommand(moduleManager *module.Manager, appExport servertypes.AppExporter, cmds ...*cobra.Command) *cobra.Command { + cmd := genutilcli.Commands(moduleManager.Modules[genutiltypes.ModuleName].(genutil.AppModule), moduleManager, appExport) for _, subCmd := range cmds { cmd.AddCommand(subCmd) } diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 007bdd5b93820..5734452f0bd09 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -109,7 +109,7 @@ func NewRootCmd() *cobra.Command { }, } - initRootCmd(rootCmd, encodingConfig.TxConfig, tempApp.ModuleManager) + initRootCmd(rootCmd, tempApp.ModuleManager) // autocli opts customClientTemplate, customClientConfig := initClientConfig() diff --git a/simapp/simd/cmd/root_di.go b/simapp/simd/cmd/root_di.go index 4ed5437d16379..08fc997af43d4 100644 --- a/simapp/simd/cmd/root_di.go +++ b/simapp/simd/cmd/root_di.go @@ -81,7 +81,7 @@ func NewRootCmd() *cobra.Command { }, } - initRootCmd(rootCmd, clientCtx.TxConfig, moduleManager) + initRootCmd(rootCmd, moduleManager) if err := autoCliOpts.EnhanceRootCommand(rootCmd); err != nil { panic(err) diff --git a/simapp/simd/main.go b/simapp/simd/main.go index 9643af43bc80a..4e7549b214115 100644 --- a/simapp/simd/main.go +++ b/simapp/simd/main.go @@ -4,6 +4,7 @@ import ( "fmt" "os" + clientv2helpers "cosmossdk.io/client/v2/helpers" "cosmossdk.io/simapp" "cosmossdk.io/simapp/simd/cmd" @@ -12,7 +13,7 @@ import ( func main() { rootCmd := cmd.NewRootCmd() - if err := svrcmd.Execute(rootCmd, "", simapp.DefaultNodeHome); err != nil { + if err := svrcmd.Execute(rootCmd, clientv2helpers.EnvPrefix, simapp.DefaultNodeHome); err != nil { fmt.Fprintln(rootCmd.OutOrStderr(), err) os.Exit(1) } diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 363698a137ea8..bce25b2832428 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/require" "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" sdkmath "cosmossdk.io/math" pruningtypes "cosmossdk.io/store/pruning/types" authtypes "cosmossdk.io/x/auth/types" @@ -46,7 +47,7 @@ func setup(withGenesis bool, invCheckPeriod uint) (*SimApp, GenesisState) { appOptions[flags.FlagHome] = DefaultNodeHome appOptions[server.FlagInvCheckPeriod] = invCheckPeriod - app := NewSimApp(log.NewNopLogger(), db, nil, true, appOptions) + app := NewSimApp(coretesting.NewNopLogger(), db, nil, true, appOptions) if withGenesis { return app, app.DefaultGenesis() } @@ -225,7 +226,7 @@ func NewTestNetworkFixture() network.TestFixture { } defer os.RemoveAll(dir) - app := NewSimApp(log.NewNopLogger(), dbm.NewMemDB(), nil, true, simtestutil.NewAppOptionsWithFlagHome(dir)) + app := NewSimApp(coretesting.NewNopLogger(), dbm.NewMemDB(), nil, true, simtestutil.NewAppOptionsWithFlagHome(dir)) appCtr := func(val network.ValidatorI) servertypes.Application { return NewSimApp( diff --git a/simapp/upgrades.go b/simapp/upgrades.go index 7ff7377840d83..d8b1852c7289f 100644 --- a/simapp/upgrades.go +++ b/simapp/upgrades.go @@ -10,6 +10,8 @@ import ( epochstypes "cosmossdk.io/x/epochs/types" protocolpooltypes "cosmossdk.io/x/protocolpool/types" upgradetypes "cosmossdk.io/x/upgrade/types" + + countertypes "github.com/cosmos/cosmos-sdk/testutil/x/counter/types" ) // UpgradeName defines the on-chain upgrade name for the sample SimApp upgrade @@ -45,6 +47,7 @@ func (app SimApp) RegisterUpgradeHandlers() { accounts.StoreKey, protocolpooltypes.StoreKey, epochstypes.StoreKey, + countertypes.StoreKey, // This module is used for testing purposes only. }, Deleted: []string{"crisis"}, // The SDK discontinued the crisis module in v0.52.0 } diff --git a/simapp/v2/app_di.go b/simapp/v2/app_di.go index b1e05095d9048..5f4b2455bc8d1 100644 --- a/simapp/v2/app_di.go +++ b/simapp/v2/app_di.go @@ -224,7 +224,6 @@ func NewSimApp[T transaction.Tx]( if err := app.LoadLatest(); err != nil { panic(err) } - return app } diff --git a/simapp/v2/go.mod b/simapp/v2/go.mod index 8fc91127cfb24..535cf5c7ac0ad 100644 --- a/simapp/v2/go.mod +++ b/simapp/v2/go.mod @@ -4,15 +4,16 @@ go 1.22.2 require ( cosmossdk.io/api v0.7.5 - cosmossdk.io/collections v0.4.0 // indirect + cosmossdk.io/client/v2 v2.0.0-00010101000000-000000000000 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/log v1.3.1 cosmossdk.io/math v1.3.0 cosmossdk.io/runtime/v2 v2.0.0-00010101000000-000000000000 cosmossdk.io/server/v2 v2.0.0-00010101000000-000000000000 cosmossdk.io/server/v2/cometbft v0.0.0-00010101000000-000000000000 cosmossdk.io/store/v2 v2.0.0 + cosmossdk.io/tools/confix v0.0.0-00010101000000-000000000000 cosmossdk.io/x/accounts v0.0.0-20240226161501-23359a0b6d91 cosmossdk.io/x/auth v0.0.0-00010101000000-000000000000 cosmossdk.io/x/authz v0.0.0-00010101000000-000000000000 @@ -29,27 +30,19 @@ require ( cosmossdk.io/x/protocolpool v0.0.0-20230925135524-a1bc045b3190 cosmossdk.io/x/slashing v0.0.0-00010101000000-000000000000 cosmossdk.io/x/staking v0.0.0-00010101000000-000000000000 - cosmossdk.io/x/tx v0.13.3 // indirect cosmossdk.io/x/upgrade v0.0.0-20230613133644-0a778132a60f github.com/cometbft/cometbft v1.0.0-rc1 github.com/cosmos/cosmos-db v1.0.2 // this version is not used as it is always replaced by the latest Cosmos SDK version github.com/cosmos/cosmos-sdk v0.51.0 - github.com/cosmos/gogoproto v1.5.0 // indirect - github.com/golang/mock v1.6.0 // indirect - github.com/spf13/cast v1.6.0 // indirect github.com/spf13/cobra v1.8.1 github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.19.0 github.com/stretchr/testify v1.9.0 - golang.org/x/sync v0.7.0 // indirect google.golang.org/protobuf v1.34.2 ) -require ( - cosmossdk.io/client/v2 v2.0.0-00010101000000-000000000000 - cosmossdk.io/tools/confix v0.0.0-00010101000000-000000000000 -) +require cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 require ( buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2 // indirect @@ -60,7 +53,7 @@ require ( cloud.google.com/go/compute/metadata v0.3.0 // indirect cloud.google.com/go/iam v1.1.8 // indirect cloud.google.com/go/storage v1.42.0 // indirect - cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 // indirect + cosmossdk.io/collections v0.4.0 // indirect cosmossdk.io/errors v1.0.1 // indirect cosmossdk.io/schema v0.1.1 // indirect cosmossdk.io/server/v2/appmanager v0.0.0-00010101000000-000000000000 // indirect @@ -69,6 +62,7 @@ require ( cosmossdk.io/x/accounts/defaults/lockup v0.0.0-20240417181816-5e7aae0db1f5 // indirect cosmossdk.io/x/accounts/defaults/multisig v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/x/epochs v0.0.0-20240522060652-a1ae4c3e0337 // indirect + cosmossdk.io/x/tx v0.13.3 // indirect filippo.io/edwards25519 v1.1.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.2 // indirect @@ -94,9 +88,10 @@ require ( github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-proto v1.0.0-beta.5 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect + github.com/cosmos/gogoproto v1.5.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect github.com/cosmos/ics23/go v0.10.0 // indirect github.com/cosmos/ledger-cosmos-go v0.13.3 // indirect @@ -125,6 +120,7 @@ require ( github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/glog v1.2.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect + github.com/golang/mock v1.6.0 // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/btree v1.1.2 // indirect @@ -200,6 +196,7 @@ require ( github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/sourcegraph/conc v0.3.0 // indirect github.com/spf13/afero v1.11.0 // indirect + github.com/spf13/cast v1.6.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/supranational/blst v0.3.12 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect @@ -223,6 +220,7 @@ require ( golang.org/x/mod v0.17.0 // indirect golang.org/x/net v0.27.0 // indirect golang.org/x/oauth2 v0.21.0 // indirect + golang.org/x/sync v0.7.0 // indirect golang.org/x/sys v0.22.0 // indirect golang.org/x/term v0.22.0 // indirect golang.org/x/text v0.16.0 // indirect @@ -252,7 +250,6 @@ replace ( cosmossdk.io/client/v2 => ../../client/v2 cosmossdk.io/collections => ../../collections cosmossdk.io/core => ../../core - cosmossdk.io/depinject => ../../depinject cosmossdk.io/tools/confix => ../../tools/confix cosmossdk.io/x/accounts => ../../x/accounts cosmossdk.io/x/accounts/defaults/lockup => ../../x/accounts/defaults/lockup diff --git a/simapp/v2/go.sum b/simapp/v2/go.sum index 7da31d74ddc56..b95c10d44d36e 100644 --- a/simapp/v2/go.sum +++ b/simapp/v2/go.sum @@ -192,6 +192,8 @@ cloud.google.com/go/webrisk v1.4.0/go.mod h1:Hn8X6Zr+ziE2aNd8SliSDWpEnSS1u4R9+xX cloud.google.com/go/webrisk v1.5.0/go.mod h1:iPG6fr52Tv7sGk0H6qUFzmL3HHZev1htXuWDEEsqMTg= cloud.google.com/go/workflows v1.6.0/go.mod h1:6t9F5h/unJz41YqfBmqSASJSXccBLtD1Vwf+KmJENM0= cloud.google.com/go/workflows v1.7.0/go.mod h1:JhSrZuVZWuiDfKEFxU0/F1PQjmpnpcoISEXH2bcHC3M= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -310,8 +312,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/simapp/v2/simdv2/cmd/commands.go b/simapp/v2/simdv2/cmd/commands.go index 017f601605bf7..fd32461c56ce6 100644 --- a/simapp/v2/simdv2/cmd/commands.go +++ b/simapp/v2/simdv2/cmd/commands.go @@ -10,8 +10,8 @@ import ( "github.com/spf13/viper" "cosmossdk.io/client/v2/offchain" + "cosmossdk.io/core/log" "cosmossdk.io/core/transaction" - "cosmossdk.io/log" runtimev2 "cosmossdk.io/runtime/v2" serverv2 "cosmossdk.io/server/v2" "cosmossdk.io/server/v2/api/grpc" @@ -32,53 +32,13 @@ import ( genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" ) -var _ transaction.Codec[transaction.Tx] = &temporaryTxDecoder[transaction.Tx]{} - -type temporaryTxDecoder[T transaction.Tx] struct { - txConfig client.TxConfig -} - -// Decode implements transaction.Codec. -func (t *temporaryTxDecoder[T]) Decode(bz []byte) (T, error) { - var out T - tx, err := t.txConfig.TxDecoder()(bz) - if err != nil { - return out, err - } - - var ok bool - out, ok = tx.(T) - if !ok { - return out, errors.New("unexpected Tx type") - } - - return out, nil -} - -// DecodeJSON implements transaction.Codec. -func (t *temporaryTxDecoder[T]) DecodeJSON(bz []byte) (T, error) { - var out T - tx, err := t.txConfig.TxJSONDecoder()(bz) - if err != nil { - return out, err - } - - var ok bool - out, ok = tx.(T) - if !ok { - return out, errors.New("unexpected Tx type") - } - - return out, nil -} - -func newApp[AppT serverv2.AppI[T], T transaction.Tx]( +func newApp[T transaction.Tx]( logger log.Logger, viper *viper.Viper, -) AppT { - return serverv2.AppI[T](simapp.NewSimApp[T](logger, viper)).(AppT) +) serverv2.AppI[T] { + return serverv2.AppI[T](simapp.NewSimApp[T](logger, viper)) } -func initRootCmd[AppT serverv2.AppI[T], T transaction.Tx]( +func initRootCmd[T transaction.Tx]( rootCmd *cobra.Command, txConfig client.TxConfig, moduleManager *runtimev2.MM[T], @@ -102,20 +62,20 @@ func initRootCmd[AppT serverv2.AppI[T], T transaction.Tx]( // add keybase, auxiliary RPC, query, genesis, and tx child commands rootCmd.AddCommand( - genesisCommand[T](txConfig, moduleManager, appExport[T]), + genesisCommand(moduleManager, appExport[T]), queryCommand(), txCommand(), keys.Commands(), offchain.OffChain(), ) - // Add empty server struct here for writing default config + // wire server commands if err = serverv2.AddCommands( rootCmd, newApp, logger, - cometbft.New[AppT, T](&temporaryTxDecoder[T]{txConfig}, cometbft.DefaultServerOptions[T]()), - grpc.New[AppT, T](), + cometbft.New(&genericTxDecoder[T]{txConfig}, cometbft.DefaultServerOptions[T]()), + grpc.New[T](), ); err != nil { panic(err) } @@ -123,7 +83,6 @@ func initRootCmd[AppT serverv2.AppI[T], T transaction.Tx]( // genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter func genesisCommand[T transaction.Tx]( - txConfig client.TxConfig, moduleManager *runtimev2.MM[T], appExport func(logger log.Logger, height int64, @@ -143,7 +102,7 @@ func genesisCommand[T transaction.Tx]( return appExport(logger, height, forZeroHeight, jailAllowedAddrs, viperAppOpts, modulesToExport) } - cmd := genutilcli.Commands(txConfig, moduleManager.Modules()[genutiltypes.ModuleName].(genutil.AppModule), moduleManager, compatAppExporter) + cmd := genutilcli.Commands(moduleManager.Modules()[genutiltypes.ModuleName].(genutil.AppModule), moduleManager, compatAppExporter) for _, subCmd := range cmds { cmd.AddCommand(subCmd) } @@ -221,3 +180,43 @@ func appExport[T transaction.Tx]( return simApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) } + +var _ transaction.Codec[transaction.Tx] = &genericTxDecoder[transaction.Tx]{} + +type genericTxDecoder[T transaction.Tx] struct { + txConfig client.TxConfig +} + +// Decode implements transaction.Codec. +func (t *genericTxDecoder[T]) Decode(bz []byte) (T, error) { + var out T + tx, err := t.txConfig.TxDecoder()(bz) + if err != nil { + return out, err + } + + var ok bool + out, ok = tx.(T) + if !ok { + return out, errors.New("unexpected Tx type") + } + + return out, nil +} + +// DecodeJSON implements transaction.Codec. +func (t *genericTxDecoder[T]) DecodeJSON(bz []byte) (T, error) { + var out T + tx, err := t.txConfig.TxJSONDecoder()(bz) + if err != nil { + return out, err + } + + var ok bool + out, ok = tx.(T) + if !ok { + return out, errors.New("unexpected Tx type") + } + + return out, nil +} diff --git a/simapp/v2/simdv2/cmd/root_di.go b/simapp/v2/simdv2/cmd/root_di.go index 61c3551803864..6051bede8e9c1 100644 --- a/simapp/v2/simdv2/cmd/root_di.go +++ b/simapp/v2/simdv2/cmd/root_di.go @@ -12,7 +12,6 @@ import ( "cosmossdk.io/depinject" "cosmossdk.io/log" "cosmossdk.io/runtime/v2" - serverv2 "cosmossdk.io/server/v2" "cosmossdk.io/simapp/v2" "cosmossdk.io/x/auth/tx" authtxconfig "cosmossdk.io/x/auth/tx/config" @@ -26,7 +25,7 @@ import ( ) // NewRootCmd creates a new root command for simd. It is called once in the main function. -func NewRootCmd[AppT serverv2.AppI[T], T transaction.Tx]() *cobra.Command { +func NewRootCmd[T transaction.Tx]() *cobra.Command { var ( autoCliOpts autocli.AppOptions moduleManager *runtime.MM[T] @@ -81,7 +80,7 @@ func NewRootCmd[AppT serverv2.AppI[T], T transaction.Tx]() *cobra.Command { }, } - initRootCmd[AppT, T](rootCmd, clientCtx.TxConfig, moduleManager) + initRootCmd[T](rootCmd, clientCtx.TxConfig, moduleManager) if err := autoCliOpts.EnhanceRootCommand(rootCmd); err != nil { panic(err) } diff --git a/simapp/v2/simdv2/cmd/root_test.go b/simapp/v2/simdv2/cmd/root_test.go index ebca74ba70b97..7c51b1b211709 100644 --- a/simapp/v2/simdv2/cmd/root_test.go +++ b/simapp/v2/simdv2/cmd/root_test.go @@ -7,17 +7,16 @@ import ( "github.com/stretchr/testify/require" "cosmossdk.io/core/transaction" - serverv2 "cosmossdk.io/server/v2" + svrcmd "cosmossdk.io/server/v2" "cosmossdk.io/simapp/v2" "cosmossdk.io/simapp/v2/simdv2/cmd" "github.com/cosmos/cosmos-sdk/client/flags" - svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" ) func TestInitCmd(t *testing.T) { - rootCmd := cmd.NewRootCmd[serverv2.AppI[transaction.Tx], transaction.Tx]() + rootCmd := cmd.NewRootCmd[transaction.Tx]() rootCmd.SetArgs([]string{ "init", // Test the init cmd "simapp-test", // Moniker @@ -30,7 +29,7 @@ func TestInitCmd(t *testing.T) { func TestHomeFlagRegistration(t *testing.T) { homeDir := "/tmp/foo" - rootCmd := cmd.NewRootCmd[serverv2.AppI[transaction.Tx], transaction.Tx]() + rootCmd := cmd.NewRootCmd[transaction.Tx]() rootCmd.SetArgs([]string{ "query", fmt.Sprintf("--%s", flags.FlagHome), diff --git a/simapp/v2/simdv2/cmd/testnet.go b/simapp/v2/simdv2/cmd/testnet.go index 61387b42301a1..b0a755a971900 100644 --- a/simapp/v2/simdv2/cmd/testnet.go +++ b/simapp/v2/simdv2/cmd/testnet.go @@ -14,7 +14,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/pflag" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/core/transaction" "cosmossdk.io/math" "cosmossdk.io/math/unsafe" @@ -40,6 +40,7 @@ import ( ) var ( + flagMinGasPrices = "min-gas-prices" flagNodeDirPrefix = "node-dir-prefix" flagNumValidators = "validator-count" flagOutputDir = "output-dir" @@ -70,7 +71,7 @@ func addTestnetFlagsToCmd(cmd *cobra.Command) { cmd.Flags().IntP(flagNumValidators, "n", 4, "Number of validators to initialize the testnet with") cmd.Flags().StringP(flagOutputDir, "o", "./.testnets", "Directory to store initialization data for the testnet") cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") - cmd.Flags().String(cometbft.FlagMinGasPrices, fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom), "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01photino,0.001stake)") + cmd.Flags().String(flagMinGasPrices, fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom), "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01photino,0.001stake)") cmd.Flags().String(flags.FlagKeyType, string(hd.Secp256k1Type), "Key signing algorithm to generate keys for") // support old flags name for backwards compatibility @@ -127,7 +128,7 @@ Example: args.outputDir, _ = cmd.Flags().GetString(flagOutputDir) args.keyringBackend, _ = cmd.Flags().GetString(flags.FlagKeyringBackend) args.chainID, _ = cmd.Flags().GetString(flags.FlagChainID) - args.minGasPrices, _ = cmd.Flags().GetString(cometbft.FlagMinGasPrices) + args.minGasPrices, _ = cmd.Flags().GetString(flagMinGasPrices) args.nodeDirPrefix, _ = cmd.Flags().GetString(flagNodeDirPrefix) args.nodeDaemonHome, _ = cmd.Flags().GetString(flagNodeDaemonHome) args.startingIPAddress, _ = cmd.Flags().GetString(flagStartingIPAddress) @@ -198,7 +199,7 @@ func initTestnetFiles[T transaction.Tx]( // generate private keys, node IDs, and initial transactions for i := 0; i < args.numValidators; i++ { var portOffset int - var grpcConfig *grpc.Config + grpcConfig := grpc.DefaultConfig() if args.singleMachine { portOffset = i p2pPortStart = 16656 // use different start point to not conflict with rpc port @@ -336,9 +337,13 @@ func initTestnetFiles[T transaction.Tx]( } // Write server config - cometServer := cometbft.New[serverv2.AppI[T], T](&temporaryTxDecoder[T]{clientCtx.TxConfig}, cometbft.ServerOptions[T]{}, cometbft.OverwriteDefaultCometConfig(nodeConfig)) - grpcServer := grpc.New[serverv2.AppI[T], T](grpc.OverwriteDefaultConfig(grpcConfig)) - server := serverv2.NewServer(log.NewNopLogger(), cometServer, grpcServer) + cometServer := cometbft.New[T]( + &genericTxDecoder[T]{clientCtx.TxConfig}, + cometbft.ServerOptions[T]{}, + cometbft.OverwriteDefaultConfigTomlConfig(nodeConfig), + ) + grpcServer := grpc.New[T](grpc.OverwriteDefaultConfig(grpcConfig)) + server := serverv2.NewServer(coretesting.NewNopLogger(), cometServer, grpcServer) err = server.WriteConfig(filepath.Join(nodeDir, "config")) if err != nil { return err diff --git a/simapp/v2/simdv2/cmd/testnet_test.go b/simapp/v2/simdv2/cmd/testnet_test.go new file mode 100644 index 0000000000000..145a32608e604 --- /dev/null +++ b/simapp/v2/simdv2/cmd/testnet_test.go @@ -0,0 +1,27 @@ +package cmd_test + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/require" + + "cosmossdk.io/core/transaction" + svrcmd "cosmossdk.io/server/v2" + "cosmossdk.io/simapp/v2" + "cosmossdk.io/simapp/v2/simdv2/cmd" + + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/crypto/keyring" +) + +func TestInitTestFilesCmd(t *testing.T) { + rootCmd := cmd.NewRootCmd[transaction.Tx]() + rootCmd.SetArgs([]string{ + "testnet", // Test the testnet init-files command + "init-files", + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), // Set keyring-backend to test + }) + + require.NoError(t, svrcmd.Execute(rootCmd, "", simapp.DefaultNodeHome)) +} diff --git a/simapp/v2/simdv2/main.go b/simapp/v2/simdv2/main.go index e41ba6ffc13ce..eb7d9a1b005b9 100644 --- a/simapp/v2/simdv2/main.go +++ b/simapp/v2/simdv2/main.go @@ -4,6 +4,7 @@ import ( "fmt" "os" + clientv2helpers "cosmossdk.io/client/v2/helpers" "cosmossdk.io/core/transaction" serverv2 "cosmossdk.io/server/v2" "cosmossdk.io/simapp/v2" @@ -11,8 +12,8 @@ import ( ) func main() { - rootCmd := cmd.NewRootCmd[serverv2.AppI[transaction.Tx], transaction.Tx]() - if err := serverv2.Execute(rootCmd, "", simapp.DefaultNodeHome); err != nil { + rootCmd := cmd.NewRootCmd[transaction.Tx]() + if err := serverv2.Execute(rootCmd, clientv2helpers.EnvPrefix, simapp.DefaultNodeHome); err != nil { fmt.Fprintln(rootCmd.OutOrStderr(), err) os.Exit(1) } diff --git a/store/dbadapter/store.go b/store/dbadapter/store.go index 369a173ec1406..d69e4ebf1357d 100644 --- a/store/dbadapter/store.go +++ b/store/dbadapter/store.go @@ -10,7 +10,7 @@ import ( "cosmossdk.io/store/types" ) -// Wrapper type for dbm.Db with implementation of KVStore +// Store is wrapper type for dbm.Db with implementation of KVStore type Store struct { dbm.DB } diff --git a/store/gaskv/store.go b/store/gaskv/store.go index e0f96af7151ec..41242d49284b5 100644 --- a/store/gaskv/store.go +++ b/store/gaskv/store.go @@ -26,12 +26,12 @@ func NewStore(parent types.KVStore, gasMeter types.GasMeter, gasConfig types.Gas return kvs } -// Implements Store. +// GetStoreType implements Store. func (gs *Store) GetStoreType() types.StoreType { return gs.parent.GetStoreType() } -// Implements KVStore. +// Get implements KVStore. func (gs *Store) Get(key []byte) (value []byte) { gs.gasMeter.ConsumeGas(gs.gasConfig.ReadCostFlat, types.GasReadCostFlatDesc) value = gs.parent.Get(key) @@ -43,7 +43,7 @@ func (gs *Store) Get(key []byte) (value []byte) { return value } -// Implements KVStore. +// Set implements KVStore. func (gs *Store) Set(key, value []byte) { types.AssertValidKey(key) types.AssertValidValue(value) @@ -54,13 +54,13 @@ func (gs *Store) Set(key, value []byte) { gs.parent.Set(key, value) } -// Implements KVStore. +// Has implements KVStore. func (gs *Store) Has(key []byte) bool { gs.gasMeter.ConsumeGas(gs.gasConfig.HasCost, types.GasHasDesc) return gs.parent.Has(key) } -// Implements KVStore. +// Delete implements KVStore. func (gs *Store) Delete(key []byte) { // charge gas to prevent certain attack vectors even though space is being freed gs.gasMeter.ConsumeGas(gs.gasConfig.DeleteCost, types.GasDeleteDesc) @@ -82,7 +82,7 @@ func (gs *Store) ReverseIterator(start, end []byte) types.Iterator { return gs.iterator(start, end, false) } -// Implements KVStore. +// CacheWrap implements KVStore. func (gs *Store) CacheWrap() types.CacheWrap { panic("cannot CacheWrap a GasKVStore") } @@ -120,12 +120,12 @@ func newGasIterator(gasMeter types.GasMeter, gasConfig types.GasConfig, parent t } } -// Implements Iterator. +// Domain implements Iterator. func (gi *gasIterator) Domain() (start, end []byte) { return gi.parent.Domain() } -// Implements Iterator. +// Valid implements Iterator. func (gi *gasIterator) Valid() bool { return gi.parent.Valid() } @@ -152,7 +152,7 @@ func (gi *gasIterator) Value() (value []byte) { return value } -// Implements Iterator. +// Close implements Iterator. func (gi *gasIterator) Close() error { return gi.parent.Close() } diff --git a/store/go.mod b/store/go.mod index 3eb28acabd9d7..4b18cd027a017 100644 --- a/store/go.mod +++ b/store/go.mod @@ -3,7 +3,8 @@ module cosmossdk.io/store go 1.22.2 require ( - cosmossdk.io/core v0.0.0-00010101000000-000000000000 + cosmossdk.io/core v0.12.0 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 cosmossdk.io/errors v1.0.1 cosmossdk.io/log v1.3.1 cosmossdk.io/math v1.3.0 @@ -29,6 +30,8 @@ require ( replace cosmossdk.io/core => ../core +replace cosmossdk.io/core/testing => ../core/testing + replace cosmossdk.io/log => ../log require ( diff --git a/store/iavl/store.go b/store/iavl/store.go index d97995b05e8aa..8e1905b7a38b3 100644 --- a/store/iavl/store.go +++ b/store/iavl/store.go @@ -163,7 +163,7 @@ func (st *Store) SetPruning(_ pruningtypes.PruningOptions) { panic("cannot set pruning options on an initialized IAVL store") } -// SetPruning panics as pruning options should be provided at initialization +// GetPruning panics as pruning options should be provided at initialization // since IAVl accepts pruning options directly. func (st *Store) GetPruning() pruningtypes.PruningOptions { panic("cannot get pruning options on an initialized IAVL store") @@ -179,12 +179,12 @@ func (st *Store) GetAllVersions() []int { return st.tree.AvailableVersions() } -// Implements Store. +// GetStoreType implements Store. func (st *Store) GetStoreType() types.StoreType { return types.StoreTypeIAVL } -// Implements Store. +// CacheWrap implements Store. func (st *Store) CacheWrap() types.CacheWrap { return cachekv.NewStore(st) } @@ -194,7 +194,7 @@ func (st *Store) CacheWrapWithTrace(w io.Writer, tc types.TraceContext) types.Ca return cachekv.NewStore(tracekv.NewStore(st, w, tc)) } -// Implements types.KVStore. +// Set implements types.KVStore. func (st *Store) Set(key, value []byte) { types.AssertValidKey(key) types.AssertValidValue(value) @@ -204,7 +204,7 @@ func (st *Store) Set(key, value []byte) { } } -// Implements types.KVStore. +// Get implements types.KVStore. func (st *Store) Get(key []byte) []byte { defer st.metrics.MeasureSince("store", "iavl", "get") value, err := st.tree.Get(key) @@ -214,7 +214,7 @@ func (st *Store) Get(key []byte) []byte { return value } -// Implements types.KVStore. +// Has implements types.KVStore. func (st *Store) Has(key []byte) (exists bool) { defer st.metrics.MeasureSince("store", "iavl", "has") has, err := st.tree.Has(key) @@ -224,7 +224,7 @@ func (st *Store) Has(key []byte) (exists bool) { return has } -// Implements types.KVStore. +// Delete implements types.KVStore. func (st *Store) Delete(key []byte) { defer st.metrics.MeasureSince("store", "iavl", "delete") _, _, err := st.tree.Remove(key) @@ -246,7 +246,7 @@ func (st *Store) LoadVersionForOverwriting(targetVersion int64) error { return st.tree.LoadVersionForOverwriting(targetVersion) } -// Implements types.KVStore. +// Iterator implements types.KVStore. func (st *Store) Iterator(start, end []byte) types.Iterator { iterator, err := st.tree.Iterator(start, end, true) if err != nil { @@ -255,7 +255,7 @@ func (st *Store) Iterator(start, end []byte) types.Iterator { return iterator } -// Implements types.KVStore. +// ReverseIterator implements types.KVStore. func (st *Store) ReverseIterator(start, end []byte) types.Iterator { iterator, err := st.tree.Iterator(start, end, false) if err != nil { @@ -270,7 +270,7 @@ func (st *Store) SetInitialVersion(version int64) { st.tree.SetInitialVersion(uint64(version)) } -// Exports the IAVL store at the given version, returning an iavl.Exporter for the tree. +// Export exports the IAVL store at the given version, returning an iavl.Exporter for the tree. func (st *Store) Export(version int64) (*iavl.Exporter, error) { istore, err := st.GetImmutable(version) if err != nil { diff --git a/store/internal/maps/maps.go b/store/internal/maps/maps.go index 40aa0b44d9f86..6db2be666caef 100644 --- a/store/internal/maps/maps.go +++ b/store/internal/maps/maps.go @@ -120,7 +120,7 @@ func (sm *simpleMap) Sort() { sm.sorted = true } -// Returns a copy of sorted KVPairs. +// KVPairs returns a copy of sorted KVPairs. // NOTE these contain the hashed key and value. func (sm *simpleMap) KVPairs() kv.Pairs { sm.Sort() @@ -134,7 +134,7 @@ func (sm *simpleMap) KVPairs() kv.Pairs { //---------------------------------------- -// A local extension to KVPair that can be hashed. +// KVPair is a local extension to KVPair that can be hashed. // Key and value are length prefixed and concatenated, // then hashed. type KVPair kv.Pair diff --git a/store/prefix/store.go b/store/prefix/store.go index 62f451fa430df..26b8b0344a796 100644 --- a/store/prefix/store.go +++ b/store/prefix/store.go @@ -42,12 +42,12 @@ func (s Store) key(key []byte) (res []byte) { return } -// Implements Store +// GetStoreType implements Store func (s Store) GetStoreType() types.StoreType { return s.parent.GetStoreType() } -// Implements CacheWrap +// CacheWrap implements CacheWrap func (s Store) CacheWrap() types.CacheWrap { return cachekv.NewStore(s) } @@ -57,30 +57,30 @@ func (s Store) CacheWrapWithTrace(w io.Writer, tc types.TraceContext) types.Cach return cachekv.NewStore(tracekv.NewStore(s, w, tc)) } -// Implements KVStore +// Get implements KVStore func (s Store) Get(key []byte) []byte { res := s.parent.Get(s.key(key)) return res } -// Implements KVStore +// Has implements KVStore func (s Store) Has(key []byte) bool { return s.parent.Has(s.key(key)) } -// Implements KVStore +// Set implements KVStore func (s Store) Set(key, value []byte) { types.AssertValidKey(key) types.AssertValidValue(value) s.parent.Set(s.key(key), value) } -// Implements KVStore +// Delete implements KVStore func (s Store) Delete(key []byte) { s.parent.Delete(s.key(key)) } -// Implements KVStore +// Iterator implements KVStore // Check https://github.com/cometbft/cometbft/blob/master/libs/db/prefix_db.go#L106 func (s Store) Iterator(start, end []byte) types.Iterator { newstart := cloneAppend(s.prefix, start) @@ -134,17 +134,17 @@ func newPrefixIterator(prefix, start, end []byte, parent types.Iterator) *prefix } } -// Implements Iterator +// Domain implements Iterator func (pi *prefixIterator) Domain() ([]byte, []byte) { return pi.start, pi.end } -// Implements Iterator +// Valid implements Iterator func (pi *prefixIterator) Valid() bool { return pi.valid && pi.iter.Valid() } -// Implements Iterator +// Next implements Iterator func (pi *prefixIterator) Next() { if !pi.valid { panic("prefixIterator invalid, cannot call Next()") @@ -156,7 +156,7 @@ func (pi *prefixIterator) Next() { } } -// Implements Iterator +// Key implements Iterator func (pi *prefixIterator) Key() (key []byte) { if !pi.valid { panic("prefixIterator invalid, cannot call Key()") @@ -168,7 +168,7 @@ func (pi *prefixIterator) Key() (key []byte) { return } -// Implements Iterator +// Value implements Iterator func (pi *prefixIterator) Value() []byte { if !pi.valid { panic("prefixIterator invalid, cannot call Value()") @@ -177,7 +177,7 @@ func (pi *prefixIterator) Value() []byte { return pi.iter.Value() } -// Implements Iterator +// Close implements Iterator func (pi *prefixIterator) Close() error { return pi.iter.Close() } diff --git a/store/pruning/manager_test.go b/store/pruning/manager_test.go index bc754f973b00b..fe4aae74cc46f 100644 --- a/store/pruning/manager_test.go +++ b/store/pruning/manager_test.go @@ -9,7 +9,7 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/mock" "cosmossdk.io/store/pruning" "cosmossdk.io/store/pruning/types" @@ -18,7 +18,7 @@ import ( const dbErr = "db error" func TestNewManager(t *testing.T) { - manager := pruning.NewManager(db.NewMemDB(), log.NewNopLogger()) + manager := pruning.NewManager(db.NewMemDB(), coretesting.NewNopLogger()) require.NotNil(t, manager) require.Equal(t, types.PruningNothing, manager.GetOptions().GetPruningStrategy()) } @@ -79,7 +79,7 @@ func TestStrategies(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - manager := pruning.NewManager(db.NewMemDB(), log.NewNopLogger()) + manager := pruning.NewManager(db.NewMemDB(), coretesting.NewNopLogger()) require.NotNil(t, manager) curStrategy := tc.strategy @@ -186,7 +186,7 @@ func TestPruningHeight_Inputs(t *testing.T) { for name, tc := range testcases { t.Run(name, func(t *testing.T) { - manager := pruning.NewManager(db.NewMemDB(), log.NewNopLogger()) + manager := pruning.NewManager(db.NewMemDB(), coretesting.NewNopLogger()) require.NotNil(t, manager) manager.SetOptions(types.NewPruningOptions(tc.strategy)) @@ -204,7 +204,7 @@ func TestHandleSnapshotHeight_DbErr_Panic(t *testing.T) { dbMock.EXPECT().SetSync(gomock.Any(), gomock.Any()).Return(errors.New(dbErr)).Times(1) - manager := pruning.NewManager(dbMock, log.NewNopLogger()) + manager := pruning.NewManager(dbMock, coretesting.NewNopLogger()) manager.SetOptions(types.NewPruningOptions(types.PruningEverything)) require.NotNil(t, manager) @@ -222,7 +222,7 @@ func TestHandleSnapshotHeight_LoadFromDisk(t *testing.T) { // Setup db := db.NewMemDB() - manager := pruning.NewManager(db, log.NewNopLogger()) + manager := pruning.NewManager(db, coretesting.NewNopLogger()) require.NotNil(t, manager) manager.SetOptions(types.NewPruningOptions(types.PruningEverything)) @@ -253,7 +253,7 @@ func TestHandleSnapshotHeight_LoadFromDisk(t *testing.T) { func TestLoadPruningSnapshotHeights(t *testing.T) { var ( - manager = pruning.NewManager(db.NewMemDB(), log.NewNopLogger()) + manager = pruning.NewManager(db.NewMemDB(), coretesting.NewNopLogger()) err error ) require.NotNil(t, manager) @@ -294,7 +294,7 @@ func TestLoadPruningSnapshotHeights(t *testing.T) { } func TestLoadSnapshotHeights_PruneNothing(t *testing.T) { - manager := pruning.NewManager(db.NewMemDB(), log.NewNopLogger()) + manager := pruning.NewManager(db.NewMemDB(), coretesting.NewNopLogger()) require.NotNil(t, manager) manager.SetOptions(types.NewPruningOptions(types.PruningNothing)) diff --git a/store/rootmulti/proof.go b/store/rootmulti/proof.go index 78217a1600bc1..5f1503be4b93a 100644 --- a/store/rootmulti/proof.go +++ b/store/rootmulti/proof.go @@ -17,6 +17,8 @@ func RequireProof(subpath string) bool { //----------------------------------------------------------------------------- +// DefaultProofRuntime returns a new ProofRuntime with default op decoders registered. +// It registers decoders for IAVL commitment and Simple Merkle commitment proof operations. // XXX: This should be managed by the rootMultiStore which may want to register // more proof ops? func DefaultProofRuntime() (prt *merkle.ProofRuntime) { diff --git a/store/rootmulti/proof_test.go b/store/rootmulti/proof_test.go index 0a26b22462e41..2019f3eb46716 100644 --- a/store/rootmulti/proof_test.go +++ b/store/rootmulti/proof_test.go @@ -6,7 +6,7 @@ import ( dbm "github.com/cosmos/cosmos-db" "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/iavl" "cosmossdk.io/store/metrics" "cosmossdk.io/store/types" @@ -15,7 +15,7 @@ import ( func TestVerifyIAVLStoreQueryProof(t *testing.T) { // Create main tree for testing. db := dbm.NewMemDB() - iStore, err := iavl.LoadStore(db, log.NewNopLogger(), types.NewKVStoreKey("test"), types.CommitID{}, iavl.DefaultIAVLCacheSize, false, metrics.NewNoOpMetrics()) + iStore, err := iavl.LoadStore(db, coretesting.NewNopLogger(), types.NewKVStoreKey("test"), types.CommitID{}, iavl.DefaultIAVLCacheSize, false, metrics.NewNoOpMetrics()) store := iStore.(*iavl.Store) require.Nil(t, err) store.Set([]byte("MYKEY"), []byte("MYVALUE")) @@ -59,7 +59,7 @@ func TestVerifyIAVLStoreQueryProof(t *testing.T) { func TestVerifyMultiStoreQueryProof(t *testing.T) { // Create main tree for testing. db := dbm.NewMemDB() - store := NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) + store := NewStore(db, coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) iavlStoreKey := types.NewKVStoreKey("iavlStoreKey") store.MountStoreWithDB(iavlStoreKey, types.StoreTypeIAVL, nil) @@ -115,7 +115,7 @@ func TestVerifyMultiStoreQueryProof(t *testing.T) { func TestVerifyMultiStoreQueryProofAbsence(t *testing.T) { // Create main tree for testing. db := dbm.NewMemDB() - store := NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) + store := NewStore(db, coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) iavlStoreKey := types.NewKVStoreKey("iavlStoreKey") store.MountStoreWithDB(iavlStoreKey, types.StoreTypeIAVL, nil) diff --git a/store/rootmulti/snapshot_test.go b/store/rootmulti/snapshot_test.go index bde679092157a..9fded8482a649 100644 --- a/store/rootmulti/snapshot_test.go +++ b/store/rootmulti/snapshot_test.go @@ -14,7 +14,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/iavl" "cosmossdk.io/store/metrics" "cosmossdk.io/store/rootmulti" @@ -24,7 +24,7 @@ import ( ) func newMultiStoreWithGeneratedData(db dbm.DB, stores uint8, storeKeys uint64) *rootmulti.Store { - multiStore := rootmulti.NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) + multiStore := rootmulti.NewStore(db, coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) r := rand.New(rand.NewSource(49872768940)) // Fixed seed for deterministic tests keys := []*types.KVStoreKey{} @@ -62,7 +62,7 @@ func newMultiStoreWithGeneratedData(db dbm.DB, stores uint8, storeKeys uint64) * } func newMultiStoreWithMixedMounts(db dbm.DB) *rootmulti.Store { - store := rootmulti.NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) + store := rootmulti.NewStore(db, coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) store.MountStoreWithDB(types.NewKVStoreKey("iavl1"), types.StoreTypeIAVL, nil) store.MountStoreWithDB(types.NewKVStoreKey("iavl2"), types.StoreTypeIAVL, nil) store.MountStoreWithDB(types.NewKVStoreKey("iavl3"), types.StoreTypeIAVL, nil) @@ -245,7 +245,7 @@ func benchmarkMultistoreSnapshot(b *testing.B, stores uint8, storeKeys uint64) { b.StartTimer() for i := 0; i < b.N; i++ { - target := rootmulti.NewStore(dbm.NewMemDB(), log.NewNopLogger(), metrics.NewNoOpMetrics()) + target := rootmulti.NewStore(dbm.NewMemDB(), coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) for _, key := range source.StoreKeysByName() { target.MountStoreWithDB(key, types.StoreTypeIAVL, nil) } @@ -281,7 +281,7 @@ func benchmarkMultistoreSnapshotRestore(b *testing.B, stores uint8, storeKeys ui b.StartTimer() for i := 0; i < b.N; i++ { - target := rootmulti.NewStore(dbm.NewMemDB(), log.NewNopLogger(), metrics.NewNoOpMetrics()) + target := rootmulti.NewStore(dbm.NewMemDB(), coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) for _, key := range source.StoreKeysByName() { target.MountStoreWithDB(key, types.StoreTypeIAVL, nil) } diff --git a/store/rootmulti/store.go b/store/rootmulti/store.go index 1be58ea36dc18..ab6402447f710 100644 --- a/store/rootmulti/store.go +++ b/store/rootmulti/store.go @@ -725,7 +725,7 @@ func (rs *Store) PruneStores(pruningHeight int64) (err error) { return nil } -// getStoreByName performs a lookup of a StoreKey given a store name typically +// GetStoreByName performs a lookup of a StoreKey given a store name typically // provided in a path. The StoreKey is then used to perform a lookup and return // a Store. If the Store is wrapped in an inter-block cache, it will be unwrapped // prior to being returned. If the StoreKey does not exist, nil is returned. diff --git a/store/rootmulti/store_test.go b/store/rootmulti/store_test.go index baa24a0625d96..39cbfaf801dd1 100644 --- a/store/rootmulti/store_test.go +++ b/store/rootmulti/store_test.go @@ -10,7 +10,7 @@ import ( dbm "github.com/cosmos/cosmos-db" "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/errors" "cosmossdk.io/store/cachemulti" "cosmossdk.io/store/iavl" @@ -22,7 +22,7 @@ import ( func TestStoreType(t *testing.T) { db := dbm.NewMemDB() - store := NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) + store := NewStore(db, coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) store.MountStoreWithDB(types.NewKVStoreKey("store1"), types.StoreTypeIAVL, db) } @@ -45,7 +45,7 @@ func TestGetCommitKVStore(t *testing.T) { func TestStoreMount(t *testing.T) { db := dbm.NewMemDB() - store := NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) + store := NewStore(db, coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) key1 := types.NewKVStoreKey("store1") key2 := types.NewKVStoreKey("store2") @@ -652,7 +652,7 @@ func (p *pauseableCommitKVStoreStub) PausePruning(b bool) { } func TestPausePruningOnCommit(t *testing.T) { - store := NewStore(dbm.NewMemDB(), log.NewNopLogger(), metrics.NewNoOpMetrics()) + store := NewStore(dbm.NewMemDB(), coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) store.SetPruning(pruningtypes.NewCustomPruningOptions(2, 11)) store.MountStoreWithDB(testStoreKey1, types.StoreTypeIAVL, nil) require.NoError(t, store.LoadLatestVersion()) @@ -833,7 +833,7 @@ var ( ) func newMultiStoreWithMounts(db dbm.DB, pruningOpts pruningtypes.PruningOptions) *Store { - store := NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) + store := NewStore(db, coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) store.SetPruning(pruningOpts) store.MountStoreWithDB(testStoreKey1, types.StoreTypeIAVL, nil) @@ -844,7 +844,7 @@ func newMultiStoreWithMounts(db dbm.DB, pruningOpts pruningtypes.PruningOptions) } func newMultiStoreWithModifiedMounts(db dbm.DB, pruningOpts pruningtypes.PruningOptions) (*Store, *types.StoreUpgrades) { - store := NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) + store := NewStore(db, coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) store.SetPruning(pruningOpts) store.MountStoreWithDB(types.NewKVStoreKey("store1"), types.StoreTypeIAVL, nil) @@ -970,7 +970,7 @@ func (stub *commitKVStoreStub) Commit() types.CommitID { func prepareStoreMap() (map[types.StoreKey]types.CommitKVStore, error) { var db dbm.DB = dbm.NewMemDB() - store := NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) + store := NewStore(db, coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) store.MountStoreWithDB(types.NewKVStoreKey("iavl1"), types.StoreTypeIAVL, nil) store.MountStoreWithDB(types.NewKVStoreKey("iavl2"), types.StoreTypeIAVL, nil) store.MountStoreWithDB(types.NewTransientStoreKey("trans1"), types.StoreTypeTransient, nil) diff --git a/store/snapshots/helpers_test.go b/store/snapshots/helpers_test.go index 3c8463e90c171..d45d068f5c750 100644 --- a/store/snapshots/helpers_test.go +++ b/store/snapshots/helpers_test.go @@ -15,7 +15,7 @@ import ( protoio "github.com/cosmos/gogoproto/io" "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" errorsmod "cosmossdk.io/errors" "cosmossdk.io/store/snapshots" snapshottypes "cosmossdk.io/store/snapshots/types" @@ -211,7 +211,7 @@ func setupBusyManager(t *testing.T) *snapshots.Manager { require.NoError(t, err) hung := newHungSnapshotter() hung.SetSnapshotInterval(opts.Interval) - mgr := snapshots.NewManager(store, opts, hung, nil, log.NewNopLogger()) + mgr := snapshots.NewManager(store, opts, hung, nil, coretesting.NewNopLogger()) require.Equal(t, opts.Interval, hung.snapshotInterval) // Channel to ensure the test doesn't finish until the goroutine is done. diff --git a/store/snapshots/manager_test.go b/store/snapshots/manager_test.go index 65d559215c212..b6ecdc261175c 100644 --- a/store/snapshots/manager_test.go +++ b/store/snapshots/manager_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/snapshots" "cosmossdk.io/store/snapshots/types" ) @@ -19,7 +19,7 @@ func TestManager_List(t *testing.T) { store := setupStore(t) snapshotter := &mockSnapshotter{} snapshotter.SetSnapshotInterval(opts.Interval) - manager := snapshots.NewManager(store, opts, snapshotter, nil, log.NewNopLogger()) + manager := snapshots.NewManager(store, opts, snapshotter, nil, coretesting.NewNopLogger()) require.Equal(t, opts.Interval, snapshotter.GetSnapshotInterval()) mgrList, err := manager.List() @@ -41,7 +41,7 @@ func TestManager_List(t *testing.T) { func TestManager_LoadChunk(t *testing.T) { store := setupStore(t) - manager := snapshots.NewManager(store, opts, &mockSnapshotter{}, nil, log.NewNopLogger()) + manager := snapshots.NewManager(store, opts, &mockSnapshotter{}, nil, coretesting.NewNopLogger()) // Existing chunk should return body chunk, err := manager.LoadChunk(2, 1, 1) @@ -74,7 +74,7 @@ func TestManager_Take(t *testing.T) { extSnapshotter := newExtSnapshotter(10) expectChunks := snapshotItems(items, extSnapshotter) - manager := snapshots.NewManager(store, opts, snapshotter, nil, log.NewNopLogger()) + manager := snapshots.NewManager(store, opts, snapshotter, nil, coretesting.NewNopLogger()) err := manager.RegisterExtensions(extSnapshotter) require.NoError(t, err) @@ -119,7 +119,7 @@ func TestManager_Prune(t *testing.T) { store := setupStore(t) snapshotter := &mockSnapshotter{} snapshotter.SetSnapshotInterval(opts.Interval) - manager := snapshots.NewManager(store, opts, snapshotter, nil, log.NewNopLogger()) + manager := snapshots.NewManager(store, opts, snapshotter, nil, coretesting.NewNopLogger()) pruned, err := manager.Prune(2) require.NoError(t, err) @@ -141,7 +141,7 @@ func TestManager_Restore(t *testing.T) { prunedHeights: make(map[int64]struct{}), } extSnapshotter := newExtSnapshotter(0) - manager := snapshots.NewManager(store, opts, target, nil, log.NewNopLogger()) + manager := snapshots.NewManager(store, opts, target, nil, coretesting.NewNopLogger()) err := manager.RegisterExtensions(extSnapshotter) require.NoError(t, err) @@ -251,7 +251,7 @@ func TestManager_TakeError(t *testing.T) { snapshotter := &mockErrorSnapshotter{} store, err := snapshots.NewStore(db.NewMemDB(), GetTempDir(t)) require.NoError(t, err) - manager := snapshots.NewManager(store, opts, snapshotter, nil, log.NewNopLogger()) + manager := snapshots.NewManager(store, opts, snapshotter, nil, coretesting.NewNopLogger()) _, err = manager.Create(1) require.Error(t, err) diff --git a/store/snapshots/store.go b/store/snapshots/store.go index aa593f5bac61b..c58461a68b4f2 100644 --- a/store/snapshots/store.go +++ b/store/snapshots/store.go @@ -92,7 +92,7 @@ func (s *Store) Get(height uint64, format uint32) (*types.Snapshot, error) { return snapshot, nil } -// Get fetches the latest snapshot from the database, if any. +// GetLatest fetches the latest snapshot from the database, if any. func (s *Store) GetLatest() (*types.Snapshot, error) { iter, err := s.db.ReverseIterator(encodeKey(0, 0), encodeKey(uint64(math.MaxUint64), math.MaxUint32)) if err != nil { diff --git a/store/snapshots/types/convert.go b/store/snapshots/types/convert.go index f326878757dd7..a5ed10929cb7c 100644 --- a/store/snapshots/types/convert.go +++ b/store/snapshots/types/convert.go @@ -7,7 +7,7 @@ import ( "cosmossdk.io/errors" ) -// Converts an ABCI snapshot to a snapshot. Mainly to decode the SDK metadata. +// SnapshotFromABCI converts an ABCI snapshot to a snapshot. Mainly to decode the SDK metadata. func SnapshotFromABCI(in *abci.Snapshot) (Snapshot, error) { snapshot := Snapshot{ Height: in.Height, @@ -22,7 +22,7 @@ func SnapshotFromABCI(in *abci.Snapshot) (Snapshot, error) { return snapshot, nil } -// Converts a Snapshot to its ABCI representation. Mainly to encode the SDK metadata. +// ToABCI converts a Snapshot to its ABCI representation. Mainly to encode the SDK metadata. func (s Snapshot) ToABCI() (abci.Snapshot, error) { out := abci.Snapshot{ Height: s.Height, diff --git a/store/streaming/abci/grpc.go b/store/streaming/abci/grpc.go index b838a153be173..89e1c01c2b262 100644 --- a/store/streaming/abci/grpc.go +++ b/store/streaming/abci/grpc.go @@ -17,7 +17,7 @@ type GRPCClient struct { client ABCIListenerServiceClient } -// ListenEndBlock listens to end block request and responses. +// ListenFinalizeBlock listens to end block request and responses. // In addition, it retrieves a types.Context from a context.Context instance. // It panics if a types.Context was not properly attached. // When the node is configured to stop on listening errors, diff --git a/store/streaming/streaming_test.go b/store/streaming/streaming_test.go index 5471a2b4dcded..3cc55c28d0599 100644 --- a/store/streaming/streaming_test.go +++ b/store/streaming/streaming_test.go @@ -16,6 +16,7 @@ import ( "github.com/stretchr/testify/suite" "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" ) @@ -58,7 +59,7 @@ func (s *PluginTestSuite) SetupTest() { require.True(s.T(), ok, "should pass type check") header := cmtproto.Header{Height: 1, Time: time.Now()} - logger := log.NewNopLogger() + logger := coretesting.NewNopLogger() streamingService := storetypes.StreamingManager{ ABCIListeners: []storetypes.ABCIListener{abciListener}, StopNodeOnErr: true, diff --git a/store/transient/store.go b/store/transient/store.go index 2794d3d9a1195..d72a72476efcd 100644 --- a/store/transient/store.go +++ b/store/transient/store.go @@ -18,13 +18,13 @@ type Store struct { dbadapter.Store } -// Constructs new MemDB adapter +// NewStore constructs new MemDB adapter func NewStore() *Store { return &Store{Store: dbadapter.Store{DB: dbm.NewMemDB()}} } -// Implements CommitStore // Commit cleans up Store. +// Implements CommitStore func (ts *Store) Commit() (id types.CommitID) { ts.Store = dbadapter.Store{DB: dbm.NewMemDB()} return @@ -38,7 +38,7 @@ func (ts *Store) GetPruning() pruningtypes.PruningOptions { return pruningtypes.NewPruningOptions(pruningtypes.PruningUndefined) } -// Implements CommitStore +// LastCommitID implements CommitStore func (ts *Store) LastCommitID() types.CommitID { return types.CommitID{} } @@ -47,7 +47,7 @@ func (ts *Store) WorkingHash() []byte { return []byte{} } -// Implements Store. +// GetStoreType implements Store. func (ts *Store) GetStoreType() types.StoreType { return types.StoreTypeTransient } diff --git a/store/types/codec.go b/store/types/codec.go index 4a5f424873f0e..3b5203747ce58 100644 --- a/store/types/codec.go +++ b/store/types/codec.go @@ -19,12 +19,13 @@ type Codec interface { // in the value pointed to by v. Unmarshal(bz []byte, ptr proto.Message) error - // Unmarshal parses the data encoded with UnmarshalLengthPrefixed method and stores + // UnmarshalLengthPrefixed parses the data encoded with UnmarshalLengthPrefixed method and stores // the result in the value pointed to by v. UnmarshalLengthPrefixed(bz []byte, ptr proto.Message) error } // ============= TestCodec ============= + // TestCodec defines a codec that utilizes Protobuf for both binary and JSON // encoding. type TestCodec struct{} diff --git a/store/types/iterator_test.go b/store/types/iterator_test.go index 409f87615c583..46d5484e4816e 100644 --- a/store/types/iterator_test.go +++ b/store/types/iterator_test.go @@ -6,7 +6,7 @@ import ( dbm "github.com/cosmos/cosmos-db" "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/iavl" "cosmossdk.io/store/metrics" "cosmossdk.io/store/types" @@ -15,7 +15,7 @@ import ( func newMemTestKVStore(t *testing.T) types.KVStore { t.Helper() db := dbm.NewMemDB() - store, err := iavl.LoadStore(db, log.NewNopLogger(), types.NewKVStoreKey("test"), types.CommitID{}, iavl.DefaultIAVLCacheSize, false, metrics.NewNoOpMetrics()) + store, err := iavl.LoadStore(db, coretesting.NewNopLogger(), types.NewKVStoreKey("test"), types.CommitID{}, iavl.DefaultIAVLCacheSize, false, metrics.NewNoOpMetrics()) require.NoError(t, err) return store } diff --git a/store/types/store.go b/store/types/store.go index ea9667691d386..7846876eeb6d0 100644 --- a/store/types/store.go +++ b/store/types/store.go @@ -17,7 +17,7 @@ type Store interface { CacheWrapper } -// something that can persist to disk +// Committer is something that can persist to disk type Committer interface { Commit() CommitID LastCommitID() CommitID @@ -37,6 +37,8 @@ type PausablePruner interface { PausePruning(bool) } +// CommitStore represents a store that can be committed and provides basic store operations. +// It combines the functionality of Committer and Store interfaces. // Stores of MultiStore must implement CommitStore. type CommitStore interface { Committer @@ -131,7 +133,7 @@ func (s *StoreUpgrades) RenamedFrom(key string) string { type MultiStore interface { Store - // Branches MultiStore into a cached storage object. + // CacheMultiStore branches MultiStore into a cached storage object. // NOTE: Caller should probably not call .Write() on each, but // call CacheMultiStore.Write(). CacheMultiStore() CacheMultiStore @@ -140,7 +142,7 @@ type MultiStore interface { // each stored is loaded at a specific version (height). CacheMultiStoreWithVersion(version int64) (CacheMultiStore, error) - // Convenience for fetching substores. + // GetStore is convenience for fetching substores. // If the store does not exist, panics. GetStore(StoreKey) Store GetKVStore(StoreKey) KVStore @@ -162,7 +164,7 @@ type MultiStore interface { LatestVersion() int64 } -// From MultiStore.CacheMultiStore().... +// CacheMultiStore is from MultiStore.CacheMultiStore().... type CacheMultiStore interface { MultiStore Write() // Writes operations to underlying KVStore @@ -174,17 +176,17 @@ type CommitMultiStore interface { MultiStore snapshottypes.Snapshotter - // Mount a store of type using the given db. + // MountStoreWithDB mount a store of type using the given db. // If db == nil, the new store will use the CommitMultiStore db. MountStoreWithDB(key StoreKey, typ StoreType, db dbm.DB) - // Panics on a nil key. + // GetCommitStore panics on a nil key. GetCommitStore(key StoreKey) CommitStore - // Panics on a nil key. + // GetCommitKVStore panics on a nil key. GetCommitKVStore(key StoreKey) CommitKVStore - // Load the latest persisted version. Called once after all calls to + // LoadLatestVersion load the latest persisted version. Called once after all calls to // Mount*Store() are complete. LoadLatestVersion() error @@ -198,13 +200,13 @@ type CommitMultiStore interface { // in order to handle breaking formats in migrations LoadVersionAndUpgrade(ver int64, upgrades *StoreUpgrades) error - // Load a specific persisted version. When you load an old version, or when + // LoadVersion load a specific persisted version. When you load an old version, or when // the last commit attempt didn't complete, the next commit after loading // must be idempotent (return the same commit id). Otherwise the behavior is // undefined. LoadVersion(ver int64) error - // Set an inter-block (persistent) cache that maintains a mapping from + // SetInterBlockCache set an inter-block (persistent) cache that maintains a mapping from // StoreKeys to CommitKVStores. SetInterBlockCache(MultiStorePersistentCache) @@ -265,7 +267,7 @@ type KVStore interface { // Exceptionally allowed for cachekv.Store, safe to write in the modules. Iterator(start, end []byte) Iterator - // Iterator over a domain of keys in descending order. End is exclusive. + // ReverseIterator iterates over a domain of keys in descending order. End is exclusive. // Start must be less than end, or the Iterator is invalid. // Iterator must be closed by caller. // CONTRACT: No writes may happen within a domain while an iterator exists over it. @@ -282,7 +284,7 @@ type Iterator = dbm.Iterator type CacheKVStore interface { KVStore - // Writes operations to underlying KVStore + // Write writes operations to underlying KVStore Write() } @@ -329,7 +331,7 @@ func (cid CommitID) String() string { //---------------------------------------- // Store types -// kind of store +// StoreType is kind of store type StoreType int const ( @@ -425,7 +427,7 @@ type TransientStoreKey struct { name string } -// Constructs new TransientStoreKey +// NewTransientStoreKey constructs new TransientStoreKey // Must return a pointer according to the ocap principle func NewTransientStoreKey(name string) *TransientStoreKey { return &TransientStoreKey{ @@ -433,12 +435,12 @@ func NewTransientStoreKey(name string) *TransientStoreKey { } } -// Implements StoreKey +// Name implements StoreKey func (key *TransientStoreKey) Name() string { return key.name } -// Implements StoreKey +// String implements StoreKey func (key *TransientStoreKey) String() string { return fmt.Sprintf("TransientStoreKey{%p, %s}", key, key.name) } @@ -494,11 +496,11 @@ func (tc TraceContext) Merge(newTc TraceContext) TraceContext { // MultiStorePersistentCache defines an interface which provides inter-block // (persistent) caching capabilities for multiple CommitKVStores based on StoreKeys. type MultiStorePersistentCache interface { - // Wrap and return the provided CommitKVStore with an inter-block (persistent) + // GetStoreCache wrap and return the provided CommitKVStore with an inter-block (persistent) // cache. GetStoreCache(key StoreKey, store CommitKVStore) CommitKVStore - // Return the underlying CommitKVStore for a StoreKey. + // Unwrap return the underlying CommitKVStore for a StoreKey. Unwrap(key StoreKey) CommitKVStore // Reset the entire set of internal caches. diff --git a/store/types/validity.go b/store/types/validity.go index a1fbaba999c70..73b15bdacc52d 100644 --- a/store/types/validity.go +++ b/store/types/validity.go @@ -1,9 +1,12 @@ package types var ( - // 128K - 1 + // MaxKeyLength is the maximum allowed length for a key in bytes. + // It is set to 128K - 1 (131,071 bytes). MaxKeyLength = (1 << 17) - 1 - // 2G - 1 + + // MaxValueLength is the maximum allowed length for a value in bytes. + // It is set to 2G - 1 (2,147,483,647 bytes). MaxValueLength = (1 << 31) - 1 ) diff --git a/store/v2/commitment/iavl/tree_test.go b/store/v2/commitment/iavl/tree_test.go index 1ef49980dd2a4..279a185d11db3 100644 --- a/store/v2/commitment/iavl/tree_test.go +++ b/store/v2/commitment/iavl/tree_test.go @@ -9,6 +9,7 @@ import ( "cosmossdk.io/core/log" corestore "cosmossdk.io/core/store" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/v2/commitment" dbm "cosmossdk.io/store/v2/db" ) @@ -32,7 +33,7 @@ func TestCommitterSuite(t *testing.T) { func generateTree() *IavlTree { cfg := DefaultConfig() db := dbm.NewMemDB() - return NewIavlTree(db, log.NewNopLogger(), cfg) + return NewIavlTree(db, coretesting.NewNopLogger(), cfg) } func TestIavlTree(t *testing.T) { diff --git a/store/v2/commitment/metadata.go b/store/v2/commitment/metadata.go index 258f32672d5d7..6b98ef22577d2 100644 --- a/store/v2/commitment/metadata.go +++ b/store/v2/commitment/metadata.go @@ -59,13 +59,19 @@ func (m *MetadataStore) GetCommitInfo(version uint64) (*proof.CommitInfo, error) return cInfo, nil } -func (m *MetadataStore) flushCommitInfo(version uint64, cInfo *proof.CommitInfo) error { +func (m *MetadataStore) flushCommitInfo(version uint64, cInfo *proof.CommitInfo) (err error) { // do nothing if commit info is nil, as will be the case for an empty, initializing store if cInfo == nil { return nil } batch := m.kv.NewBatch() + defer func() { + cErr := batch.Close() + if err == nil { + err = cErr + } + }() cInfoKey := []byte(fmt.Sprintf(commitInfoKeyFmt, version)) value, err := cInfo.Marshal() if err != nil { @@ -87,7 +93,7 @@ func (m *MetadataStore) flushCommitInfo(version uint64, cInfo *proof.CommitInfo) if err := batch.WriteSync(); err != nil { return err } - return batch.Close() + return nil } func (m *MetadataStore) deleteCommitInfo(version uint64) error { diff --git a/store/v2/commitment/store_bench_test.go b/store/v2/commitment/store_bench_test.go index 51b89fbde5b52..037d211ee7198 100644 --- a/store/v2/commitment/store_bench_test.go +++ b/store/v2/commitment/store_bench_test.go @@ -10,8 +10,8 @@ import ( "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" corestore "cosmossdk.io/core/store" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/v2/commitment" "cosmossdk.io/store/v2/commitment/iavl" dbm "cosmossdk.io/store/v2/db" @@ -63,10 +63,10 @@ func getCommitStore(b *testing.B, db corestore.KVStoreWithBatch) *commitment.Com multiTrees := make(map[string]commitment.Tree) for _, storeKey := range storeKeys { prefixDB := dbm.NewPrefixDB(db, []byte(storeKey)) - multiTrees[storeKey] = iavl.NewIavlTree(prefixDB, log.NewNopLogger(), iavl.DefaultConfig()) + multiTrees[storeKey] = iavl.NewIavlTree(prefixDB, coretesting.NewNopLogger(), iavl.DefaultConfig()) } - sc, err := commitment.NewCommitStore(multiTrees, db, log.NewNopLogger()) + sc, err := commitment.NewCommitStore(multiTrees, db, coretesting.NewNopLogger()) require.NoError(b, err) return sc diff --git a/store/v2/commitment/store_test_suite.go b/store/v2/commitment/store_test_suite.go index 4178f5944e22b..5c5c2d378a890 100644 --- a/store/v2/commitment/store_test_suite.go +++ b/store/v2/commitment/store_test_suite.go @@ -10,6 +10,7 @@ import ( "cosmossdk.io/core/log" corestore "cosmossdk.io/core/store" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/v2" dbm "cosmossdk.io/store/v2/db" "cosmossdk.io/store/v2/snapshots" @@ -30,7 +31,7 @@ type CommitStoreTestSuite struct { func (s *CommitStoreTestSuite) TestStore_Snapshotter() { storeKeys := []string{storeKey1, storeKey2} - commitStore, err := s.NewStore(dbm.NewMemDB(), storeKeys, log.NewNopLogger()) + commitStore, err := s.NewStore(dbm.NewMemDB(), storeKeys, coretesting.NewNopLogger()) s.Require().NoError(err) latestVersion := uint64(10) @@ -64,7 +65,7 @@ func (s *CommitStoreTestSuite) TestStore_Snapshotter() { }, } - targetStore, err := s.NewStore(dbm.NewMemDB(), storeKeys, log.NewNopLogger()) + targetStore, err := s.NewStore(dbm.NewMemDB(), storeKeys, coretesting.NewNopLogger()) s.Require().NoError(err) chunks := make(chan io.ReadCloser, kvCount*int(latestVersion)) @@ -126,7 +127,7 @@ func (s *CommitStoreTestSuite) TestStore_Snapshotter() { func (s *CommitStoreTestSuite) TestStore_Pruning() { storeKeys := []string{storeKey1, storeKey2} pruneOpts := store.NewPruningOptionWithCustom(10, 5) - commitStore, err := s.NewStore(dbm.NewMemDB(), storeKeys, log.NewNopLogger()) + commitStore, err := s.NewStore(dbm.NewMemDB(), storeKeys, coretesting.NewNopLogger()) s.Require().NoError(err) latestVersion := uint64(100) diff --git a/store/v2/db/prefixdb.go b/store/v2/db/prefixdb.go index 643f2e95f7a1f..fc13bbb5af0a9 100644 --- a/store/v2/db/prefixdb.go +++ b/store/v2/db/prefixdb.go @@ -247,7 +247,7 @@ func (itr *prefixDBIterator) Next() { } } -// Next implements Iterator. +// Key implements Iterator. func (itr *prefixDBIterator) Key() []byte { itr.assertIsValid() key := itr.source.Key() diff --git a/store/v2/go.mod b/store/v2/go.mod index fab1a3f69e0a5..aea6c0d464f76 100644 --- a/store/v2/go.mod +++ b/store/v2/go.mod @@ -4,6 +4,7 @@ go 1.21 require ( cosmossdk.io/core v0.12.0 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 cosmossdk.io/errors v1.0.1 cosmossdk.io/log v1.3.1 github.com/cockroachdb/pebble v1.1.0 @@ -53,7 +54,8 @@ require ( github.com/prometheus/procfs v0.15.1 // indirect github.com/rogpeppe/go-internal v1.12.0 // indirect github.com/rs/zerolog v1.33.0 // indirect - golang.org/x/crypto v0.25.0 // indirect + github.com/tidwall/btree v1.7.0 // indirect + golang.org/x/crypto v0.24.0 // indirect golang.org/x/exp v0.0.0-20240314144324-c7f7c6466f7f // indirect golang.org/x/sys v0.22.0 // indirect golang.org/x/text v0.16.0 // indirect @@ -65,4 +67,6 @@ require ( replace cosmossdk.io/core => ../../core +replace cosmossdk.io/core/testing => ../../core/testing + replace cosmossdk.io/log => ../../log diff --git a/store/v2/go.sum b/store/v2/go.sum index 9b76f3090ea14..66d125306c7a9 100644 --- a/store/v2/go.sum +++ b/store/v2/go.sum @@ -210,6 +210,8 @@ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsT github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d h1:vfofYNRScrDdvS342BElfbETmL1Aiz3i2t0zfRj16Hs= github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d/go.mod h1:RRCYJbIwD5jmqPI9XoAFR0OcDxqUctll6zUj/+B4S48= +github.com/tidwall/btree v1.7.0 h1:L1fkJH/AuEh5zBnnBbmTwQ5Lt+bRJ5A8EWecslvo9iI= +github.com/tidwall/btree v1.7.0/go.mod h1:twD9XRA5jj9VUQGELzDO4HPQTNJsoWWfYEL+EUQ2cKY= github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -217,8 +219,8 @@ golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnf golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30= -golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M= +golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI= +golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM= golang.org/x/exp v0.0.0-20240314144324-c7f7c6466f7f h1:3CW0unweImhOzd5FmYuRsD4Y4oQFKZIjAnKbjV4WIrw= golang.org/x/exp v0.0.0-20240314144324-c7f7c6466f7f/go.mod h1:CxmFvTBINI24O/j8iY7H1xHzx2i4OsyguNBmN/uPtqc= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= diff --git a/store/v2/internal/encoding/encoding.go b/store/v2/internal/encoding/encoding.go index 40d558da3871a..b73b923f11d0d 100644 --- a/store/v2/internal/encoding/encoding.go +++ b/store/v2/internal/encoding/encoding.go @@ -28,7 +28,7 @@ var uvarintPool = &sync.Pool{ }, } -// decodeBytes decodes a varint length-prefixed byte slice, returning it along with the number +// DecodeBytes decodes a varint length-prefixed byte slice, returning it along with the number // of input bytes read. // Assumes bz will not be mutated. func DecodeBytes(bz []byte) ([]byte, int, error) { @@ -55,7 +55,7 @@ func DecodeBytes(bz []byte) ([]byte, int, error) { return bz[n:end], end, nil } -// decodeUvarint decodes a varint-encoded unsigned integer from a byte slice, returning it and the +// DecodeUvarint decodes a varint-encoded unsigned integer from a byte slice, returning it and the // number of bytes decoded. func DecodeUvarint(bz []byte) (uint64, int, error) { u, n := binary.Uvarint(bz) @@ -71,7 +71,7 @@ func DecodeUvarint(bz []byte) (uint64, int, error) { return u, n, nil } -// decodeVarint decodes a varint-encoded integer from a byte slice, returning it and the number of +// DecodeVarint decodes a varint-encoded integer from a byte slice, returning it and the number of // bytes decoded. func DecodeVarint(bz []byte) (int64, int, error) { i, n := binary.Varint(bz) @@ -96,7 +96,7 @@ func EncodeBytes(w io.Writer, bz []byte) error { return err } -// encodeBytesSlice length-prefixes the byte slice and returns it. +// EncodeBytesSlice length-prefixes the byte slice and returns it. func EncodeBytesSlice(bz []byte) ([]byte, error) { buf := bufPool.Get().(*bytes.Buffer) buf.Reset() @@ -110,7 +110,7 @@ func EncodeBytesSlice(bz []byte) ([]byte, error) { return bytesCopy, err } -// encodeBytesSize returns the byte size of the given slice including length-prefixing. +// EncodeBytesSize returns the byte size of the given slice including length-prefixing. func EncodeBytesSize(bz []byte) int { return EncodeUvarintSize(uint64(len(bz))) + len(bz) } diff --git a/store/v2/migration/manager_test.go b/store/v2/migration/manager_test.go index dea337f703b5c..d8365ce075798 100644 --- a/store/v2/migration/manager_test.go +++ b/store/v2/migration/manager_test.go @@ -6,8 +6,8 @@ import ( "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" corestore "cosmossdk.io/core/store" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/v2/commitment" "cosmossdk.io/store/v2/commitment/iavl" dbm "cosmossdk.io/store/v2/db" @@ -25,35 +25,35 @@ func setupMigrationManager(t *testing.T, noCommitStore bool) (*Manager, *commitm multiTrees := make(map[string]commitment.Tree) for _, storeKey := range storeKeys { prefixDB := dbm.NewPrefixDB(db, []byte(storeKey)) - multiTrees[storeKey] = iavl.NewIavlTree(prefixDB, log.NewNopLogger(), iavl.DefaultConfig()) + multiTrees[storeKey] = iavl.NewIavlTree(prefixDB, coretesting.NewNopLogger(), iavl.DefaultConfig()) } - commitStore, err := commitment.NewCommitStore(multiTrees, db, log.NewNopLogger()) + commitStore, err := commitment.NewCommitStore(multiTrees, db, coretesting.NewNopLogger()) require.NoError(t, err) snapshotsStore, err := snapshots.NewStore(t.TempDir()) require.NoError(t, err) - snapshotsManager := snapshots.NewManager(snapshotsStore, snapshots.NewSnapshotOptions(1500, 2), commitStore, nil, nil, log.NewNopLogger()) + snapshotsManager := snapshots.NewManager(snapshotsStore, snapshots.NewSnapshotOptions(1500, 2), commitStore, nil, nil, coretesting.NewNopLogger()) storageDB, err := pebbledb.New(t.TempDir()) require.NoError(t, err) - newStorageStore := storage.NewStorageStore(storageDB, log.NewNopLogger()) // for store/v2 + newStorageStore := storage.NewStorageStore(storageDB, coretesting.NewNopLogger()) // for store/v2 db1 := dbm.NewMemDB() multiTrees1 := make(map[string]commitment.Tree) for _, storeKey := range storeKeys { prefixDB := dbm.NewPrefixDB(db1, []byte(storeKey)) - multiTrees1[storeKey] = iavl.NewIavlTree(prefixDB, log.NewNopLogger(), iavl.DefaultConfig()) + multiTrees1[storeKey] = iavl.NewIavlTree(prefixDB, coretesting.NewNopLogger(), iavl.DefaultConfig()) } - newCommitStore, err := commitment.NewCommitStore(multiTrees1, db1, log.NewNopLogger()) // for store/v2 + newCommitStore, err := commitment.NewCommitStore(multiTrees1, db1, coretesting.NewNopLogger()) // for store/v2 require.NoError(t, err) if noCommitStore { newCommitStore = nil } - return NewManager(db, snapshotsManager, newStorageStore, newCommitStore, log.NewNopLogger()), commitStore + return NewManager(db, snapshotsManager, newStorageStore, newCommitStore, coretesting.NewNopLogger()), commitStore } func TestMigrateState(t *testing.T) { @@ -79,6 +79,11 @@ func TestMigrateState(t *testing.T) { err := m.Migrate(toVersion - 1) require.NoError(t, err) + // expecting error for conflicting process, since Migrate trigger snapshotter create migration, + // which start a snapshot process already. + _, err = m.snapshotsManager.Create(toVersion - 1) + require.Error(t, err) + if m.stateCommitment != nil { // check the migrated state for version := uint64(1); version < toVersion; version++ { diff --git a/store/v2/root/factory.go b/store/v2/root/factory.go index ced6ee91276c4..7139f48abf878 100644 --- a/store/v2/root/factory.go +++ b/store/v2/root/factory.go @@ -1,6 +1,7 @@ package root import ( + "errors" "fmt" "os" @@ -76,7 +77,7 @@ func CreateRootStore(opts *FactoryOptions) (store.RootStore, error) { ssDb, err = pebbledb.New(dir) case SSTypeRocks: // TODO: rocksdb requires build tags so is not supported here by default - return nil, fmt.Errorf("rocksdb not supported") + return nil, errors.New("rocksdb not supported") } if err != nil { return nil, err @@ -110,7 +111,7 @@ func CreateRootStore(opts *FactoryOptions) (store.RootStore, error) { case SCTypeIavl: trees[key] = iavl.NewIavlTree(db.NewPrefixDB(opts.SCRawDB, []byte(key)), opts.Logger, opts.IavlConfig) case SCTypeIavlV2: - return nil, fmt.Errorf("iavl v2 not supported") + return nil, errors.New("iavl v2 not supported") } } } diff --git a/store/v2/root/migrate_test.go b/store/v2/root/migrate_test.go index fb22ae5ded17b..4d1b62b878a5f 100644 --- a/store/v2/root/migrate_test.go +++ b/store/v2/root/migrate_test.go @@ -7,8 +7,8 @@ import ( "github.com/stretchr/testify/suite" - corelog "cosmossdk.io/core/log" corestore "cosmossdk.io/core/store" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/log" "cosmossdk.io/store/v2" "cosmossdk.io/store/v2/commitment" @@ -35,7 +35,7 @@ func TestMigrateStoreTestSuite(t *testing.T) { func (s *MigrateStoreTestSuite) SetupTest() { testLog := log.NewTestLogger(s.T()) - nopLog := corelog.NewNopLogger() + nopLog := coretesting.NewNopLogger() mdb := dbm.NewMemDB() multiTrees := make(map[string]commitment.Tree) diff --git a/store/v2/root/store_test.go b/store/v2/root/store_test.go index d962e2a192054..b2b640feb974f 100644 --- a/store/v2/root/store_test.go +++ b/store/v2/root/store_test.go @@ -9,8 +9,8 @@ import ( "github.com/stretchr/testify/suite" coreheader "cosmossdk.io/core/header" - "cosmossdk.io/core/log" corestore "cosmossdk.io/core/store" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/v2" "cosmossdk.io/store/v2/commitment" "cosmossdk.io/store/v2/commitment/iavl" @@ -46,7 +46,7 @@ func TestStorageTestSuite(t *testing.T) { } func (s *RootStoreTestSuite) SetupTest() { - noopLog := log.NewNopLogger() + noopLog := coretesting.NewNopLogger() sqliteDB, err := sqlite.New(s.T().TempDir()) s.Require().NoError(err) @@ -66,7 +66,7 @@ func (s *RootStoreTestSuite) SetupTest() { } func (s *RootStoreTestSuite) newStoreWithPruneConfig(config *store.PruningOption) { - noopLog := log.NewNopLogger() + noopLog := coretesting.NewNopLogger() sqliteDB, err := sqlite.New(s.T().TempDir()) s.Require().NoError(err) @@ -91,7 +91,7 @@ func (s *RootStoreTestSuite) newStoreWithPruneConfig(config *store.PruningOption } func (s *RootStoreTestSuite) newStoreWithBackendMount(ss store.VersionedDatabase, sc store.Committer, pm *pruning.Manager) { - noopLog := log.NewNopLogger() + noopLog := coretesting.NewNopLogger() rs, err := New(noopLog, ss, sc, pm, nil, nil) s.Require().NoError(err) @@ -554,7 +554,7 @@ func (s *RootStoreTestSuite) TestMultiStore_PruningRestart() { Interval: 11, } - noopLog := log.NewNopLogger() + noopLog := coretesting.NewNopLogger() mdb1 := dbm.NewMemDB() mdb2 := dbm.NewMemDB() @@ -630,12 +630,12 @@ func (s *RootStoreTestSuite) TestMultiStore_PruningRestart() { return false } // wait for async pruning process to finish - s.Require().Eventually(checkErr, 2*time.Second, 100*time.Millisecond, "expected error when loading height: %d", v) + s.Require().Eventually(checkErr, 5*time.Second, 100*time.Millisecond, "expected error when loading height: %d", v) } } func (s *RootStoreTestSuite) TestMultiStoreRestart() { - noopLog := log.NewNopLogger() + noopLog := coretesting.NewNopLogger() sqliteDB, err := sqlite.New(s.T().TempDir()) s.Require().NoError(err) diff --git a/store/v2/snapshots/helpers_test.go b/store/v2/snapshots/helpers_test.go index 287d2ef4ea7d0..3157f35316084 100644 --- a/store/v2/snapshots/helpers_test.go +++ b/store/v2/snapshots/helpers_test.go @@ -13,8 +13,8 @@ import ( protoio "github.com/cosmos/gogoproto/io" "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" corestore "cosmossdk.io/core/store" + coretesting "cosmossdk.io/core/testing" errorsmod "cosmossdk.io/errors" "cosmossdk.io/store/v2/snapshots" snapshotstypes "cosmossdk.io/store/v2/snapshots/types" @@ -190,7 +190,7 @@ func setupBusyManager(t *testing.T) *snapshots.Manager { store, err := snapshots.NewStore(t.TempDir()) require.NoError(t, err) hung := newHungCommitSnapshotter() - mgr := snapshots.NewManager(store, opts, hung, &mockStorageSnapshotter{}, nil, log.NewNopLogger()) + mgr := snapshots.NewManager(store, opts, hung, &mockStorageSnapshotter{}, nil, coretesting.NewNopLogger()) // Channel to ensure the test doesn't finish until the goroutine is done. // Without this, there are intermittent test failures about diff --git a/store/v2/snapshots/manager_test.go b/store/v2/snapshots/manager_test.go index 88491b647371b..2be8d40787580 100644 --- a/store/v2/snapshots/manager_test.go +++ b/store/v2/snapshots/manager_test.go @@ -7,7 +7,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" + "cosmossdk.io/log" "cosmossdk.io/store/v2/snapshots" "cosmossdk.io/store/v2/snapshots/types" ) @@ -18,7 +19,7 @@ func TestManager_List(t *testing.T) { store := setupStore(t) commitSnapshotter := &mockCommitSnapshotter{} storageSnapshotter := &mockStorageSnapshotter{} - manager := snapshots.NewManager(store, opts, commitSnapshotter, storageSnapshotter, nil, log.NewNopLogger()) + manager := snapshots.NewManager(store, opts, commitSnapshotter, storageSnapshotter, nil, coretesting.NewNopLogger()) mgrList, err := manager.List() require.NoError(t, err) @@ -39,7 +40,7 @@ func TestManager_List(t *testing.T) { func TestManager_LoadChunk(t *testing.T) { store := setupStore(t) - manager := snapshots.NewManager(store, opts, &mockCommitSnapshotter{}, &mockStorageSnapshotter{}, nil, log.NewNopLogger()) + manager := snapshots.NewManager(store, opts, &mockCommitSnapshotter{}, &mockStorageSnapshotter{}, nil, coretesting.NewNopLogger()) // Existing chunk should return body chunk, err := manager.LoadChunk(2, 1, 1) @@ -71,7 +72,7 @@ func TestManager_Take(t *testing.T) { extSnapshotter := newExtSnapshotter(10) expectChunks := snapshotItems(items, extSnapshotter) - manager := snapshots.NewManager(store, opts, commitSnapshotter, &mockStorageSnapshotter{}, nil, log.NewNopLogger()) + manager := snapshots.NewManager(store, opts, commitSnapshotter, &mockStorageSnapshotter{}, nil, coretesting.NewNopLogger()) err := manager.RegisterExtensions(extSnapshotter) require.NoError(t, err) @@ -110,7 +111,7 @@ func TestManager_Take(t *testing.T) { func TestManager_Prune(t *testing.T) { store := setupStore(t) - manager := snapshots.NewManager(store, opts, &mockCommitSnapshotter{}, &mockStorageSnapshotter{}, nil, log.NewNopLogger()) + manager := snapshots.NewManager(store, opts, &mockCommitSnapshotter{}, &mockStorageSnapshotter{}, nil, coretesting.NewNopLogger()) pruned, err := manager.Prune(2) require.NoError(t, err) @@ -130,7 +131,7 @@ func TestManager_Restore(t *testing.T) { store := setupStore(t) target := &mockCommitSnapshotter{} extSnapshotter := newExtSnapshotter(0) - manager := snapshots.NewManager(store, opts, target, &mockStorageSnapshotter{}, nil, log.NewNopLogger()) + manager := snapshots.NewManager(store, opts, target, &mockStorageSnapshotter{}, nil, coretesting.NewNopLogger()) err := manager.RegisterExtensions(extSnapshotter) require.NoError(t, err) @@ -249,8 +250,172 @@ func TestManager_TakeError(t *testing.T) { snapshotter := &mockErrorCommitSnapshotter{} store, err := snapshots.NewStore(t.TempDir()) require.NoError(t, err) - manager := snapshots.NewManager(store, opts, snapshotter, &mockStorageSnapshotter{}, nil, log.NewNopLogger()) + manager := snapshots.NewManager(store, opts, snapshotter, &mockStorageSnapshotter{}, nil, coretesting.NewNopLogger()) _, err = manager.Create(1) require.Error(t, err) } + +func TestSnapshot_Take_Restore(t *testing.T) { + store := setupStore(t) + items := [][]byte{ + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}, + } + commitSnapshotter := &mockCommitSnapshotter{ + items: items, + } + extSnapshotter := newExtSnapshotter(10) + + expectChunks := snapshotItems(items, extSnapshotter) + manager := snapshots.NewManager(store, opts, commitSnapshotter, &mockStorageSnapshotter{}, nil, coretesting.NewNopLogger()) + err := manager.RegisterExtensions(extSnapshotter) + require.NoError(t, err) + + // creating a snapshot at a higher height should be fine, and should return it + snapshot, err := manager.Create(5) + require.NoError(t, err) + + assert.Equal(t, &types.Snapshot{ + Height: 5, + Format: commitSnapshotter.SnapshotFormat(), + Chunks: 1, + Hash: []uint8{0xc5, 0xf7, 0xfe, 0xea, 0xd3, 0x4d, 0x3e, 0x87, 0xff, 0x41, 0xa2, 0x27, 0xfa, 0xcb, 0x38, 0x17, 0xa, 0x5, 0xeb, 0x27, 0x4e, 0x16, 0x5e, 0xf3, 0xb2, 0x8b, 0x47, 0xd1, 0xe6, 0x94, 0x7e, 0x8b}, + Metadata: types.Metadata{ + ChunkHashes: checksums(expectChunks), + }, + }, snapshot) + + storeSnapshot, chunks, err := store.Load(snapshot.Height, snapshot.Format) + require.NoError(t, err) + assert.Equal(t, snapshot, storeSnapshot) + assert.Equal(t, expectChunks, readChunks(chunks)) + + err = manager.Restore(*snapshot) + require.NoError(t, err) + + // Feeding the chunks should work + for i, chunk := range readChunks(chunks) { + done, err := manager.RestoreChunk(chunk) + require.NoError(t, err) + if i == len(chunks)-1 { + assert.True(t, done) + } else { + assert.False(t, done) + } + } + + // The snapshot is saved in local snapshot store + snapshots, err := store.List() + require.NoError(t, err) + require.Equal(t, uint64(5), snapshots[0].Height) + require.Equal(t, types.CurrentFormat, snapshots[0].Format) + + // Starting a new restore should fail now, because the target already has contents. + err = manager.Restore(*snapshot) + require.Error(t, err) + + storeSnapshot, chunks, err = store.Load(snapshot.Height, snapshot.Format) + require.NoError(t, err) + assert.Equal(t, snapshot, storeSnapshot) + assert.Equal(t, expectChunks, readChunks(chunks)) + + // Feeding the chunks should work + for i, chunk := range readChunks(chunks) { + done, err := manager.RestoreChunk(chunk) + require.NoError(t, err) + if i == len(chunks)-1 { + assert.True(t, done) + } else { + assert.False(t, done) + } + } + + assert.Equal(t, items, commitSnapshotter.items) + assert.Equal(t, 10, len(extSnapshotter.state)) + + snapshots, err = store.List() + require.NoError(t, err) + require.Equal(t, uint64(5), snapshots[0].Height) + require.Equal(t, types.CurrentFormat, snapshots[0].Format) +} + +func TestSnapshot_Take_Prune(t *testing.T) { + store := setupStore(t) + + items := [][]byte{ + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}, + } + commitSnapshotter := &mockCommitSnapshotter{ + items: items, + } + extSnapshotter := newExtSnapshotter(10) + + expectChunks := snapshotItems(items, extSnapshotter) + manager := snapshots.NewManager(store, opts, commitSnapshotter, &mockStorageSnapshotter{}, nil, log.NewNopLogger()) + err := manager.RegisterExtensions(extSnapshotter) + require.NoError(t, err) + + // creating a snapshot at height 4 + snapshot, err := manager.Create(4) + require.NoError(t, err) + + assert.Equal(t, &types.Snapshot{ + Height: 4, + Format: commitSnapshotter.SnapshotFormat(), + Chunks: 1, + Hash: []uint8{0xc5, 0xf7, 0xfe, 0xea, 0xd3, 0x4d, 0x3e, 0x87, 0xff, 0x41, 0xa2, 0x27, 0xfa, 0xcb, 0x38, 0x17, 0xa, 0x5, 0xeb, 0x27, 0x4e, 0x16, 0x5e, 0xf3, 0xb2, 0x8b, 0x47, 0xd1, 0xe6, 0x94, 0x7e, 0x8b}, + Metadata: types.Metadata{ + ChunkHashes: checksums(expectChunks), + }, + }, snapshot) + + pruned, err := manager.Prune(1) + require.NoError(t, err) + assert.EqualValues(t, 4, pruned) + + // creating a snapshot at a same height 4, should be error + // since we prune all the previous snapshot except the latest at height 4 + _, err = manager.Create(4) + require.Error(t, err) + + // prune all + pruned, err = manager.Prune(0) + require.NoError(t, err) + assert.EqualValues(t, 1, pruned) + + // creating a snapshot at a same height 4, should be true since we prune all the previous snapshot + snapshot, err = manager.Create(4) + require.NoError(t, err) + + assert.Equal(t, &types.Snapshot{ + Height: 4, + Format: commitSnapshotter.SnapshotFormat(), + Chunks: 1, + Hash: []uint8{0xc5, 0xf7, 0xfe, 0xea, 0xd3, 0x4d, 0x3e, 0x87, 0xff, 0x41, 0xa2, 0x27, 0xfa, 0xcb, 0x38, 0x17, 0xa, 0x5, 0xeb, 0x27, 0x4e, 0x16, 0x5e, 0xf3, 0xb2, 0x8b, 0x47, 0xd1, 0xe6, 0x94, 0x7e, 0x8b}, + Metadata: types.Metadata{ + ChunkHashes: checksums(expectChunks), + }, + }, snapshot) + + storeSnapshot, chunks, err := store.Load(snapshot.Height, snapshot.Format) + require.NoError(t, err) + assert.Equal(t, snapshot, storeSnapshot) + assert.Equal(t, expectChunks, readChunks(chunks)) + + pruned, err = manager.Prune(2) + require.NoError(t, err) + assert.EqualValues(t, 0, pruned) + + list, err := manager.List() + require.NoError(t, err) + assert.Len(t, list, 1) + + // Prune should error while a snapshot is being taken + manager = setupBusyManager(t) + _, err = manager.Prune(2) + require.Error(t, err) +} diff --git a/store/v2/storage/pebbledb/comparator.go b/store/v2/storage/pebbledb/comparator.go index 08b360e6c0791..337ff7698d845 100644 --- a/store/v2/storage/pebbledb/comparator.go +++ b/store/v2/storage/pebbledb/comparator.go @@ -202,7 +202,9 @@ func MVCCKeyCompare(a, b []byte) int { return bytes.Compare(aTS, bTS) } -// \x00[]<#version-bytes> +// MVCCEncode encodes a key and version into an MVCC format. +// The format is: \x00[]<#version-bytes> +// If the version is 0, only the key and a null byte are encoded. func MVCCEncode(key []byte, version uint64) (dst []byte) { dst = append(dst, key...) dst = append(dst, 0) diff --git a/store/v2/storage/pebbledb/db_test.go b/store/v2/storage/pebbledb/db_test.go index 5857c7f511f72..0ef4c8ca9f258 100644 --- a/store/v2/storage/pebbledb/db_test.go +++ b/store/v2/storage/pebbledb/db_test.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/suite" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/v2/storage" ) @@ -19,7 +19,7 @@ func TestStorageTestSuite(t *testing.T) { db.SetSync(false) } - return storage.NewStorageStore(db, log.NewNopLogger()), err + return storage.NewStorageStore(db, coretesting.NewNopLogger()), err }, EmptyBatchSize: 12, } diff --git a/store/v2/storage/rocksdb/db_test.go b/store/v2/storage/rocksdb/db_test.go index df98c6d316d4c..b807f07259d7a 100644 --- a/store/v2/storage/rocksdb/db_test.go +++ b/store/v2/storage/rocksdb/db_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/v2/storage" ) @@ -20,7 +20,7 @@ func TestStorageTestSuite(t *testing.T) { s := &storage.StorageTestSuite{ NewDB: func(dir string) (*storage.StorageStore, error) { db, err := New(dir) - return storage.NewStorageStore(db, log.NewNopLogger()), err + return storage.NewStorageStore(db, coretesting.NewNopLogger()), err }, EmptyBatchSize: 12, } diff --git a/store/v2/storage/sqlite/db_test.go b/store/v2/storage/sqlite/db_test.go index 62a8b220648e3..fc4c27e6bfd91 100644 --- a/store/v2/storage/sqlite/db_test.go +++ b/store/v2/storage/sqlite/db_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/v2/storage" ) @@ -18,7 +18,7 @@ func TestStorageTestSuite(t *testing.T) { s := &storage.StorageTestSuite{ NewDB: func(dir string) (*storage.StorageStore, error) { db, err := New(dir) - return storage.NewStorageStore(db, log.NewNopLogger()), err + return storage.NewStorageStore(db, coretesting.NewNopLogger()), err }, EmptyBatchSize: 0, } diff --git a/store/v2/storage/storage_bench_test.go b/store/v2/storage/storage_bench_test.go index 3084f6f87a295..960c144782a9b 100644 --- a/store/v2/storage/storage_bench_test.go +++ b/store/v2/storage/storage_bench_test.go @@ -12,8 +12,8 @@ import ( "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" corestore "cosmossdk.io/core/store" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store/v2" "cosmossdk.io/store/v2/storage" "cosmossdk.io/store/v2/storage/pebbledb" @@ -27,7 +27,7 @@ var ( backends = map[string]func(dataDir string) (store.VersionedDatabase, error){ "rocksdb_versiondb_opts": func(dataDir string) (store.VersionedDatabase, error) { db, err := rocksdb.New(dataDir) - return storage.NewStorageStore(db, log.NewNopLogger()), err + return storage.NewStorageStore(db, coretesting.NewNopLogger()), err }, "pebbledb_default_opts": func(dataDir string) (store.VersionedDatabase, error) { db, err := pebbledb.New(dataDir) @@ -35,11 +35,11 @@ var ( db.SetSync(false) } - return storage.NewStorageStore(db, log.NewNopLogger()), err + return storage.NewStorageStore(db, coretesting.NewNopLogger()), err }, "btree_sqlite": func(dataDir string) (store.VersionedDatabase, error) { db, err := sqlite.New(dataDir) - return storage.NewStorageStore(db, log.NewNopLogger()), err + return storage.NewStorageStore(db, coretesting.NewNopLogger()), err }, } rng = rand.New(rand.NewSource(567320)) diff --git a/store/v2/validation.go b/store/v2/validation.go index e1bfcfa78b88a..a495f83b781cd 100644 --- a/store/v2/validation.go +++ b/store/v2/validation.go @@ -1,10 +1,12 @@ package store var ( - // 128K - 1 + // MaxKeyLength is the maximum allowed length for a key in bytes. + // It is set to 128K - 1 (131,071 bytes). MaxKeyLength = (1 << 17) - 1 - // 2G - 1 + // MaxValueLength is the maximum allowed length for a value in bytes. + // It is set to 2G - 1 (2,147,483,647 bytes). MaxValueLength = (1 << 31) - 1 ) diff --git a/telemetry/metrics.go b/telemetry/metrics.go index 07d1020eb8926..175261408aaeb 100644 --- a/telemetry/metrics.go +++ b/telemetry/metrics.go @@ -3,6 +3,7 @@ package telemetry import ( "bytes" "encoding/json" + "errors" "fmt" "net/http" "time" @@ -192,7 +193,7 @@ func (m *Metrics) Gather(format string) (GatherResponse, error) { // If Prometheus metrics are not enabled, it returns an error. func (m *Metrics) gatherPrometheus() (GatherResponse, error) { if !m.prometheusEnabled { - return GatherResponse{}, fmt.Errorf("prometheus metrics are not enabled") + return GatherResponse{}, errors.New("prometheus metrics are not enabled") } metricsFamilies, err := prometheus.DefaultGatherer.Gather() @@ -218,7 +219,7 @@ func (m *Metrics) gatherPrometheus() (GatherResponse, error) { func (m *Metrics) gatherGeneric() (GatherResponse, error) { gm, ok := m.sink.(DisplayableSink) if !ok { - return GatherResponse{}, fmt.Errorf("non in-memory metrics sink does not support generic format") + return GatherResponse{}, errors.New("non in-memory metrics sink does not support generic format") } summary, err := gm.DisplayMetrics(nil, nil) diff --git a/tests/e2e/baseapp/block_gas_test.go b/tests/e2e/baseapp/block_gas_test.go index 431e9463c066b..df5423fb86cee 100644 --- a/tests/e2e/baseapp/block_gas_test.go +++ b/tests/e2e/baseapp/block_gas_test.go @@ -20,7 +20,6 @@ import ( _ "cosmossdk.io/x/accounts" xauthsigning "cosmossdk.io/x/auth/signing" - "github.com/cosmos/cosmos-sdk/baseapp" baseapptestutil "github.com/cosmos/cosmos-sdk/baseapp/testutil" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" @@ -74,8 +73,8 @@ func TestBaseApp_BlockGas(t *testing.T) { for _, tc := range testcases { var ( - bankKeeper baseapp.BankKeeper - accountKeeper baseapp.AuthKeeper + bankKeeper baseapputil.BankKeeper + accountKeeper baseapputil.AuthKeeper appBuilder *runtime.AppBuilder txConfig client.TxConfig cdc codec.Codec diff --git a/tests/e2e/baseapp/utils.go b/tests/e2e/baseapp/utils.go index b6a5605ee61bb..aa69a28e73ee1 100644 --- a/tests/e2e/baseapp/utils.go +++ b/tests/e2e/baseapp/utils.go @@ -1,6 +1,7 @@ package baseapp import ( + "context" "encoding/json" "testing" @@ -54,3 +55,13 @@ func GenesisStateWithSingleValidator(t *testing.T, codec codec.Codec, builder *r return genesisState } + +type BankKeeper interface { + MintCoins(ctx context.Context, moduleName string, amt sdk.Coins) error + SendCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + GetBalance(ctx context.Context, addr sdk.AccAddress, denom string) sdk.Coin +} + +type AuthKeeper interface { + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI +} diff --git a/tests/go.mod b/tests/go.mod index 34c17a8d842ae..e0ad26aa6b253 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -6,7 +6,7 @@ require ( cosmossdk.io/api v0.7.5 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 // indirect cosmossdk.io/log v1.3.1 cosmossdk.io/math v1.3.0 @@ -34,6 +34,7 @@ require ( ) require ( + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 cosmossdk.io/x/accounts v0.0.0-20240226161501-23359a0b6d91 cosmossdk.io/x/accounts/defaults/lockup v0.0.0-20240417181816-5e7aae0db1f5 cosmossdk.io/x/accounts/defaults/multisig v0.0.0-00010101000000-000000000000 @@ -64,7 +65,6 @@ require ( cloud.google.com/go/iam v1.1.8 // indirect cloud.google.com/go/storage v1.42.0 // indirect cosmossdk.io/client/v2 v2.0.0-20230630094428-02b760776860 // indirect - cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/schema v0.1.1 // indirect cosmossdk.io/x/circuit v0.0.0-20230613133644-0a778132a60f // indirect cosmossdk.io/x/epochs v0.0.0-20240522060652-a1ae4c3e0337 // indirect @@ -91,7 +91,7 @@ require ( github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect github.com/cometbft/cometbft-db v0.12.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -241,7 +241,6 @@ replace ( cosmossdk.io/collections => ../collections cosmossdk.io/core => ../core cosmossdk.io/core/testing => ../core/testing - cosmossdk.io/depinject => ../depinject cosmossdk.io/log => ../log cosmossdk.io/store => ../store cosmossdk.io/x/accounts => ../x/accounts diff --git a/tests/go.sum b/tests/go.sum index 8181c3143afd5..5c9a5948ff5e4 100644 --- a/tests/go.sum +++ b/tests/go.sum @@ -192,6 +192,8 @@ cloud.google.com/go/webrisk v1.4.0/go.mod h1:Hn8X6Zr+ziE2aNd8SliSDWpEnSS1u4R9+xX cloud.google.com/go/webrisk v1.5.0/go.mod h1:iPG6fr52Tv7sGk0H6qUFzmL3HHZev1htXuWDEEsqMTg= cloud.google.com/go/workflows v1.6.0/go.mod h1:6t9F5h/unJz41YqfBmqSASJSXccBLtD1Vwf+KmJENM0= cloud.google.com/go/workflows v1.7.0/go.mod h1:JhSrZuVZWuiDfKEFxU0/F1PQjmpnpcoISEXH2bcHC3M= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -306,8 +308,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/tests/integration/example/example_test.go b/tests/integration/example/example_test.go index 92fdbbeebb079..56f49dab8ed46 100644 --- a/tests/integration/example/example_test.go +++ b/tests/integration/example/example_test.go @@ -137,7 +137,7 @@ func Example() { // Output: 10000 } -// ExampleOneModule shows how to use the integration test framework to test the integration of a single module. +// Example_oneModule shows how to use the integration test framework to test the integration of a single module. // That module has no dependency on other modules. func Example_oneModule() { // in this example we are testing the integration of the auth module: diff --git a/tests/integration/server/grpc/out_of_gas_test.go b/tests/integration/server/grpc/out_of_gas_test.go new file mode 100644 index 0000000000000..f662d2a25ff83 --- /dev/null +++ b/tests/integration/server/grpc/out_of_gas_test.go @@ -0,0 +1,98 @@ +package grpc_test + +import ( + "context" + "fmt" + "testing" + + "github.com/stretchr/testify/suite" + "google.golang.org/grpc" + "google.golang.org/grpc/metadata" + + _ "cosmossdk.io/x/accounts" + _ "cosmossdk.io/x/auth" + _ "cosmossdk.io/x/auth/tx/config" + _ "cosmossdk.io/x/bank" + banktypes "cosmossdk.io/x/bank/types" + _ "cosmossdk.io/x/consensus" + _ "cosmossdk.io/x/staking" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/testutil/configurator" + "github.com/cosmos/cosmos-sdk/testutil/network" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +type IntegrationTestOutOfGasSuite struct { + suite.Suite + + cfg network.Config + network network.NetworkI + conn *grpc.ClientConn +} + +func (s *IntegrationTestOutOfGasSuite) SetupSuite() { + var err error + s.T().Log("setting up integration test suite") + + s.cfg, err = network.DefaultConfigWithAppConfigWithQueryGasLimit(configurator.NewAppConfig( + configurator.AccountsModule(), + configurator.AuthModule(), + configurator.BankModule(), + configurator.GenutilModule(), + configurator.StakingModule(), + configurator.ConsensusModule(), + configurator.TxModule(), + ), 10) + s.NoError(err) + s.cfg.NumValidators = 1 + + s.network, err = network.New(s.T(), s.T().TempDir(), s.cfg) + s.Require().NoError(err) + + _, err = s.network.WaitForHeight(2) + s.Require().NoError(err) + + val0 := s.network.GetValidators()[0] + s.conn, err = grpc.NewClient( + val0.GetAppConfig().GRPC.Address, + grpc.WithInsecure(), //nolint:staticcheck // ignore SA1019, we don't need to use a secure connection for tests + grpc.WithDefaultCallOptions(grpc.ForceCodec(codec.NewProtoCodec(s.cfg.InterfaceRegistry).GRPCCodec())), + ) + s.Require().NoError(err) +} + +func (s *IntegrationTestOutOfGasSuite) TearDownSuite() { + s.T().Log("tearing down integration test suite") + s.conn.Close() + s.network.Cleanup() +} + +func (s *IntegrationTestOutOfGasSuite) TestGRPCServer_TestService() { + // gRPC query to test service should work + testClient := testdata.NewQueryClient(s.conn) + testRes, err := testClient.Echo(context.Background(), &testdata.EchoRequest{Message: "hello"}) + s.Require().NoError(err) + s.Require().Equal("hello", testRes.Message) +} + +func (s *IntegrationTestOutOfGasSuite) TestGRPCServer_BankBalance_OutOfGas() { + val0 := s.network.GetValidators()[0] + + // gRPC query to bank service should work + denom := fmt.Sprintf("%stoken", val0.GetMoniker()) + bankClient := banktypes.NewQueryClient(s.conn) + var header metadata.MD + _, err := bankClient.Balance( + context.Background(), + &banktypes.QueryBalanceRequest{Address: val0.GetAddress().String(), Denom: denom}, + grpc.Header(&header), // Also fetch grpc header + ) + + s.Require().ErrorContains(err, sdkerrors.ErrOutOfGas.Error()) +} + +func TestIntegrationTestOutOfGasSuite(t *testing.T) { + suite.Run(t, new(IntegrationTestOutOfGasSuite)) +} diff --git a/tests/integration/store/rootmulti/rollback_test.go b/tests/integration/store/rootmulti/rollback_test.go index 0d6f9d074fa20..c06dadcf82f74 100644 --- a/tests/integration/store/rootmulti/rollback_test.go +++ b/tests/integration/store/rootmulti/rollback_test.go @@ -9,7 +9,7 @@ import ( dbm "github.com/cosmos/cosmos-db" "gotest.tools/v3/assert" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/simapp" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" @@ -18,7 +18,7 @@ import ( func TestRollback(t *testing.T) { db := dbm.NewMemDB() options := simapp.SetupOptions{ - Logger: log.NewNopLogger(), + Logger: coretesting.NewNopLogger(), DB: db, AppOpts: simtestutil.NewAppOptionsWithFlagHome(t.TempDir()), } diff --git a/tests/sims/authz/operations_test.go b/tests/sims/authz/operations_test.go new file mode 100644 index 0000000000000..7e59d00a827f6 --- /dev/null +++ b/tests/sims/authz/operations_test.go @@ -0,0 +1,224 @@ +package authz + +import ( + "math/rand" + "testing" + "time" + + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/suite" + + "cosmossdk.io/core/header" + coretesting "cosmossdk.io/core/testing" + "cosmossdk.io/depinject" + _ "cosmossdk.io/x/accounts" // import as blank for app wiring + _ "cosmossdk.io/x/auth" // import as blank for app wiring + authkeeper "cosmossdk.io/x/auth/keeper" + _ "cosmossdk.io/x/auth/tx/config" // import as blank for app wiring + "cosmossdk.io/x/authz" + authzkeeper "cosmossdk.io/x/authz/keeper" + _ "cosmossdk.io/x/authz/module" // import as blank for app wiring + "cosmossdk.io/x/authz/simulation" + _ "cosmossdk.io/x/bank" // import as blank for app wiring + bankkeeper "cosmossdk.io/x/bank/keeper" + banktestutil "cosmossdk.io/x/bank/testutil" + banktypes "cosmossdk.io/x/bank/types" + _ "cosmossdk.io/x/consensus" // import as blank for app wiring + _ "cosmossdk.io/x/gov" // import as blank for app wiring + _ "cosmossdk.io/x/mint" // import as blank for app wiring + _ "cosmossdk.io/x/staking" // import as blank for app wiring + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/runtime" + "github.com/cosmos/cosmos-sdk/testutil/configurator" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring +) + +var AppConfig = configurator.NewAppConfig( + configurator.AccountsModule(), + configurator.AuthModule(), + configurator.BankModule(), + configurator.StakingModule(), + configurator.TxModule(), + configurator.ConsensusModule(), + configurator.GenutilModule(), + configurator.AuthzModule(), + configurator.MintModule(), +) + +type SimTestSuite struct { + suite.Suite + + ctx sdk.Context + + app *runtime.App + codec codec.Codec + interfaceRegistry codectypes.InterfaceRegistry + txConfig client.TxConfig + accountKeeper authkeeper.AccountKeeper + bankKeeper bankkeeper.Keeper + authzKeeper authzkeeper.Keeper +} + +func (suite *SimTestSuite) SetupTest() { + app, err := simtestutil.Setup( + depinject.Configs( + AppConfig, + depinject.Supply(coretesting.NewNopLogger()), + ), + &suite.codec, + &suite.interfaceRegistry, + &suite.txConfig, + &suite.accountKeeper, + &suite.bankKeeper, + &suite.authzKeeper, + ) + suite.Require().NoError(err) + suite.app = app + suite.ctx = app.BaseApp.NewContext(false) +} + +func (suite *SimTestSuite) TestWeightedOperations() { + cdc := suite.codec + appParams := make(simtypes.AppParams) + + weightedOps := simulation.WeightedOperations(suite.interfaceRegistry, appParams, cdc, suite.txConfig, suite.accountKeeper, + suite.bankKeeper, suite.authzKeeper) + + s := rand.NewSource(3) + r := rand.New(s) + // setup 2 accounts + accs := suite.getTestingAccounts(r, 2) + + expected := []struct { + weight int + opMsgRoute string + opMsgName string + }{ + {simulation.WeightGrant, authz.ModuleName, simulation.TypeMsgGrant}, + {simulation.WeightExec, authz.ModuleName, simulation.TypeMsgExec}, + {simulation.WeightRevoke, authz.ModuleName, simulation.TypeMsgRevoke}, + } + + require := suite.Require() + for i, w := range weightedOps { + op, _, err := w.Op()(r, suite.app.BaseApp, suite.ctx, accs, "") + require.NoError(err) + + // the following checks are very much dependent from the ordering of the output given + // by WeightedOperations. if the ordering in WeightedOperations changes some tests + // will fail + require.Equal(expected[i].weight, w.Weight(), "weight should be the same. %v", op.Comment) + require.Equal(expected[i].opMsgRoute, op.Route, "route should be the same. %v", op.Comment) + require.Equal(expected[i].opMsgName, op.Name, "operation Msg name should be the same %v", op.Comment) + } +} + +func (suite *SimTestSuite) getTestingAccounts(r *rand.Rand, n int) []simtypes.Account { + accounts := simtypes.RandomAccounts(r, n) + + initAmt := sdk.TokensFromConsensusPower(200000, sdk.DefaultPowerReduction) + initCoins := sdk.NewCoins(sdk.NewCoin("stake", initAmt)) + + // add coins to the accounts + for _, account := range accounts { + acc := suite.accountKeeper.NewAccountWithAddress(suite.ctx, account.Address) + suite.accountKeeper.SetAccount(suite.ctx, acc) + suite.Require().NoError(banktestutil.FundAccount(suite.ctx, suite.bankKeeper, account.Address, initCoins)) + } + + return accounts +} + +func (suite *SimTestSuite) TestSimulateGrant() { + s := rand.NewSource(1) + r := rand.New(s) + accounts := suite.getTestingAccounts(r, 2) + blockTime := time.Now().UTC() + ctx := suite.ctx.WithHeaderInfo(header.Info{Time: blockTime}) + + granter := accounts[0] + grantee := accounts[1] + + // execute operation + op := simulation.SimulateMsgGrant(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.authzKeeper) + operationMsg, futureOperations, err := op(r, suite.app.BaseApp, ctx, accounts, "") + suite.Require().NoError(err) + + var msg authz.MsgGrant + err = proto.Unmarshal(operationMsg.Msg, &msg) + suite.Require().NoError(err) + suite.Require().True(operationMsg.OK) + suite.Require().Equal(granter.Address.String(), msg.Granter) + suite.Require().Equal(grantee.Address.String(), msg.Grantee) + suite.Require().Len(futureOperations, 0) +} + +func (suite *SimTestSuite) TestSimulateRevoke() { + // setup 3 accounts + s := rand.NewSource(2) + r := rand.New(s) + accounts := suite.getTestingAccounts(r, 3) + initAmt := sdk.TokensFromConsensusPower(200000, sdk.DefaultPowerReduction) + initCoins := sdk.NewCoins(sdk.NewCoin("stake", initAmt)) + + granter := accounts[0] + grantee := accounts[1] + a := banktypes.NewSendAuthorization(initCoins, nil, suite.accountKeeper.AddressCodec()) + expire := time.Now().Add(30 * time.Hour) + + err := suite.authzKeeper.SaveGrant(suite.ctx, grantee.Address, granter.Address, a, &expire) + suite.Require().NoError(err) + + // execute operation + op := simulation.SimulateMsgRevoke(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.authzKeeper) + operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") + suite.Require().NoError(err) + + var msg authz.MsgRevoke + err = proto.Unmarshal(operationMsg.Msg, &msg) + suite.Require().NoError(err) + suite.Require().True(operationMsg.OK) + suite.Require().Equal(granter.Address.String(), msg.Granter) + suite.Require().Equal(grantee.Address.String(), msg.Grantee) + suite.Require().Equal(banktypes.SendAuthorization{}.MsgTypeURL(), msg.MsgTypeUrl) + suite.Require().Len(futureOperations, 0) +} + +func (suite *SimTestSuite) TestSimulateExec() { + // setup 3 accounts + s := rand.NewSource(1) + r := rand.New(s) + accounts := suite.getTestingAccounts(r, 3) + initAmt := sdk.TokensFromConsensusPower(200000, sdk.DefaultPowerReduction) + initCoins := sdk.NewCoins(sdk.NewCoin("stake", initAmt)) + + granter := accounts[0] + grantee := accounts[1] + a := banktypes.NewSendAuthorization(initCoins, nil, suite.accountKeeper.AddressCodec()) + expire := suite.ctx.HeaderInfo().Time.Add(1 * time.Hour) + + err := suite.authzKeeper.SaveGrant(suite.ctx, grantee.Address, granter.Address, a, &expire) + suite.Require().NoError(err) + + // execute operation + op := simulation.SimulateMsgExec(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.authzKeeper, suite.codec) + operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") + suite.Require().NoError(err) + + var msg authz.MsgExec + err = proto.Unmarshal(operationMsg.Msg, &msg) + suite.Require().NoError(err) + suite.Require().True(operationMsg.OK) + suite.Require().Equal(grantee.Address.String(), msg.Grantee) + suite.Require().Len(futureOperations, 0) +} + +func TestSimTestSuite(t *testing.T) { + suite.Run(t, new(SimTestSuite)) +} diff --git a/tests/systemtests/go.mod b/tests/systemtests/go.mod index 7ff21661a355e..e7c9ac0f2c4ed 100644 --- a/tests/systemtests/go.mod +++ b/tests/systemtests/go.mod @@ -36,7 +36,7 @@ require ( cosmossdk.io/api v0.7.5 // indirect cosmossdk.io/collections v0.4.0 // indirect cosmossdk.io/core v0.11.0 // indirect - cosmossdk.io/depinject v1.0.0-alpha.4 // indirect + cosmossdk.io/depinject v1.0.0 // indirect cosmossdk.io/errors v1.0.1 // indirect cosmossdk.io/log v1.3.1 // indirect cosmossdk.io/store v1.1.0 // indirect diff --git a/tests/systemtests/go.sum b/tests/systemtests/go.sum index bed8c0c8f9c82..a0aa43940f9e7 100644 --- a/tests/systemtests/go.sum +++ b/tests/systemtests/go.sum @@ -6,8 +6,8 @@ cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= cosmossdk.io/core v0.11.0 h1:vtIafqUi+1ZNAE/oxLOQQ7Oek2n4S48SWLG8h/+wdbo= cosmossdk.io/core v0.11.0/go.mod h1:LaTtayWBSoacF5xNzoF8tmLhehqlA9z1SWiPuNC6X1w= -cosmossdk.io/depinject v1.0.0-alpha.4 h1:PLNp8ZYAMPTUKyG9IK2hsbciDWqna2z1Wsl98okJopc= -cosmossdk.io/depinject v1.0.0-alpha.4/go.mod h1:HeDk7IkR5ckZ3lMGs/o91AVUc7E596vMaOmslGFM3yU= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/log v1.3.1 h1:UZx8nWIkfbbNEWusZqzAx3ZGvu54TZacWib3EzUYmGI= diff --git a/testutil/context.go b/testutil/context.go index 366d93bd38ee9..105638ab191df 100644 --- a/testutil/context.go +++ b/testutil/context.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/assert" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/store" "cosmossdk.io/store/metrics" storetypes "cosmossdk.io/store/types" @@ -19,14 +19,14 @@ import ( // DefaultContext creates a sdk.Context with a fresh MemDB that can be used in tests. func DefaultContext(key, tkey storetypes.StoreKey) sdk.Context { db := dbm.NewMemDB() - cms := store.NewCommitMultiStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) + cms := store.NewCommitMultiStore(db, coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) cms.MountStoreWithDB(key, storetypes.StoreTypeIAVL, db) cms.MountStoreWithDB(tkey, storetypes.StoreTypeTransient, db) err := cms.LoadLatestVersion() if err != nil { panic(err) } - ctx := sdk.NewContext(cms, false, log.NewNopLogger()) + ctx := sdk.NewContext(cms, false, coretesting.NewNopLogger()) return ctx } @@ -39,7 +39,7 @@ func DefaultContextWithKeys( memKeys map[string]*storetypes.MemoryStoreKey, ) sdk.Context { db := dbm.NewMemDB() - cms := store.NewCommitMultiStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) + cms := store.NewCommitMultiStore(db, coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) for _, key := range keys { cms.MountStoreWithDB(key, storetypes.StoreTypeIAVL, db) @@ -58,7 +58,7 @@ func DefaultContextWithKeys( panic(err) } - return sdk.NewContext(cms, false, log.NewNopLogger()) + return sdk.NewContext(cms, false, coretesting.NewNopLogger()) } type TestContext struct { @@ -70,13 +70,13 @@ type TestContext struct { func DefaultContextWithDB(tb testing.TB, key, tkey storetypes.StoreKey) TestContext { tb.Helper() db := dbm.NewMemDB() - cms := store.NewCommitMultiStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) + cms := store.NewCommitMultiStore(db, coretesting.NewNopLogger(), metrics.NewNoOpMetrics()) cms.MountStoreWithDB(key, storetypes.StoreTypeIAVL, db) cms.MountStoreWithDB(tkey, storetypes.StoreTypeTransient, db) err := cms.LoadLatestVersion() assert.NoError(tb, err) - ctx := sdk.NewContext(cms, false, log.NewNopLogger()).WithHeaderInfo(header.Info{Time: time.Now()}) + ctx := sdk.NewContext(cms, false, coretesting.NewNopLogger()).WithHeaderInfo(header.Info{Time: time.Now()}) return TestContext{ctx, db, cms} } diff --git a/testutil/integration/router.go b/testutil/integration/router.go index 0e4724779425d..952d371df1912 100644 --- a/testutil/integration/router.go +++ b/testutil/integration/router.go @@ -64,10 +64,10 @@ func NewIntegrationApp( bApp := baseapp.NewBaseApp(appName, logger, db, txConfig.TxDecoder(), baseapp.SetChainID(appName)) bApp.MountKVStores(keys) - bApp.SetInitChainer(func(ctx sdk.Context, _ *cmtabcitypes.InitChainRequest) (*cmtabcitypes.InitChainResponse, error) { + bApp.SetInitChainer(func(_ sdk.Context, _ *cmtabcitypes.InitChainRequest) (*cmtabcitypes.InitChainResponse, error) { for _, mod := range modules { if m, ok := mod.(module.HasGenesis); ok { - if err := m.InitGenesis(ctx, m.DefaultGenesis()); err != nil { + if err := m.InitGenesis(sdkCtx, m.DefaultGenesis()); err != nil { return nil, err } } diff --git a/testutil/key.go b/testutil/key.go index 8f4c052aeb3b4..3525bd4ba8e35 100644 --- a/testutil/key.go +++ b/testutil/key.go @@ -1,7 +1,7 @@ package testutil import ( - "fmt" + "errors" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -47,12 +47,12 @@ func GenerateSaveCoinKey( // ensure no overwrite if !overwrite && exists { - return sdk.AccAddress{}, "", fmt.Errorf("key already exists, overwrite is disabled") + return sdk.AccAddress{}, "", errors.New("key already exists, overwrite is disabled") } if exists { if err := keybase.Delete(keyName); err != nil { - return sdk.AccAddress{}, "", fmt.Errorf("failed to overwrite key") + return sdk.AccAddress{}, "", errors.New("failed to overwrite key") } } diff --git a/testutil/mock/types_mock_appmodule.go b/testutil/mock/types_mock_appmodule.go index 3c9c7908d020f..b0b94179ae991 100644 --- a/testutil/mock/types_mock_appmodule.go +++ b/testutil/mock/types_mock_appmodule.go @@ -10,6 +10,7 @@ import ( reflect "reflect" appmodule "cosmossdk.io/core/appmodule" + appmodule0 "cosmossdk.io/core/appmodule/v2" types "github.com/cosmos/cosmos-sdk/types" module "github.com/cosmos/cosmos-sdk/types/module" gomock "github.com/golang/mock/gomock" @@ -253,33 +254,33 @@ func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) EndBlock(arg0 interfac } // ExportGenesis mocks base method. -func (m *MockAppModuleWithAllExtensionsABCI) ExportGenesis(arg0 context.Context) (json.RawMessage, error) { +func (m *MockAppModuleWithAllExtensionsABCI) ExportGenesis(ctx context.Context) (json.RawMessage, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ExportGenesis", arg0) + ret := m.ctrl.Call(m, "ExportGenesis", ctx) ret0, _ := ret[0].(json.RawMessage) ret1, _ := ret[1].(error) return ret0, ret1 } // ExportGenesis indicates an expected call of ExportGenesis. -func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) ExportGenesis(arg0 interface{}) *gomock.Call { +func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) ExportGenesis(ctx interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExportGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).ExportGenesis), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExportGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).ExportGenesis), ctx) } // InitGenesis mocks base method. -func (m *MockAppModuleWithAllExtensionsABCI) InitGenesis(arg0 context.Context, arg1 json.RawMessage) ([]module.ValidatorUpdate, error) { +func (m *MockAppModuleWithAllExtensionsABCI) InitGenesis(ctx context.Context, data json.RawMessage) ([]appmodule0.ValidatorUpdate, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "InitGenesis", arg0, arg1) - ret0, _ := ret[0].([]module.ValidatorUpdate) + ret := m.ctrl.Call(m, "InitGenesis", ctx, data) + ret0, _ := ret[0].([]appmodule0.ValidatorUpdate) ret1, _ := ret[1].(error) return ret0, ret1 } // InitGenesis indicates an expected call of InitGenesis. -func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) InitGenesis(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) InitGenesis(ctx, data interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).InitGenesis), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).InitGenesis), ctx, data) } // IsAppModule mocks base method. @@ -345,17 +346,17 @@ func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) RegisterServices(arg0 } // ValidateGenesis mocks base method. -func (m *MockAppModuleWithAllExtensionsABCI) ValidateGenesis(arg0 json.RawMessage) error { +func (m *MockAppModuleWithAllExtensionsABCI) ValidateGenesis(data json.RawMessage) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ValidateGenesis", arg0) + ret := m.ctrl.Call(m, "ValidateGenesis", data) ret0, _ := ret[0].(error) return ret0 } // ValidateGenesis indicates an expected call of ValidateGenesis. -func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) ValidateGenesis(arg0 interface{}) *gomock.Call { +func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) ValidateGenesis(data interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).ValidateGenesis), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).ValidateGenesis), data) } // MockCoreAppModule is a mock of CoreAppModule interface. diff --git a/testutil/mock/types_module_module.go b/testutil/mock/types_module_module.go index e3327ca7b30d7..6e8832ec9cfc5 100644 --- a/testutil/mock/types_module_module.go +++ b/testutil/mock/types_module_module.go @@ -6,7 +6,6 @@ package mock import ( context "context" - json "encoding/json" reflect "reflect" legacy "cosmossdk.io/core/legacy" @@ -40,20 +39,6 @@ func (m *MockAppModuleBasic) EXPECT() *MockAppModuleBasicMockRecorder { return m.recorder } -// Name mocks base method. -func (m *MockAppModuleBasic) Name() string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Name") - ret0, _ := ret[0].(string) - return ret0 -} - -// Name indicates an expected call of Name. -func (mr *MockAppModuleBasicMockRecorder) Name() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockAppModuleBasic)(nil).Name)) -} - // RegisterGRPCGatewayRoutes mocks base method. func (m *MockAppModuleBasic) RegisterGRPCGatewayRoutes(arg0 client.Context, arg1 *runtime.ServeMux) { m.ctrl.T.Helper() @@ -139,108 +124,6 @@ func (mr *MockAppModuleMockRecorder) Name() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockAppModule)(nil).Name)) } -// MockHasName is a mock of HasName interface. -type MockHasName struct { - ctrl *gomock.Controller - recorder *MockHasNameMockRecorder -} - -// MockHasNameMockRecorder is the mock recorder for MockHasName. -type MockHasNameMockRecorder struct { - mock *MockHasName -} - -// NewMockHasName creates a new mock instance. -func NewMockHasName(ctrl *gomock.Controller) *MockHasName { - mock := &MockHasName{ctrl: ctrl} - mock.recorder = &MockHasNameMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHasName) EXPECT() *MockHasNameMockRecorder { - return m.recorder -} - -// Name mocks base method. -func (m *MockHasName) Name() string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Name") - ret0, _ := ret[0].(string) - return ret0 -} - -// Name indicates an expected call of Name. -func (mr *MockHasNameMockRecorder) Name() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockHasName)(nil).Name)) -} - -// MockHasGenesisBasics is a mock of HasGenesisBasics interface. -type MockHasGenesisBasics struct { - ctrl *gomock.Controller - recorder *MockHasGenesisBasicsMockRecorder -} - -// MockHasGenesisBasicsMockRecorder is the mock recorder for MockHasGenesisBasics. -type MockHasGenesisBasicsMockRecorder struct { - mock *MockHasGenesisBasics -} - -// NewMockHasGenesisBasics creates a new mock instance. -func NewMockHasGenesisBasics(ctrl *gomock.Controller) *MockHasGenesisBasics { - mock := &MockHasGenesisBasics{ctrl: ctrl} - mock.recorder = &MockHasGenesisBasicsMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHasGenesisBasics) EXPECT() *MockHasGenesisBasicsMockRecorder { - return m.recorder -} - -// DefaultGenesis mocks base method. -func (m *MockHasGenesisBasics) DefaultGenesis() json.RawMessage { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DefaultGenesis") - ret0, _ := ret[0].(json.RawMessage) - return ret0 -} - -// DefaultGenesis indicates an expected call of DefaultGenesis. -func (mr *MockHasGenesisBasicsMockRecorder) DefaultGenesis() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultGenesis", reflect.TypeOf((*MockHasGenesisBasics)(nil).DefaultGenesis)) -} - -// Name mocks base method. -func (m *MockHasGenesisBasics) Name() string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Name") - ret0, _ := ret[0].(string) - return ret0 -} - -// Name indicates an expected call of Name. -func (mr *MockHasGenesisBasicsMockRecorder) Name() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockHasGenesisBasics)(nil).Name)) -} - -// ValidateGenesis mocks base method. -func (m *MockHasGenesisBasics) ValidateGenesis(arg0 json.RawMessage) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ValidateGenesis", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// ValidateGenesis indicates an expected call of ValidateGenesis. -func (mr *MockHasGenesisBasicsMockRecorder) ValidateGenesis(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockHasGenesisBasics)(nil).ValidateGenesis), arg0) -} - // MockHasAminoCodec is a mock of HasAminoCodec interface. type MockHasAminoCodec struct { ctrl *gomock.Controller @@ -311,101 +194,6 @@ func (mr *MockHasGRPCGatewayMockRecorder) RegisterGRPCGatewayRoutes(arg0, arg1 i return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterGRPCGatewayRoutes", reflect.TypeOf((*MockHasGRPCGateway)(nil).RegisterGRPCGatewayRoutes), arg0, arg1) } -// MockHasABCIGenesis is a mock of HasABCIGenesis interface. -type MockHasABCIGenesis struct { - ctrl *gomock.Controller - recorder *MockHasABCIGenesisMockRecorder -} - -// MockHasABCIGenesisMockRecorder is the mock recorder for MockHasABCIGenesis. -type MockHasABCIGenesisMockRecorder struct { - mock *MockHasABCIGenesis -} - -// NewMockHasABCIGenesis creates a new mock instance. -func NewMockHasABCIGenesis(ctrl *gomock.Controller) *MockHasABCIGenesis { - mock := &MockHasABCIGenesis{ctrl: ctrl} - mock.recorder = &MockHasABCIGenesisMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHasABCIGenesis) EXPECT() *MockHasABCIGenesisMockRecorder { - return m.recorder -} - -// DefaultGenesis mocks base method. -func (m *MockHasABCIGenesis) DefaultGenesis() json.RawMessage { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DefaultGenesis") - ret0, _ := ret[0].(json.RawMessage) - return ret0 -} - -// DefaultGenesis indicates an expected call of DefaultGenesis. -func (mr *MockHasABCIGenesisMockRecorder) DefaultGenesis() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).DefaultGenesis)) -} - -// ExportGenesis mocks base method. -func (m *MockHasABCIGenesis) ExportGenesis(arg0 context.Context) (json.RawMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ExportGenesis", arg0) - ret0, _ := ret[0].(json.RawMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ExportGenesis indicates an expected call of ExportGenesis. -func (mr *MockHasABCIGenesisMockRecorder) ExportGenesis(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExportGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).ExportGenesis), arg0) -} - -// InitGenesis mocks base method. -func (m *MockHasABCIGenesis) InitGenesis(arg0 context.Context, arg1 json.RawMessage) ([]module.ValidatorUpdate, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "InitGenesis", arg0, arg1) - ret0, _ := ret[0].([]module.ValidatorUpdate) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// InitGenesis indicates an expected call of InitGenesis. -func (mr *MockHasABCIGenesisMockRecorder) InitGenesis(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).InitGenesis), arg0, arg1) -} - -// Name mocks base method. -func (m *MockHasABCIGenesis) Name() string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Name") - ret0, _ := ret[0].(string) - return ret0 -} - -// Name indicates an expected call of Name. -func (mr *MockHasABCIGenesisMockRecorder) Name() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockHasABCIGenesis)(nil).Name)) -} - -// ValidateGenesis mocks base method. -func (m *MockHasABCIGenesis) ValidateGenesis(arg0 json.RawMessage) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ValidateGenesis", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// ValidateGenesis indicates an expected call of ValidateGenesis. -func (mr *MockHasABCIGenesisMockRecorder) ValidateGenesis(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).ValidateGenesis), arg0) -} - // MockHasInvariants is a mock of HasInvariants interface. type MockHasInvariants struct { ctrl *gomock.Controller diff --git a/testutil/network/network.go b/testutil/network/network.go index 0d0e942a9fb2e..fb2bbd54ae690 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -164,6 +164,10 @@ func DefaultConfig(factory TestFixtureFactory) Config { } func DefaultConfigWithAppConfig(appConfig depinject.Config) (Config, error) { + return DefaultConfigWithAppConfigWithQueryGasLimit(appConfig, 0) +} + +func DefaultConfigWithAppConfigWithQueryGasLimit(appConfig depinject.Config, queryGasLimit uint64) (Config, error) { var ( appBuilder *runtime.AppBuilder txConfig client.TxConfig @@ -221,6 +225,7 @@ func DefaultConfigWithAppConfig(appConfig depinject.Config) (Config, error) { baseapp.SetPruning(pruningtypes.NewPruningOptionsFromString(val.GetAppConfig().Pruning)), baseapp.SetMinGasPrices(val.GetAppConfig().MinGasPrices), baseapp.SetChainID(cfg.ChainID), + baseapp.SetQueryGasLimit(queryGasLimit), ) testdata.RegisterQueryServer(app.GRPCQueryRouter(), testdata.QueryImpl{}) diff --git a/testutil/testdata/animal.go b/testutil/testdata/animal.go index 7d5afa6152804..327b8851e1eaf 100644 --- a/testutil/testdata/animal.go +++ b/testutil/testdata/animal.go @@ -4,8 +4,7 @@ import ( "fmt" "github.com/cosmos/gogoproto/proto" - - "github.com/cosmos/cosmos-sdk/codec/types" + gogoprotoany "github.com/cosmos/gogoproto/types/any" ) type Animal interface { @@ -32,9 +31,9 @@ func (d Dog) Greet() string { return fmt.Sprintf("Roof, my name is %s", d.Name) } -var _ types.UnpackInterfacesMessage = HasAnimal{} +var _ gogoprotoany.UnpackInterfacesMessage = HasAnimal{} -func (m HasAnimal) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (m HasAnimal) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var animal Animal return unpacker.UnpackAny(m.Animal, &animal) } @@ -59,9 +58,9 @@ func (m HasHasAnimal) TheHasAnimal() HasAnimalI { return m.HasAnimal.GetCachedValue().(HasAnimalI) } -var _ types.UnpackInterfacesMessage = HasHasAnimal{} +var _ gogoprotoany.UnpackInterfacesMessage = HasHasAnimal{} -func (m HasHasAnimal) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (m HasHasAnimal) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var animal HasAnimalI return unpacker.UnpackAny(m.HasAnimal, &animal) } @@ -76,9 +75,9 @@ func (m HasHasHasAnimal) TheHasHasAnimal() HasHasAnimalI { return m.HasHasAnimal.GetCachedValue().(HasHasAnimalI) } -var _ types.UnpackInterfacesMessage = HasHasHasAnimal{} +var _ gogoprotoany.UnpackInterfacesMessage = HasHasHasAnimal{} -func (m HasHasHasAnimal) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (m HasHasHasAnimal) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var animal HasHasAnimalI return unpacker.UnpackAny(m.HasHasAnimal, &animal) } diff --git a/testutil/testdata/grpc_query.go b/testutil/testdata/grpc_query.go index 1078f60b8b814..d4ca6c73d8883 100644 --- a/testutil/testdata/grpc_query.go +++ b/testutil/testdata/grpc_query.go @@ -5,6 +5,7 @@ import ( "fmt" "testing" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "github.com/cosmos/gogoproto/types/any/test" "github.com/cosmos/gogoproto/proto" @@ -49,16 +50,16 @@ func (e QueryImpl) SayHello(_ context.Context, request *SayHelloRequest) (*SayHe return &SayHelloResponse{Greeting: greeting}, nil } -var _ types.UnpackInterfacesMessage = &TestAnyRequest{} +var _ gogoprotoany.UnpackInterfacesMessage = &TestAnyRequest{} -func (m *TestAnyRequest) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (m *TestAnyRequest) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var animal test.Animal return unpacker.UnpackAny(m.AnyAnimal, &animal) } -var _ types.UnpackInterfacesMessage = &TestAnyResponse{} +var _ gogoprotoany.UnpackInterfacesMessage = &TestAnyResponse{} -func (m *TestAnyResponse) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (m *TestAnyResponse) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { return m.HasAnimal.UnpackInterfaces(unpacker) } diff --git a/testutil/x/counter/autocli.go b/testutil/x/counter/autocli.go new file mode 100644 index 0000000000000..2067df6b81d5e --- /dev/null +++ b/testutil/x/counter/autocli.go @@ -0,0 +1,34 @@ +package counter + +import ( + autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" + counterv1 "cosmossdk.io/api/cosmos/counter/v1" +) + +// AutoCLIOptions implements the autocli.HasAutoCLIConfig interface. +func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions { + return &autocliv1.ModuleOptions{ + Query: &autocliv1.ServiceCommandDescriptor{ + Service: counterv1.Query_ServiceDesc.ServiceName, + RpcCommandOptions: []*autocliv1.RpcCommandOptions{ + { + RpcMethod: "GetCount", + Use: "count", + Short: "Query the current counter value", + }, + }, + }, + Tx: &autocliv1.ServiceCommandDescriptor{ + Service: counterv1.Msg_ServiceDesc.ServiceName, + RpcCommandOptions: []*autocliv1.RpcCommandOptions{ + { + RpcMethod: "IncreaseCount", + Use: "increase-count [count]", + Alias: []string{"increase-counter", "increase", "inc", "bump"}, + Short: "Increase the counter by the specified amount", + PositionalArgs: []*autocliv1.PositionalArgDescriptor{{ProtoField: "count"}}, + }, + }, + }, + } +} diff --git a/testutil/x/counter/depinject.go b/testutil/x/counter/depinject.go index fcb8df1e3c2d6..b529d7f54297a 100644 --- a/testutil/x/counter/depinject.go +++ b/testutil/x/counter/depinject.go @@ -1,12 +1,12 @@ package counter import ( - modulev1 "cosmossdk.io/api/cosmos/counter/module/v1" "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" "cosmossdk.io/depinject/appconfig" "github.com/cosmos/cosmos-sdk/testutil/x/counter/keeper" + "github.com/cosmos/cosmos-sdk/testutil/x/counter/types" ) var _ depinject.OnePerModuleType = AppModule{} @@ -16,7 +16,7 @@ func (am AppModule) IsOnePerModuleType() {} func init() { appconfig.RegisterModule( - &modulev1.Module{}, + &types.Module{}, appconfig.Provide(ProvideModule), ) } @@ -24,7 +24,7 @@ func init() { type ModuleInputs struct { depinject.In - Config *modulev1.Module + Config *types.Module Environment appmodule.Environment } diff --git a/testutil/x/counter/module.go b/testutil/x/counter/module.go index f5a4a0a68341c..39f18857d8a57 100644 --- a/testutil/x/counter/module.go +++ b/testutil/x/counter/module.go @@ -8,12 +8,9 @@ import ( "github.com/cosmos/cosmos-sdk/testutil/x/counter/keeper" "github.com/cosmos/cosmos-sdk/testutil/x/counter/types" - "github.com/cosmos/cosmos-sdk/types/module" ) var ( - _ module.HasName = AppModule{} - _ appmodule.AppModule = AppModule{} _ appmodule.HasRegisterInterfaces = AppModule{} ) @@ -43,7 +40,8 @@ func NewAppModule(keeper keeper.Keeper) AppModule { // ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return 1 } -// Name returns the consensus module's name. +// Name returns the module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } // RegisterInterfaces registers interfaces and implementations of the bank module. diff --git a/testutil/x/counter/proto/cosmos/counter/module/v1/module.proto b/testutil/x/counter/proto/cosmos/counter/module/v1/module.proto index f4be1da83c4a2..7c0fa4055d11c 100644 --- a/testutil/x/counter/proto/cosmos/counter/module/v1/module.proto +++ b/testutil/x/counter/proto/cosmos/counter/module/v1/module.proto @@ -4,6 +4,8 @@ package cosmos.counter.module.v1; import "cosmos/app/v1alpha1/module.proto"; +option go_package = "github.com/cosmos/cosmos-sdk/testutil/x/counter/types"; + // Module is the config object of the counter module. message Module { option (cosmos.app.v1alpha1.module) = { diff --git a/testutil/x/counter/types/module.pb.go b/testutil/x/counter/types/module.pb.go new file mode 100644 index 0000000000000..37b734e319bca --- /dev/null +++ b/testutil/x/counter/types/module.pb.go @@ -0,0 +1,322 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/counter/module/v1/module.proto + +package types + +import ( + _ "cosmossdk.io/depinject/appconfig/v1alpha1" + fmt "fmt" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// Module is the config object of the counter module. +type Module struct { + // authority defines the custom module authority. If not set, defaults to the governance module. + Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` +} + +func (m *Module) Reset() { *m = Module{} } +func (m *Module) String() string { return proto.CompactTextString(m) } +func (*Module) ProtoMessage() {} +func (*Module) Descriptor() ([]byte, []int) { + return fileDescriptor_917f5b05718fd5a3, []int{0} +} +func (m *Module) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Module) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Module.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Module) XXX_Merge(src proto.Message) { + xxx_messageInfo_Module.Merge(m, src) +} +func (m *Module) XXX_Size() int { + return m.Size() +} +func (m *Module) XXX_DiscardUnknown() { + xxx_messageInfo_Module.DiscardUnknown(m) +} + +var xxx_messageInfo_Module proto.InternalMessageInfo + +func (m *Module) GetAuthority() string { + if m != nil { + return m.Authority + } + return "" +} + +func init() { + proto.RegisterType((*Module)(nil), "cosmos.counter.module.v1.Module") +} + +func init() { + proto.RegisterFile("cosmos/counter/module/v1/module.proto", fileDescriptor_917f5b05718fd5a3) +} + +var fileDescriptor_917f5b05718fd5a3 = []byte{ + // 201 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4d, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0x4f, 0xce, 0x2f, 0xcd, 0x2b, 0x49, 0x2d, 0xd2, 0xcf, 0xcd, 0x4f, 0x29, 0xcd, + 0x49, 0xd5, 0x2f, 0x33, 0x84, 0xb2, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x24, 0x20, 0xca, + 0xf4, 0xa0, 0xca, 0xf4, 0xa0, 0x92, 0x65, 0x86, 0x52, 0x0a, 0x50, 0x03, 0x12, 0x0b, 0x0a, 0xf4, + 0xcb, 0x0c, 0x13, 0x73, 0x0a, 0x32, 0x12, 0x51, 0xf5, 0x2a, 0xc5, 0x73, 0xb1, 0xf9, 0x82, 0xf9, + 0x42, 0x32, 0x5c, 0x9c, 0x89, 0xa5, 0x25, 0x19, 0xf9, 0x45, 0x99, 0x25, 0x95, 0x12, 0x8c, 0x0a, + 0x8c, 0x1a, 0x9c, 0x41, 0x08, 0x01, 0x2b, 0xf3, 0x5d, 0x07, 0xa6, 0xdd, 0x62, 0x34, 0xe4, 0xd2, + 0x4f, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x87, 0xbb, 0x0e, 0x44, 0xe9, + 0x16, 0xa7, 0x64, 0xeb, 0x97, 0xa4, 0x16, 0x97, 0x94, 0x96, 0x64, 0xe6, 0xe8, 0x57, 0xc0, 0xdc, + 0xec, 0xe4, 0x7f, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, + 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0xa6, 0x24, 0x1a, + 0xa5, 0x5f, 0x52, 0x59, 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0x76, 0xb8, 0x31, 0x20, 0x00, 0x00, 0xff, + 0xff, 0x76, 0xab, 0xc7, 0x18, 0x1d, 0x01, 0x00, 0x00, +} + +func (m *Module) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Module) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Module) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Authority) > 0 { + i -= len(m.Authority) + copy(dAtA[i:], m.Authority) + i = encodeVarintModule(dAtA, i, uint64(len(m.Authority))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintModule(dAtA []byte, offset int, v uint64) int { + offset -= sovModule(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Module) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Authority) + if l > 0 { + n += 1 + l + sovModule(uint64(l)) + } + return n +} + +func sovModule(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozModule(x uint64) (n int) { + return sovModule(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Module) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Module: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Module: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthModule + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Authority = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipModule(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowModule + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowModule + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowModule + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthModule + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupModule + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthModule + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthModule = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowModule = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupModule = fmt.Errorf("proto: unexpected end of group") +) diff --git a/tools/confix/cmd/migrate_test.go b/tools/confix/cmd/migrate_test.go index a0e9c545f9f80..733f784b73ce5 100644 --- a/tools/confix/cmd/migrate_test.go +++ b/tools/confix/cmd/migrate_test.go @@ -33,7 +33,7 @@ func TestMigrateCmd(t *testing.T) { assert.Assert(t, strings.Contains(out.String(), "add app-db-backend key")) // this should work - out, err = clitestutil.ExecTestCLICmd(clientCtx, cmd.MigrateCommand(), []string{"v0.51", filepath.Join(clientCtx.HomeDir, "config", "client.toml"), "--client", "--verbose"}) + out, err = clitestutil.ExecTestCLICmd(clientCtx, cmd.MigrateCommand(), []string{"v0.52", filepath.Join(clientCtx.HomeDir, "config", "client.toml"), "--client", "--verbose"}) assert.NilError(t, err) assert.Assert(t, strings.Contains(out.String(), "add keyring-default-keyname key")) } diff --git a/tools/confix/data/v0.51-app.toml b/tools/confix/data/v0.52-app.toml similarity index 99% rename from tools/confix/data/v0.51-app.toml rename to tools/confix/data/v0.52-app.toml index c2c061a857f47..d6e3cf95ab01e 100644 --- a/tools/confix/data/v0.51-app.toml +++ b/tools/confix/data/v0.52-app.toml @@ -66,7 +66,7 @@ index-events = [] # IavlCacheSize set the size of the iavl tree cache (in number of nodes). iavl-cache-size = 781250 -# IAVLDisableFastNode enables or disables the fast node feature of IAVL. +# IAVLDisableFastNode enables or disables the fast node feature of IAVL. # Default is false. iavl-disable-fastnode = false @@ -126,7 +126,7 @@ datadog-hostname = "" [api] # Enable defines if the API server should be enabled. -enable = true +enable = false # Swagger defines if swagger documentation should automatically be registered. swagger = false @@ -217,7 +217,7 @@ stop-node-on-err = true [mempool] # Setting max-txs to 0 will allow for a unbounded amount of transactions in the mempool. -# Setting max_txs to negative 1 (-1) will disable transactions from being inserted into the mempool. +# Setting max_txs to negative 1 (-1) will disable transactions from being inserted into the mempool (no-op mempool). # Setting max_txs to a positive number (> 0) will limit the number of transactions in the mempool, by the specified amount. # # Note, this configuration only applies to SDK built-in app-side mempool diff --git a/tools/confix/data/v0.51-client.toml b/tools/confix/data/v0.52-client.toml similarity index 74% rename from tools/confix/data/v0.51-client.toml rename to tools/confix/data/v0.52-client.toml index a284426a8d04a..785ecf499cde9 100644 --- a/tools/confix/data/v0.51-client.toml +++ b/tools/confix/data/v0.52-client.toml @@ -17,3 +17,11 @@ output = "text" node = "tcp://localhost:26657" # Transaction broadcasting mode (sync|async) broadcast-mode = "sync" + +# gRPC server endpoint to which the client will connect. +# It can be overwritten by the --grpc-addr flag in each command. +grpc-address = "" + +# Allow the gRPC client to connect over insecure channels. +# It can be overwritten by the --grpc-insecure flag in each command. +grpc-insecure = false diff --git a/tools/confix/go.mod b/tools/confix/go.mod index fc186fed6c149..d7c74d44b60bd 100644 --- a/tools/confix/go.mod +++ b/tools/confix/go.mod @@ -17,7 +17,7 @@ require ( cosmossdk.io/api v0.7.5 // indirect cosmossdk.io/collections v0.4.0 // indirect cosmossdk.io/core v0.11.0 // indirect - cosmossdk.io/depinject v1.0.0-alpha.4 // indirect + cosmossdk.io/depinject v1.0.0 // indirect cosmossdk.io/errors v1.0.1 // indirect cosmossdk.io/log v1.3.1 // indirect cosmossdk.io/math v1.3.0 // indirect diff --git a/tools/confix/go.sum b/tools/confix/go.sum index 5737494ce2ceb..bdb33226732d1 100644 --- a/tools/confix/go.sum +++ b/tools/confix/go.sum @@ -6,8 +6,8 @@ cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= cosmossdk.io/core v0.11.0 h1:vtIafqUi+1ZNAE/oxLOQQ7Oek2n4S48SWLG8h/+wdbo= cosmossdk.io/core v0.11.0/go.mod h1:LaTtayWBSoacF5xNzoF8tmLhehqlA9z1SWiPuNC6X1w= -cosmossdk.io/depinject v1.0.0-alpha.4 h1:PLNp8ZYAMPTUKyG9IK2hsbciDWqna2z1Wsl98okJopc= -cosmossdk.io/depinject v1.0.0-alpha.4/go.mod h1:HeDk7IkR5ckZ3lMGs/o91AVUc7E596vMaOmslGFM3yU= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/log v1.3.1 h1:UZx8nWIkfbbNEWusZqzAx3ZGvu54TZacWib3EzUYmGI= diff --git a/tools/confix/migrations.go b/tools/confix/migrations.go index a164858bb610c..2eece120fe5a1 100644 --- a/tools/confix/migrations.go +++ b/tools/confix/migrations.go @@ -26,7 +26,7 @@ var Migrations = MigrationMap{ "v0.46": PlanBuilder, "v0.47": PlanBuilder, "v0.50": PlanBuilder, - "v0.51": PlanBuilder, + "v0.52": PlanBuilder, // "v0.xx.x": PlanBuilder, // add specific migration in case of configuration changes in minor versions } diff --git a/tools/cosmovisor/go.mod b/tools/cosmovisor/go.mod index 76129739f97c7..21a5fea45e52f 100644 --- a/tools/cosmovisor/go.mod +++ b/tools/cosmovisor/go.mod @@ -6,7 +6,7 @@ toolchain go1.22.4 require ( cosmossdk.io/log v1.3.1 - cosmossdk.io/x/upgrade v0.1.3 + cosmossdk.io/x/upgrade v0.1.4 github.com/otiai10/copy v1.14.0 github.com/pelletier/go-toml/v2 v2.2.2 github.com/spf13/cobra v1.8.1 @@ -24,7 +24,7 @@ require ( cosmossdk.io/api v0.7.5 // indirect cosmossdk.io/collections v0.4.0 // indirect cosmossdk.io/core v0.11.0 // indirect - cosmossdk.io/depinject v1.0.0-alpha.4 // indirect + cosmossdk.io/depinject v1.0.0 // indirect cosmossdk.io/errors v1.0.1 // indirect cosmossdk.io/math v1.3.0 // indirect cosmossdk.io/store v1.1.0 // indirect @@ -47,7 +47,7 @@ require ( github.com/cockroachdb/pebble v1.1.0 // indirect github.com/cockroachdb/redact v1.1.5 // indirect github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect - github.com/cometbft/cometbft v0.38.8 // indirect + github.com/cometbft/cometbft v0.38.9 // indirect github.com/cometbft/cometbft-db v0.12.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect diff --git a/tools/cosmovisor/go.sum b/tools/cosmovisor/go.sum index 8bc8cb3f59e25..a36072f7b7b14 100644 --- a/tools/cosmovisor/go.sum +++ b/tools/cosmovisor/go.sum @@ -194,8 +194,8 @@ cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= cosmossdk.io/core v0.11.0 h1:vtIafqUi+1ZNAE/oxLOQQ7Oek2n4S48SWLG8h/+wdbo= cosmossdk.io/core v0.11.0/go.mod h1:LaTtayWBSoacF5xNzoF8tmLhehqlA9z1SWiPuNC6X1w= -cosmossdk.io/depinject v1.0.0-alpha.4 h1:PLNp8ZYAMPTUKyG9IK2hsbciDWqna2z1Wsl98okJopc= -cosmossdk.io/depinject v1.0.0-alpha.4/go.mod h1:HeDk7IkR5ckZ3lMGs/o91AVUc7E596vMaOmslGFM3yU= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/log v1.3.1 h1:UZx8nWIkfbbNEWusZqzAx3ZGvu54TZacWib3EzUYmGI= @@ -206,8 +206,8 @@ cosmossdk.io/store v1.1.0 h1:LnKwgYMc9BInn9PhpTFEQVbL9UK475G2H911CGGnWHk= cosmossdk.io/store v1.1.0/go.mod h1:oZfW/4Fc/zYqu3JmQcQdUJ3fqu5vnYTn3LZFFy8P8ng= cosmossdk.io/x/tx v0.13.3 h1:Ha4mNaHmxBc6RMun9aKuqul8yHiL78EKJQ8g23Zf73g= cosmossdk.io/x/tx v0.13.3/go.mod h1:I8xaHv0rhUdIvIdptKIqzYy27+n2+zBVaxO6fscFhys= -cosmossdk.io/x/upgrade v0.1.3 h1:q4XpXc6zp0dX6x74uBtfN6+J7ikaQev5Bla6Q0ADLK8= -cosmossdk.io/x/upgrade v0.1.3/go.mod h1:jOdQhnaY5B8CDUoUbed23/Lre0Dk+r6BMQE40iKlVVQ= +cosmossdk.io/x/upgrade v0.1.4 h1:/BWJim24QHoXde8Bc64/2BSEB6W4eTydq0X/2f8+g38= +cosmossdk.io/x/upgrade v0.1.4/go.mod h1:9v0Aj+fs97O+Ztw+tG3/tp5JSlrmT7IcFhAebQHmOPo= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= @@ -312,8 +312,8 @@ github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZ github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= -github.com/cometbft/cometbft v0.38.8 h1:XyJ9Cu3xqap6xtNxiemrO8roXZ+KS2Zlu7qQ0w1trvU= -github.com/cometbft/cometbft v0.38.8/go.mod h1:xOoGZrtUT+A5izWfHSJgl0gYZUE7lu7Z2XIS1vWG/QQ= +github.com/cometbft/cometbft v0.38.9 h1:cJBJBG0mPKz+sqelCi/hlfZjadZQGdDNnu6YQ1ZsUHQ= +github.com/cometbft/cometbft v0.38.9/go.mod h1:xOoGZrtUT+A5izWfHSJgl0gYZUE7lu7Z2XIS1vWG/QQ= github.com/cometbft/cometbft-db v0.12.0 h1:v77/z0VyfSU7k682IzZeZPFZrQAKiQwkqGN0QzAjMi0= github.com/cometbft/cometbft-db v0.12.0/go.mod h1:aX2NbCrjNVd2ZajYxt1BsiFf/Z+TQ2MN0VxdicheYuw= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= diff --git a/tools/cosmovisor/process.go b/tools/cosmovisor/process.go index 8eb4eae6a0737..dfda812efe49d 100644 --- a/tools/cosmovisor/process.go +++ b/tools/cosmovisor/process.go @@ -176,7 +176,7 @@ func (l Launcher) doBackup() error { } if uInfo.Name == "" { - return fmt.Errorf("upgrade-info.json is empty") + return errors.New("upgrade-info.json is empty") } // a destination directory, Format YYYY-MM-DD @@ -241,7 +241,7 @@ func (l Launcher) doCustomPreUpgrade() error { if oldMode != newMode { if err := os.Chmod(preupgradeFile, newMode); err != nil { l.logger.Info("COSMOVISOR_CUSTOM_PREUPGRADE could not add execute permission") - return fmt.Errorf("COSMOVISOR_CUSTOM_PREUPGRADE could not add execute permission") + return errors.New("COSMOVISOR_CUSTOM_PREUPGRADE could not add execute permission") } } diff --git a/tools/hubl/go.mod b/tools/hubl/go.mod index d16db41828612..ac8fa90b1dc1b 100644 --- a/tools/hubl/go.mod +++ b/tools/hubl/go.mod @@ -7,7 +7,7 @@ require ( cosmossdk.io/client/v2 v2.0.0-beta.1.0.20240118210941-3897926e722e cosmossdk.io/core v0.11.0 cosmossdk.io/errors v1.0.1 - github.com/cosmos/cosmos-sdk v0.50.7 + github.com/cosmos/cosmos-sdk v0.50.8 github.com/manifoldco/promptui v0.9.0 github.com/pelletier/go-toml/v2 v2.2.2 github.com/spf13/cobra v1.8.1 @@ -17,7 +17,7 @@ require ( require ( cosmossdk.io/collections v0.4.0 // indirect - cosmossdk.io/depinject v1.0.0-alpha.4 // indirect + cosmossdk.io/depinject v1.0.0 // indirect cosmossdk.io/log v1.3.1 // indirect cosmossdk.io/math v1.3.0 // indirect cosmossdk.io/store v1.1.0 // indirect @@ -39,7 +39,7 @@ require ( github.com/cockroachdb/pebble v1.1.0 // indirect github.com/cockroachdb/redact v1.1.5 // indirect github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect - github.com/cometbft/cometbft v0.38.8 // indirect + github.com/cometbft/cometbft v0.38.9 // indirect github.com/cometbft/cometbft-db v0.9.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect diff --git a/tools/hubl/go.sum b/tools/hubl/go.sum index 6c20b42851496..954afa4073f51 100644 --- a/tools/hubl/go.sum +++ b/tools/hubl/go.sum @@ -8,8 +8,8 @@ cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= cosmossdk.io/core v0.11.0 h1:vtIafqUi+1ZNAE/oxLOQQ7Oek2n4S48SWLG8h/+wdbo= cosmossdk.io/core v0.11.0/go.mod h1:LaTtayWBSoacF5xNzoF8tmLhehqlA9z1SWiPuNC6X1w= -cosmossdk.io/depinject v1.0.0-alpha.4 h1:PLNp8ZYAMPTUKyG9IK2hsbciDWqna2z1Wsl98okJopc= -cosmossdk.io/depinject v1.0.0-alpha.4/go.mod h1:HeDk7IkR5ckZ3lMGs/o91AVUc7E596vMaOmslGFM3yU= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/log v1.3.1 h1:UZx8nWIkfbbNEWusZqzAx3ZGvu54TZacWib3EzUYmGI= @@ -131,8 +131,8 @@ github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZ github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= -github.com/cometbft/cometbft v0.38.8 h1:XyJ9Cu3xqap6xtNxiemrO8roXZ+KS2Zlu7qQ0w1trvU= -github.com/cometbft/cometbft v0.38.8/go.mod h1:xOoGZrtUT+A5izWfHSJgl0gYZUE7lu7Z2XIS1vWG/QQ= +github.com/cometbft/cometbft v0.38.9 h1:cJBJBG0mPKz+sqelCi/hlfZjadZQGdDNnu6YQ1ZsUHQ= +github.com/cometbft/cometbft v0.38.9/go.mod h1:xOoGZrtUT+A5izWfHSJgl0gYZUE7lu7Z2XIS1vWG/QQ= github.com/cometbft/cometbft-db v0.9.1 h1:MIhVX5ja5bXNHF8EYrThkG9F7r9kSfv8BX4LWaxWJ4M= github.com/cometbft/cometbft-db v0.9.1/go.mod h1:iliyWaoV0mRwBJoizElCwwRA9Tf7jZJOURcRZF9m60U= github.com/containerd/continuity v0.3.0 h1:nisirsYROK15TAMVukJOUyGJjz4BNQJBVsNvAXZJ/eg= @@ -149,8 +149,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/cosmos-sdk v0.50.7 h1:LsBGKxifENR/DN4E1RZaitsyL93HU44x0p8EnMHp4V4= -github.com/cosmos/cosmos-sdk v0.50.7/go.mod h1:84xDDJEHttRT7NDGwBaUOLVOMN0JNE9x7NbsYIxXs1s= +github.com/cosmos/cosmos-sdk v0.50.8 h1:2UJHssUaGHTl4/dFp8xyREKAnfiRU6VVfqtKG9n8w5g= +github.com/cosmos/cosmos-sdk v0.50.8/go.mod h1:Zb+DgHtiByNwgj71IlJBXwOq6dLhtyAq3AgqpXm/jHo= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/types/mempool/mempool_test.go b/types/mempool/mempool_test.go index 5c95b3ac0a631..8cfb1d0252f1a 100644 --- a/types/mempool/mempool_test.go +++ b/types/mempool/mempool_test.go @@ -11,7 +11,7 @@ import ( _ "cosmossdk.io/api/cosmos/counter/v1" _ "cosmossdk.io/api/cosmos/crypto/secp256k1" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/core/transaction" "cosmossdk.io/x/auth/signing" @@ -174,7 +174,7 @@ func fetchTxs(iterator mempool.Iterator, maxBytes int64) []sdk.Tx { func (s *MempoolTestSuite) TestDefaultMempool() { t := s.T() - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) accounts := simtypes.RandomAccounts(rand.New(rand.NewSource(0)), 10) txCount := 1000 var txs []testTx @@ -266,7 +266,7 @@ func TestMempoolTestSuite(t *testing.T) { } func (s *MempoolTestSuite) TestSampleTxs() { - ctxt := sdk.NewContext(nil, false, log.NewNopLogger()) + ctxt := sdk.NewContext(nil, false, coretesting.NewNopLogger()) t := s.T() s.resetMempool() mp := s.mempool diff --git a/types/mempool/priority_nonce_test.go b/types/mempool/priority_nonce_test.go index b3e0df4fe62b8..3357c2684fdb1 100644 --- a/types/mempool/priority_nonce_test.go +++ b/types/mempool/priority_nonce_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/x/auth/signing" sdk "github.com/cosmos/cosmos-sdk/types" @@ -83,7 +83,7 @@ func (a signerExtractionAdapter) GetSigners(tx sdk.Tx) ([]mempool.SignerData, er func (s *MempoolTestSuite) TestPriorityNonceTxOrderWithAdapter() { t := s.T() - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) accounts := simtypes.RandomAccounts(rand.New(rand.NewSource(0)), 5) sa := accounts[0].Address sb := accounts[1].Address @@ -142,7 +142,7 @@ func (s *MempoolTestSuite) TestPriorityNonceTxOrderWithAdapter() { func (s *MempoolTestSuite) TestPriorityNonceTxOrder() { t := s.T() - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) accounts := simtypes.RandomAccounts(rand.New(rand.NewSource(0)), 5) sa := accounts[0].Address sb := accounts[1].Address @@ -341,7 +341,7 @@ func (s *MempoolTestSuite) TestPriorityNonceTxOrder() { func (s *MempoolTestSuite) TestIterator() { t := s.T() - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) accounts := simtypes.RandomAccounts(rand.New(rand.NewSource(0)), 2) sa := accounts[0].Address sb := accounts[1].Address @@ -396,7 +396,7 @@ func (s *MempoolTestSuite) TestIterator() { } func (s *MempoolTestSuite) TestPriorityTies() { - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) accounts := simtypes.RandomAccounts(rand.New(rand.NewSource(0)), 3) sa := accounts[0].Address sb := accounts[1].Address @@ -520,7 +520,7 @@ func (s *MempoolTestSuite) TestRandomGeneratedTxs() { ) t := s.T() - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) seed := time.Now().UnixNano() t.Logf("running with seed: %d", seed) @@ -556,7 +556,7 @@ func (s *MempoolTestSuite) TestRandomWalkTxs() { s.mempool = mempool.DefaultPriorityMempool() t := s.T() - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) seed := time.Now().UnixNano() // interesting failing seeds: @@ -729,7 +729,7 @@ func TestTxOrderN(t *testing.T) { func TestPriorityNonceMempool_NextSenderTx(t *testing.T) { accounts := simtypes.RandomAccounts(rand.New(rand.NewSource(0)), 2) - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) accA := accounts[0].Address accB := accounts[1].Address @@ -759,7 +759,7 @@ func TestPriorityNonceMempool_NextSenderTx(t *testing.T) { func TestNextSenderTx_TxLimit(t *testing.T) { accounts := simtypes.RandomAccounts(rand.New(rand.NewSource(0)), 2) - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) sa := accounts[0].Address sb := accounts[1].Address @@ -835,7 +835,7 @@ func TestNextSenderTx_TxLimit(t *testing.T) { func TestNextSenderTx_TxReplacement(t *testing.T) { accounts := simtypes.RandomAccounts(rand.New(rand.NewSource(0)), 1) - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) sa := accounts[0].Address txs := []testTx{ diff --git a/types/mempool/sender_nonce_property_test.go b/types/mempool/sender_nonce_property_test.go index 55baf64ee82d9..b4eb36f758159 100644 --- a/types/mempool/sender_nonce_property_test.go +++ b/types/mempool/sender_nonce_property_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" "pgregory.net/rapid" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/x/auth/signing" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -33,7 +33,7 @@ func AddressGenerator(t *rapid.T) *rapid.Generator[sdk.AccAddress] { } func testMempoolProperties(t *rapid.T) { - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) mp := mempool.NewSenderNonceMempool() genMultipleAddress := rapid.SliceOfNDistinct(AddressGenerator(t), 1, 10, func(acc sdk.AccAddress) string { diff --git a/types/mempool/sender_nonce_test.go b/types/mempool/sender_nonce_test.go index f1d347ca70171..8b56a8a0299ce 100644 --- a/types/mempool/sender_nonce_test.go +++ b/types/mempool/sender_nonce_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/mempool" @@ -16,7 +16,7 @@ import ( func (s *MempoolTestSuite) TestTxOrder() { t := s.T() - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) accounts := simtypes.RandomAccounts(rand.New(rand.NewSource(0)), 5) sa := accounts[0].Address sb := accounts[1].Address @@ -140,7 +140,7 @@ func (s *MempoolTestSuite) TestTxOrder() { func (s *MempoolTestSuite) TestMaxTx() { t := s.T() - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) accounts := simtypes.RandomAccounts(rand.New(rand.NewSource(0)), 1) mp := mempool.NewSenderNonceMempool(mempool.SenderNonceMaxTxOpt(1)) @@ -170,7 +170,7 @@ func (s *MempoolTestSuite) TestMaxTx() { func (s *MempoolTestSuite) TestTxNotFoundOnSender() { t := s.T() - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) accounts := simtypes.RandomAccounts(rand.New(rand.NewSource(0)), 1) mp := mempool.NewSenderNonceMempool(mempool.SenderNonceMaxTxOpt(5000)) diff --git a/types/module/core_module.go b/types/module/core_module.go index 97466ffeb165a..34274d35f2c41 100644 --- a/types/module/core_module.go +++ b/types/module/core_module.go @@ -20,7 +20,6 @@ import ( var ( _ appmodule.AppModule = coreAppModuleAdaptor{} - _ HasName = coreAppModuleAdaptor{} _ HasAminoCodec = coreAppModuleAdaptor{} _ HasGRPCGateway = coreAppModuleAdaptor{} _ appmodule.HasRegisterInterfaces = coreAppModuleAdaptor{} @@ -154,7 +153,8 @@ func (c coreAppModuleAdaptor) InitGenesis(ctx context.Context, bz json.RawMessag return nil, nil } -// Name implements HasName +// Name implements legacy Name() interface +// Kept for legacy reasons func (c coreAppModuleAdaptor) Name() string { return c.name } diff --git a/types/module/mock_appmodule_test.go b/types/module/mock_appmodule_test.go index 1be48c8822645..5d5782b599ec9 100644 --- a/types/module/mock_appmodule_test.go +++ b/types/module/mock_appmodule_test.go @@ -18,18 +18,16 @@ type AppModuleWithAllExtensions interface { appmodulev2.HasConsensusVersion appmodulev2.HasGenesis module.HasABCIEndBlock - module.HasName } // mocks to be used in module tests. type AppModuleWithAllExtensionsABCI interface { module.AppModule module.HasServices - module.HasABCIGenesis + appmodulev2.HasABCIGenesis module.HasInvariants appmodulev2.HasConsensusVersion module.HasABCIEndBlock - module.HasName } // CoreAppModule is solely here for the purpose of generating diff --git a/types/module/module.go b/types/module/module.go index 1d6df7df4e301..7ea5db116bc5a 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -46,34 +46,21 @@ import ( // Deprecated: use the embed extension interfaces instead, when needed. type AppModuleBasic interface { - HasName HasGRPCGateway HasAminoCodec } -// AppModule is the form for an application module. Most of -// its functionality has been moved to extension interfaces. +// AppModule is the form for an application module. +// Most of its functionality has been moved to extension interfaces. // Deprecated: use appmodule.AppModule with a combination of extension interfaces instead. type AppModule interface { - HasName + Name() string appmodulev2.AppModule } -// HasName allows the module to provide its own name for legacy purposes. -// Newer apps should specify the name for their modules using a map -// using NewManagerFromMap. -type HasName interface { - Name() string -} - // HasGenesisBasics is the legacy interface for stateless genesis methods. -type HasGenesisBasics interface { - HasName - - DefaultGenesis() json.RawMessage - ValidateGenesis(json.RawMessage) error -} +type HasGenesisBasics = appmodule.HasGenesisBasics // HasAminoCodec is the interface for modules that have amino codec registration. // Deprecated: modules should not need to register their own amino codecs. @@ -91,11 +78,7 @@ type HasGRPCGateway interface { type HasGenesis = appmodulev2.HasGenesis // HasABCIGenesis is the extension interface for stateful genesis methods which returns validator updates. -type HasABCIGenesis interface { - HasGenesisBasics - InitGenesis(context.Context, json.RawMessage) ([]ValidatorUpdate, error) - ExportGenesis(context.Context) (json.RawMessage, error) -} +type HasABCIGenesis = appmodulev2.HasABCIGenesis // HasInvariants is the interface for registering invariants. type HasInvariants interface { @@ -139,6 +122,7 @@ type Manager struct { } // NewManager creates a new Manager object. +// Deprecated: Use NewManagerFromMap instead. func NewManager(modules ...AppModule) *Manager { moduleMap := make(map[string]appmodule.AppModule) modulesStr := make([]string, 0, len(modules)) @@ -168,7 +152,6 @@ func NewManager(modules ...AppModule) *Manager { } // NewManagerFromMap creates a new Manager object from a map of module names to module implementations. -// This method should be used for apps and modules which have migrated to the cosmossdk.io/core.appmodule.AppModule API. func NewManagerFromMap(moduleMap map[string]appmodule.AppModule) *Manager { simpleModuleMap := make(map[string]appmodule.AppModule) modulesStr := make([]string, 0, len(simpleModuleMap)) @@ -321,7 +304,7 @@ func (m *Manager) DefaultGenesis() map[string]json.RawMessage { genesisData := make(map[string]json.RawMessage) for name, b := range m.Modules { if mod, ok := b.(HasGenesisBasics); ok { - genesisData[mod.Name()] = mod.DefaultGenesis() + genesisData[name] = mod.DefaultGenesis() } else if mod, ok := b.(appmodule.HasGenesis); ok { genesisData[name] = mod.DefaultGenesis() } else { @@ -336,7 +319,7 @@ func (m *Manager) DefaultGenesis() map[string]json.RawMessage { func (m *Manager) ValidateGenesis(genesisData map[string]json.RawMessage) error { for name, b := range m.Modules { if mod, ok := b.(HasGenesisBasics); ok { - if err := mod.ValidateGenesis(genesisData[mod.Name()]); err != nil { + if err := mod.ValidateGenesis(genesisData[name]); err != nil { return err } } else if mod, ok := b.(appmodule.HasGenesis); ok { diff --git a/types/module/module_test.go b/types/module/module_test.go index ccd22bf024628..7d1ecfee0bad7 100644 --- a/types/module/module_test.go +++ b/types/module/module_test.go @@ -14,7 +14,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" authtypes "cosmossdk.io/x/auth/types" "github.com/cosmos/cosmos-sdk/codec" @@ -171,7 +171,7 @@ func TestManager_InitGenesis(t *testing.T) { require.NotNil(t, mm) require.Equal(t, 3, len(mm.Modules)) - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) genesisData := map[string]json.RawMessage{"module1": json.RawMessage(`{"key": "value"}`)} // this should error since the validator set is empty even after init genesis @@ -220,7 +220,7 @@ func TestManager_ExportGenesis(t *testing.T) { require.NotNil(t, mm) require.Equal(t, 3, len(mm.Modules)) - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) mockAppModule1.EXPECT().ExportGenesis(gomock.Eq(ctx)).AnyTimes().Return(json.RawMessage(`{"key1": "value1"}`), nil) mockAppModule2.EXPECT().ExportGenesis(gomock.Eq(ctx)).AnyTimes().Return(json.RawMessage(`{"key2": "value2"}`), nil) @@ -304,7 +304,7 @@ func TestCoreAPIManager_InitGenesis(t *testing.T) { require.NotNil(t, mm) require.Equal(t, 1, len(mm.Modules)) - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) genesisData := map[string]json.RawMessage{"module1": json.RawMessage(`{"key": "value"}`)} // this should panic since the validator set is empty even after init genesis @@ -326,7 +326,7 @@ func TestCoreAPIManager_ExportGenesis(t *testing.T) { require.NotNil(t, mm) require.Equal(t, 2, len(mm.Modules)) - ctx := sdk.NewContext(nil, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, false, coretesting.NewNopLogger()) want := map[string]json.RawMessage{ "module1": json.RawMessage(`{ "someField": "someKey" diff --git a/types/result.go b/types/result.go index 148847eecf2b2..b4724151e9da7 100644 --- a/types/result.go +++ b/types/result.go @@ -7,6 +7,7 @@ import ( cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" coretypes "github.com/cometbft/cometbft/rpc/core/types" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -159,13 +160,13 @@ func ParseABCILogs(logs string) (res ABCIMessageLogs, err error) { return res, err } -var _, _ codectypes.UnpackInterfacesMessage = SearchTxsResult{}, TxResponse{} +var _, _ gogoprotoany.UnpackInterfacesMessage = SearchTxsResult{}, TxResponse{} // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces // // types.UnpackInterfaces needs to be called for each nested Tx because // there are generally interfaces to unpack in Tx's -func (s SearchTxsResult) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (s SearchTxsResult) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, tx := range s.Txs { err := codectypes.UnpackInterfaces(tx, unpacker) if err != nil { @@ -176,7 +177,7 @@ func (s SearchTxsResult) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (r TxResponse) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (r TxResponse) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { if r.Tx != nil { var tx HasMsgs return unpacker.UnpackAny(r.Tx, &tx) diff --git a/types/tx/direct_aux.go b/types/tx/direct_aux.go index 52c9fc214a8ed..d685a837ad294 100644 --- a/types/tx/direct_aux.go +++ b/types/tx/direct_aux.go @@ -1,7 +1,8 @@ package tx import ( - codectypes "github.com/cosmos/cosmos-sdk/codec/types" + gogoprotoany "github.com/cosmos/gogoproto/types/any" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/tx/signing" @@ -21,7 +22,7 @@ func (s *SignDocDirectAux) ValidateBasic() error { } // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method -func (s *SignDocDirectAux) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (s *SignDocDirectAux) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { return unpacker.UnpackAny(s.PublicKey, new(cryptotypes.PubKey)) } @@ -60,6 +61,6 @@ func (a *AuxSignerData) GetSignatureV2() (signing.SignatureV2, error) { } // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method -func (a *AuxSignerData) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (a *AuxSignerData) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { return a.GetSignDoc().UnpackInterfaces(unpacker) } diff --git a/types/tx/ext.go b/types/tx/ext.go index fb2e1ed448bce..e51be337d5b1a 100644 --- a/types/tx/ext.go +++ b/types/tx/ext.go @@ -1,6 +1,8 @@ package tx import ( + gogoprotoany "github.com/cosmos/gogoproto/types/any" + "github.com/cosmos/cosmos-sdk/codec/types" ) @@ -8,7 +10,7 @@ import ( type TxExtensionOptionI interface{} // unpackTxExtensionOptionsI unpacks Any's to TxExtensionOptionI's. -func unpackTxExtensionOptionsI(unpacker types.AnyUnpacker, anys []*types.Any) error { +func unpackTxExtensionOptionsI(unpacker gogoprotoany.AnyUnpacker, anys []*types.Any) error { for _, any := range anys { var opt TxExtensionOptionI err := unpacker.UnpackAny(any, &opt) diff --git a/types/tx/msgs.go b/types/tx/msgs.go index 2f2f9a80f9129..036f9a2414c8c 100644 --- a/types/tx/msgs.go +++ b/types/tx/msgs.go @@ -3,6 +3,8 @@ package tx import ( "fmt" + gogoprotoany "github.com/cosmos/gogoproto/types/any" + "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -53,7 +55,7 @@ func GetMsgs(anys []*types.Any, name string) ([]sdk.Msg, error) { } // UnpackInterfaces unpacks Any's to sdk.Msg's. -func UnpackInterfaces(unpacker types.AnyUnpacker, anys []*types.Any) error { +func UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker, anys []*types.Any) error { for _, any := range anys { var msg sdk.Msg err := unpacker.UnpackAny(any, &msg) diff --git a/types/tx/signing/signature.go b/types/tx/signing/signature.go index a9549bab9a125..a27ea27b86eb5 100644 --- a/types/tx/signing/signature.go +++ b/types/tx/signing/signature.go @@ -3,7 +3,8 @@ package signing import ( "fmt" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" + gogoprotoany "github.com/cosmos/gogoproto/types/any" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" ) @@ -86,10 +87,10 @@ func SignatureDataFromProto(descData *SignatureDescriptor_Data) SignatureData { } } -var _, _ codectypes.UnpackInterfacesMessage = &SignatureDescriptors{}, &SignatureDescriptor{} +var _, _ gogoprotoany.UnpackInterfacesMessage = &SignatureDescriptors{}, &SignatureDescriptor{} // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method -func (sds *SignatureDescriptors) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (sds *SignatureDescriptors) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, sig := range sds.Signatures { err := sig.UnpackInterfaces(unpacker) if err != nil { @@ -101,6 +102,6 @@ func (sds *SignatureDescriptors) UnpackInterfaces(unpacker codectypes.AnyUnpacke } // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method -func (sd *SignatureDescriptor) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (sd *SignatureDescriptor) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { return unpacker.UnpackAny(sd.PublicKey, new(cryptotypes.PubKey)) } diff --git a/types/tx/types.go b/types/tx/types.go index c5a2e91ef37e4..b8a61946538c8 100644 --- a/types/tx/types.go +++ b/types/tx/types.go @@ -1,15 +1,15 @@ package tx import ( - "fmt" + "errors" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "google.golang.org/protobuf/reflect/protoreflect" "cosmossdk.io/core/registry" errorsmod "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -20,7 +20,7 @@ const MaxGasWanted = uint64((1 << 63) - 1) // Interface implementation checks. var ( - _, _, _, _ codectypes.UnpackInterfacesMessage = &Tx{}, &TxBody{}, &AuthInfo{}, &SignerInfo{} + _, _, _, _ gogoprotoany.UnpackInterfacesMessage = &Tx{}, &TxBody{}, &AuthInfo{}, &SignerInfo{} ) // GetMsgs implements the GetMsgs method on sdk.Tx. @@ -40,22 +40,22 @@ func (t *Tx) GetMsgs() []sdk.Msg { // ValidateBasic implements the ValidateBasic method on sdk.Tx. func (t *Tx) ValidateBasic() error { if t == nil { - return fmt.Errorf("bad Tx") + return errors.New("bad Tx") } body := t.Body if body == nil { - return fmt.Errorf("missing TxBody") + return errors.New("missing TxBody") } authInfo := t.AuthInfo if authInfo == nil { - return fmt.Errorf("missing AuthInfo") + return errors.New("missing AuthInfo") } fee := authInfo.Fee if fee == nil { - return fmt.Errorf("missing fee") + return errors.New("missing fee") } if fee.GasLimit > MaxGasWanted { @@ -177,7 +177,7 @@ func (t *Tx) FeeGranter(cdc codec.Codec) []byte { } // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method -func (t *Tx) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (t *Tx) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { if t.Body != nil { if err := t.Body.UnpackInterfaces(unpacker); err != nil { return err @@ -192,7 +192,7 @@ func (t *Tx) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { } // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method -func (m *TxBody) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (m *TxBody) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { if err := UnpackInterfaces(unpacker, m.Messages); err != nil { return err } @@ -209,7 +209,7 @@ func (m *TxBody) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { } // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method -func (m *AuthInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (m *AuthInfo) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, signerInfo := range m.SignerInfos { err := signerInfo.UnpackInterfaces(unpacker) if err != nil { @@ -220,7 +220,7 @@ func (m *AuthInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { } // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method -func (m *SignerInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (m *SignerInfo) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { return unpacker.UnpackAny(m.PublicKey, new(cryptotypes.PubKey)) } diff --git a/x/accounts/defaults/lockup/continuous_locking_account_test.go b/x/accounts/defaults/lockup/continuous_locking_account_test.go index dd208b26be742..cbccbb224ec54 100644 --- a/x/accounts/defaults/lockup/continuous_locking_account_test.go +++ b/x/accounts/defaults/lockup/continuous_locking_account_test.go @@ -19,7 +19,7 @@ import ( func setupContinousAccount(t *testing.T, ctx context.Context, ss store.KVStoreService) *ContinuousLockingAccount { t.Helper() deps := makeMockDependencies(ss) - owner := "owner" + owner := "owner" //nolint:goconst // adding constants for this would impede readability acc, err := NewContinuousLockingAccount(deps) require.NoError(t, err) diff --git a/x/accounts/defaults/lockup/go.mod b/x/accounts/defaults/lockup/go.mod index 5cfac25f21f33..daa4b58f5325b 100644 --- a/x/accounts/defaults/lockup/go.mod +++ b/x/accounts/defaults/lockup/go.mod @@ -18,10 +18,10 @@ require cosmossdk.io/x/consensus v0.0.0-00010101000000-000000000000 // indirect require ( buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2 // indirect cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 // indirect - cosmossdk.io/depinject v1.0.0-alpha.4 // indirect + cosmossdk.io/depinject v1.0.0 // indirect cosmossdk.io/schema v0.1.1 // indirect github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/dgraph-io/badger/v4 v4.2.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/google/flatbuffers v2.0.8+incompatible // indirect @@ -176,7 +176,6 @@ replace ( cosmossdk.io/collections => ../../../../collections // TODO tag new collections ASAP cosmossdk.io/core => ../../../../core cosmossdk.io/core/testing => ../../../../core/testing - cosmossdk.io/depinject => ../../../../depinject cosmossdk.io/log => ../../../../log cosmossdk.io/x/accounts => ../../. cosmossdk.io/x/auth => ../../../auth diff --git a/x/accounts/defaults/lockup/go.sum b/x/accounts/defaults/lockup/go.sum index 63401cd6bf728..7c088816d9a37 100644 --- a/x/accounts/defaults/lockup/go.sum +++ b/x/accounts/defaults/lockup/go.sum @@ -4,6 +4,8 @@ buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88e buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2/go.mod h1:HqcXMSa5qnNuakaMUo+hWhF51mKbcrZxGl9Vp5EeJXc= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -92,8 +94,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/accounts/defaults/lockup/lockup.go b/x/accounts/defaults/lockup/lockup.go index 08f22b304963f..060e656aa273b 100644 --- a/x/accounts/defaults/lockup/lockup.go +++ b/x/accounts/defaults/lockup/lockup.go @@ -3,7 +3,7 @@ package lockup import ( "bytes" "context" - "fmt" + "errors" "time" "github.com/cosmos/gogoproto/proto" @@ -349,7 +349,7 @@ func (bva *BaseLockup) WithdrawUnlockedCoins( } } if len(amount) == 0 { - return nil, fmt.Errorf("no tokens available for withdrawing") + return nil, errors.New("no tokens available for withdrawing") } msgSend := &banktypes.MsgSend{ @@ -379,7 +379,7 @@ func (bva *BaseLockup) checkSender(ctx context.Context, sender string) error { return sdkerrors.ErrInvalidAddress.Wrapf("invalid sender address: %s", err.Error()) } if !bytes.Equal(owner, senderBytes) { - return fmt.Errorf("sender is not the owner of this vesting account") + return errors.New("sender is not the owner of this vesting account") } return nil diff --git a/x/accounts/defaults/lockup/utils_test.go b/x/accounts/defaults/lockup/utils_test.go index 56cd3316edeae..a7032ceedeb3c 100644 --- a/x/accounts/defaults/lockup/utils_test.go +++ b/x/accounts/defaults/lockup/utils_test.go @@ -2,7 +2,7 @@ package lockup import ( "context" - "fmt" + "errors" "testing" gogoproto "github.com/cosmos/gogoproto/proto" @@ -87,7 +87,7 @@ func newMockContext(t *testing.T) (context.Context, store.KVStoreService) { case "/cosmos.bank.v1beta1.MsgSend": return &banktypes.MsgSendResponse{}, nil default: - return nil, fmt.Errorf("unrecognized request type") + return nil, errors.New("unrecognized request type") } }, func(ctx context.Context, req, resp ProtoMsg) error { _, ok := req.(*banktypes.QueryBalanceRequest) diff --git a/x/accounts/defaults/multisig/go.mod b/x/accounts/defaults/multisig/go.mod index 0157842d862c4..4a7254390618e 100644 --- a/x/accounts/defaults/multisig/go.mod +++ b/x/accounts/defaults/multisig/go.mod @@ -20,7 +20,7 @@ require ( buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2 // indirect cosmossdk.io/api v0.7.5 // indirect cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 // indirect - cosmossdk.io/depinject v1.0.0-alpha.4 // indirect + cosmossdk.io/depinject v1.0.0 // indirect cosmossdk.io/errors v1.0.1 // indirect cosmossdk.io/log v1.3.1 // indirect cosmossdk.io/schema v0.1.1 // indirect @@ -49,7 +49,7 @@ require ( github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -177,7 +177,6 @@ replace ( cosmossdk.io/collections => ../../../../collections // TODO tag new collections ASAP cosmossdk.io/core => ../../../../core cosmossdk.io/core/testing => ../../../../core/testing - cosmossdk.io/depinject => ../../../../depinject cosmossdk.io/log => ../../../../log cosmossdk.io/x/accounts => ../../. cosmossdk.io/x/auth => ../../../auth @@ -188,4 +187,5 @@ replace ( cosmossdk.io/x/protocolpool => ../../../protocolpool cosmossdk.io/x/slashing => ../../../slashing cosmossdk.io/x/staking => ../../../staking + cosmossdk.io/x/tx => ../../../tx ) diff --git a/x/accounts/defaults/multisig/go.sum b/x/accounts/defaults/multisig/go.sum index 1924d5aae7d2c..1516cc35ec121 100644 --- a/x/accounts/defaults/multisig/go.sum +++ b/x/accounts/defaults/multisig/go.sum @@ -4,6 +4,8 @@ buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88e buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2/go.mod h1:HqcXMSa5qnNuakaMUo+hWhF51mKbcrZxGl9Vp5EeJXc= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -12,8 +14,6 @@ cosmossdk.io/schema v0.1.1 h1:I0M6pgI7R10nq+/HCQfbO6BsGBZA8sQy+duR1Y3aKcA= cosmossdk.io/schema v0.1.1/go.mod h1:RDAhxIeNB4bYqAlF4NBJwRrgtnciMcyyg0DOKnhNZQQ= cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc h1:R9O9d75e0qZYUsVV0zzi+D7cNLnX2JrUOQNoIPaF0Bg= cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc/go.mod h1:amTTatOUV3u1PsKmNb87z6/galCxrRbz9kRdJkL0DyU= -cosmossdk.io/x/tx v0.13.3 h1:Ha4mNaHmxBc6RMun9aKuqul8yHiL78EKJQ8g23Zf73g= -cosmossdk.io/x/tx v0.13.3/go.mod h1:I8xaHv0rhUdIvIdptKIqzYy27+n2+zBVaxO6fscFhys= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs= @@ -102,8 +102,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/accounts/go.mod b/x/accounts/go.mod index a1365529b5e98..30ddbf7df8f7e 100644 --- a/x/accounts/go.mod +++ b/x/accounts/go.mod @@ -7,7 +7,7 @@ require ( cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/x/accounts/defaults/multisig v0.0.0-00010101000000-000000000000 cosmossdk.io/x/bank v0.0.0-20240226161501-23359a0b6d91 cosmossdk.io/x/tx v0.13.3 @@ -59,7 +59,7 @@ require ( github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect github.com/cosmos/cosmos-proto v1.0.0-beta.5 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -184,7 +184,6 @@ replace ( cosmossdk.io/collections => ../../collections cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts/defaults/multisig => ./defaults/multisig cosmossdk.io/x/auth => ../auth diff --git a/x/accounts/go.sum b/x/accounts/go.sum index ee55768fa5639..35a069913927f 100644 --- a/x/accounts/go.sum +++ b/x/accounts/go.sum @@ -4,6 +4,8 @@ buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88e buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2/go.mod h1:HqcXMSa5qnNuakaMUo+hWhF51mKbcrZxGl9Vp5EeJXc= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -102,8 +104,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/accounts/keeper.go b/x/accounts/keeper.go index 98b27e5eab03c..91ef5d707c821 100644 --- a/x/accounts/keeper.go +++ b/x/accounts/keeper.go @@ -331,10 +331,10 @@ func (k Keeper) makeAccountContext(ctx context.Context, accountNumber uint64, ac nil, nil, func(ctx context.Context, sender []byte, msg, msgResp implementation.ProtoMsg) error { - return fmt.Errorf("cannot execute in query context") + return errors.New("cannot execute in query context") }, func(ctx context.Context, sender []byte, msg implementation.ProtoMsg) (implementation.ProtoMsg, error) { - return nil, fmt.Errorf("cannot execute in query context") + return nil, errors.New("cannot execute in query context") }, k.queryModule, ) diff --git a/x/accounts/module.go b/x/accounts/module.go index 2a85cf47180a0..8a848141923e9 100644 --- a/x/accounts/module.go +++ b/x/accounts/module.go @@ -14,7 +14,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types/address" - "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/msgservice" ) @@ -29,8 +28,6 @@ const ( var ModuleAccountAddress = address.Module(ModuleName) var ( - _ module.HasName = AppModule{} - _ appmodule.AppModule = AppModule{} _ appmodule.HasServices = AppModule{} _ appmodule.HasGenesis = AppModule{} @@ -48,6 +45,8 @@ type AppModule struct { func (m AppModule) IsAppModule() {} +// Name returns the module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return ModuleName } func (m AppModule) RegisterInterfaces(registrar registry.InterfaceRegistrar) { diff --git a/x/accounts/utils_test.go b/x/accounts/utils_test.go index 8b6e171607c09..5e1cf037883e2 100644 --- a/x/accounts/utils_test.go +++ b/x/accounts/utils_test.go @@ -12,7 +12,6 @@ import ( basev1beta1 "cosmossdk.io/api/cosmos/base/v1beta1" "cosmossdk.io/core/address" "cosmossdk.io/core/event" - "cosmossdk.io/core/log" coretesting "cosmossdk.io/core/testing" coretransaction "cosmossdk.io/core/transaction" "cosmossdk.io/x/accounts/internal/implementation" @@ -74,7 +73,7 @@ func newKeeper(t *testing.T, accounts ...implementation.AccountCreatorFunc) (Kee ctx := coretesting.Context() ss := coretesting.KVStoreService(ctx, "test") - env := runtime.NewEnvironment(ss, log.NewNopLogger(), runtime.EnvWithQueryRouterService(queryRouter), runtime.EnvWithMsgRouterService(msgRouter)) + env := runtime.NewEnvironment(ss, coretesting.NewNopLogger(), runtime.EnvWithQueryRouterService(queryRouter), runtime.EnvWithMsgRouterService(msgRouter)) env.EventService = eventService{} m, err := NewKeeper(codec.NewProtoCodec(ir), env, addressCodec, ir, accounts...) require.NoError(t, err) diff --git a/x/auth/CHANGELOG.md b/x/auth/CHANGELOG.md index 6fe1a31ff4c57..594f89f872672 100644 --- a/x/auth/CHANGELOG.md +++ b/x/auth/CHANGELOG.md @@ -63,4 +63,5 @@ Ref: https://keepachangelog.com/en/1.0.0/ * [#19148](https://github.com/cosmos/cosmos-sdk/pull/19148) Checks the consumed gas for verifying a multisig pubKey signature during simulation. * [#19239](https://github.com/cosmos/cosmos-sdk/pull/19239) Sets from flag in multi-sign command to avoid no key name provided error. * [#19099](https://github.com/cosmos/cosmos-sdk/pull/19099) `verifyIsOnCurve` now checks if we are simulating to avoid malformed public key error. -* [#20323](https://github.com/cosmos/cosmos-sdk/pull/20323) Ignore undecodable txs in GetBlocksWithTxs. \ No newline at end of file +* [#20323](https://github.com/cosmos/cosmos-sdk/pull/20323) Ignore undecodable txs in GetBlocksWithTxs. +* [#20963](https://github.com/cosmos/cosmos-sdk/pull/20963) UseGrantedFees used to return error with raw addresses. Now it uses addresses in string format. \ No newline at end of file diff --git a/x/auth/ante/fee.go b/x/auth/ante/fee.go index 21b5300fd53c7..298fae30a4cc1 100644 --- a/x/auth/ante/fee.go +++ b/x/auth/ante/fee.go @@ -98,7 +98,15 @@ func (dfd DeductFeeDecorator) checkDeductFee(ctx sdk.Context, sdkTx sdk.Tx, fee } else if !bytes.Equal(feeGranterAddr, feePayer) { err := dfd.feegrantKeeper.UseGrantedFees(ctx, feeGranterAddr, feePayer, fee, sdkTx.GetMsgs()) if err != nil { - return errorsmod.Wrapf(err, "%s does not allow to pay fees for %s", feeGranter, feePayer) + granterAddr, acErr := dfd.accountKeeper.AddressCodec().BytesToString(feeGranter) + if acErr != nil { + return errorsmod.Wrapf(err, "%s, feeGranter does not allow to pay fees", acErr.Error()) + } + payerAddr, acErr := dfd.accountKeeper.AddressCodec().BytesToString(feePayer) + if acErr != nil { + return errorsmod.Wrapf(err, "%s, feeGranter does not allow to pay fees", acErr.Error()) + } + return errorsmod.Wrapf(err, "%s does not allow to pay fees for %s", granterAddr, payerAddr) } } diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index c16ec1e40b5b9..a435ba03bdfa6 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -464,7 +464,7 @@ func NewValidateSigCountDecorator(ak AccountKeeper) ValidateSigCountDecorator { } } -// AnteHandler implements an ante decorator for ValidateSigCountDecorator +// AnteHandle implements an ante decorator for ValidateSigCountDecorator func (vscd ValidateSigCountDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { if err := vscd.ValidateTx(ctx, tx); err != nil { return ctx, err @@ -623,7 +623,7 @@ func CountSubKeys(pub cryptotypes.PubKey) int { // as well as the aggregated signature. func signatureDataToBz(data signing.SignatureData) ([][]byte, error) { if data == nil { - return nil, fmt.Errorf("got empty SignatureData") + return nil, errors.New("got empty SignatureData") } switch data := data.(type) { diff --git a/x/auth/ante/testutil_test.go b/x/auth/ante/testutil_test.go index 294e17db8900e..f9ea3b397d708 100644 --- a/x/auth/ante/testutil_test.go +++ b/x/auth/ante/testutil_test.go @@ -13,7 +13,7 @@ import ( _ "cosmossdk.io/api/cosmos/bank/v1beta1" _ "cosmossdk.io/api/cosmos/crypto/secp256k1" "cosmossdk.io/core/appmodule" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/auth" "cosmossdk.io/x/auth/ante" @@ -105,9 +105,9 @@ func SetupTestSuite(t *testing.T, isCheckTx bool) *AnteTestSuite { }, nil).AnyTimes() consensustypes.RegisterQueryServer(grpcQueryRouter, suite.consensusKeeper) - suite.env = runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger(), runtime.EnvWithQueryRouterService(grpcQueryRouter), runtime.EnvWithMsgRouterService(msgRouter)) + suite.env = runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger(), runtime.EnvWithQueryRouterService(grpcQueryRouter), runtime.EnvWithMsgRouterService(msgRouter)) suite.accountKeeper = keeper.NewAccountKeeper( - runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()), suite.encCfg.Codec, types.ProtoBaseAccount, suite.acctsModKeeper, maccPerms, authcodec.NewBech32Codec("cosmos"), + runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()), suite.encCfg.Codec, types.ProtoBaseAccount, suite.acctsModKeeper, maccPerms, authcodec.NewBech32Codec("cosmos"), sdk.Bech32MainPrefix, types.NewModuleAddress("gov").String(), ) suite.accountKeeper.GetModuleAccount(suite.ctx, types.FeeCollectorName) diff --git a/x/auth/client/cli/query.go b/x/auth/client/cli/query.go index e2fd6f5eb53bc..93210ea7c7db4 100644 --- a/x/auth/client/cli/query.go +++ b/x/auth/client/cli/query.go @@ -1,6 +1,7 @@ package cli import ( + "errors" "fmt" "strings" @@ -11,7 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" querytypes "github.com/cosmos/cosmos-sdk/types/query" "github.com/cosmos/cosmos-sdk/version" ) @@ -101,7 +102,7 @@ $ %s query tx --%s=%s , switch typ { case TypeHash: if args[0] == "" { - return fmt.Errorf("argument should be a tx hash") + return errors.New("argument should be a tx hash") } // if hash is given, then query the tx by hash @@ -135,19 +136,19 @@ $ %s query tx --%s=%s , } if len(txs.Txs) == 0 { - return fmt.Errorf("found no txs matching given signatures") + return errors.New("found no txs matching given signatures") } if len(txs.Txs) > 1 { // This case means there's a bug somewhere else in the code as this // should not happen. - return errors.ErrLogic.Wrapf("found %d txs matching given signatures", len(txs.Txs)) + return sdkerrors.ErrLogic.Wrapf("found %d txs matching given signatures", len(txs.Txs)) } return clientCtx.PrintProto(txs.Txs[0]) case TypeAccSeq: if args[0] == "" { - return fmt.Errorf("`acc_seq` type takes an argument '/'") + return errors.New("`acc_seq` type takes an argument '/'") } query := fmt.Sprintf("%s.%s='%s'", sdk.EventTypeTx, sdk.AttributeKeyAccountSequence, args[0]) @@ -158,7 +159,7 @@ $ %s query tx --%s=%s , } if len(txs.Txs) == 0 { - return fmt.Errorf("found no txs matching given address and sequence combination") + return errors.New("found no txs matching given address and sequence combination") } if len(txs.Txs) > 1 { // This case means there's a bug somewhere else in the code as this @@ -183,7 +184,7 @@ $ %s query tx --%s=%s , // ParseSigArgs parses comma-separated signatures from the CLI arguments. func ParseSigArgs(args []string) ([]string, error) { if len(args) != 1 || args[0] == "" { - return nil, fmt.Errorf("argument should be comma-separated signatures") + return nil, errors.New("argument should be comma-separated signatures") } return strings.Split(args[0], ","), nil diff --git a/x/auth/client/cli/tx_multisign.go b/x/auth/client/cli/tx_multisign.go index 41ff8a25b0584..ced781fed8455 100644 --- a/x/auth/client/cli/tx_multisign.go +++ b/x/auth/client/cli/tx_multisign.go @@ -1,6 +1,7 @@ package cli import ( + "errors" "fmt" "os" "strings" @@ -137,7 +138,7 @@ func makeMultiSignCmd() func(cmd *cobra.Command, args []string) (err error) { } if txFactory.ChainID() == "" { - return fmt.Errorf("set the chain id with either the --chain-id flag or config file") + return errors.New("set the chain id with either the --chain-id flag or config file") } for _, sig := range sigs { diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 8f420e6181711..b4d062884ccbf 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -1,6 +1,7 @@ package cli import ( + "errors" "fmt" "os" @@ -257,7 +258,7 @@ func multisigSign(clientCtx client.Context, txBuilder client.TxBuilder, txFactor } if !isSigner { - return fmt.Errorf("signing key is not a part of multisig key") + return errors.New("signing key is not a part of multisig key") } if err = authclient.SignTxWithSignerAddress( @@ -449,7 +450,7 @@ func signTx(cmd *cobra.Command, clientCtx client.Context, txFactory tx.Factory, return err } if !isSigner { - return fmt.Errorf("signing key is not a part of multisig key") + return errors.New("signing key is not a part of multisig key") } err = authclient.SignTxWithSignerAddress( diff --git a/x/auth/client/cli/validate_sigs.go b/x/auth/client/cli/validate_sigs.go index 846fc8cee5816..0638f78c38a96 100644 --- a/x/auth/client/cli/validate_sigs.go +++ b/x/auth/client/cli/validate_sigs.go @@ -2,7 +2,7 @@ package cli import ( "bytes" - "fmt" + "errors" "github.com/spf13/cobra" "google.golang.org/protobuf/types/known/anypb" @@ -52,7 +52,7 @@ func makeValidateSignaturesCmd() func(cmd *cobra.Command, args []string) error { } if !printAndValidateSigs(cmd, clientCtx, txBldr.ChainID(), stdTx, clientCtx.Offline) { - return fmt.Errorf("signatures validation failed") + return errors.New("signatures validation failed") } return nil diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index 0f505ccc3c877..ce0800eaf88fe 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -3,6 +3,7 @@ package client import ( "bufio" "bytes" + "errors" "fmt" "io" "os" @@ -15,7 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/tx/signing" ) @@ -53,7 +54,7 @@ func SignTx(txFactory tx.Factory, clientCtx client.Context, name string, txBuild return err } if !isTxSigner(addr, signers) { - return fmt.Errorf("%w: %s", errors.ErrorInvalidSigner, name) + return fmt.Errorf("%w: %s", sdkerrors.ErrorInvalidSigner, name) } if !offline { txFactory, err = populateAccountFromState(txFactory, clientCtx, addr) @@ -142,7 +143,7 @@ func ReadTxsFromFile(ctx client.Context, filename string) (txs []sdk.Tx, err err // Unlike ReadTxFromFile, this function does not decode the txs. func ReadTxsFromInput(txCfg client.TxConfig, filenames ...string) (scanner *BatchScanner, err error) { if len(filenames) == 0 { - return nil, fmt.Errorf("no file name provided") + return nil, errors.New("no file name provided") } var infile io.Reader = os.Stdin diff --git a/x/auth/go.mod b/x/auth/go.mod index c6efc0f8a9d3c..a22cb0b4b0d7e 100644 --- a/x/auth/go.mod +++ b/x/auth/go.mod @@ -7,7 +7,7 @@ require ( cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/math v1.3.0 cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc @@ -59,7 +59,7 @@ require ( github.com/cometbft/cometbft-db v0.12.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -177,7 +177,6 @@ replace ( cosmossdk.io/collections => ../../collections cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/bank => ../bank diff --git a/x/auth/go.sum b/x/auth/go.sum index 0b0081734c7bb..4879cfa34550a 100644 --- a/x/auth/go.sum +++ b/x/auth/go.sum @@ -4,6 +4,8 @@ buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88e buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2/go.mod h1:HqcXMSa5qnNuakaMUo+hWhF51mKbcrZxGl9Vp5EeJXc= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -100,8 +102,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/auth/keeper/deterministic_test.go b/x/auth/keeper/deterministic_test.go index 75057368fb9d5..d20d5dff57940 100644 --- a/x/auth/keeper/deterministic_test.go +++ b/x/auth/keeper/deterministic_test.go @@ -13,7 +13,7 @@ import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/auth" authcodec "cosmossdk.io/x/auth/codec" @@ -62,7 +62,7 @@ func (suite *DeterministicTestSuite) SetupTest() { suite.Require() key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) - env := runtime.NewEnvironment(storeService, log.NewNopLogger()) + env := runtime.NewEnvironment(storeService, coretesting.NewNopLogger()) testCtx := testutil.DefaultContextWithDB(suite.T(), key, storetypes.NewTransientStoreKey("transient_test")) suite.ctx = testCtx.Ctx.WithHeaderInfo(header.Info{}) @@ -107,7 +107,7 @@ func (suite *DeterministicTestSuite) SetupTest() { suite.accountNumberLanes = 1 } -// createAndSetAccount creates a random account and sets to the keeper store. +// createAndSetAccounts creates a random account and sets to the keeper store. func (suite *DeterministicTestSuite) createAndSetAccounts(t *rapid.T, count int) []sdk.AccountI { accs := make([]sdk.AccountI, 0, count) @@ -155,7 +155,7 @@ func (suite *DeterministicTestSuite) TestGRPCQueryAccount() { } // pubkeyGenerator creates and returns a random pubkey generator using rapid. -func pubkeyGenerator(t *rapid.T) *rapid.Generator[secp256k1.PubKey] { +func pubkeyGenerator(_ *rapid.T) *rapid.Generator[secp256k1.PubKey] { return rapid.Custom(func(t *rapid.T) secp256k1.PubKey { pkBz := rapid.SliceOfN(rapid.Byte(), 33, 33).Draw(t, "hex") return secp256k1.PubKey{Key: pkBz} diff --git a/x/auth/keeper/keeper_test.go b/x/auth/keeper/keeper_test.go index e1cb88ed9415d..f3f0fcd13cbf6 100644 --- a/x/auth/keeper/keeper_test.go +++ b/x/auth/keeper/keeper_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/suite" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/auth" authcodec "cosmossdk.io/x/auth/codec" @@ -55,7 +55,7 @@ func (suite *KeeperTestSuite) SetupTest() { key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) - env := runtime.NewEnvironment(storeService, log.NewNopLogger()) + env := runtime.NewEnvironment(storeService, coretesting.NewNopLogger()) testCtx := testutil.DefaultContextWithDB(suite.T(), key, storetypes.NewTransientStoreKey("transient_test")) suite.ctx = testCtx.Ctx.WithHeaderInfo(header.Info{}) diff --git a/x/auth/migrations/legacytx/stdsign.go b/x/auth/migrations/legacytx/stdsign.go index e8d00f67594c7..6ef08f4c8a022 100644 --- a/x/auth/migrations/legacytx/stdsign.go +++ b/x/auth/migrations/legacytx/stdsign.go @@ -2,11 +2,13 @@ package legacytx import ( "encoding/json" + "errors" "fmt" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "sigs.k8s.io/yaml" - "cosmossdk.io/errors" + errorsmod "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" @@ -62,7 +64,7 @@ func mustSortJSON(bz []byte) []byte { // Deprecated: Please use x/tx/signing/aminojson instead. func StdSignBytes(chainID string, accnum, sequence, timeout uint64, fee StdFee, msgs []sdk.Msg, memo string) []byte { if RegressionTestingAminoCodec == nil { - panic(fmt.Errorf("must set RegressionTestingAminoCodec before calling StdSignBytes")) + panic(errors.New("must set RegressionTestingAminoCodec before calling StdSignBytes")) } msgsBytes := make([]json.RawMessage, 0, len(msgs)) for _, msg := range msgs { @@ -129,7 +131,7 @@ func (ss StdSignature) MarshalYAML() (interface{}, error) { return string(bz), err } -func (ss StdSignature) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (ss StdSignature) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { return codectypes.UnpackInterfaces(ss.PubKey, unpacker) } @@ -172,7 +174,7 @@ func pubKeySigToSigData(cdc *codec.LegacyAmino, key cryptotypes.PubKey, sig []by if bitArray.GetIndex(i) { data, err := pubKeySigToSigData(cdc, pubKeys[i], multiSig.Sigs[sigIdx]) if err != nil { - return nil, errors.Wrapf(err, "Unable to convert Signature to SigData %d", sigIdx) + return nil, errorsmod.Wrapf(err, "Unable to convert Signature to SigData %d", sigIdx) } sigDatas[sigIdx] = data diff --git a/x/auth/migrations/legacytx/stdsignmsg.go b/x/auth/migrations/legacytx/stdsignmsg.go index 561a64463f50c..1fd8c585015f4 100644 --- a/x/auth/migrations/legacytx/stdsignmsg.go +++ b/x/auth/migrations/legacytx/stdsignmsg.go @@ -1,11 +1,13 @@ package legacytx import ( + gogoprotoany "github.com/cosmos/gogoproto/types/any" + "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" ) -var _ types.UnpackInterfacesMessage = StdSignMsg{} +var _ gogoprotoany.UnpackInterfacesMessage = StdSignMsg{} // StdSignMsg is a convenience structure for passing along a Msg with the other // requirements for a StdSignDoc before it is signed. For use in the CLI. @@ -19,7 +21,7 @@ type StdSignMsg struct { Memo string `json:"memo" yaml:"memo"` } -func (msg StdSignMsg) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (msg StdSignMsg) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, m := range msg.Msgs { err := types.UnpackInterfaces(m, unpacker) if err != nil { diff --git a/x/auth/migrations/legacytx/stdtx.go b/x/auth/migrations/legacytx/stdtx.go index dc5dba098860b..5e67518716d55 100644 --- a/x/auth/migrations/legacytx/stdtx.go +++ b/x/auth/migrations/legacytx/stdtx.go @@ -1,6 +1,8 @@ package legacytx import ( + gogoprotoany "github.com/cosmos/gogoproto/types/any" + errorsmod "cosmossdk.io/errors" "cosmossdk.io/math" @@ -13,9 +15,9 @@ import ( // Interface implementation checks var ( - _ codectypes.UnpackInterfacesMessage = (*StdTx)(nil) + _ gogoprotoany.UnpackInterfacesMessage = (*StdTx)(nil) - _ codectypes.UnpackInterfacesMessage = (*StdSignature)(nil) + _ gogoprotoany.UnpackInterfacesMessage = (*StdSignature)(nil) ) // StdFee includes the amount of coins paid in fees and the maximum @@ -169,7 +171,7 @@ func (tx StdTx) FeeGranter() sdk.AccAddress { return nil } -func (tx StdTx) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (tx StdTx) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, m := range tx.Msgs { err := codectypes.UnpackInterfaces(m, unpacker) if err != nil { diff --git a/x/auth/module.go b/x/auth/module.go index a82425d93c482..ec502dd44849c 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -34,7 +34,6 @@ const ( var ( _ module.AppModuleSimulation = AppModule{} - _ module.HasName = AppModule{} _ appmodulev2.HasGenesis = AppModule{} _ appmodulev2.AppModule = AppModule{} @@ -68,7 +67,8 @@ func NewAppModule( } } -// Name returns the auth module's name. +// Name returns the module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } diff --git a/x/auth/tx/builder.go b/x/auth/tx/builder.go index 506412b23f6c8..84dd54bb3002f 100644 --- a/x/auth/tx/builder.go +++ b/x/auth/tx/builder.go @@ -1,6 +1,7 @@ package tx import ( + "errors" "fmt" "google.golang.org/protobuf/proto" @@ -241,7 +242,7 @@ func (w *builder) SetNonCriticalExtensionOptions(extOpts ...*codectypes.Any) { w.nonCriticalExtensionOptions = extOpts } -func (w *builder) AddAuxSignerData(data tx.AuxSignerData) error { return fmt.Errorf("not supported") } +func (w *builder) AddAuxSignerData(data tx.AuxSignerData) error { return errors.New("not supported") } func (w *builder) getFee() (fee *txv1beta1.Fee, err error) { granterStr := "" diff --git a/x/auth/tx/config.go b/x/auth/tx/config.go index 2b7675cd257f7..bd9811a76c55e 100644 --- a/x/auth/tx/config.go +++ b/x/auth/tx/config.go @@ -149,7 +149,7 @@ func NewSigningHandlerMap(configOpts ConfigOptions) (*txsigning.HandlerMap, erro TypeResolver: signingOpts.TypeResolver, }) if configOpts.TextualCoinMetadataQueryFn == nil { - return nil, fmt.Errorf("cannot enable SIGN_MODE_TEXTUAL without a TextualCoinMetadataQueryFn") + return nil, errors.New("cannot enable SIGN_MODE_TEXTUAL without a TextualCoinMetadataQueryFn") } if err != nil { return nil, err diff --git a/x/auth/tx/config/depinject.go b/x/auth/tx/config/depinject.go index f3b02370e8d29..d85c2921fc8c0 100644 --- a/x/auth/tx/config/depinject.go +++ b/x/auth/tx/config/depinject.go @@ -2,6 +2,7 @@ package tx import ( "context" + "errors" "fmt" gogoproto "github.com/cosmos/gogoproto/proto" @@ -144,7 +145,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { func newAnteHandler(txConfig client.TxConfig, in ModuleInputs) (sdk.AnteHandler, error) { if in.BankKeeper == nil { - return nil, fmt.Errorf("both AccountKeeper and BankKeeper are required") + return nil, errors.New("both AccountKeeper and BankKeeper are required") } anteHandler, err := ante.NewAnteHandler( diff --git a/x/auth/tx/sigs.go b/x/auth/tx/sigs.go index 1c182567f9cf4..7885cf6b3343e 100644 --- a/x/auth/tx/sigs.go +++ b/x/auth/tx/sigs.go @@ -1,6 +1,7 @@ package tx import ( + "errors" "fmt" txv1beta1 "cosmossdk.io/api/cosmos/tx/v1beta1" @@ -105,7 +106,7 @@ func decodeMultisignatures(bz []byte) ([][]byte, error) { // malleability in the protobuf message. Basically an attacker could bloat a MultiSignature message with unknown // fields, thus bloating the transaction and causing it to fail. if len(multisig.XXX_unrecognized) > 0 { - return nil, fmt.Errorf("rejecting unrecognized fields found in MultiSignature") + return nil, errors.New("rejecting unrecognized fields found in MultiSignature") } return multisig.Signatures, nil } diff --git a/x/auth/types/account.go b/x/auth/types/account.go index 791803174b5cf..ccdff269125f8 100644 --- a/x/auth/types/account.go +++ b/x/auth/types/account.go @@ -7,6 +7,8 @@ import ( "fmt" "strings" + gogoprotoany "github.com/cosmos/gogoproto/types/any" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -14,11 +16,11 @@ import ( ) var ( - _ sdk.AccountI = (*BaseAccount)(nil) - _ GenesisAccount = (*BaseAccount)(nil) - _ codectypes.UnpackInterfacesMessage = (*BaseAccount)(nil) - _ GenesisAccount = (*ModuleAccount)(nil) - _ sdk.ModuleAccountI = (*ModuleAccount)(nil) + _ sdk.AccountI = (*BaseAccount)(nil) + _ GenesisAccount = (*BaseAccount)(nil) + _ gogoprotoany.UnpackInterfacesMessage = (*BaseAccount)(nil) + _ GenesisAccount = (*ModuleAccount)(nil) + _ sdk.ModuleAccountI = (*ModuleAccount)(nil) ) // NewBaseAccount creates a new BaseAccount object. @@ -132,7 +134,7 @@ func (acc BaseAccount) Validate() error { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (acc BaseAccount) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (acc BaseAccount) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { if acc.PubKey == nil { return nil } @@ -207,7 +209,7 @@ func (ma ModuleAccount) GetPermissions() []string { // SetPubKey - Implements AccountI func (ma ModuleAccount) SetPubKey(pubKey cryptotypes.PubKey) error { - return fmt.Errorf("not supported for module accounts") + return errors.New("not supported for module accounts") } // Validate checks for errors on the account fields diff --git a/x/auth/types/credentials.go b/x/auth/types/credentials.go index 4c63fc8d8c41c..c2da54c225282 100644 --- a/x/auth/types/credentials.go +++ b/x/auth/types/credentials.go @@ -2,6 +2,7 @@ package types import ( "bytes" + "errors" "fmt" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -12,7 +13,7 @@ import ( // NewBaseAccountWithPubKey creates an account with an a pubkey. func NewBaseAccountWithPubKey(pubkey cryptotypes.PubKey) (*BaseAccount, error) { if pubkey == nil { - return nil, fmt.Errorf("pubkey cannot be nil") + return nil, errors.New("pubkey cannot be nil") } baseAccount := NewBaseAccountWithAddress(sdk.AccAddress(pubkey.Address())) diff --git a/x/auth/types/genesis.go b/x/auth/types/genesis.go index b31c686bc43f8..d0b6db9dbefd3 100644 --- a/x/auth/types/genesis.go +++ b/x/auth/types/genesis.go @@ -7,6 +7,7 @@ import ( "sort" "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/types" @@ -14,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" ) -var _ types.UnpackInterfacesMessage = GenesisState{} +var _ gogoprotoany.UnpackInterfacesMessage = GenesisState{} // RandomGenesisAccountsFn defines the function required to generate custom account types type RandomGenesisAccountsFn func(simState *module.SimulationState) GenesisAccounts @@ -32,7 +33,7 @@ func NewGenesisState(params Params, accounts GenesisAccounts) *GenesisState { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (g GenesisState) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (g GenesisState) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, any := range g.Accounts { var account GenesisAccount err := unpacker.UnpackAny(any, &account) diff --git a/x/auth/types/params_test.go b/x/auth/types/params_test.go index fdef7174cf097..8f66844032971 100644 --- a/x/auth/types/params_test.go +++ b/x/auth/types/params_test.go @@ -1,7 +1,7 @@ package types_test import ( - "fmt" + "errors" "testing" "github.com/stretchr/testify/require" @@ -26,15 +26,15 @@ func TestParams_Validate(t *testing.T) { }{ {"default params", types.DefaultParams(), nil}, {"invalid tx signature limit", types.NewParams(types.DefaultMaxMemoCharacters, 0, types.DefaultTxSizeCostPerByte, - types.DefaultSigVerifyCostED25519, types.DefaultSigVerifyCostSecp256k1), fmt.Errorf("invalid tx signature limit: 0")}, + types.DefaultSigVerifyCostED25519, types.DefaultSigVerifyCostSecp256k1), errors.New("invalid tx signature limit: 0")}, {"invalid ED25519 signature verification cost", types.NewParams(types.DefaultMaxMemoCharacters, types.DefaultTxSigLimit, types.DefaultTxSizeCostPerByte, - 0, types.DefaultSigVerifyCostSecp256k1), fmt.Errorf("invalid ED25519 signature verification cost: 0")}, + 0, types.DefaultSigVerifyCostSecp256k1), errors.New("invalid ED25519 signature verification cost: 0")}, {"invalid SECK256k1 signature verification cost", types.NewParams(types.DefaultMaxMemoCharacters, types.DefaultTxSigLimit, types.DefaultTxSizeCostPerByte, - types.DefaultSigVerifyCostED25519, 0), fmt.Errorf("invalid SECK256k1 signature verification cost: 0")}, + types.DefaultSigVerifyCostED25519, 0), errors.New("invalid SECK256k1 signature verification cost: 0")}, {"invalid max memo characters", types.NewParams(0, types.DefaultTxSigLimit, types.DefaultTxSizeCostPerByte, - types.DefaultSigVerifyCostED25519, types.DefaultSigVerifyCostSecp256k1), fmt.Errorf("invalid max memo characters: 0")}, + types.DefaultSigVerifyCostED25519, types.DefaultSigVerifyCostSecp256k1), errors.New("invalid max memo characters: 0")}, {"invalid tx size cost per byte", types.NewParams(types.DefaultMaxMemoCharacters, types.DefaultTxSigLimit, 0, - types.DefaultSigVerifyCostED25519, types.DefaultSigVerifyCostSecp256k1), fmt.Errorf("invalid tx size cost per byte: 0")}, + types.DefaultSigVerifyCostED25519, types.DefaultSigVerifyCostSecp256k1), errors.New("invalid tx size cost per byte: 0")}, } for _, tt := range tests { tt := tt diff --git a/x/auth/types/permissions.go b/x/auth/types/permissions.go index 8547235003c43..6d78a4b56a8d2 100644 --- a/x/auth/types/permissions.go +++ b/x/auth/types/permissions.go @@ -1,7 +1,7 @@ package types import ( - "fmt" + "errors" "strings" sdk "github.com/cosmos/cosmos-sdk/types" @@ -52,7 +52,7 @@ func (pa PermissionsForAddress) GetPermissions() []string { func validatePermissions(permissions ...string) error { for _, perm := range permissions { if strings.TrimSpace(perm) == "" { - return fmt.Errorf("module permission is empty") + return errors.New("module permission is empty") } } return nil diff --git a/x/auth/types/query.go b/x/auth/types/query.go index 8ab9df38f9f07..96b089e18a740 100644 --- a/x/auth/types/query.go +++ b/x/auth/types/query.go @@ -1,13 +1,14 @@ package types import ( - codectypes "github.com/cosmos/cosmos-sdk/codec/types" + gogoprotoany "github.com/cosmos/gogoproto/types/any" + sdk "github.com/cosmos/cosmos-sdk/types" ) -func (m *QueryAccountResponse) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (m *QueryAccountResponse) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var account sdk.AccountI return unpacker.UnpackAny(m.Account, &account) } -var _ codectypes.UnpackInterfacesMessage = &QueryAccountResponse{} +var _ gogoprotoany.UnpackInterfacesMessage = &QueryAccountResponse{} diff --git a/x/auth/vesting/module.go b/x/auth/vesting/module.go index 0baec3da3b01c..fc85b46f96544 100644 --- a/x/auth/vesting/module.go +++ b/x/auth/vesting/module.go @@ -6,16 +6,9 @@ import ( "cosmossdk.io/core/registry" "cosmossdk.io/x/auth/keeper" "cosmossdk.io/x/auth/vesting/types" - - "github.com/cosmos/cosmos-sdk/types/module" ) -var ( - _ module.AppModule = AppModule{} - _ module.HasName = AppModule{} - - _ appmodule.AppModule = AppModule{} -) +var _ appmodule.AppModule = AppModule{} // AppModule implementing the AppModule interface. type AppModule struct { @@ -34,6 +27,7 @@ func NewAppModule(ak keeper.AccountKeeper, bk types.BankKeeper) AppModule { func (am AppModule) IsAppModule() {} // Name returns the module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } diff --git a/x/auth/vesting/types/codec.go b/x/auth/vesting/types/codec.go index 99246287c3155..9ebc5a2c46a94 100644 --- a/x/auth/vesting/types/codec.go +++ b/x/auth/vesting/types/codec.go @@ -26,7 +26,7 @@ func RegisterLegacyAminoCodec(cdc corelegacy.Amino) { legacy.RegisterAminoMsg(cdc, &MsgCreatePeriodicVestingAccount{}, "cosmos-sdk/MsgCreatePeriodVestAccount") } -// RegisterInterface associates protoName with AccountI and VestingAccount +// RegisterInterfaces associates protoName with AccountI and VestingAccount // Interfaces and creates a registry of it's concrete implementations func RegisterInterfaces(registrar registry.InterfaceRegistrar) { registrar.RegisterInterface( diff --git a/x/auth/vesting/types/vesting_account_test.go b/x/auth/vesting/types/vesting_account_test.go index f5f4f8e8732de..502ce29c4ce07 100644 --- a/x/auth/vesting/types/vesting_account_test.go +++ b/x/auth/vesting/types/vesting_account_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/suite" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" authcodec "cosmossdk.io/x/auth/codec" "cosmossdk.io/x/auth/keeper" @@ -44,7 +44,7 @@ func (s *VestingAccountTestSuite) SetupTest() { encCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, vesting.AppModule{}) key := storetypes.NewKVStoreKey(authtypes.StoreKey) - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) s.ctx = testCtx.Ctx.WithHeaderInfo(header.Info{}) diff --git a/x/authz/authorization_grant.go b/x/authz/authorization_grant.go index 9dd8aced37914..c054eb0814033 100644 --- a/x/authz/authorization_grant.go +++ b/x/authz/authorization_grant.go @@ -4,10 +4,10 @@ import ( "time" "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" errorsmod "cosmossdk.io/errors" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -22,7 +22,7 @@ func NewGrant(blockTime time.Time, a Authorization, expiration *time.Time) (Gran if !ok { return Grant{}, sdkerrors.ErrPackAny.Wrapf("cannot proto marshal %T", a) } - any, err := cdctypes.NewAnyWithValue(msg) + any, err := gogoprotoany.NewAnyWithCacheWithValue(msg) if err != nil { return Grant{}, err } @@ -32,10 +32,10 @@ func NewGrant(blockTime time.Time, a Authorization, expiration *time.Time) (Gran }, nil } -var _ cdctypes.UnpackInterfacesMessage = &Grant{} +var _ gogoprotoany.UnpackInterfacesMessage = &Grant{} // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (g Grant) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { +func (g Grant) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var authorization Authorization return unpacker.UnpackAny(g.Authorization, &authorization) } diff --git a/x/authz/client/cli/tx.go b/x/authz/client/cli/tx.go index d065c57cc2887..e90d9a5b28b59 100644 --- a/x/authz/client/cli/tx.go +++ b/x/authz/client/cli/tx.go @@ -137,7 +137,7 @@ Examples: } if !spendLimit.IsAllPositive() { - return fmt.Errorf("spend-limit should be greater than zero") + return errors.New("spend-limit should be greater than zero") } allowList, err := cmd.Flags().GetStringSlice(FlagAllowList) @@ -202,7 +202,7 @@ Examples: } if !spendLimit.IsPositive() { - return fmt.Errorf("spend-limit should be greater than zero") + return errors.New("spend-limit should be greater than zero") } delegateLimit = &spendLimit } diff --git a/x/authz/genesis.go b/x/authz/genesis.go index 2e7dde1b7260f..f2afc47cad914 100644 --- a/x/authz/genesis.go +++ b/x/authz/genesis.go @@ -3,7 +3,7 @@ package authz import ( "fmt" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + gogoprotoany "github.com/cosmos/gogoproto/types/any" ) // NewGenesisState creates new GenesisState object @@ -32,10 +32,10 @@ func DefaultGenesisState() *GenesisState { return &GenesisState{} } -var _ cdctypes.UnpackInterfacesMessage = GenesisState{} +var _ gogoprotoany.UnpackInterfacesMessage = GenesisState{} // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (data GenesisState) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { +func (data GenesisState) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, a := range data.Authorization { err := a.UnpackInterfaces(unpacker) if err != nil { @@ -46,7 +46,7 @@ func (data GenesisState) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (msg GrantAuthorization) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { +func (msg GrantAuthorization) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var a Authorization return unpacker.UnpackAny(msg.Authorization, &a) } diff --git a/x/authz/go.mod b/x/authz/go.mod index 1109855902992..a262c055d6fc1 100644 --- a/x/authz/go.mod +++ b/x/authz/go.mod @@ -5,7 +5,7 @@ go 1.22.2 require ( cosmossdk.io/api v0.7.5 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/math v1.3.0 cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc @@ -50,7 +50,7 @@ require ( github.com/cometbft/cometbft/api v1.0.0-rc.1 github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -165,6 +165,8 @@ require ( sigs.k8s.io/yaml v1.4.0 // indirect ) +require cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 + require ( buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2 // indirect cosmossdk.io/log v1.3.1 // indirect @@ -180,9 +182,7 @@ replace ( cosmossdk.io/collections => ../../collections cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log - cosmossdk.io/logger => ../../logger cosmossdk.io/store => ../../store cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/authz/go.sum b/x/authz/go.sum index af1f81c0e2f09..c89bb859d7590 100644 --- a/x/authz/go.sum +++ b/x/authz/go.sum @@ -4,6 +4,8 @@ buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88e buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2/go.mod h1:HqcXMSa5qnNuakaMUo+hWhF51mKbcrZxGl9Vp5EeJXc= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -98,8 +100,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/authz/keeper/genesis_test.go b/x/authz/keeper/genesis_test.go index 46887c5865159..20a4c0acb1686 100644 --- a/x/authz/keeper/genesis_test.go +++ b/x/authz/keeper/genesis_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/suite" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/authz/keeper" @@ -58,7 +58,7 @@ func (suite *GenesisTestSuite) SetupTest() { suite.baseApp = baseapp.NewBaseApp( "authz", - log.NewNopLogger(), + coretesting.NewNopLogger(), testCtx.DB, suite.encCfg.TxConfig.TxDecoder(), ) @@ -68,7 +68,7 @@ func (suite *GenesisTestSuite) SetupTest() { msr := suite.baseApp.MsgServiceRouter() msr.SetInterfaceRegistry(suite.encCfg.InterfaceRegistry) - env := runtime.NewEnvironment(storeService, log.NewNopLogger(), runtime.EnvWithMsgRouterService(msr)) + env := runtime.NewEnvironment(storeService, coretesting.NewNopLogger(), runtime.EnvWithMsgRouterService(msr)) suite.keeper = keeper.NewKeeper(env, suite.encCfg.Codec, suite.accountKeeper) } diff --git a/x/authz/keeper/keeper_test.go b/x/authz/keeper/keeper_test.go index 3cda4e1132820..ac8cda6adb655 100644 --- a/x/authz/keeper/keeper_test.go +++ b/x/authz/keeper/keeper_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/suite" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/authz" authzkeeper "cosmossdk.io/x/authz/keeper" @@ -56,7 +56,7 @@ func (s *TestSuite) SetupTest() { s.baseApp = baseapp.NewBaseApp( "authz", - log.NewNopLogger(), + coretesting.NewNopLogger(), testCtx.DB, s.encCfg.TxConfig.TxDecoder(), ) @@ -75,7 +75,7 @@ func (s *TestSuite) SetupTest() { banktypes.RegisterInterfaces(s.encCfg.InterfaceRegistry) banktypes.RegisterMsgServer(s.baseApp.MsgServiceRouter(), s.bankKeeper) - env := runtime.NewEnvironment(storeService, log.NewNopLogger(), runtime.EnvWithQueryRouterService(s.baseApp.GRPCQueryRouter()), runtime.EnvWithMsgRouterService(s.baseApp.MsgServiceRouter())) + env := runtime.NewEnvironment(storeService, coretesting.NewNopLogger(), runtime.EnvWithQueryRouterService(s.baseApp.GRPCQueryRouter()), runtime.EnvWithMsgRouterService(s.baseApp.MsgServiceRouter())) s.authzKeeper = authzkeeper.NewKeeper(env, s.encCfg.Codec, s.accountKeeper) queryHelper := baseapp.NewQueryServerTestHelper(s.ctx, s.encCfg.InterfaceRegistry) diff --git a/x/authz/migrations/v2/store_test.go b/x/authz/migrations/v2/store_test.go index 0f5cd17359d97..efe6d5f0b4538 100644 --- a/x/authz/migrations/v2/store_test.go +++ b/x/authz/migrations/v2/store_test.go @@ -8,7 +8,7 @@ import ( govtypes "cosmossdk.io/api/cosmos/gov/v1beta1" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/authz" v2 "cosmossdk.io/x/authz/migrations/v2" @@ -106,7 +106,7 @@ func TestMigration(t *testing.T) { storeService := runtime.NewKVStoreService(authzKey) store := storeService.OpenKVStore(ctx) - env := runtime.NewEnvironment(storeService, log.NewNopLogger()) + env := runtime.NewEnvironment(storeService, coretesting.NewNopLogger()) for _, g := range grants { grant := g.authorization() diff --git a/x/authz/module/abci_test.go b/x/authz/module/abci_test.go index 131063f48adee..b2c8dbb9f5aa7 100644 --- a/x/authz/module/abci_test.go +++ b/x/authz/module/abci_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" "cosmossdk.io/x/authz" @@ -36,7 +36,7 @@ func TestExpiredGrantsQueue(t *testing.T) { baseApp := baseapp.NewBaseApp( "authz", - log.NewNopLogger(), + coretesting.NewNopLogger(), testCtx.DB, encCfg.TxConfig.TxDecoder(), ) @@ -66,7 +66,7 @@ func TestExpiredGrantsQueue(t *testing.T) { accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec("cosmos")).AnyTimes() - env := runtime.NewEnvironment(storeService, log.NewNopLogger(), runtime.EnvWithQueryRouterService(baseApp.GRPCQueryRouter()), runtime.EnvWithMsgRouterService(baseApp.MsgServiceRouter())) + env := runtime.NewEnvironment(storeService, coretesting.NewNopLogger(), runtime.EnvWithQueryRouterService(baseApp.GRPCQueryRouter()), runtime.EnvWithMsgRouterService(baseApp.MsgServiceRouter())) authzKeeper := keeper.NewKeeper(env, encCfg.Codec, accountKeeper) save := func(grantee sdk.AccAddress, exp *time.Time) { diff --git a/x/authz/module/module.go b/x/authz/module/module.go index 2723787c582b0..caf302e5447dc 100644 --- a/x/authz/module/module.go +++ b/x/authz/module/module.go @@ -29,7 +29,6 @@ import ( const ConsensusVersion = 2 var ( - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.AppModuleSimulation = AppModule{} @@ -66,6 +65,7 @@ func NewAppModule( func (AppModule) IsAppModule() {} // Name returns the authz module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return authz.ModuleName } diff --git a/x/authz/msgs.go b/x/authz/msgs.go index 0964f45cb34b0..b7c7c6c9cd308 100644 --- a/x/authz/msgs.go +++ b/x/authz/msgs.go @@ -4,6 +4,7 @@ import ( "time" "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -15,8 +16,8 @@ var ( _ sdk.Msg = &MsgRevoke{} _ sdk.Msg = &MsgExec{} - _ cdctypes.UnpackInterfacesMessage = &MsgGrant{} - _ cdctypes.UnpackInterfacesMessage = &MsgExec{} + _ gogoprotoany.UnpackInterfacesMessage = &MsgGrant{} + _ gogoprotoany.UnpackInterfacesMessage = &MsgExec{} ) // NewMsgGrant creates a new MsgGrant @@ -44,7 +45,7 @@ func (msg *MsgGrant) SetAuthorization(a Authorization) error { if !ok { return sdkerrors.ErrPackAny.Wrapf("can't proto marshal %T", m) } - any, err := cdctypes.NewAnyWithValue(m) + any, err := gogoprotoany.NewAnyWithCacheWithValue(m) if err != nil { return err } @@ -53,7 +54,7 @@ func (msg *MsgGrant) SetAuthorization(a Authorization) error { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (msg MsgExec) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { +func (msg MsgExec) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, x := range msg.Msgs { var msgExecAuthorized sdk.Msg err := unpacker.UnpackAny(x, &msgExecAuthorized) @@ -66,7 +67,7 @@ func (msg MsgExec) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (msg MsgGrant) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { +func (msg MsgGrant) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { return msg.Grant.UnpackInterfaces(unpacker) } diff --git a/x/authz/simulation/operations.go b/x/authz/simulation/operations.go new file mode 100644 index 0000000000000..374a451cfc23b --- /dev/null +++ b/x/authz/simulation/operations.go @@ -0,0 +1,395 @@ +package simulation + +import ( + "context" + "math/rand" + "time" + + gogoprotoany "github.com/cosmos/gogoproto/types/any" + + "cosmossdk.io/core/address" + "cosmossdk.io/core/appmodule" + corecontext "cosmossdk.io/core/context" + coregas "cosmossdk.io/core/gas" + coreheader "cosmossdk.io/core/header" + "cosmossdk.io/x/authz" + "cosmossdk.io/x/authz/keeper" + banktype "cosmossdk.io/x/bank/types" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// authz message types +var ( + TypeMsgGrant = sdk.MsgTypeURL(&authz.MsgGrant{}) + TypeMsgRevoke = sdk.MsgTypeURL(&authz.MsgRevoke{}) + TypeMsgExec = sdk.MsgTypeURL(&authz.MsgExec{}) +) + +// Simulation operation weights constants +const ( + OpWeightMsgGrant = "op_weight_msg_grant" + OpWeightRevoke = "op_weight_msg_revoke" + OpWeightExec = "op_weight_msg_execute" +) + +// authz operations weights +const ( + WeightGrant = 100 + WeightRevoke = 90 + WeightExec = 90 +) + +// WeightedOperations returns all the operations from the module with their respective weights +func WeightedOperations( + registry cdctypes.InterfaceRegistry, + appParams simtypes.AppParams, + cdc codec.JSONCodec, + txGen client.TxConfig, + ak authz.AccountKeeper, + bk authz.BankKeeper, + k keeper.Keeper, +) simulation.WeightedOperations { + var ( + weightMsgGrant int + weightExec int + weightRevoke int + ) + + appParams.GetOrGenerate(OpWeightMsgGrant, &weightMsgGrant, nil, func(_ *rand.Rand) { + weightMsgGrant = WeightGrant + }) + + appParams.GetOrGenerate(OpWeightExec, &weightExec, nil, func(_ *rand.Rand) { + weightExec = WeightExec + }) + + appParams.GetOrGenerate(OpWeightRevoke, &weightRevoke, nil, func(_ *rand.Rand) { + weightRevoke = WeightRevoke + }) + + pCdc := codec.NewProtoCodec(registry) + + return simulation.WeightedOperations{ + simulation.NewWeightedOperation( + weightMsgGrant, + SimulateMsgGrant(pCdc, txGen, ak, bk, k), + ), + simulation.NewWeightedOperation( + weightExec, + SimulateMsgExec(pCdc, txGen, ak, bk, k, registry), + ), + simulation.NewWeightedOperation( + weightRevoke, + SimulateMsgRevoke(pCdc, txGen, ak, bk, k), + ), + } +} + +// SimulateMsgGrant generates a MsgGrant with random values. +func SimulateMsgGrant( + cdc *codec.ProtoCodec, + txCfg client.TxConfig, + ak authz.AccountKeeper, + bk authz.BankKeeper, + _ keeper.Keeper, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + granter, _ := simtypes.RandomAcc(r, accs) + grantee, _ := simtypes.RandomAcc(r, accs) + + if granter.Address.Equals(grantee.Address) { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, "granter and grantee are same"), nil, nil + } + + granterAcc := ak.GetAccount(ctx, granter.Address) + spendableCoins := bk.SpendableCoins(ctx, granter.Address) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, err.Error()), nil, err + } + + spendLimit := spendableCoins.Sub(fees...) + if len(spendLimit) == 0 { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, "spend limit is nil"), nil, nil + } + + var expiration *time.Time + t1 := simtypes.RandTimestamp(r) + if !t1.Before(ctx.HeaderInfo().Time) { + expiration = &t1 + } + randomAuthz := generateRandomAuthorization(r, spendLimit, ak.AddressCodec()) + + granterAddr, err := ak.AddressCodec().BytesToString(granter.Address) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, "could not get granter address"), nil, nil + } + granteeAddr, err := ak.AddressCodec().BytesToString(grantee.Address) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, "could not get grantee address"), nil, nil + } + msg, err := authz.NewMsgGrant(granterAddr, granteeAddr, randomAuthz, expiration) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, err.Error()), nil, err + } + tx, err := simtestutil.GenSignedMockTx( + r, + txCfg, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{granterAcc.GetAccountNumber()}, + []uint64{granterAcc.GetSequence()}, + granter.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txCfg.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +func generateRandomAuthorization(r *rand.Rand, spendLimit sdk.Coins, addressCodec address.Codec) authz.Authorization { + authorizations := make([]authz.Authorization, 2) + sendAuthz := banktype.NewSendAuthorization(spendLimit, nil, addressCodec) + authorizations[0] = sendAuthz + authorizations[1] = authz.NewGenericAuthorization(sdk.MsgTypeURL(&banktype.MsgSend{})) + + return authorizations[r.Intn(len(authorizations))] +} + +// SimulateMsgRevoke generates a MsgRevoke with random values. +func SimulateMsgRevoke( + cdc *codec.ProtoCodec, + txCfg client.TxConfig, + ak authz.AccountKeeper, + bk authz.BankKeeper, + k keeper.Keeper, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + var granterAddr, granteeAddr sdk.AccAddress + var grant authz.Grant + hasGrant := false + + err := k.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, g authz.Grant) (bool, error) { + grant = g + granterAddr = granter + granteeAddr = grantee + hasGrant = true + return true, nil + }) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, err.Error()), nil, err + } + + if !hasGrant { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, "no grants"), nil, nil + } + + granterAcc, ok := simtypes.FindAccount(accs, granterAddr) + if !ok { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, "account not found"), nil, sdkerrors.ErrNotFound.Wrapf("account not found") + } + + spendableCoins := bk.SpendableCoins(ctx, granterAddr) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, "fee error"), nil, err + } + + a, err := grant.GetAuthorization() + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, "authorization error"), nil, err + } + + granterStrAddr, err := ak.AddressCodec().BytesToString(granterAddr) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, "could not get granter address"), nil, nil + } + granteeStrAddr, err := ak.AddressCodec().BytesToString(granteeAddr) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, "could not get grantee address"), nil, nil + } + msg := authz.NewMsgRevoke(granterStrAddr, granteeStrAddr, a.MsgTypeURL()) + account := ak.GetAccount(ctx, granterAddr) + tx, err := simtestutil.GenSignedMockTx( + r, + txCfg, + []sdk.Msg{&msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + granterAcc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, err.Error()), nil, err + } + + _, _, err = app.SimDeliver(txCfg.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, "unable to execute tx: "+err.Error()), nil, err + } + + return simtypes.NewOperationMsg(&msg, true, ""), nil, nil + } +} + +// SimulateMsgExec generates a MsgExec with random values. +func SimulateMsgExec( + cdc *codec.ProtoCodec, + txCfg client.TxConfig, + ak authz.AccountKeeper, + bk authz.BankKeeper, + k keeper.Keeper, + unpacker gogoprotoany.AnyUnpacker, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + var granterAddr sdk.AccAddress + var granteeAddr sdk.AccAddress + var sendAuth *banktype.SendAuthorization + var err error + err = k.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, grant authz.Grant) (bool, error) { + granterAddr = granter + granteeAddr = grantee + var a authz.Authorization + a, err = grant.GetAuthorization() + if err != nil { + return true, err + } + var ok bool + sendAuth, ok = a.(*banktype.SendAuthorization) + return ok, nil + }) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, err.Error()), nil, err + } + if sendAuth == nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, "no grant found"), nil, nil + } + + grantee, ok := simtypes.FindAccount(accs, granteeAddr) + if !ok { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, "Account not found"), nil, sdkerrors.ErrNotFound.Wrapf("grantee account not found") + } + + if _, ok := simtypes.FindAccount(accs, granterAddr); !ok { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, "Account not found"), nil, sdkerrors.ErrNotFound.Wrapf("granter account not found") + } + + granterspendableCoins := bk.SpendableCoins(ctx, granterAddr) + coins := simtypes.RandSubsetCoins(r, granterspendableCoins) + // if coins slice is empty, we can not create valid banktype.MsgSend + if len(coins) == 0 { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, "empty coins slice"), nil, nil + } + + // Check send_enabled status of each sent coin denom + if err := bk.IsSendEnabledCoins(ctx, coins...); err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, err.Error()), nil, nil + } + + graStr, err := ak.AddressCodec().BytesToString(granterAddr) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, err.Error()), nil, err + } + greStr, err := ak.AddressCodec().BytesToString(granteeAddr) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, err.Error()), nil, err + } + + msg := []sdk.Msg{banktype.NewMsgSend(graStr, greStr, coins)} + + goCtx := context.WithValue(ctx.Context(), corecontext.EnvironmentContextKey, appmodule.Environment{ + HeaderService: headerService{}, + GasService: mockGasService{}, + }) + + _, err = sendAuth.Accept(goCtx, msg[0]) + if err != nil { + if sdkerrors.ErrInsufficientFunds.Is(err) { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, err.Error()), nil, nil + } + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, err.Error()), nil, err + + } + + msgExec := authz.NewMsgExec(greStr, msg) + granteeSpendableCoins := bk.SpendableCoins(ctx, granteeAddr) + fees, err := simtypes.RandomFees(r, granteeSpendableCoins) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, "fee error"), nil, err + } + + granteeAcc := ak.GetAccount(ctx, granteeAddr) + tx, err := simtestutil.GenSignedMockTx( + r, + txCfg, + []sdk.Msg{&msgExec}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{granteeAcc.GetAccountNumber()}, + []uint64{granteeAcc.GetSequence()}, + grantee.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, err.Error()), nil, err + } + + _, _, err = app.SimDeliver(txCfg.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, err.Error()), nil, err + } + + err = msgExec.UnpackInterfaces(unpacker) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, "unmarshal error"), nil, err + } + return simtypes.NewOperationMsg(&msgExec, true, "success"), nil, nil + } +} + +type headerService struct{} + +func (h headerService) HeaderInfo(ctx context.Context) coreheader.Info { + return sdk.UnwrapSDKContext(ctx).HeaderInfo() +} + +type mockGasService struct { + coregas.Service +} + +func (m mockGasService) GasMeter(ctx context.Context) coregas.Meter { + return mockGasMeter{} +} + +type mockGasMeter struct { + coregas.Meter +} + +func (m mockGasMeter) Consume(amount coregas.Gas, descriptor string) error { + return nil +} diff --git a/x/bank/client/cli/tx.go b/x/bank/client/cli/tx.go index a480d3b1a2ccb..1e86b92f7564b 100644 --- a/x/bank/client/cli/tx.go +++ b/x/bank/client/cli/tx.go @@ -1,6 +1,7 @@ package cli import ( + "errors" "fmt" "github.com/spf13/cobra" @@ -64,7 +65,7 @@ When using '--dry-run' a key name cannot be used, only a bech32 address.`, } if coins.IsZero() { - return fmt.Errorf("must send positive amount") + return errors.New("must send positive amount") } split, err := cmd.Flags().GetBool(FlagSplit) diff --git a/x/bank/go.mod b/x/bank/go.mod index ec24abda68791..480d7c39ba4e6 100644 --- a/x/bank/go.mod +++ b/x/bank/go.mod @@ -6,7 +6,7 @@ require ( cosmossdk.io/api v0.7.5 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/log v1.3.1 // indirect cosmossdk.io/math v1.3.0 @@ -52,7 +52,7 @@ require ( github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -166,6 +166,8 @@ require ( sigs.k8s.io/yaml v1.4.0 // indirect ) +require cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 + require ( cosmossdk.io/schema v0.1.1 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect @@ -179,7 +181,6 @@ replace ( cosmossdk.io/collections => ../../collections cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/bank/go.sum b/x/bank/go.sum index 0b0081734c7bb..4879cfa34550a 100644 --- a/x/bank/go.sum +++ b/x/bank/go.sum @@ -4,6 +4,8 @@ buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88e buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2/go.mod h1:HqcXMSa5qnNuakaMUo+hWhF51mKbcrZxGl9Vp5EeJXc= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -100,8 +102,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/bank/keeper/collections_test.go b/x/bank/keeper/collections_test.go index d1df19e53c259..b97cf02b95d3c 100644 --- a/x/bank/keeper/collections_test.go +++ b/x/bank/keeper/collections_test.go @@ -9,7 +9,7 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -31,7 +31,7 @@ func TestBankStateCompatibility(t *testing.T) { ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) encCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}) - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) // gomock initializations ctrl := gomock.NewController(t) diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index 5820d95422848..6db7c0a7b97c9 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -15,7 +15,7 @@ import ( coreevent "cosmossdk.io/core/event" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" errorsmod "cosmossdk.io/errors" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" @@ -132,7 +132,7 @@ func (suite *KeeperTestSuite) SetupTest() { ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) encCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}) - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) ac := codectestutil.CodecOptions{}.GetAddressCodec() addr, err := ac.BytesToString(accAddrs[4]) @@ -310,7 +310,7 @@ func (suite *KeeperTestSuite) TestPrependSendRestriction() { } func (suite *KeeperTestSuite) TestGetAuthority() { - env := runtime.NewEnvironment(runtime.NewKVStoreService(storetypes.NewKVStoreKey(banktypes.StoreKey)), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(storetypes.NewKVStoreKey(banktypes.StoreKey)), coretesting.NewNopLogger()) NewKeeperWithAuthority := func(authority string) keeper.BaseKeeper { return keeper.NewBaseKeeper( env, diff --git a/x/bank/module.go b/x/bank/module.go index 6d75c72615191..4832a69504b4e 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -30,7 +30,6 @@ import ( const ConsensusVersion = 4 var ( - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.AppModuleSimulation = AppModule{} @@ -63,6 +62,7 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.Acc func (am AppModule) IsAppModule() {} // Name returns the bank module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } // RegisterLegacyAminoCodec registers the bank module's types on the LegacyAmino codec. diff --git a/x/bank/simulation/genesis_test.go b/x/bank/simulation/genesis_test.go index 19556a2b76651..f5e93943d7392 100644 --- a/x/bank/simulation/genesis_test.go +++ b/x/bank/simulation/genesis_test.go @@ -59,7 +59,7 @@ func TestRandomizedGenState(t *testing.T) { } } -// TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. +// TestRandomizedGenState1 tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) diff --git a/x/circuit/go.mod b/x/circuit/go.mod index 90c80613ed7ca..68b9e5ca1ff61 100644 --- a/x/circuit/go.mod +++ b/x/circuit/go.mod @@ -6,7 +6,8 @@ require ( cosmossdk.io/api v0.7.5 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc cosmossdk.io/x/auth v0.0.0-00010101000000-000000000000 @@ -50,7 +51,7 @@ require ( github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect github.com/cosmos/cosmos-proto v1.0.0-beta.5 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -176,7 +177,6 @@ replace ( cosmossdk.io/api => ../../api cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/circuit/go.sum b/x/circuit/go.sum index 6a2618f159fc5..08da56c9d15ef 100644 --- a/x/circuit/go.sum +++ b/x/circuit/go.sum @@ -6,6 +6,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -102,8 +104,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/circuit/keeper/genesis_test.go b/x/circuit/keeper/genesis_test.go index b7c7eb53c41f7..493e28f7b5ddc 100644 --- a/x/circuit/keeper/genesis_test.go +++ b/x/circuit/keeper/genesis_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/suite" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" "cosmossdk.io/x/circuit" @@ -51,7 +51,7 @@ func (s *GenesisTestSuite) SetupTest() { s.Require().NoError(err) s.addrBytes = bz - s.keeper = keeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()), s.cdc, authority, ac) + s.keeper = keeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()), s.cdc, authority, ac) } func (s *GenesisTestSuite) TestInitExportGenesis() { diff --git a/x/circuit/keeper/keeper_test.go b/x/circuit/keeper/keeper_test.go index 48d063cf563e6..f6f3c177dce87 100644 --- a/x/circuit/keeper/keeper_test.go +++ b/x/circuit/keeper/keeper_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" "cosmossdk.io/core/address" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" "cosmossdk.io/x/circuit" @@ -45,7 +45,7 @@ func initFixture(t *testing.T) *fixture { ac := addresscodec.NewBech32Codec("cosmos") mockStoreKey := storetypes.NewKVStoreKey("test") - env := runtime.NewEnvironment(runtime.NewKVStoreService(mockStoreKey), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(mockStoreKey), coretesting.NewNopLogger()) authority, err := ac.BytesToString(authtypes.NewModuleAddress("gov")) require.NoError(t, err) k := keeper.NewKeeper(env, encCfg.Codec, authority, ac) diff --git a/x/circuit/keeper/query.go b/x/circuit/keeper/query.go index a8b39e4d4a82b..34d331c1ef265 100644 --- a/x/circuit/keeper/query.go +++ b/x/circuit/keeper/query.go @@ -35,7 +35,7 @@ func (qs QueryServer) Account(ctx context.Context, req *types.QueryAccountReques return &types.AccountResponse{Permission: &perms}, nil } -// Account returns account permissions. +// Accounts returns multiple accounts permissions. func (qs QueryServer) Accounts(ctx context.Context, req *types.QueryAccountsRequest) (*types.AccountsResponse, error) { results, pageRes, err := query.CollectionPaginate( ctx, diff --git a/x/circuit/module.go b/x/circuit/module.go index 32dd066776517..7223b74b8ce54 100644 --- a/x/circuit/module.go +++ b/x/circuit/module.go @@ -22,7 +22,6 @@ import ( const ConsensusVersion = 1 var ( - _ module.HasName = AppModule{} _ module.HasGRPCGateway = AppModule{} _ appmodule.AppModule = AppModule{} @@ -41,6 +40,7 @@ type AppModule struct { func (AppModule) IsAppModule() {} // Name returns the circuit module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the circuit module. diff --git a/x/circuit/proto/cosmos/circuit/v1/query.proto b/x/circuit/proto/cosmos/circuit/v1/query.proto index 0115d335f4391..35949819cfdaf 100644 --- a/x/circuit/proto/cosmos/circuit/v1/query.proto +++ b/x/circuit/proto/cosmos/circuit/v1/query.proto @@ -16,7 +16,7 @@ service Query { option (google.api.http).get = "/cosmos/circuit/v1/accounts/{address}"; } - // Account returns account permissions. + // Accounts returns multiple accounts permissions. rpc Accounts(QueryAccountsRequest) returns (AccountsResponse) { option (cosmos.query.v1.module_query_safe) = true; option (google.api.http).get = "/cosmos/circuit/v1/accounts"; @@ -52,7 +52,7 @@ message AccountsResponse { cosmos.base.query.v1beta1.PageResponse pagination = 2; } -// QueryDisableListRequest is the request type for the Query/DisabledList RPC method. +// QueryDisabledListRequest is the request type for the Query/DisabledList RPC method. message QueryDisabledListRequest {} // DisabledListResponse is the response type for the Query/DisabledList RPC method. diff --git a/x/circuit/types/query.pb.go b/x/circuit/types/query.pb.go index 3933e4432621e..c327a4bae9e74 100644 --- a/x/circuit/types/query.pb.go +++ b/x/circuit/types/query.pb.go @@ -219,7 +219,7 @@ func (m *AccountsResponse) GetPagination() *query.PageResponse { return nil } -// QueryDisableListRequest is the request type for the Query/DisabledList RPC method. +// QueryDisabledListRequest is the request type for the Query/DisabledList RPC method. type QueryDisabledListRequest struct { } @@ -363,7 +363,7 @@ const _ = grpc.SupportPackageIsVersion4 type QueryClient interface { // Account returns account permissions. Account(ctx context.Context, in *QueryAccountRequest, opts ...grpc.CallOption) (*AccountResponse, error) - // Account returns account permissions. + // Accounts returns multiple accounts permissions. Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*AccountsResponse, error) // DisabledList returns a list of disabled message urls DisabledList(ctx context.Context, in *QueryDisabledListRequest, opts ...grpc.CallOption) (*DisabledListResponse, error) @@ -408,7 +408,7 @@ func (c *queryClient) DisabledList(ctx context.Context, in *QueryDisabledListReq type QueryServer interface { // Account returns account permissions. Account(context.Context, *QueryAccountRequest) (*AccountResponse, error) - // Account returns account permissions. + // Accounts returns multiple accounts permissions. Accounts(context.Context, *QueryAccountsRequest) (*AccountsResponse, error) // DisabledList returns a list of disabled message urls DisabledList(context.Context, *QueryDisabledListRequest) (*DisabledListResponse, error) diff --git a/x/consensus/go.mod b/x/consensus/go.mod index a558c15e78429..3ca3a4af640b1 100644 --- a/x/consensus/go.mod +++ b/x/consensus/go.mod @@ -6,7 +6,8 @@ require ( cosmossdk.io/api v0.7.5 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc github.com/cometbft/cometbft v1.0.0-rc1 github.com/cometbft/cometbft/api v1.0.0-rc.1 @@ -49,7 +50,7 @@ require ( github.com/cometbft/cometbft-db v0.12.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -173,7 +174,6 @@ replace ( cosmossdk.io/api => ../../api cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/consensus/go.sum b/x/consensus/go.sum index df6c51ee037a9..496f78619dc06 100644 --- a/x/consensus/go.sum +++ b/x/consensus/go.sum @@ -6,6 +6,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -102,8 +104,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/consensus/keeper/keeper_test.go b/x/consensus/keeper/keeper_test.go index 4fa47e670743b..d1961fbfa7a9c 100644 --- a/x/consensus/keeper/keeper_test.go +++ b/x/consensus/keeper/keeper_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/suite" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" consensusparamkeeper "cosmossdk.io/x/consensus/keeper" "cosmossdk.io/x/consensus/types" @@ -43,7 +43,7 @@ func (s *KeeperTestSuite) SetupTest(enabledFeatures bool) { testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 5}) encCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}) - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) authority, err := codectestutil.CodecOptions{}.GetAddressCodec().BytesToString(address.Module("gov")) s.Require().NoError(err) diff --git a/x/consensus/module.go b/x/consensus/module.go index 4ef57fcb39e60..02504cfcff195 100644 --- a/x/consensus/module.go +++ b/x/consensus/module.go @@ -21,7 +21,6 @@ import ( const ConsensusVersion = 1 var ( - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} @@ -47,6 +46,7 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper) AppModule { func (AppModule) IsAppModule() {} // Name returns the consensus module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } // RegisterLegacyAminoCodec registers the consensus module's types on the LegacyAmino codec. diff --git a/x/distribution/go.mod b/x/distribution/go.mod index 64450ded141c0..5773e7fb3c210 100644 --- a/x/distribution/go.mod +++ b/x/distribution/go.mod @@ -6,7 +6,8 @@ require ( cosmossdk.io/api v0.7.5 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/log v1.3.1 cosmossdk.io/math v1.3.0 @@ -61,7 +62,7 @@ require ( github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -181,7 +182,6 @@ replace ( cosmossdk.io/collections => ../../collections cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/distribution/go.sum b/x/distribution/go.sum index 5772854e84170..58a04eb3afea2 100644 --- a/x/distribution/go.sum +++ b/x/distribution/go.sum @@ -4,6 +4,8 @@ buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88e buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2/go.mod h1:HqcXMSa5qnNuakaMUo+hWhF51mKbcrZxGl9Vp5EeJXc= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -102,8 +104,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index 1729a3982010d..b76b3409fbc94 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -11,7 +11,7 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/comet" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -53,7 +53,7 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) poolKeeper := distrtestutil.NewMockPoolKeeper(ctrl) - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) valCodec := address.NewBech32Codec("cosmosvaloper") @@ -125,7 +125,7 @@ func TestAllocateTokensToManyValidators(t *testing.T) { accountKeeper.EXPECT().GetModuleAccount(gomock.Any(), "fee_collector").Return(feeCollectorAcc) stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec("cosmosvaloper")).AnyTimes() - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) authorityAddr, err := cdcOpts.GetAddressCodec().BytesToString(authtypes.NewModuleAddress("gov")) require.NoError(t, err) @@ -266,7 +266,7 @@ func TestAllocateTokensTruncation(t *testing.T) { accountKeeper.EXPECT().GetModuleAccount(gomock.Any(), "fee_collector").Return(feeCollectorAcc) stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec("cosmosvaloper")).AnyTimes() - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) authorityAddr, err := cdcOpts.GetAddressCodec().BytesToString(authtypes.NewModuleAddress("gov")) require.NoError(t, err) diff --git a/x/distribution/keeper/delegation.go b/x/distribution/keeper/delegation.go index e175d48795b6c..7bf2091edb897 100644 --- a/x/distribution/keeper/delegation.go +++ b/x/distribution/keeper/delegation.go @@ -52,12 +52,12 @@ func (k Keeper) calculateDelegationRewardsBetween(ctx context.Context, val sdk.V ) (sdk.DecCoins, error) { // sanity check if startingPeriod > endingPeriod { - return sdk.DecCoins{}, fmt.Errorf("startingPeriod cannot be greater than endingPeriod") + return sdk.DecCoins{}, errors.New("startingPeriod cannot be greater than endingPeriod") } // sanity check if stake.IsNegative() { - return sdk.DecCoins{}, fmt.Errorf("stake should not be negative") + return sdk.DecCoins{}, errors.New("stake should not be negative") } valBz, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) @@ -78,7 +78,7 @@ func (k Keeper) calculateDelegationRewardsBetween(ctx context.Context, val sdk.V difference := ending.CumulativeRewardRatio.Sub(starting.CumulativeRewardRatio) if difference.IsAnyNegative() { - return sdk.DecCoins{}, fmt.Errorf("negative rewards should not be possible") + return sdk.DecCoins{}, errors.New("negative rewards should not be possible") } // note: necessary to truncate so we don't allow withdrawing more rewards than owed rewards := difference.MulDecTruncate(stake) diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index f1bae825e36dd..76bcfb628787b 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -8,7 +8,7 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -42,7 +42,7 @@ func TestCalculateRewardsBasic(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) authorityAddr, err := accountKeeper.AddressCodec().BytesToString(authtypes.NewModuleAddress("gov")) require.NoError(t, err) @@ -156,7 +156,7 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) authorityAddr, err := accountKeeper.AddressCodec().BytesToString(authtypes.NewModuleAddress("gov")) require.NoError(t, err) @@ -273,7 +273,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) authorityAddr, err := accountKeeper.AddressCodec().BytesToString(authtypes.NewModuleAddress("gov")) require.NoError(t, err) @@ -411,7 +411,7 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) authorityAddr, err := accountKeeper.AddressCodec().BytesToString(authtypes.NewModuleAddress("gov")) require.NoError(t, err) @@ -522,7 +522,7 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) authorityAddr, err := accountKeeper.AddressCodec().BytesToString(authtypes.NewModuleAddress("gov")) require.NoError(t, err) @@ -611,7 +611,7 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) authorityAddr, err := accountKeeper.AddressCodec().BytesToString(authtypes.NewModuleAddress("gov")) require.NoError(t, err) @@ -741,7 +741,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) authorityAddr, err := accountKeeper.AddressCodec().BytesToString(authtypes.NewModuleAddress("gov")) require.NoError(t, err) @@ -895,7 +895,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) authorityAddr, err := accountKeeper.AddressCodec().BytesToString(authtypes.NewModuleAddress("gov")) require.NoError(t, err) @@ -1110,7 +1110,7 @@ func Test100PercentCommissionReward(t *testing.T) { stakingKeeper.EXPECT().BondDenom(gomock.Any()).Return("stake", nil).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) authorityAddr, err := accountKeeper.AddressCodec().BytesToString(authtypes.NewModuleAddress("gov")) require.NoError(t, err) diff --git a/x/distribution/keeper/keeper_test.go b/x/distribution/keeper/keeper_test.go index 7833762a3b0ea..8b6afcebd9ce7 100644 --- a/x/distribution/keeper/keeper_test.go +++ b/x/distribution/keeper/keeper_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -58,7 +58,7 @@ func initFixture(t *testing.T) (sdk.Context, []sdk.AccAddress, keeper.Keeper, de bankKeeper.EXPECT().BlockedAddr(withdrawAddr).Return(false).AnyTimes() bankKeeper.EXPECT().BlockedAddr(distrAcc.GetAddress()).Return(true).AnyTimes() - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) authorityAddr, err := cdcOpts.GetAddressCodec().BytesToString(authtypes.NewModuleAddress("gov")) require.NoError(t, err) diff --git a/x/distribution/migrations/v4/migrate_test.go b/x/distribution/migrations/v4/migrate_test.go index a19ad21471872..8b5ef70c4dfee 100644 --- a/x/distribution/migrations/v4/migrate_test.go +++ b/x/distribution/migrations/v4/migrate_test.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/distribution" v4 "cosmossdk.io/x/distribution/migrations/v4" @@ -25,7 +25,7 @@ func TestMigration(t *testing.T) { tKey := storetypes.NewTransientStoreKey("transient_test") ctx := testutil.DefaultContext(storeKey, tKey) - env := runtime.NewEnvironment(storeService, log.NewNopLogger()) + env := runtime.NewEnvironment(storeService, coretesting.NewNopLogger()) addr1 := secp256k1.GenPrivKey().PubKey().Address() consAddr1 := sdk.ConsAddress(addr1) diff --git a/x/distribution/module.go b/x/distribution/module.go index ecf09808356ec..a726d91b3c9b6 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -29,7 +29,6 @@ import ( const ConsensusVersion = 4 var ( - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.AppModuleSimulation = AppModule{} @@ -63,6 +62,7 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, stakingKeeper types.Sta func (am AppModule) IsAppModule() {} // Name returns the distribution module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } diff --git a/x/distribution/simulation/genesis_test.go b/x/distribution/simulation/genesis_test.go index 0448d66909a73..6c74a5e2bffcd 100644 --- a/x/distribution/simulation/genesis_test.go +++ b/x/distribution/simulation/genesis_test.go @@ -53,7 +53,7 @@ func TestRandomizedGenState(t *testing.T) { require.Len(t, distrGenesis.ValidatorSlashEvents, 0) } -// TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. +// TestRandomizedGenState1 tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) diff --git a/x/distribution/types/params.go b/x/distribution/types/params.go index b8438ca738127..b37cd8844fe1d 100644 --- a/x/distribution/types/params.go +++ b/x/distribution/types/params.go @@ -1,6 +1,7 @@ package types import ( + "errors" "fmt" "cosmossdk.io/math" @@ -28,7 +29,7 @@ func validateCommunityTax(i interface{}) error { } if v.IsNil() { - return fmt.Errorf("community tax must be not nil") + return errors.New("community tax must be not nil") } if v.IsNegative() { return fmt.Errorf("community tax must be positive: %s", v) diff --git a/x/epochs/go.mod b/x/epochs/go.mod index e39a401767847..4642488a952e4 100644 --- a/x/epochs/go.mod +++ b/x/epochs/go.mod @@ -6,7 +6,8 @@ require ( cosmossdk.io/api v0.7.5 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc github.com/cosmos/cosmos-proto v1.0.0-beta.5 @@ -47,7 +48,7 @@ require ( github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -178,7 +179,6 @@ replace ( cosmossdk.io/api => ../../api cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/epochs/go.sum b/x/epochs/go.sum index df6c51ee037a9..496f78619dc06 100644 --- a/x/epochs/go.sum +++ b/x/epochs/go.sum @@ -6,6 +6,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -102,8 +104,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/epochs/keeper/keeper_test.go b/x/epochs/keeper/keeper_test.go index 07cc9a35eb161..19e8749248a12 100644 --- a/x/epochs/keeper/keeper_test.go +++ b/x/epochs/keeper/keeper_test.go @@ -9,7 +9,7 @@ import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" epochskeeper "cosmossdk.io/x/epochs/keeper" "cosmossdk.io/x/epochs/types" @@ -54,7 +54,7 @@ func Setup(t *testing.T) (sdk.Context, *epochskeeper.Keeper, appmodule.Environme key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) - environment := runtime.NewEnvironment(storeService, log.NewNopLogger()) + environment := runtime.NewEnvironment(storeService, coretesting.NewNopLogger()) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) encCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}) diff --git a/x/epochs/module.go b/x/epochs/module.go index 86535d79b4801..993eb8357dffa 100644 --- a/x/epochs/module.go +++ b/x/epochs/module.go @@ -21,7 +21,6 @@ import ( ) var ( - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.AppModuleSimulation = AppModule{} @@ -51,6 +50,7 @@ func NewAppModule(cdc codec.Codec, keeper *keeper.Keeper) AppModule { func (am AppModule) IsAppModule() {} // Name returns the epochs module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } diff --git a/x/evidence/go.mod b/x/evidence/go.mod index 9cf0ecc6233be..680c72d2d6ce7 100644 --- a/x/evidence/go.mod +++ b/x/evidence/go.mod @@ -6,7 +6,8 @@ require ( cosmossdk.io/api v0.7.5 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/math v1.3.0 cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc @@ -53,7 +54,7 @@ require ( github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -176,7 +177,6 @@ replace ( cosmossdk.io/api => ../../api cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/evidence/go.sum b/x/evidence/go.sum index 6a2618f159fc5..08da56c9d15ef 100644 --- a/x/evidence/go.sum +++ b/x/evidence/go.sum @@ -6,6 +6,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -102,8 +104,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/evidence/keeper/keeper_test.go b/x/evidence/keeper/keeper_test.go index 53ee2b417d26a..cb5b54bc9b4be 100644 --- a/x/evidence/keeper/keeper_test.go +++ b/x/evidence/keeper/keeper_test.go @@ -12,7 +12,7 @@ import ( "cosmossdk.io/collections" coreaddress "cosmossdk.io/core/address" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/evidence" "cosmossdk.io/x/evidence/exported" @@ -90,7 +90,7 @@ type KeeperTestSuite struct { func (suite *KeeperTestSuite) SetupTest() { encCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, evidence.AppModule{}) key := storetypes.NewKVStoreKey(types.StoreKey) - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) tkey := storetypes.NewTransientStoreKey("evidence_transient_store") testCtx := testutil.DefaultContextWithDB(suite.T(), key, tkey) suite.ctx = testCtx.Ctx diff --git a/x/evidence/module.go b/x/evidence/module.go index 9dfde118af0b0..02e4cdff9ce6b 100644 --- a/x/evidence/module.go +++ b/x/evidence/module.go @@ -26,7 +26,6 @@ import ( ) var ( - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.AppModuleSimulation = AppModule{} @@ -61,6 +60,7 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, cometService comet.Serv func (am AppModule) IsAppModule() {} // Name returns the evidence module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } diff --git a/x/evidence/types/genesis.go b/x/evidence/types/genesis.go index d9ccaefbe7290..ce9363f580259 100644 --- a/x/evidence/types/genesis.go +++ b/x/evidence/types/genesis.go @@ -1,16 +1,18 @@ package types import ( + "errors" "fmt" "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "cosmossdk.io/x/evidence/exported" "github.com/cosmos/cosmos-sdk/codec/types" ) -var _ types.UnpackInterfacesMessage = GenesisState{} +var _ gogoprotoany.UnpackInterfacesMessage = GenesisState{} // NewGenesisState creates a new genesis state for the evidence module. func NewGenesisState(e []exported.Evidence) *GenesisState { @@ -44,7 +46,7 @@ func (gs GenesisState) Validate() error { for _, e := range gs.Evidence { evi, ok := e.GetCachedValue().(exported.Evidence) if !ok { - return fmt.Errorf("expected evidence") + return errors.New("expected evidence") } if err := evi.ValidateBasic(); err != nil { return err @@ -55,7 +57,7 @@ func (gs GenesisState) Validate() error { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (gs GenesisState) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (gs GenesisState) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, any := range gs.Evidence { var evi exported.Evidence err := unpacker.UnpackAny(any, &evi) diff --git a/x/evidence/types/genesis_test.go b/x/evidence/types/genesis_test.go index 20b5967ac2eb7..786b2103f7621 100644 --- a/x/evidence/types/genesis_test.go +++ b/x/evidence/types/genesis_test.go @@ -5,6 +5,7 @@ import ( "testing" "time" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "github.com/stretchr/testify/require" "cosmossdk.io/x/evidence/exported" @@ -130,7 +131,7 @@ func TestUnpackInterfaces(t *testing.T) { testCases := []struct { msg string - unpacker codectypes.AnyUnpacker + unpacker gogoprotoany.AnyUnpacker expPass bool }{ { diff --git a/x/evidence/types/msgs.go b/x/evidence/types/msgs.go index 92df414692a55..03e70b5ab7df2 100644 --- a/x/evidence/types/msgs.go +++ b/x/evidence/types/msgs.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "cosmossdk.io/x/evidence/exported" @@ -12,9 +13,9 @@ import ( ) var ( - _ sdk.Msg = &MsgSubmitEvidence{} - _ types.UnpackInterfacesMessage = MsgSubmitEvidence{} - _ exported.MsgSubmitEvidenceI = &MsgSubmitEvidence{} + _ sdk.Msg = &MsgSubmitEvidence{} + _ gogoprotoany.UnpackInterfacesMessage = MsgSubmitEvidence{} + _ exported.MsgSubmitEvidenceI = &MsgSubmitEvidence{} ) // NewMsgSubmitEvidence returns a new MsgSubmitEvidence with a signer/submitter. @@ -51,7 +52,7 @@ func (m MsgSubmitEvidence) GetSubmitter() sdk.AccAddress { return accAddr } -func (m MsgSubmitEvidence) UnpackInterfaces(ctx types.AnyUnpacker) error { +func (m MsgSubmitEvidence) UnpackInterfaces(ctx gogoprotoany.AnyUnpacker) error { var evi exported.Evidence return ctx.UnpackAny(m.Evidence, &evi) } diff --git a/x/feegrant/basic_fee.go b/x/feegrant/basic_fee.go index 1bace70b02edc..2100cd5be3b1e 100644 --- a/x/feegrant/basic_fee.go +++ b/x/feegrant/basic_fee.go @@ -2,7 +2,7 @@ package feegrant import ( "context" - "fmt" + "errors" "time" "cosmossdk.io/core/appmodule" @@ -28,7 +28,7 @@ var _ FeeAllowanceI = (*BasicAllowance)(nil) func (a *BasicAllowance) Accept(ctx context.Context, fee sdk.Coins, _ []sdk.Msg) (bool, error) { environment, ok := ctx.Value(corecontext.EnvironmentContextKey).(appmodule.Environment) if !ok { - return false, fmt.Errorf("environment not set") + return false, errors.New("environment not set") } headerInfo := environment.HeaderService.HeaderInfo(ctx) if a.Expiration != nil && a.Expiration.Before(headerInfo.Time) { diff --git a/x/feegrant/filtered_fee.go b/x/feegrant/filtered_fee.go index 6e001ef947e95..68e2fa681cfd7 100644 --- a/x/feegrant/filtered_fee.go +++ b/x/feegrant/filtered_fee.go @@ -2,10 +2,11 @@ package feegrant import ( "context" - "fmt" + "errors" "time" "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "cosmossdk.io/core/appmodule" corecontext "cosmossdk.io/core/context" @@ -23,12 +24,12 @@ const ( ) var ( - _ FeeAllowanceI = (*AllowedMsgAllowance)(nil) - _ types.UnpackInterfacesMessage = (*AllowedMsgAllowance)(nil) + _ FeeAllowanceI = (*AllowedMsgAllowance)(nil) + _ gogoprotoany.UnpackInterfacesMessage = (*AllowedMsgAllowance)(nil) ) // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (a *AllowedMsgAllowance) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (a *AllowedMsgAllowance) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var allowance FeeAllowanceI return unpacker.UnpackAny(a.Allowance, &allowance) } @@ -99,7 +100,7 @@ func (a *AllowedMsgAllowance) allowedMsgsToMap(ctx context.Context) (map[string] msgsMap := make(map[string]bool, len(a.AllowedMessages)) environment, ok := ctx.Value(corecontext.EnvironmentContextKey).(appmodule.Environment) if !ok { - return nil, fmt.Errorf("environment not set") + return nil, errors.New("environment not set") } gasMeter := environment.GasService.GasMeter(ctx) for _, msg := range a.AllowedMessages { @@ -119,7 +120,7 @@ func (a *AllowedMsgAllowance) allMsgTypesAllowed(ctx context.Context, msgs []sdk } environment, ok := ctx.Value(corecontext.EnvironmentContextKey).(appmodule.Environment) if !ok { - return false, fmt.Errorf("environment not set") + return false, errors.New("environment not set") } gasMeter := environment.GasService.GasMeter(ctx) for _, msg := range msgs { diff --git a/x/feegrant/genesis.go b/x/feegrant/genesis.go index 83b29baeb85d2..71ddf943a3e39 100644 --- a/x/feegrant/genesis.go +++ b/x/feegrant/genesis.go @@ -1,10 +1,10 @@ package feegrant import ( - "github.com/cosmos/cosmos-sdk/codec/types" + gogoprotoany "github.com/cosmos/gogoproto/types/any" ) -var _ types.UnpackInterfacesMessage = GenesisState{} +var _ gogoprotoany.UnpackInterfacesMessage = GenesisState{} // NewGenesisState creates new GenesisState object func NewGenesisState(entries []Grant) *GenesisState { @@ -34,7 +34,7 @@ func DefaultGenesisState() *GenesisState { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (data GenesisState) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (data GenesisState) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, f := range data.Allowances { err := f.UnpackInterfaces(unpacker) if err != nil { diff --git a/x/feegrant/go.mod b/x/feegrant/go.mod index b8204421c10ec..87acb3ccf6483 100644 --- a/x/feegrant/go.mod +++ b/x/feegrant/go.mod @@ -6,7 +6,8 @@ require ( cosmossdk.io/api v0.7.5 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/math v1.3.0 cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc @@ -31,6 +32,7 @@ require ( buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2 // indirect buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2 // indirect cosmossdk.io/log v1.3.1 // indirect + cosmossdk.io/schema v0.1.1 // indirect cosmossdk.io/x/auth v0.0.0-00010101000000-000000000000 cosmossdk.io/x/consensus v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/x/protocolpool v0.0.0-20230925135524-a1bc045b3190 // indirect @@ -56,7 +58,7 @@ require ( github.com/cometbft/cometbft/api v1.0.0-rc.1 github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -120,6 +122,7 @@ require ( github.com/mitchellh/go-testing-interface v1.14.1 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mtibben/percent v0.2.1 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a // indirect github.com/oklog/run v1.1.0 // indirect github.com/pelletier/go-toml/v2 v2.2.2 // indirect @@ -171,11 +174,6 @@ require ( sigs.k8s.io/yaml v1.4.0 // indirect ) -require ( - cosmossdk.io/schema v0.1.1 // indirect - github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect -) - replace github.com/cosmos/cosmos-sdk => ../../. // TODO remove post spinning out all modules @@ -184,7 +182,6 @@ replace ( cosmossdk.io/collections => ../../collections cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/feegrant/go.sum b/x/feegrant/go.sum index 52b2532652402..5f0cfa9d7fd60 100644 --- a/x/feegrant/go.sum +++ b/x/feegrant/go.sum @@ -4,6 +4,8 @@ buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88e buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2/go.mod h1:HqcXMSa5qnNuakaMUo+hWhF51mKbcrZxGl9Vp5EeJXc= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -108,8 +110,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/feegrant/grant.go b/x/feegrant/grant.go index 0fb85dd5a2264..a483475c6b417 100644 --- a/x/feegrant/grant.go +++ b/x/feegrant/grant.go @@ -2,6 +2,7 @@ package feegrant import ( "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" errorsmod "cosmossdk.io/errors" @@ -9,7 +10,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -var _ types.UnpackInterfacesMessage = &Grant{} +var _ gogoprotoany.UnpackInterfacesMessage = &Grant{} // NewGrant creates a new FeeAllowanceGrant. func NewGrant(granter, grantee string, feeAllowance FeeAllowanceI) (Grant, error) { @@ -62,7 +63,7 @@ func (a Grant) GetGrant() (FeeAllowanceI, error) { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (a Grant) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (a Grant) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var allowance FeeAllowanceI return unpacker.UnpackAny(a.Allowance, &allowance) } diff --git a/x/feegrant/keeper/genesis_test.go b/x/feegrant/keeper/genesis_test.go index a2d2300111e9a..db7a39b67a228 100644 --- a/x/feegrant/keeper/genesis_test.go +++ b/x/feegrant/keeper/genesis_test.go @@ -7,7 +7,7 @@ import ( "github.com/golang/mock/gomock" "gotest.tools/v3/assert" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -52,7 +52,7 @@ func initFixture(t *testing.T) *genesisFixture { return &genesisFixture{ ctx: testCtx.Ctx, - feegrantKeeper: keeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()), encCfg.Codec, accountKeeper), + feegrantKeeper: keeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()), encCfg.Codec, accountKeeper), accountKeeper: accountKeeper, } } diff --git a/x/feegrant/keeper/keeper_test.go b/x/feegrant/keeper/keeper_test.go index e67a17c6a4bcd..04c11eda9d1ea 100644 --- a/x/feegrant/keeper/keeper_test.go +++ b/x/feegrant/keeper/keeper_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/suite" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -62,7 +62,7 @@ func (suite *KeeperTestSuite) SetupTest() { suite.encodedAddrs = append(suite.encodedAddrs, str) } - suite.feegrantKeeper = keeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()), encCfg.Codec, suite.accountKeeper) + suite.feegrantKeeper = keeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()), encCfg.Codec, suite.accountKeeper) suite.ctx = testCtx.Ctx suite.msgSrvr = keeper.NewMsgServerImpl(suite.feegrantKeeper) suite.atom = sdk.NewCoins(sdk.NewCoin("atom", sdkmath.NewInt(555))) diff --git a/x/feegrant/migrations/v2/store_test.go b/x/feegrant/migrations/v2/store_test.go index 59879d40014c5..31559a193239f 100644 --- a/x/feegrant/migrations/v2/store_test.go +++ b/x/feegrant/migrations/v2/store_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/feegrant" @@ -89,7 +89,7 @@ func TestMigration(t *testing.T) { } ctx = ctx.WithHeaderInfo(header.Info{Time: now.Add(30 * time.Hour)}) - require.NoError(t, v2.MigrateStore(ctx, runtime.NewEnvironment(runtime.NewKVStoreService(feegrantKey), log.NewNopLogger()), cdc)) + require.NoError(t, v2.MigrateStore(ctx, runtime.NewEnvironment(runtime.NewKVStoreService(feegrantKey), coretesting.NewNopLogger()), cdc)) store = ctx.KVStore(feegrantKey) require.NotNil(t, store.Get(v2.FeeAllowanceKey(granter1, grantee1))) diff --git a/x/feegrant/module/abci_test.go b/x/feegrant/module/abci_test.go index 0241165fa24b1..feeead80a5f63 100644 --- a/x/feegrant/module/abci_test.go +++ b/x/feegrant/module/abci_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -49,7 +49,7 @@ func TestFeegrantPruning(t *testing.T) { ac := address.NewBech32Codec("cosmos") accountKeeper.EXPECT().AddressCodec().Return(ac).AnyTimes() - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) feegrantKeeper := keeper.NewKeeper(env, encCfg.Codec, accountKeeper) diff --git a/x/feegrant/module/module.go b/x/feegrant/module/module.go index a823ad7dde946..dbb3d295939df 100644 --- a/x/feegrant/module/module.go +++ b/x/feegrant/module/module.go @@ -24,7 +24,6 @@ import ( ) var ( - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.AppModuleSimulation = AppModule{} @@ -58,6 +57,7 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, registry cdctypes.Inter func (AppModule) IsAppModule() {} // Name returns the feegrant module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return feegrant.ModuleName } diff --git a/x/feegrant/msgs.go b/x/feegrant/msgs.go index c049c73d4f3f4..e79c5ce39ab94 100644 --- a/x/feegrant/msgs.go +++ b/x/feegrant/msgs.go @@ -2,6 +2,7 @@ package feegrant import ( "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" errorsmod "cosmossdk.io/errors" @@ -11,8 +12,8 @@ import ( ) var ( - _, _ sdk.Msg = &MsgGrantAllowance{}, &MsgRevokeAllowance{} - _ types.UnpackInterfacesMessage = &MsgGrantAllowance{} + _, _ sdk.Msg = &MsgGrantAllowance{}, &MsgRevokeAllowance{} + _ gogoprotoany.UnpackInterfacesMessage = &MsgGrantAllowance{} ) // NewMsgGrantAllowance creates a new MsgGrantAllowance. @@ -44,7 +45,7 @@ func (msg MsgGrantAllowance) GetFeeAllowanceI() (FeeAllowanceI, error) { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (msg MsgGrantAllowance) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (msg MsgGrantAllowance) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var allowance FeeAllowanceI return unpacker.UnpackAny(msg.Allowance, &allowance) } diff --git a/x/genutil/client/cli/commands.go b/x/genutil/client/cli/commands.go index 6e0c50ee608c9..4793db294eb10 100644 --- a/x/genutil/client/cli/commands.go +++ b/x/genutil/client/cli/commands.go @@ -21,13 +21,13 @@ type genesisMM interface { } // Commands adds core sdk's sub-commands into genesis command. -func Commands(txConfig client.TxConfig, genutilModule genutil.AppModule, genMM genesisMM, appExport servertypes.AppExporter) *cobra.Command { - return CommandsWithCustomMigrationMap(txConfig, genutilModule, genMM, appExport, MigrationMap) +func Commands(genutilModule genutil.AppModule, genMM genesisMM, appExport servertypes.AppExporter) *cobra.Command { + return CommandsWithCustomMigrationMap(genutilModule, genMM, appExport, MigrationMap) } // CommandsWithCustomMigrationMap adds core sdk's sub-commands into genesis command with custom migration map. // This custom migration map can be used by the application to add its own migration map. -func CommandsWithCustomMigrationMap(txConfig client.TxConfig, genutilModule genutil.AppModule, genMM genesisMM, appExport servertypes.AppExporter, migrationMap genutiltypes.MigrationMap) *cobra.Command { +func CommandsWithCustomMigrationMap(genutilModule genutil.AppModule, genMM genesisMM, appExport servertypes.AppExporter, migrationMap genutiltypes.MigrationMap) *cobra.Command { cmd := &cobra.Command{ Use: "genesis", Short: "Application's genesis-related subcommands", @@ -36,11 +36,11 @@ func CommandsWithCustomMigrationMap(txConfig client.TxConfig, genutilModule genu RunE: client.ValidateCmd, } cmd.AddCommand( - GenTxCmd(genMM, txConfig, banktypes.GenesisBalancesIterator{}, txConfig.SigningContext().ValidatorAddressCodec()), + GenTxCmd(genMM, banktypes.GenesisBalancesIterator{}), MigrateGenesisCmd(migrationMap), CollectGenTxsCmd(genutilModule.GenTxValidator()), ValidateGenesisCmd(genMM), - AddGenesisAccountCmd(txConfig.SigningContext().AddressCodec()), + AddGenesisAccountCmd(), ExportCmd(appExport), ) diff --git a/x/genutil/client/cli/export_test.go b/x/genutil/client/cli/export_test.go index e492e100b11f3..f5f8c570d3347 100644 --- a/x/genutil/client/cli/export_test.go +++ b/x/genutil/client/cli/export_test.go @@ -3,7 +3,7 @@ package cli_test import ( "context" "encoding/json" - "fmt" + "errors" "io" "os" "path/filepath" @@ -164,7 +164,7 @@ func (e *mockExporter) Export( modulesToExport []string, ) (types.ExportedApp, error) { if e.Err == nil && isZeroExportedApp(e.ExportApp) { - panic(fmt.Errorf("(*mockExporter).Export called without setting e.ExportApp or e.Err")) + panic(errors.New("(*mockExporter).Export called without setting e.ExportApp or e.Err")) } e.WasCalled = true @@ -311,7 +311,7 @@ func TestExportCLI(t *testing.T) { t.Parallel() e := new(mockExporter) - e.Err = fmt.Errorf("whoopsie") + e.Err = errors.New("whoopsie") sys := NewExportSystem(t, e.Export) _ = sys.MustRun(t, "init", "some_moniker") diff --git a/x/genutil/client/cli/genaccount.go b/x/genutil/client/cli/genaccount.go index 8debe3f97a6df..bafd4f2f94265 100644 --- a/x/genutil/client/cli/genaccount.go +++ b/x/genutil/client/cli/genaccount.go @@ -6,8 +6,6 @@ import ( "github.com/spf13/cobra" - "cosmossdk.io/core/address" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -25,7 +23,7 @@ const ( // AddGenesisAccountCmd returns add-genesis-account cobra Command. // This command is provided as a default, applications are expected to provide their own command if custom genesis accounts are needed. -func AddGenesisAccountCmd(addressCodec address.Codec) *cobra.Command { +func AddGenesisAccountCmd() *cobra.Command { cmd := &cobra.Command{ Use: "add-genesis-account [address_or_key_name] [coin][,[coin]]", Short: "Add a genesis account to genesis.json", @@ -39,6 +37,7 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa clientCtx := client.GetClientContextFromCmd(cmd) config := client.GetConfigFromCmd(cmd) + addressCodec := clientCtx.TxConfig.SigningContext().AddressCodec() var kr keyring.Keyring addr, err := addressCodec.StringToBytes(args[0]) if err != nil { diff --git a/x/genutil/client/cli/genaccount_test.go b/x/genutil/client/cli/genaccount_test.go index d2c6c08b67481..9acf60e29ade4 100644 --- a/x/genutil/client/cli/genaccount_test.go +++ b/x/genutil/client/cli/genaccount_test.go @@ -12,7 +12,6 @@ import ( "cosmossdk.io/x/auth" "github.com/cosmos/cosmos-sdk/client" - addresscodec "github.com/cosmos/cosmos-sdk/codec/address" codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -71,15 +70,18 @@ func TestAddGenesisAccountCmd(t *testing.T) { t.Run(tc.name, func(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() - viper := viper.New() + v := viper.New() - appCodec := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, auth.AppModule{}).Codec + encodingConfig := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, auth.AppModule{}) + appCodec := encodingConfig.Codec + txConfig := encodingConfig.TxConfig err = genutiltest.ExecInitCmd(testMbm, home, appCodec) require.NoError(t, err) - err := writeAndTrackDefaultConfig(viper, home) + err := writeAndTrackDefaultConfig(v, home) require.NoError(t, err) - clientCtx := client.Context{}.WithCodec(appCodec).WithHomeDir(home).WithAddressCodec(ac) + clientCtx := client.Context{}.WithCodec(appCodec).WithHomeDir(home). + WithAddressCodec(ac).WithTxConfig(txConfig) if tc.withKeyring { path := hd.CreateHDPath(118, 0, 0).String() @@ -92,10 +94,10 @@ func TestAddGenesisAccountCmd(t *testing.T) { ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - ctx = context.WithValue(ctx, corectx.ViperContextKey, viper) + ctx = context.WithValue(ctx, corectx.ViperContextKey, v) ctx = context.WithValue(ctx, corectx.LoggerContextKey, logger) - cmd := genutilcli.AddGenesisAccountCmd(addresscodec.NewBech32Codec("cosmos")) + cmd := genutilcli.AddGenesisAccountCmd() cmd.SetArgs([]string{ tc.addr, tc.denom, diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 695eadcb240a5..8e13028633209 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -11,7 +11,6 @@ import ( "github.com/spf13/cobra" - "cosmossdk.io/core/address" "cosmossdk.io/errors" authclient "cosmossdk.io/x/auth/client" "cosmossdk.io/x/staking/client/cli" @@ -28,7 +27,7 @@ import ( ) // GenTxCmd builds the application's gentx command. -func GenTxCmd(genMM genesisMM, txEncCfg client.TxEncodingConfig, genBalIterator types.GenesisBalancesIterator, valAdddressCodec address.Codec) *cobra.Command { +func GenTxCmd(genMM genesisMM, genBalIterator types.GenesisBalancesIterator) *cobra.Command { ipDefault, _ := server.ExternalIP() fsCreateValidator, defaultsDesc := cli.CreateValidatorMsgFlagSet(ipDefault) @@ -139,11 +138,7 @@ $ %s gentx my-key-name 1000000stake --home=/path/to/home/dir --keyring-backend=o return err } - pub, err := key.GetAddress() - if err != nil { - return err - } - clientCtx = clientCtx.WithInput(inBuf).WithFromAddress(pub) + clientCtx = clientCtx.WithInput(inBuf).WithFromAddress(addr) // The following line comes from a discrepancy between the `gentx` // and `create-validator` commands: @@ -159,7 +154,7 @@ $ %s gentx my-key-name 1000000stake --home=/path/to/home/dir --keyring-backend=o createValCfg.Amount = amount // create a 'create-validator' message - txBldr, msg, err := cli.BuildCreateValidatorMsg(clientCtx, createValCfg, txFactory, true, valAdddressCodec) + txBldr, msg, err := cli.BuildCreateValidatorMsg(clientCtx, createValCfg, txFactory, true) if err != nil { return errors.Wrap(err, "failed to build create-validator message") } diff --git a/x/genutil/client/cli/gentx_test.go b/x/genutil/client/cli/gentx_test.go index fac78ec67721f..1991822b0a9c2 100644 --- a/x/genutil/client/cli/gentx_test.go +++ b/x/genutil/client/cli/gentx_test.go @@ -17,7 +17,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec/address" codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" "github.com/cosmos/cosmos-sdk/crypto/keyring" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" @@ -124,7 +123,7 @@ func (s *CLITestSuite) TestGenTxCmd() { clientCtx := s.clientCtx ctx := svrcmd.CreateExecuteContext(context.Background()) - cmd := cli.GenTxCmd(module.NewManager(), clientCtx.TxConfig, banktypes.GenesisBalancesIterator{}, address.NewBech32Codec("cosmosvaloper")) + cmd := cli.GenTxCmd(module.NewManager(), banktypes.GenesisBalancesIterator{}) cmd.SetContext(ctx) cmd.SetArgs(tc.args) diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 6fbf9f5a6f475..557050b10aeef 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -89,6 +89,9 @@ func InitCmd(mm genesisMM) *cobra.Command { default: chainID = fmt.Sprintf("test-chain-%v", unsafe.Str(6)) } + if config.RootDir == "" { + config.RootDir = clientCtx.HomeDir + } // Get bip39 mnemonic var mnemonic string diff --git a/x/genutil/module.go b/x/genutil/module.go index 89cc972b7113f..df3b8d85dd518 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -16,7 +16,6 @@ import ( ) var ( - _ module.HasName = AppModule{} _ module.HasABCIGenesis = AppModule{} _ appmodule.AppModule = AppModule{} @@ -56,6 +55,7 @@ func NewAppModule( func (AppModule) IsAppModule() {} // Name returns the genutil module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } diff --git a/x/genutil/types/genesis.go b/x/genutil/types/genesis.go index bfbb17b15533d..f4b2d53f9dabe 100644 --- a/x/genutil/types/genesis.go +++ b/x/genutil/types/genesis.go @@ -209,7 +209,7 @@ func (cs *ConsensusGenesis) UnmarshalJSON(b []byte) error { func (cs *ConsensusGenesis) ValidateAndComplete() error { if cs == nil { - return fmt.Errorf("consensus genesis cannot be nil") + return errors.New("consensus genesis cannot be nil") } if cs.Params == nil { diff --git a/x/genutil/utils.go b/x/genutil/utils.go index e06e440d9a201..b20b7bfa6ec86 100644 --- a/x/genutil/utils.go +++ b/x/genutil/utils.go @@ -2,6 +2,7 @@ package genutil import ( "encoding/json" + "errors" "fmt" "os" "path/filepath" @@ -60,7 +61,7 @@ func InitializeNodeValidatorFilesFromMnemonic(config *cfg.Config, mnemonic, keyT nodeID string, valPubKey cryptotypes.PubKey, err error, ) { if len(mnemonic) > 0 && !bip39.IsMnemonicValid(mnemonic) { - return "", nil, fmt.Errorf("invalid mnemonic") + return "", nil, errors.New("invalid mnemonic") } nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile()) if err != nil { @@ -103,7 +104,7 @@ func InitializeNodeValidatorFilesFromMnemonic(config *cfg.Config, mnemonic, keyT privKey = tmed25519.GenPrivKeyFromSecret([]byte(mnemonic)) case "bls12_381": // TODO: need to add support for getting from mnemonic in Comet. - return "", nil, fmt.Errorf("BLS key type does not support mnemonic") + return "", nil, errors.New("BLS key type does not support mnemonic") default: privKey = tmed25519.GenPrivKeyFromSecret([]byte(mnemonic)) } diff --git a/x/gov/client/cli/util.go b/x/gov/client/cli/util.go index 166a4c7077da8..f8628f9cffed4 100644 --- a/x/gov/client/cli/util.go +++ b/x/gov/client/cli/util.go @@ -2,6 +2,7 @@ package cli import ( "encoding/json" + "errors" "fmt" "os" "strings" @@ -28,15 +29,15 @@ type legacyProposal struct { // validate the legacyProposal func (p legacyProposal) validate() error { if p.Type == "" { - return fmt.Errorf("proposal type is required") + return errors.New("proposal type is required") } if p.Title == "" { - return fmt.Errorf("proposal title is required") + return errors.New("proposal title is required") } if p.Description == "" { - return fmt.Errorf("proposal description is required") + return errors.New("proposal description is required") } return nil } diff --git a/x/gov/go.mod b/x/gov/go.mod index 4687e9ef4091f..c15954f2056ae 100644 --- a/x/gov/go.mod +++ b/x/gov/go.mod @@ -3,22 +3,20 @@ module cosmossdk.io/x/gov go 1.22.2 require ( - buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2 // indirect cosmossdk.io/api v0.7.5 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/log v1.3.1 // indirect cosmossdk.io/math v1.3.0 cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc cosmossdk.io/x/auth v0.0.0-00010101000000-000000000000 cosmossdk.io/x/bank v0.0.0-20240226161501-23359a0b6d91 - cosmossdk.io/x/consensus v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/x/protocolpool v0.0.0-20230925135524-a1bc045b3190 cosmossdk.io/x/staking v0.0.0-00010101000000-000000000000 github.com/chzyer/readline v1.5.1 - github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect github.com/cometbft/cometbft v1.0.0-rc1 github.com/cosmos/cosmos-proto v1.0.0-beta.5 github.com/cosmos/cosmos-sdk v0.51.0 @@ -39,6 +37,9 @@ require ( require ( buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2 // indirect + buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2 // indirect + cosmossdk.io/schema v0.1.1 // indirect + cosmossdk.io/x/consensus v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/x/tx v0.13.3 // indirect filippo.io/edwards25519 v1.1.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect @@ -54,11 +55,12 @@ require ( github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect github.com/cockroachdb/pebble v1.1.0 // indirect github.com/cockroachdb/redact v1.1.5 // indirect + github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect github.com/cometbft/cometbft-db v0.12.0 // indirect github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -121,6 +123,7 @@ require ( github.com/mitchellh/go-testing-interface v1.14.1 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mtibben/percent v0.2.1 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a // indirect github.com/oklog/run v1.1.0 // indirect github.com/pelletier/go-toml/v2 v2.2.2 // indirect @@ -170,11 +173,6 @@ require ( sigs.k8s.io/yaml v1.4.0 // indirect ) -require ( - cosmossdk.io/schema v0.1.1 // indirect - github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect -) - replace github.com/cosmos/cosmos-sdk => ../../. // TODO remove post spinning out all modules @@ -183,7 +181,6 @@ replace ( cosmossdk.io/collections => ../../collections cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/gov/go.sum b/x/gov/go.sum index 52db8c4b46155..94340b7551c8d 100644 --- a/x/gov/go.sum +++ b/x/gov/go.sum @@ -4,6 +4,8 @@ buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88e buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2/go.mod h1:HqcXMSa5qnNuakaMUo+hWhF51mKbcrZxGl9Vp5EeJXc= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -106,8 +108,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/gov/keeper/common_test.go b/x/gov/keeper/common_test.go index e6d1dbea95c15..7a59f7e5a42e3 100644 --- a/x/gov/keeper/common_test.go +++ b/x/gov/keeper/common_test.go @@ -1,6 +1,7 @@ package keeper_test import ( + "errors" "fmt" "testing" "time" @@ -9,7 +10,7 @@ import ( "github.com/stretchr/testify/require" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -126,14 +127,14 @@ func setupGovKeeper(t *testing.T, expectations ...func(sdk.Context, mocks)) ( baseApp := baseapp.NewBaseApp( "authz", - log.NewNopLogger(), + coretesting.NewNopLogger(), testCtx.DB, encCfg.TxConfig.TxDecoder(), ) baseApp.SetCMS(testCtx.CMS) baseApp.SetInterfaceRegistry(encCfg.InterfaceRegistry) - environment := runtime.NewEnvironment(storeService, log.NewNopLogger(), runtime.EnvWithQueryRouterService(baseApp.GRPCQueryRouter()), runtime.EnvWithMsgRouterService(baseApp.MsgServiceRouter())) + environment := runtime.NewEnvironment(storeService, coretesting.NewNopLogger(), runtime.EnvWithQueryRouterService(baseApp.GRPCQueryRouter()), runtime.EnvWithMsgRouterService(baseApp.MsgServiceRouter())) // gomock initializations ctrl := gomock.NewController(t) @@ -192,14 +193,14 @@ func setupGovKeeperWithMaxVoteOptionsLen(t *testing.T, maxVoteOptionsLen uint64, baseApp := baseapp.NewBaseApp( "authz", - log.NewNopLogger(), + coretesting.NewNopLogger(), testCtx.DB, encCfg.TxConfig.TxDecoder(), ) baseApp.SetCMS(testCtx.CMS) baseApp.SetInterfaceRegistry(encCfg.InterfaceRegistry) - environment := runtime.NewEnvironment(storeService, log.NewNopLogger(), runtime.EnvWithQueryRouterService(baseApp.GRPCQueryRouter()), runtime.EnvWithMsgRouterService(baseApp.MsgServiceRouter())) + environment := runtime.NewEnvironment(storeService, coretesting.NewNopLogger(), runtime.EnvWithQueryRouterService(baseApp.GRPCQueryRouter()), runtime.EnvWithMsgRouterService(baseApp.MsgServiceRouter())) // gomock initializations ctrl := gomock.NewController(t) @@ -266,7 +267,7 @@ func trackMockBalances(bankKeeper *govtestutil.MockBankKeeper) error { } newBalance, negative := balances[senderAddr].SafeSub(coins...) if negative { - return fmt.Errorf("not enough balance") + return errors.New("not enough balance") } balances[senderAddr] = newBalance return nil diff --git a/x/gov/module.go b/x/gov/module.go index d46d514f0b412..63e48236fbad3 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -30,7 +30,6 @@ import ( const ConsensusVersion = 6 var ( - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.AppModuleSimulation = AppModule{} @@ -75,6 +74,7 @@ func NewAppModule( func (am AppModule) IsAppModule() {} // Name returns the gov module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return govtypes.ModuleName } diff --git a/x/gov/simulation/genesis_test.go b/x/gov/simulation/genesis_test.go index ce0a2c45acfb4..215225085d3ae 100644 --- a/x/gov/simulation/genesis_test.go +++ b/x/gov/simulation/genesis_test.go @@ -77,7 +77,7 @@ func TestRandomizedGenState(t *testing.T) { require.Equal(t, []*v1.Proposal{}, govGenesis.Proposals) } -// TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. +// TestRandomizedGenState1 tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) diff --git a/x/gov/types/v1/genesis.go b/x/gov/types/v1/genesis.go index 21721e4b024ed..e4a8ae2805094 100644 --- a/x/gov/types/v1/genesis.go +++ b/x/gov/types/v1/genesis.go @@ -4,11 +4,10 @@ import ( "errors" "fmt" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "golang.org/x/sync/errgroup" "cosmossdk.io/core/address" - - "github.com/cosmos/cosmos-sdk/codec/types" ) // NewGenesisState creates a new genesis state for the governance module @@ -107,10 +106,10 @@ func ValidateGenesis(ac address.Codec, data *GenesisState) error { return errGroup.Wait() } -var _ types.UnpackInterfacesMessage = GenesisState{} +var _ gogoprotoany.UnpackInterfacesMessage = GenesisState{} // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (data GenesisState) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (data GenesisState) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, p := range data.Proposals { err := p.UnpackInterfaces(unpacker) if err != nil { diff --git a/x/gov/types/v1/msgs.go b/x/gov/types/v1/msgs.go index d25a9ed33aad1..70b4b90c5c737 100644 --- a/x/gov/types/v1/msgs.go +++ b/x/gov/types/v1/msgs.go @@ -4,6 +4,8 @@ import ( "errors" "fmt" + gogoprotoany "github.com/cosmos/gogoproto/types/any" + "cosmossdk.io/x/gov/types/v1beta1" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -12,8 +14,8 @@ import ( ) var ( - _, _, _, _, _, _, _, _ sdk.Msg = &MsgSubmitProposal{}, &MsgDeposit{}, &MsgVote{}, &MsgVoteWeighted{}, &MsgExecLegacyContent{}, &MsgUpdateParams{}, &MsgCancelProposal{}, &MsgSubmitMultipleChoiceProposal{} - _, _ codectypes.UnpackInterfacesMessage = &MsgSubmitProposal{}, &MsgExecLegacyContent{} + _, _, _, _, _, _, _, _ sdk.Msg = &MsgSubmitProposal{}, &MsgDeposit{}, &MsgVote{}, &MsgVoteWeighted{}, &MsgExecLegacyContent{}, &MsgUpdateParams{}, &MsgCancelProposal{}, &MsgSubmitMultipleChoiceProposal{} + _, _ gogoprotoany.UnpackInterfacesMessage = &MsgSubmitProposal{}, &MsgExecLegacyContent{} ) // NewMsgSubmitProposal creates a new MsgSubmitProposal. @@ -60,7 +62,7 @@ func (m *MsgSubmitProposal) SetMsgs(msgs []sdk.Msg) error { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (m MsgSubmitProposal) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (m MsgSubmitProposal) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { return sdktx.UnpackInterfaces(unpacker, m.Messages) } @@ -120,7 +122,7 @@ func (c MsgExecLegacyContent) ValidateBasic() error { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (c MsgExecLegacyContent) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (c MsgExecLegacyContent) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var content v1beta1.Content return unpacker.UnpackAny(c.Content, &content) } diff --git a/x/gov/types/v1/proposal.go b/x/gov/types/v1/proposal.go index be5931c217aec..e9a901934c584 100644 --- a/x/gov/types/v1/proposal.go +++ b/x/gov/types/v1/proposal.go @@ -5,7 +5,8 @@ import ( "strings" "time" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" + gogoprotoany "github.com/cosmos/gogoproto/types/any" + sdk "github.com/cosmos/cosmos-sdk/types" sdktx "github.com/cosmos/cosmos-sdk/types/tx" ) @@ -74,14 +75,14 @@ func (p Proposal) GetMinDepositFromParams(params Params) sdk.Coins { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (p Proposal) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (p Proposal) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { return sdktx.UnpackInterfaces(unpacker, p.Messages) } // Proposals is an array of proposal type Proposals []*Proposal -var _ codectypes.UnpackInterfacesMessage = Proposals{} +var _ gogoprotoany.UnpackInterfacesMessage = Proposals{} // String implements stringer interface func (p Proposals) String() string { @@ -94,7 +95,7 @@ func (p Proposals) String() string { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (p Proposals) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (p Proposals) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, x := range p { err := x.UnpackInterfaces(unpacker) if err != nil { diff --git a/x/gov/types/v1beta1/genesis.go b/x/gov/types/v1beta1/genesis.go index d71c008d88605..d2c288574db6d 100644 --- a/x/gov/types/v1beta1/genesis.go +++ b/x/gov/types/v1beta1/genesis.go @@ -3,9 +3,9 @@ package v1beta1 import ( "fmt" - "cosmossdk.io/math" + gogoprotoany "github.com/cosmos/gogoproto/types/any" - "github.com/cosmos/cosmos-sdk/codec/types" + "cosmossdk.io/math" ) // NewGenesisState creates a new genesis state for the governance module @@ -66,10 +66,10 @@ func ValidateGenesis(data *GenesisState) error { return nil } -var _ types.UnpackInterfacesMessage = GenesisState{} +var _ gogoprotoany.UnpackInterfacesMessage = GenesisState{} // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (data GenesisState) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (data GenesisState) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, p := range data.Proposals { err := p.UnpackInterfaces(unpacker) if err != nil { diff --git a/x/gov/types/v1beta1/msgs.go b/x/gov/types/v1beta1/msgs.go index 298f26c592eb0..984bed1500933 100644 --- a/x/gov/types/v1beta1/msgs.go +++ b/x/gov/types/v1beta1/msgs.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -20,7 +21,7 @@ const ( var ( _, _, _, _ sdk.Msg = &MsgSubmitProposal{}, &MsgDeposit{}, &MsgVote{}, &MsgVoteWeighted{} - _ codectypes.UnpackInterfacesMessage = &MsgSubmitProposal{} + _ gogoprotoany.UnpackInterfacesMessage = &MsgSubmitProposal{} ) // NewMsgSubmitProposal creates a new MsgSubmitProposal. @@ -73,7 +74,7 @@ func (m *MsgSubmitProposal) SetContent(content Content) error { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (m MsgSubmitProposal) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (m MsgSubmitProposal) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var content Content return unpacker.UnpackAny(m.Content, &content) } diff --git a/x/gov/types/v1beta1/proposal.go b/x/gov/types/v1beta1/proposal.go index b29753edb33b5..8143014068617 100644 --- a/x/gov/types/v1beta1/proposal.go +++ b/x/gov/types/v1beta1/proposal.go @@ -7,6 +7,7 @@ import ( "time" "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" errorsmod "cosmossdk.io/errors" "cosmossdk.io/x/gov/types" @@ -81,7 +82,7 @@ func (p Proposal) GetTitle() string { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (p Proposal) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (p Proposal) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var content Content return unpacker.UnpackAny(p.Content, &content) } @@ -89,7 +90,7 @@ func (p Proposal) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { // Proposals is an array of proposal type Proposals []Proposal -var _ codectypes.UnpackInterfacesMessage = Proposals{} +var _ gogoprotoany.UnpackInterfacesMessage = Proposals{} // Equal returns true if two slices (order-dependant) of proposals are equal. func (p Proposals) Equal(other Proposals) bool { @@ -118,7 +119,7 @@ func (p Proposals) String() string { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (p Proposals) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (p Proposals) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, x := range p { err := x.UnpackInterfaces(unpacker) if err != nil { diff --git a/x/group/client/cli/util.go b/x/group/client/cli/util.go index 7b5cc73591553..162a7addd3108 100644 --- a/x/group/client/cli/util.go +++ b/x/group/client/cli/util.go @@ -2,6 +2,7 @@ package cli import ( "encoding/json" + "errors" "fmt" "os" @@ -14,7 +15,7 @@ import ( // parseDecisionPolicy reads and parses the decision policy. func parseDecisionPolicy(cdc codec.Codec, decisionPolicyFile string) (group.DecisionPolicy, error) { if decisionPolicyFile == "" { - return nil, fmt.Errorf("decision policy is required") + return nil, errors.New("decision policy is required") } contents, err := os.ReadFile(decisionPolicyFile) diff --git a/x/group/genesis.go b/x/group/genesis.go index eccf1f941e05d..2a7e073890bae 100644 --- a/x/group/genesis.go +++ b/x/group/genesis.go @@ -3,9 +3,10 @@ package group import ( "fmt" + gogoprotoany "github.com/cosmos/gogoproto/types/any" + errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/codec/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -83,7 +84,7 @@ func (s GenesisState) Validate() error { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (s GenesisState) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (s GenesisState) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { for _, g := range s.GroupPolicies { err := g.UnpackInterfaces(unpacker) if err != nil { diff --git a/x/group/go.mod b/x/group/go.mod index e2881115810e9..e0b54245f1d7a 100644 --- a/x/group/go.mod +++ b/x/group/go.mod @@ -5,7 +5,7 @@ go 1.22.2 require ( cosmossdk.io/api v0.7.5 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/log v1.3.1 cosmossdk.io/math v1.3.0 @@ -66,7 +66,7 @@ require ( github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect github.com/cometbft/cometbft-db v0.12.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -188,7 +188,6 @@ replace ( cosmossdk.io/collections => ../../collections cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/accounts/defaults/multisig => ../accounts/defaults/multisig diff --git a/x/group/go.sum b/x/group/go.sum index 66266e9c680de..64812e2010477 100644 --- a/x/group/go.sum +++ b/x/group/go.sum @@ -4,6 +4,8 @@ buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88e buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2/go.mod h1:HqcXMSa5qnNuakaMUo+hWhF51mKbcrZxGl9Vp5EeJXc= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -112,8 +114,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/group/internal/math/dec.go b/x/group/internal/math/dec.go index 02a0ca847678f..973aa7024a40b 100644 --- a/x/group/internal/math/dec.go +++ b/x/group/internal/math/dec.go @@ -2,12 +2,12 @@ package math import ( - "fmt" + "errors" "github.com/cockroachdb/apd/v2" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/x/group/errors" + grouperrors "cosmossdk.io/x/group/errors" ) // Dec is a wrapper struct around apd.Decimal that does no mutation of apd.Decimal's when performing @@ -23,10 +23,10 @@ type Dec struct { func NewPositiveDecFromString(s string) (Dec, error) { d, err := NewDecFromString(s) if err != nil { - return Dec{}, errors.ErrInvalidDecString.Wrap(err.Error()) + return Dec{}, grouperrors.ErrInvalidDecString.Wrap(err.Error()) } if !d.IsPositive() { - return Dec{}, errors.ErrInvalidDecString.Wrapf("expected a positive decimal, got %s", s) + return Dec{}, grouperrors.ErrInvalidDecString.Wrapf("expected a positive decimal, got %s", s) } return d, nil } @@ -34,10 +34,10 @@ func NewPositiveDecFromString(s string) (Dec, error) { func NewNonNegativeDecFromString(s string) (Dec, error) { d, err := NewDecFromString(s) if err != nil { - return Dec{}, errors.ErrInvalidDecString.Wrap(err.Error()) + return Dec{}, grouperrors.ErrInvalidDecString.Wrap(err.Error()) } if d.IsNegative() { - return Dec{}, errors.ErrInvalidDecString.Wrapf("expected a non-negative decimal, got %s", s) + return Dec{}, grouperrors.ErrInvalidDecString.Wrapf("expected a non-negative decimal, got %s", s) } return d, nil } @@ -51,11 +51,11 @@ func (x Dec) IsPositive() bool { func NewDecFromString(s string) (Dec, error) { d, _, err := apd.NewFromString(s) if err != nil { - return Dec{}, errors.ErrInvalidDecString.Wrap(err.Error()) + return Dec{}, grouperrors.ErrInvalidDecString.Wrap(err.Error()) } if d.Form != apd.Finite { - return Dec{}, errors.ErrInvalidDecString.Wrapf("expected a finite decimal, got %s", s) + return Dec{}, grouperrors.ErrInvalidDecString.Wrapf("expected a finite decimal, got %s", s) } return Dec{*d}, nil @@ -136,7 +136,7 @@ func SubNonNegative(x, y Dec) (Dec, error) { } if z.IsNegative() { - return z, fmt.Errorf("result negative during non-negative subtraction") + return z, errors.New("result negative during non-negative subtraction") } return z, nil diff --git a/x/group/internal/orm/iterator.go b/x/group/internal/orm/iterator.go index a19d238e906dc..c2612a4954fc8 100644 --- a/x/group/internal/orm/iterator.go +++ b/x/group/internal/orm/iterator.go @@ -1,13 +1,13 @@ package orm import ( - "fmt" + "errors" "reflect" "github.com/cosmos/gogoproto/proto" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/x/group/errors" + grouperrors "cosmossdk.io/x/group/errors" "github.com/cosmos/cosmos-sdk/types/query" ) @@ -20,7 +20,7 @@ const defaultPageLimit = 100 type IteratorFunc func(dest proto.Message) (RowID, error) // LoadNext loads the next value in the sequence into the pointer passed as dest and returns the key. If there -// are no more items the errors.ErrORMIteratorDone error is returned +// are no more items the grouperrors.ErrORMIteratorDone error is returned // The key is the rowID and not any MultiKeyIndex key. func (i IteratorFunc) LoadNext(dest proto.Message) (RowID, error) { return i(dest) @@ -35,10 +35,10 @@ func NewSingleValueIterator(rowID RowID, val []byte) Iterator { var closed bool return IteratorFunc(func(dest proto.Message) (RowID, error) { if dest == nil { - return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "destination object must not be nil") + return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "destination object must not be nil") } if closed || val == nil { - return nil, errors.ErrORMIteratorDone + return nil, grouperrors.ErrORMIteratorDone } closed = true return rowID, proto.Unmarshal(val, dest) @@ -48,7 +48,7 @@ func NewSingleValueIterator(rowID RowID, val []byte) Iterator { // Iterator that return ErrORMInvalidIterator only. func NewInvalidIterator() Iterator { return IteratorFunc(func(dest proto.Message) (RowID, error) { - return nil, errors.ErrORMInvalidIterator + return nil, grouperrors.ErrORMInvalidIterator }) } @@ -63,20 +63,20 @@ type LimitedIterator struct { // max can be 0 or any positive number func LimitIterator(parent Iterator, max int) (*LimitedIterator, error) { if max < 0 { - return nil, errors.ErrORMInvalidArgument.Wrap("quantity must not be negative") + return nil, grouperrors.ErrORMInvalidArgument.Wrap("quantity must not be negative") } if parent == nil { - return nil, errors.ErrORMInvalidArgument.Wrap("parent iterator must not be nil") + return nil, grouperrors.ErrORMInvalidArgument.Wrap("parent iterator must not be nil") } return &LimitedIterator{remainingCount: max, parentIterator: parent}, nil } // LoadNext loads the next value in the sequence into the pointer passed as dest and returns the key. If there -// are no more items or the defined max number of elements was returned the `errors.ErrORMIteratorDone` error is returned +// are no more items or the defined max number of elements was returned the `grouperrors.ErrORMIteratorDone` error is returned // The key is the rowID and not any MultiKeyIndex key. func (i *LimitedIterator) LoadNext(dest proto.Message) (RowID, error) { if i.remainingCount == 0 { - return nil, errors.ErrORMIteratorDone + return nil, grouperrors.ErrORMIteratorDone } i.remainingCount-- return i.parentIterator.LoadNext(dest) @@ -91,7 +91,7 @@ func (i LimitedIterator) Close() error { // When the iterator is closed or has no elements the according error is passed as return value. func First(it Iterator, dest proto.Message) (RowID, error) { if it == nil { - return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "iterator must not be nil") + return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "iterator must not be nil") } defer it.Close() binKey, err := it.LoadNext(dest) @@ -136,7 +136,7 @@ func Paginate( countTotal := pageRequest.CountTotal if offset > 0 && key != nil { - return nil, fmt.Errorf("invalid request, either offset or key is expected, got both") + return nil, errors.New("invalid request, either offset or key is expected, got both") } if limit == 0 { @@ -147,7 +147,7 @@ func Paginate( } if it == nil { - return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "iterator must not be nil") + return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "iterator must not be nil") } defer it.Close() @@ -177,11 +177,11 @@ func Paginate( modelProto, ok := model.Interface().(proto.Message) if !ok { - return nil, errorsmod.Wrapf(errors.ErrORMInvalidArgument, "%s should implement codec.ProtoMarshaler", elemType) + return nil, errorsmod.Wrapf(grouperrors.ErrORMInvalidArgument, "%s should implement codec.ProtoMarshaler", elemType) } binKey, err := it.LoadNext(modelProto) if err != nil { - if errors.ErrORMIteratorDone.Is(err) { + if grouperrors.ErrORMIteratorDone.Is(err) { break } return nil, err @@ -237,7 +237,7 @@ type ModelSlicePtr interface{} // require.NoError(t, err) func ReadAll(it Iterator, dest ModelSlicePtr) ([]RowID, error) { if it == nil { - return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "iterator must not be nil") + return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "iterator must not be nil") } defer it.Close() @@ -261,7 +261,7 @@ func ReadAll(it Iterator, dest ModelSlicePtr) ([]RowID, error) { switch { case err == nil: tmpSlice = reflect.Append(tmpSlice, val) - case errors.ErrORMIteratorDone.Is(err): + case grouperrors.ErrORMIteratorDone.Is(err): destRef.Set(tmpSlice) return rowIDs, nil default: @@ -276,14 +276,14 @@ func ReadAll(it Iterator, dest ModelSlicePtr) ([]RowID, error) { // It overwrites destRef and tmpSlice using reflection. func assertDest(dest ModelSlicePtr, destRef, tmpSlice *reflect.Value) (reflect.Type, error) { if dest == nil { - return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "destination must not be nil") + return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "destination must not be nil") } tp := reflect.ValueOf(dest) if tp.Kind() != reflect.Ptr { - return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "destination must be a pointer to a slice") + return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "destination must be a pointer to a slice") } if tp.Elem().Kind() != reflect.Slice { - return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "destination must point to a slice") + return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "destination must point to a slice") } // Since dest is just an interface{}, we overwrite destRef using reflection @@ -291,7 +291,7 @@ func assertDest(dest ModelSlicePtr, destRef, tmpSlice *reflect.Value) (reflect.T *destRef = tp.Elem() // We need to verify that we can call Set() on destRef. if !destRef.CanSet() { - return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "destination not assignable") + return nil, errorsmod.Wrap(grouperrors.ErrORMInvalidArgument, "destination not assignable") } elemType := reflect.TypeOf(dest).Elem().Elem() @@ -299,7 +299,7 @@ func assertDest(dest ModelSlicePtr, destRef, tmpSlice *reflect.Value) (reflect.T protoMarshaler := reflect.TypeOf((*proto.Message)(nil)).Elem() if !elemType.Implements(protoMarshaler) && !reflect.PtrTo(elemType).Implements(protoMarshaler) { - return nil, errorsmod.Wrapf(errors.ErrORMInvalidArgument, "unsupported type :%s", elemType) + return nil, errorsmod.Wrapf(grouperrors.ErrORMInvalidArgument, "unsupported type :%s", elemType) } // tmpSlice is a slice value for the specified type diff --git a/x/group/keeper/msg_server_test.go b/x/group/keeper/msg_server_test.go index 20eb8a7b184b0..b3100a50287fb 100644 --- a/x/group/keeper/msg_server_test.go +++ b/x/group/keeper/msg_server_test.go @@ -3,7 +3,7 @@ package keeper_test import ( "bytes" "context" - "fmt" + "errors" "sort" "strings" "time" @@ -2706,7 +2706,7 @@ func (s *TestSuite) TestExecProposal() { setupProposal: func(ctx context.Context) uint64 { msgs := []sdk.Msg{msgSend1, msgSend2} s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil) - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, fmt.Errorf("error")) + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, errors.New("error")) return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) }, @@ -2723,7 +2723,7 @@ func (s *TestSuite) TestExecProposal() { // Wait after min execution period end before Exec sdkCtx := sdk.UnwrapSDKContext(ctx) sdkCtx = sdkCtx.WithHeaderInfo(header.Info{Time: sdkCtx.HeaderInfo().Time.Add(minExecutionPeriod)}) // MinExecutionPeriod is 5s - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, fmt.Errorf("error")) + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, errors.New("error")) _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: s.addrsStr[0], ProposalId: myProposalID}) s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, nil) @@ -2902,7 +2902,7 @@ func (s *TestSuite) TestExecPrunedProposalsAndVotes() { } msgs := []sdk.Msg{msgSend1, msgSend2} - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, fmt.Errorf("error")) + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, errors.New("error")) return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) }, @@ -2920,7 +2920,7 @@ func (s *TestSuite) TestExecPrunedProposalsAndVotes() { myProposalID := submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, fmt.Errorf("error")) + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, errors.New("error")) // Wait for min execution period end sdkCtx := sdk.UnwrapSDKContext(ctx) diff --git a/x/group/module/module.go b/x/group/module/module.go index e55c398b0c9be..d38fa978e0d4a 100644 --- a/x/group/module/module.go +++ b/x/group/module/module.go @@ -30,7 +30,6 @@ import ( const ConsensusVersion = 2 var ( - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.AppModuleSimulation = AppModule{} @@ -68,6 +67,7 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak group.AccountKeeper, func (AppModule) IsAppModule() {} // Name returns the group module's name. +// Deprecated: kept for legacy reasons. func (am AppModule) Name() string { return group.ModuleName } diff --git a/x/group/msgs.go b/x/group/msgs.go index d9aad25d63b39..a9e36c207f482 100644 --- a/x/group/msgs.go +++ b/x/group/msgs.go @@ -2,6 +2,7 @@ package group import ( "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -27,9 +28,9 @@ var ( _ sdk.Msg = &MsgSubmitProposal{} _ sdk.Msg = &MsgCreateGroupPolicy{} - _ types.UnpackInterfacesMessage = MsgCreateGroupPolicy{} - _ types.UnpackInterfacesMessage = MsgUpdateGroupPolicyDecisionPolicy{} - _ types.UnpackInterfacesMessage = MsgCreateGroupWithPolicy{} + _ gogoprotoany.UnpackInterfacesMessage = MsgCreateGroupPolicy{} + _ gogoprotoany.UnpackInterfacesMessage = MsgUpdateGroupPolicyDecisionPolicy{} + _ gogoprotoany.UnpackInterfacesMessage = MsgCreateGroupWithPolicy{} ) // GetGroupID gets the group id of the MsgUpdateGroupMetadata. @@ -83,7 +84,7 @@ func (m *MsgCreateGroupWithPolicy) SetDecisionPolicy(decisionPolicy DecisionPoli } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (m MsgCreateGroupWithPolicy) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (m MsgCreateGroupWithPolicy) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var decisionPolicy DecisionPolicy return unpacker.UnpackAny(m.DecisionPolicy, &decisionPolicy) } @@ -126,7 +127,7 @@ func (m *MsgUpdateGroupPolicyDecisionPolicy) GetDecisionPolicy() (DecisionPolicy } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (m MsgUpdateGroupPolicyDecisionPolicy) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (m MsgUpdateGroupPolicyDecisionPolicy) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var decisionPolicy DecisionPolicy return unpacker.UnpackAny(m.DecisionPolicy, &decisionPolicy) } @@ -180,7 +181,7 @@ func (m *MsgCreateGroupPolicy) SetDecisionPolicy(decisionPolicy DecisionPolicy) } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (m MsgCreateGroupPolicy) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (m MsgCreateGroupPolicy) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var decisionPolicy DecisionPolicy return unpacker.UnpackAny(m.DecisionPolicy, &decisionPolicy) } @@ -218,6 +219,6 @@ func (m MsgSubmitProposal) GetMsgs() ([]sdk.Msg, error) { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (m MsgSubmitProposal) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (m MsgSubmitProposal) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { return tx.UnpackInterfaces(unpacker, m.Messages) } diff --git a/x/group/proposal.go b/x/group/proposal.go index a47ee5115c3bf..642e8981a487f 100644 --- a/x/group/proposal.go +++ b/x/group/proposal.go @@ -1,7 +1,8 @@ package group import ( - "github.com/cosmos/cosmos-sdk/codec/types" + gogoprotoany "github.com/cosmos/gogoproto/types/any" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx" ) @@ -22,6 +23,6 @@ func (p *Proposal) SetMsgs(msgs []sdk.Msg) error { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (p Proposal) UnpackInterfaces(unpacker types.AnyUnpacker) error { +func (p Proposal) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { return tx.UnpackInterfaces(unpacker, p.Messages) } diff --git a/x/group/simulation/operations.go b/x/group/simulation/operations.go new file mode 100644 index 0000000000000..d0eb1b8f79891 --- /dev/null +++ b/x/group/simulation/operations.go @@ -0,0 +1,1509 @@ +package simulation + +import ( + "context" + "fmt" + "math/rand" + "strings" + "sync/atomic" + "time" + + gogoprotoany "github.com/cosmos/gogoproto/types/any" + + "cosmossdk.io/core/address" + "cosmossdk.io/x/group" + "cosmossdk.io/x/group/keeper" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +const unsetGroupID = 100000000000000 + +// group message types +var ( + TypeMsgCreateGroup = sdk.MsgTypeURL(&group.MsgCreateGroup{}) + TypeMsgUpdateGroupMembers = sdk.MsgTypeURL(&group.MsgUpdateGroupMembers{}) + TypeMsgUpdateGroupAdmin = sdk.MsgTypeURL(&group.MsgUpdateGroupAdmin{}) + TypeMsgUpdateGroupMetadata = sdk.MsgTypeURL(&group.MsgUpdateGroupMetadata{}) + TypeMsgCreateGroupWithPolicy = sdk.MsgTypeURL(&group.MsgCreateGroupWithPolicy{}) + TypeMsgCreateGroupPolicy = sdk.MsgTypeURL(&group.MsgCreateGroupPolicy{}) + TypeMsgUpdateGroupPolicyAdmin = sdk.MsgTypeURL(&group.MsgUpdateGroupPolicyAdmin{}) + TypeMsgUpdateGroupPolicyDecisionPolicy = sdk.MsgTypeURL(&group.MsgUpdateGroupPolicyDecisionPolicy{}) + TypeMsgUpdateGroupPolicyMetadata = sdk.MsgTypeURL(&group.MsgUpdateGroupPolicyMetadata{}) + TypeMsgSubmitProposal = sdk.MsgTypeURL(&group.MsgSubmitProposal{}) + TypeMsgWithdrawProposal = sdk.MsgTypeURL(&group.MsgWithdrawProposal{}) + TypeMsgVote = sdk.MsgTypeURL(&group.MsgVote{}) + TypeMsgExec = sdk.MsgTypeURL(&group.MsgExec{}) + TypeMsgLeaveGroup = sdk.MsgTypeURL(&group.MsgLeaveGroup{}) +) + +// Simulation operation weights constants +const ( + OpMsgCreateGroup = "op_weight_msg_create_group" + OpMsgUpdateGroupAdmin = "op_weight_msg_update_group_admin" + OpMsgUpdateGroupMetadata = "op_wieght_msg_update_group_metadata" + OpMsgUpdateGroupMembers = "op_weight_msg_update_group_members" + OpMsgCreateGroupPolicy = "op_weight_msg_create_group_account" + OpMsgCreateGroupWithPolicy = "op_weight_msg_create_group_with_policy" + OpMsgUpdateGroupPolicyAdmin = "op_weight_msg_update_group_account_admin" + OpMsgUpdateGroupPolicyDecisionPolicy = "op_weight_msg_update_group_account_decision_policy" + OpMsgUpdateGroupPolicyMetaData = "op_weight_msg_update_group_account_metadata" + OpMsgSubmitProposal = "op_weight_msg_submit_proposal" + OpMsgWithdrawProposal = "op_weight_msg_withdraw_proposal" + OpMsgVote = "op_weight_msg_vote" + OpMsgExec = "ops_weight_msg_exec" + OpMsgLeaveGroup = "ops_weight_msg_leave_group" +) + +// If update group or group policy txn's executed, `SimulateMsgVote` & `SimulateMsgExec` txn's returns `noOp`. +// That's why we have less weight for update group & group-policy txn's. +const ( + WeightMsgCreateGroup = 100 + WeightMsgCreateGroupPolicy = 50 + WeightMsgSubmitProposal = 90 + WeightMsgVote = 90 + WeightMsgExec = 90 + WeightMsgLeaveGroup = 5 + WeightMsgUpdateGroupMetadata = 5 + WeightMsgUpdateGroupAdmin = 5 + WeightMsgUpdateGroupMembers = 5 + WeightMsgUpdateGroupPolicyAdmin = 5 + WeightMsgUpdateGroupPolicyDecisionPolicy = 5 + WeightMsgUpdateGroupPolicyMetadata = 5 + WeightMsgWithdrawProposal = 20 + WeightMsgCreateGroupWithPolicy = 50 +) + +// SharedState shared state between message invocations +type SharedState struct { + minGroupID atomic.Uint64 +} + +// NewSharedState constructor +func NewSharedState() *SharedState { + r := &SharedState{} + r.setMinGroupID(unsetGroupID) + return r +} + +func (s *SharedState) getMinGroupID() uint64 { + return s.minGroupID.Load() +} + +func (s *SharedState) setMinGroupID(id uint64) { + s.minGroupID.Store(id) +} + +// WeightedOperations returns all the operations from the module with their respective weights +func WeightedOperations( + registry cdctypes.InterfaceRegistry, + appParams simtypes.AppParams, cdc codec.JSONCodec, txGen client.TxConfig, + ak group.AccountKeeper, bk group.BankKeeper, k keeper.Keeper, + appCdc gogoprotoany.AnyUnpacker, +) simulation.WeightedOperations { + var ( + weightMsgCreateGroup int + weightMsgUpdateGroupAdmin int + weightMsgUpdateGroupMetadata int + weightMsgUpdateGroupMembers int + weightMsgCreateGroupPolicy int + weightMsgUpdateGroupPolicyAdmin int + weightMsgUpdateGroupPolicyDecisionPolicy int + weightMsgUpdateGroupPolicyMetadata int + weightMsgSubmitProposal int + weightMsgVote int + weightMsgExec int + weightMsgLeaveGroup int + weightMsgWithdrawProposal int + weightMsgCreateGroupWithPolicy int + ) + + appParams.GetOrGenerate(OpMsgCreateGroup, &weightMsgCreateGroup, nil, func(_ *rand.Rand) { + weightMsgCreateGroup = WeightMsgCreateGroup + }) + appParams.GetOrGenerate(OpMsgCreateGroupPolicy, &weightMsgCreateGroupPolicy, nil, func(_ *rand.Rand) { + weightMsgCreateGroupPolicy = WeightMsgCreateGroupPolicy + }) + appParams.GetOrGenerate(OpMsgLeaveGroup, &weightMsgLeaveGroup, nil, func(_ *rand.Rand) { + weightMsgLeaveGroup = WeightMsgLeaveGroup + }) + appParams.GetOrGenerate(OpMsgCreateGroupWithPolicy, &weightMsgCreateGroupWithPolicy, nil, func(_ *rand.Rand) { + weightMsgCreateGroupWithPolicy = WeightMsgCreateGroupWithPolicy + }) + appParams.GetOrGenerate(OpMsgSubmitProposal, &weightMsgSubmitProposal, nil, func(_ *rand.Rand) { + weightMsgSubmitProposal = WeightMsgSubmitProposal + }) + appParams.GetOrGenerate(OpMsgVote, &weightMsgVote, nil, func(_ *rand.Rand) { + weightMsgVote = WeightMsgVote + }) + appParams.GetOrGenerate(OpMsgExec, &weightMsgExec, nil, func(_ *rand.Rand) { + weightMsgExec = WeightMsgExec + }) + appParams.GetOrGenerate(OpMsgUpdateGroupMetadata, &weightMsgUpdateGroupMetadata, nil, func(_ *rand.Rand) { + weightMsgUpdateGroupMetadata = WeightMsgUpdateGroupMetadata + }) + appParams.GetOrGenerate(OpMsgUpdateGroupAdmin, &weightMsgUpdateGroupAdmin, nil, func(_ *rand.Rand) { + weightMsgUpdateGroupAdmin = WeightMsgUpdateGroupAdmin + }) + appParams.GetOrGenerate(OpMsgUpdateGroupMembers, &weightMsgUpdateGroupMembers, nil, func(_ *rand.Rand) { + weightMsgUpdateGroupMembers = WeightMsgUpdateGroupMembers + }) + appParams.GetOrGenerate(OpMsgUpdateGroupPolicyAdmin, &weightMsgUpdateGroupPolicyAdmin, nil, func(_ *rand.Rand) { + weightMsgUpdateGroupPolicyAdmin = WeightMsgUpdateGroupPolicyAdmin + }) + appParams.GetOrGenerate(OpMsgUpdateGroupPolicyDecisionPolicy, &weightMsgUpdateGroupPolicyDecisionPolicy, nil, func(_ *rand.Rand) { + weightMsgUpdateGroupPolicyDecisionPolicy = WeightMsgUpdateGroupPolicyDecisionPolicy + }) + appParams.GetOrGenerate(OpMsgUpdateGroupPolicyMetaData, &weightMsgUpdateGroupPolicyMetadata, nil, func(_ *rand.Rand) { + weightMsgUpdateGroupPolicyMetadata = WeightMsgUpdateGroupPolicyMetadata + }) + appParams.GetOrGenerate(OpMsgWithdrawProposal, &weightMsgWithdrawProposal, nil, func(_ *rand.Rand) { + weightMsgWithdrawProposal = WeightMsgWithdrawProposal + }) + + pCdc := codec.NewProtoCodec(registry) + + state := NewSharedState() + + // create two proposals for weightedOperations + var createProposalOps simulation.WeightedOperations + for i := 0; i < 2; i++ { + createProposalOps = append(createProposalOps, simulation.NewWeightedOperation( + weightMsgSubmitProposal, + SimulateMsgSubmitProposal(pCdc, txGen, ak, bk, k, state), + )) + } + + wPreCreateProposalOps := simulation.WeightedOperations{ + simulation.NewWeightedOperation( + weightMsgCreateGroup, + SimulateMsgCreateGroup(pCdc, txGen, ak, bk), + ), + simulation.NewWeightedOperation( + weightMsgCreateGroupPolicy, + SimulateMsgCreateGroupPolicy(pCdc, txGen, ak, bk, k, state), + ), + simulation.NewWeightedOperation( + weightMsgCreateGroupWithPolicy, + SimulateMsgCreateGroupWithPolicy(pCdc, txGen, ak, bk), + ), + } + + wPostCreateProposalOps := simulation.WeightedOperations{ + simulation.NewWeightedOperation( + WeightMsgWithdrawProposal, + SimulateMsgWithdrawProposal(pCdc, txGen, ak, bk, k, state), + ), + simulation.NewWeightedOperation( + weightMsgVote, + SimulateMsgVote(pCdc, txGen, ak, bk, k, state), + ), + simulation.NewWeightedOperation( + weightMsgExec, + SimulateMsgExec(pCdc, txGen, ak, bk, k, state), + ), + simulation.NewWeightedOperation( + weightMsgUpdateGroupMetadata, + SimulateMsgUpdateGroupMetadata(pCdc, txGen, ak, bk, k, state), + ), + simulation.NewWeightedOperation( + weightMsgUpdateGroupAdmin, + SimulateMsgUpdateGroupAdmin(pCdc, txGen, ak, bk, k, state), + ), + simulation.NewWeightedOperation( + weightMsgUpdateGroupMembers, + SimulateMsgUpdateGroupMembers(pCdc, txGen, ak, bk, k, state), + ), + simulation.NewWeightedOperation( + weightMsgUpdateGroupPolicyAdmin, + SimulateMsgUpdateGroupPolicyAdmin(pCdc, txGen, ak, bk, k, state), + ), + simulation.NewWeightedOperation( + weightMsgUpdateGroupPolicyDecisionPolicy, + SimulateMsgUpdateGroupPolicyDecisionPolicy(pCdc, txGen, ak, bk, k, state), + ), + simulation.NewWeightedOperation( + weightMsgUpdateGroupPolicyMetadata, + SimulateMsgUpdateGroupPolicyMetadata(pCdc, txGen, ak, bk, k, state), + ), + simulation.NewWeightedOperation( + weightMsgLeaveGroup, + SimulateMsgLeaveGroup(pCdc, txGen, k, ak, bk, state), + ), + } + + return append(wPreCreateProposalOps, append(createProposalOps, wPostCreateProposalOps...)...) +} + +// SimulateMsgCreateGroup generates a MsgCreateGroup with random values +func SimulateMsgCreateGroup( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + acc, _ := simtypes.RandomAcc(r, accounts) + account := ak.GetAccount(ctx, acc.Address) + accAddr, err := ak.AddressCodec().BytesToString(acc.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroup, "error getting account address"), nil, err + } + + spendableCoins := bk.SpendableCoins(ctx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroup, "fee error"), nil, err + } + + members, err := genGroupMembers(r, accounts, ak.AddressCodec()) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroup, "error generating group members"), nil, err + } + msg := &group.MsgCreateGroup{Admin: accAddr, Members: members, Metadata: simtypes.RandStringOfLength(r, 10)} + + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + acc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroup, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +// SimulateMsgCreateGroupWithPolicy generates a MsgCreateGroupWithPolicy with random values +func SimulateMsgCreateGroupWithPolicy( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + acc, _ := simtypes.RandomAcc(r, accounts) + account := ak.GetAccount(ctx, acc.Address) + accAddr, err := ak.AddressCodec().BytesToString(acc.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroup, "error getting account address"), nil, err + } + + spendableCoins := bk.SpendableCoins(ctx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroup, "fee error"), nil, err + } + + members, err := genGroupMembers(r, accounts, ak.AddressCodec()) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroup, "error generating group members"), nil, err + } + decisionPolicy := &group.ThresholdDecisionPolicy{ + Threshold: fmt.Sprintf("%d", simtypes.RandIntBetween(r, 1, 10)), + Windows: &group.DecisionPolicyWindows{ + VotingPeriod: time.Second * time.Duration(30*24*60*60), + }, + } + + msg := &group.MsgCreateGroupWithPolicy{ + Admin: accAddr, + Members: members, + GroupMetadata: simtypes.RandStringOfLength(r, 10), + GroupPolicyMetadata: simtypes.RandStringOfLength(r, 10), + GroupPolicyAsAdmin: r.Float32() < 0.5, + } + err = msg.SetDecisionPolicy(decisionPolicy) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to set decision policy"), nil, err + } + + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + acc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroupWithPolicy, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, nil + } +} + +// SimulateMsgCreateGroupPolicy generates a NewMsgCreateGroupPolicy with random values +func SimulateMsgCreateGroupPolicy( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, + s *SharedState, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + groupInfo, acc, account, err := randomGroup(r, k, ak, sdkCtx, accounts, s) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroupPolicy, ""), nil, err + } + if groupInfo == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroupPolicy, ""), nil, nil + } + groupID := groupInfo.Id + + spendableCoins := bk.SpendableCoins(sdkCtx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroupPolicy, "fee error"), nil, err + } + + accAddr, err := ak.AddressCodec().BytesToString(acc.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroupPolicy, "error generating admin address"), nil, err + } + + msg, err := group.NewMsgCreateGroupPolicy( + accAddr, + groupID, + simtypes.RandStringOfLength(r, 10), + &group.ThresholdDecisionPolicy{ + Threshold: fmt.Sprintf("%d", simtypes.RandIntBetween(r, 1, 10)), + Windows: &group.DecisionPolicyWindows{ + VotingPeriod: time.Second * time.Duration(30*24*60*60), + }, + }, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroupPolicy, err.Error()), nil, err + } + + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + acc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroupPolicy, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + fmt.Printf("ERR DELIVER %v\n", err) + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +// SimulateMsgSubmitProposal generates a NewMsgSubmitProposal with random values +func SimulateMsgSubmitProposal( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, + s *SharedState, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + g, groupPolicy, _, _, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts, s) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgSubmitProposal, ""), nil, err + } + if g == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgSubmitProposal, "no group found"), nil, nil + } + if groupPolicy == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgSubmitProposal, "no group policy found"), nil, nil + } + groupID := g.Id + groupPolicyAddr := groupPolicy.Address + + // Return a no-op if we know the proposal cannot be created + policy, err := groupPolicy.GetDecisionPolicy() + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgSubmitProposal, ""), nil, nil + } + err = policy.Validate(*g, group.DefaultConfig()) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgSubmitProposal, ""), nil, nil + } + + // Pick a random member from the group + acc, account, err := randomMember(sdkCtx, r, k, ak, accounts, groupID) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgSubmitProposal, ""), nil, err + } + if account == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgSubmitProposal, "no group member found"), nil, nil + } + + spendableCoins := bk.SpendableCoins(sdkCtx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgSubmitProposal, "fee error"), nil, err + } + + accAddr, err := ak.AddressCodec().BytesToString(acc.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgSubmitProposal, "error getting account address"), nil, err + } + + msg := &group.MsgSubmitProposal{ + GroupPolicyAddress: groupPolicyAddr, + Proposers: []string{accAddr}, + Metadata: simtypes.RandStringOfLength(r, 10), + Title: "Test Proposal", + Summary: "Summary of the proposal", + } + + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + acc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgSubmitProposal, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +// SimulateMsgUpdateGroupAdmin generates a MsgUpdateGroupAdmin with random values +func SimulateMsgUpdateGroupAdmin( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, + s *SharedState, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + groupInfo, acc, account, err := randomGroup(r, k, ak, sdkCtx, accounts, s) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupAdmin, ""), nil, err + } + if groupInfo == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupAdmin, ""), nil, nil + } + groupID := groupInfo.Id + + spendableCoins := bk.SpendableCoins(sdkCtx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupAdmin, "fee error"), nil, err + } + + if len(accounts) == 1 { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupAdmin, "can't set a new admin with only one account"), nil, nil + } + newAdmin, _ := simtypes.RandomAcc(r, accounts) + // disallow setting current admin as new admin + for acc.PubKey.Equals(newAdmin.PubKey) { + newAdmin, _ = simtypes.RandomAcc(r, accounts) + } + + accAddr, err := ak.AddressCodec().BytesToString(account.GetAddress()) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupAdmin, "error getting admin address"), nil, err + } + newAdminAddr, err := ak.AddressCodec().BytesToString(newAdmin.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupAdmin, "error getting new admin address"), nil, err + } + msg := &group.MsgUpdateGroupAdmin{ + GroupId: groupID, + Admin: accAddr, + NewAdmin: newAdminAddr, + } + + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + acc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupAdmin, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +// SimulateMsgUpdateGroupMetadata generates a MsgUpdateGroupMetadata with random values +func SimulateMsgUpdateGroupMetadata( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, + s *SharedState, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + groupInfo, acc, account, err := randomGroup(r, k, ak, sdkCtx, accounts, s) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupMetadata, ""), nil, err + } + if groupInfo == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupMetadata, ""), nil, nil + } + groupID := groupInfo.Id + + spendableCoins := bk.SpendableCoins(sdkCtx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupMetadata, "fee error"), nil, err + } + + adminAddr, err := ak.AddressCodec().BytesToString(account.GetAddress()) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupMetadata, "error getting admin address"), nil, err + } + msg := &group.MsgUpdateGroupMetadata{ + GroupId: groupID, + Admin: adminAddr, + Metadata: simtypes.RandStringOfLength(r, 10), + } + + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + acc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupMetadata, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +// SimulateMsgUpdateGroupMembers generates a MsgUpdateGroupMembers with random values +func SimulateMsgUpdateGroupMembers( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, + s *SharedState, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + groupInfo, acc, account, err := randomGroup(r, k, ak, sdkCtx, accounts, s) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupMembers, ""), nil, err + } + if groupInfo == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupMembers, ""), nil, nil + } + groupID := groupInfo.Id + + spendableCoins := bk.SpendableCoins(sdkCtx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupMembers, "fee error"), nil, err + } + + members, err := genGroupMembers(r, accounts, ak.AddressCodec()) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroup, "error generating group members"), nil, err + } + ctx := sdk.UnwrapSDKContext(sdkCtx) + res, err := k.GroupMembers(ctx, &group.QueryGroupMembersRequest{GroupId: groupID}) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupMembers, "group members"), nil, err + } + + // set existing random group member weight to zero to remove from the group + existigMembers := res.Members + if len(existigMembers) > 0 { + memberToRemove := existigMembers[r.Intn(len(existigMembers))] + var isDuplicateMember bool + for idx, m := range members { + if m.Address == memberToRemove.Member.Address { + members[idx].Weight = "0" + isDuplicateMember = true + break + } + } + + if !isDuplicateMember { + m := memberToRemove.Member + m.Weight = "0" + members = append(members, group.MemberToMemberRequest(m)) + } + } + + adminAddr, err := ak.AddressCodec().BytesToString(acc.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupMembers, "error getting admin address"), nil, err + } + msg := &group.MsgUpdateGroupMembers{ + GroupId: groupID, + Admin: adminAddr, + MemberUpdates: members, + } + + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + acc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupMembers, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +// SimulateMsgUpdateGroupPolicyAdmin generates a MsgUpdateGroupPolicyAdmin with random values +func SimulateMsgUpdateGroupPolicyAdmin( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, + s *SharedState, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + _, groupPolicy, acc, account, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts, s) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyAdmin, ""), nil, err + } + if groupPolicy == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyAdmin, "no group policy found"), nil, nil + } + groupPolicyAddr := groupPolicy.Address + + spendableCoins := bk.SpendableCoins(sdkCtx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyAdmin, "fee error"), nil, err + } + + if len(accounts) == 1 { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyAdmin, "can't set a new admin with only one account"), nil, nil + } + newAdmin, _ := simtypes.RandomAcc(r, accounts) + // disallow setting current admin as new admin + for acc.PubKey.Equals(newAdmin.PubKey) { + newAdmin, _ = simtypes.RandomAcc(r, accounts) + } + + adminAddr, err := ak.AddressCodec().BytesToString(acc.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyAdmin, "error getting admin address"), nil, err + } + newAdminAddr, err := ak.AddressCodec().BytesToString(newAdmin.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyAdmin, "error getting new admin address"), nil, err + } + msg := &group.MsgUpdateGroupPolicyAdmin{ + Admin: adminAddr, + GroupPolicyAddress: groupPolicyAddr, + NewAdmin: newAdminAddr, + } + + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + acc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyAdmin, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +// // SimulateMsgUpdateGroupPolicyDecisionPolicy generates a NewMsgUpdateGroupPolicyDecisionPolicy with random values +func SimulateMsgUpdateGroupPolicyDecisionPolicy( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, + s *SharedState, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + _, groupPolicy, acc, account, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts, s) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyDecisionPolicy, ""), nil, err + } + if groupPolicy == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyDecisionPolicy, "no group policy found"), nil, nil + } + groupPolicyAddr := groupPolicy.Address + + spendableCoins := bk.SpendableCoins(sdkCtx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyDecisionPolicy, "fee error"), nil, err + } + + groupPolicyBech32, err := sdk.AccAddressFromBech32(groupPolicyAddr) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyDecisionPolicy, fmt.Sprintf("fail to decide bech32 address: %s", err.Error())), nil, nil + } + + accAddr, err := ak.AddressCodec().BytesToString(acc.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyDecisionPolicy, "error getting admin address"), nil, err + } + groupPolicyStrAddr, err := ak.AddressCodec().BytesToString(groupPolicyBech32) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyDecisionPolicy, "error group policy admin address"), nil, err + } + + msg, err := group.NewMsgUpdateGroupPolicyDecisionPolicy(accAddr, groupPolicyStrAddr, &group.ThresholdDecisionPolicy{ + Threshold: fmt.Sprintf("%d", simtypes.RandIntBetween(r, 1, 10)), + Windows: &group.DecisionPolicyWindows{ + VotingPeriod: time.Second * time.Duration(simtypes.RandIntBetween(r, 100, 1000)), + }, + }) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyDecisionPolicy, err.Error()), nil, err + } + + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + acc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyDecisionPolicy, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +// // SimulateMsgUpdateGroupPolicyMetadata generates a MsgUpdateGroupPolicyMetadata with random values +func SimulateMsgUpdateGroupPolicyMetadata( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, + s *SharedState, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + _, groupPolicy, acc, account, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts, s) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyMetadata, ""), nil, err + } + if groupPolicy == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyMetadata, "no group policy found"), nil, nil + } + groupPolicyAddr := groupPolicy.Address + + spendableCoins := bk.SpendableCoins(sdkCtx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyMetadata, "fee error"), nil, err + } + + adminAddr, err := ak.AddressCodec().BytesToString(acc.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyMetadata, "error getting admin address"), nil, err + } + msg := &group.MsgUpdateGroupPolicyMetadata{ + Admin: adminAddr, + GroupPolicyAddress: groupPolicyAddr, + Metadata: simtypes.RandStringOfLength(r, 10), + } + + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + acc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyMetadata, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +// SimulateMsgWithdrawProposal generates a MsgWithdrawProposal with random values +func SimulateMsgWithdrawProposal( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, + s *SharedState, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + g, groupPolicy, _, _, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts, s) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, ""), nil, err + } + if g == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, "no group found"), nil, nil + } + if groupPolicy == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, "no group policy found"), nil, nil + } + + groupPolicyAddr := groupPolicy.Address + policy, err := groupPolicy.GetDecisionPolicy() + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, err.Error()), nil, nil + } + err = policy.Validate(*g, group.DefaultConfig()) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, err.Error()), nil, nil + } + + proposalsResult, err := k.ProposalsByGroupPolicy(sdkCtx, &group.QueryProposalsByGroupPolicyRequest{Address: groupPolicyAddr}) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, "fail to query group info"), nil, err + } + + proposals := proposalsResult.GetProposals() + if len(proposals) == 0 { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, "no proposals found"), nil, nil + } + + var proposal *group.Proposal + proposalID := -1 + + for _, p := range proposals { + if p.Status == group.PROPOSAL_STATUS_SUBMITTED { + timeout := p.VotingPeriodEnd + proposal = p + proposalID = int(p.Id) + if timeout.Before(sdkCtx.HeaderInfo().Time) || timeout.Equal(sdkCtx.HeaderInfo().Time) { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, "voting period ended: skipping"), nil, nil + } + break + } + } + + // return no-op if no proposal found + if proposalID == -1 { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, "no proposals found"), nil, nil + } + + // select a random proposer + proposers := proposal.Proposers + n := randIntInRange(r, len(proposers)) + proposerIdx, err := findAccount(accounts, proposers[n], ak.AddressCodec()) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, "could not find account"), nil, err + } + proposer := accounts[proposerIdx] + proposerAcc := ak.GetAccount(sdkCtx, proposer.Address) + + spendableCoins := bk.SpendableCoins(sdkCtx, proposer.Address) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, "fee error"), nil, err + } + + proposerAddr, err := ak.AddressCodec().BytesToString(proposer.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, "error getting voter address"), nil, err + } + + msg := &group.MsgWithdrawProposal{ + ProposalId: uint64(proposalID), + Address: proposerAddr, + } + + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{proposerAcc.GetAccountNumber()}, + []uint64{proposerAcc.GetSequence()}, + proposer.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyMetadata, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + if strings.Contains(err.Error(), "group was modified") || strings.Contains(err.Error(), "group policy was modified") { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "no-op:group/group-policy was modified"), nil, nil + } + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +// SimulateMsgVote generates a MsgVote with random values +func SimulateMsgVote( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, + s *SharedState, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + g, groupPolicy, _, _, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts, s) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, ""), nil, err + } + if g == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, "no group found"), nil, nil + } + if groupPolicy == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, "no group policy found"), nil, nil + } + groupPolicyAddr := groupPolicy.Address + + // Pick a random member from the group + acc, account, err := randomMember(sdkCtx, r, k, ak, accounts, g.Id) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, ""), nil, err + } + if account == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, "no group member found"), nil, nil + } + + spendableCoins := bk.SpendableCoins(sdkCtx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, "fee error"), nil, err + } + + proposalsResult, err := k.ProposalsByGroupPolicy(sdkCtx, &group.QueryProposalsByGroupPolicyRequest{Address: groupPolicyAddr}) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, "fail to query group info"), nil, err + } + proposals := proposalsResult.GetProposals() + if len(proposals) == 0 { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, "no proposals found"), nil, nil + } + + proposalID := -1 + + for _, p := range proposals { + if p.Status == group.PROPOSAL_STATUS_SUBMITTED { + timeout := p.VotingPeriodEnd + proposalID = int(p.Id) + if timeout.Before(sdkCtx.HeaderInfo().Time) || timeout.Equal(sdkCtx.HeaderInfo().Time) { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, "voting period ended: skipping"), nil, nil + } + break + } + } + + // return no-op if no proposal found + if proposalID == -1 { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, "no proposals found"), nil, nil + } + + voterAddr, err := ak.AddressCodec().BytesToString(acc.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, "error getting voter address"), nil, err + } + + // Ensure member hasn't already voted + res, _ := k.VoteByProposalVoter(sdkCtx, &group.QueryVoteByProposalVoterRequest{ + Voter: voterAddr, + ProposalId: uint64(proposalID), + }) + if res != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, "member has already voted"), nil, nil + } + + msg := &group.MsgVote{ + ProposalId: uint64(proposalID), + Voter: voterAddr, + Option: group.VOTE_OPTION_YES, + Metadata: simtypes.RandStringOfLength(r, 10), + } + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + acc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyMetadata, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + if strings.Contains(err.Error(), "group was modified") || strings.Contains(err.Error(), "group policy was modified") { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "no-op:group/group-policy was modified"), nil, nil + } + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +// // SimulateMsgExec generates a MsgExec with random values +func SimulateMsgExec( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, + s *SharedState, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + _, groupPolicy, acc, account, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts, s) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgExec, ""), nil, err + } + if groupPolicy == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgExec, "no group policy found"), nil, nil + } + groupPolicyAddr := groupPolicy.Address + + spendableCoins := bk.SpendableCoins(sdkCtx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgExec, "fee error"), nil, err + } + + proposalsResult, err := k.ProposalsByGroupPolicy(sdkCtx, &group.QueryProposalsByGroupPolicyRequest{Address: groupPolicyAddr}) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgExec, "fail to query group info"), nil, err + } + proposals := proposalsResult.GetProposals() + if len(proposals) == 0 { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgExec, "no proposals found"), nil, nil + } + + proposalID := -1 + + for _, proposal := range proposals { + if proposal.Status == group.PROPOSAL_STATUS_ACCEPTED { + proposalID = int(proposal.Id) + break + } + } + + // return no-op if no proposal found + if proposalID == -1 { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgExec, "no proposals found"), nil, nil + } + + accAddr, err := ak.AddressCodec().BytesToString(acc.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgExec, "error getting executor address"), nil, err + } + msg := &group.MsgExec{ + ProposalId: uint64(proposalID), + Executor: accAddr, + } + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + acc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyMetadata, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + if strings.Contains(err.Error(), "group was modified") || strings.Contains(err.Error(), "group policy was modified") { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "no-op:group/group-policy was modified"), nil, nil + } + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, err + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +// SimulateMsgLeaveGroup generates a MsgLeaveGroup with random values +func SimulateMsgLeaveGroup( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + k keeper.Keeper, + ak group.AccountKeeper, + bk group.BankKeeper, + s *SharedState, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + groupInfo, policyInfo, _, _, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts, s) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgLeaveGroup, ""), nil, err + } + + if policyInfo == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgLeaveGroup, "no policy found"), nil, nil + } + + // Pick a random member from the group + acc, account, err := randomMember(sdkCtx, r, k, ak, accounts, groupInfo.Id) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgLeaveGroup, ""), nil, err + } + if account == nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgLeaveGroup, "no group member found"), nil, nil + } + + spendableCoins := bk.SpendableCoins(sdkCtx, acc.Address) + fees, err := simtypes.RandomFees(r, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgLeaveGroup, "fee error"), nil, err + } + + accAddr, err := ak.AddressCodec().BytesToString(acc.Address) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgLeaveGroup, "error getting account address"), nil, err + } + msg := &group.MsgLeaveGroup{ + Address: accAddr, + GroupId: groupInfo.Id, + } + + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + acc.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, TypeMsgLeaveGroup, "unable to generate mock tx"), nil, err + } + + _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), err.Error()), nil, err + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +func randomGroup(r *rand.Rand, k keeper.Keeper, ak group.AccountKeeper, + ctx sdk.Context, accounts []simtypes.Account, s *SharedState, +) (groupInfo *group.GroupInfo, acc simtypes.Account, account sdk.AccountI, err error) { + groupID := k.GetGroupSequence(ctx) + + if initialGroupID := s.getMinGroupID(); initialGroupID == unsetGroupID { + s.setMinGroupID(groupID) + } else if initialGroupID < groupID { + groupID = uint64(simtypes.RandIntBetween(r, int(initialGroupID+1), int(groupID+1))) + } + + // when groupID is 0, it proves that SimulateMsgCreateGroup has never been called. that is, no group exists in the chain + if groupID == 0 { + return nil, simtypes.Account{}, nil, nil + } + + res, err := k.GroupInfo(ctx, &group.QueryGroupInfoRequest{GroupId: groupID}) + if err != nil { + return nil, simtypes.Account{}, nil, err + } + + groupInfo = res.Info + groupAdmin := groupInfo.Admin + found := -1 + for i := range accounts { + addr, err := ak.AddressCodec().BytesToString(accounts[i].Address) + if err != nil { + return nil, simtypes.Account{}, nil, err + } + if addr == groupAdmin { + found = i + break + } + } + if found < 0 { + return nil, simtypes.Account{}, nil, nil + } + acc = accounts[found] + account = ak.GetAccount(ctx, acc.Address) + return groupInfo, acc, account, nil +} + +func randomGroupPolicy(r *rand.Rand, k keeper.Keeper, ak group.AccountKeeper, + ctx sdk.Context, accounts []simtypes.Account, s *SharedState, +) (groupInfo *group.GroupInfo, groupPolicyInfo *group.GroupPolicyInfo, acc simtypes.Account, account sdk.AccountI, err error) { + groupInfo, _, _, err = randomGroup(r, k, ak, ctx, accounts, s) + if err != nil { + return nil, nil, simtypes.Account{}, nil, err + } + if groupInfo == nil { + return nil, nil, simtypes.Account{}, nil, nil + } + groupID := groupInfo.Id + + result, err := k.GroupPoliciesByGroup(ctx, &group.QueryGroupPoliciesByGroupRequest{GroupId: groupID}) + if err != nil { + return groupInfo, nil, simtypes.Account{}, nil, err + } + + n := randIntInRange(r, len(result.GroupPolicies)) + if n < 0 { + return groupInfo, nil, simtypes.Account{}, nil, nil + } + groupPolicyInfo = result.GroupPolicies[n] + + idx, err := findAccount(accounts, groupPolicyInfo.Admin, ak.AddressCodec()) + if err != nil { + return groupInfo, nil, simtypes.Account{}, nil, nil + } + + if idx < 0 { + return groupInfo, nil, simtypes.Account{}, nil, nil + } + acc = accounts[idx] + account = ak.GetAccount(ctx, acc.Address) + return groupInfo, groupPolicyInfo, acc, account, nil +} + +func randomMember(ctx context.Context, r *rand.Rand, k keeper.Keeper, ak group.AccountKeeper, + accounts []simtypes.Account, groupID uint64, +) (acc simtypes.Account, account sdk.AccountI, err error) { + res, err := k.GroupMembers(ctx, &group.QueryGroupMembersRequest{ + GroupId: groupID, + }) + if err != nil { + return simtypes.Account{}, nil, err + } + n := randIntInRange(r, len(res.Members)) + if n < 0 { + return simtypes.Account{}, nil, err + } + idx, err := findAccount(accounts, res.Members[n].Member.Address, ak.AddressCodec()) + if err != nil { + return simtypes.Account{}, nil, err + } + if idx < 0 { + return simtypes.Account{}, nil, err + } + acc = accounts[idx] + account = ak.GetAccount(sdk.UnwrapSDKContext(ctx), acc.Address) + return acc, account, nil +} + +func randIntInRange(r *rand.Rand, l int) int { + if l == 0 { + return -1 + } + if l == 1 { + return 0 + } + return simtypes.RandIntBetween(r, 0, l-1) +} + +func findAccount(accounts []simtypes.Account, addr string, addressCodec address.Codec) (idx int, err error) { + idx = -1 + for i := range accounts { + accAddr, err := addressCodec.BytesToString(accounts[i].Address) + if err != nil { + return idx, err + } + if accAddr == addr { + idx = i + break + } + } + return idx, err +} + +func genGroupMembers(r *rand.Rand, accounts []simtypes.Account, addressCodec address.Codec) ([]group.MemberRequest, error) { + if len(accounts) == 1 { + addr, err := addressCodec.BytesToString(accounts[0].Address) + if err != nil { + return nil, err + } + return []group.MemberRequest{ + { + Address: addr, + Weight: fmt.Sprintf("%d", simtypes.RandIntBetween(r, 1, 10)), + Metadata: simtypes.RandStringOfLength(r, 10), + }, + }, nil + } + + max := 5 + if len(accounts) < max { + max = len(accounts) + } + + membersLen := simtypes.RandIntBetween(r, 1, max) + members := make([]group.MemberRequest, membersLen) + + for i := 0; i < membersLen; i++ { + addr, err := addressCodec.BytesToString(accounts[i].Address) + if err != nil { + return nil, err + } + members[i] = group.MemberRequest{ + Address: addr, + Weight: fmt.Sprintf("%d", simtypes.RandIntBetween(r, 1, 10)), + Metadata: simtypes.RandStringOfLength(r, 10), + } + } + + return members, nil +} diff --git a/x/group/types.go b/x/group/types.go index 4a8b2cd7d5642..d91d4fd897047 100644 --- a/x/group/types.go +++ b/x/group/types.go @@ -5,6 +5,7 @@ import ( "time" "github.com/cosmos/gogoproto/proto" + gogoprotoany "github.com/cosmos/gogoproto/types/any" "cosmossdk.io/core/address" errorsmod "cosmossdk.io/errors" @@ -286,7 +287,7 @@ func (g GroupPolicyInfo) GetDecisionPolicy() (DecisionPolicy, error) { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (g GroupPolicyInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (g GroupPolicyInfo) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var decisionPolicy DecisionPolicy return unpacker.UnpackAny(g.DecisionPolicy, &decisionPolicy) } @@ -458,16 +459,16 @@ func (v Vote) ValidateBasic() error { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (q QueryGroupPoliciesByGroupResponse) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (q QueryGroupPoliciesByGroupResponse) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { return unpackGroupPolicies(unpacker, q.GroupPolicies) } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (q QueryGroupPoliciesByAdminResponse) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (q QueryGroupPoliciesByAdminResponse) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { return unpackGroupPolicies(unpacker, q.GroupPolicies) } -func unpackGroupPolicies(unpacker codectypes.AnyUnpacker, accs []*GroupPolicyInfo) error { +func unpackGroupPolicies(unpacker gogoprotoany.AnyUnpacker, accs []*GroupPolicyInfo) error { for _, g := range accs { err := g.UnpackInterfaces(unpacker) if err != nil { diff --git a/x/mint/go.mod b/x/mint/go.mod index 311371d90042c..6305bbf9f42c7 100644 --- a/x/mint/go.mod +++ b/x/mint/go.mod @@ -6,7 +6,7 @@ require ( cosmossdk.io/api v0.7.5 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/log v1.3.1 cosmossdk.io/math v1.3.0 @@ -159,10 +159,11 @@ require ( require ( buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2 // indirect + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/schema v0.1.1 // indirect cosmossdk.io/x/consensus v0.0.0-00010101000000-000000000000 // indirect github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/dgraph-io/badger/v4 v4.2.0 // indirect github.com/gofrs/uuid v4.4.0+incompatible // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect @@ -180,7 +181,6 @@ replace ( cosmossdk.io/api => ../../api cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/mint/go.sum b/x/mint/go.sum index 9ed4b55914f0d..edcd1d37e230f 100644 --- a/x/mint/go.sum +++ b/x/mint/go.sum @@ -6,6 +6,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -104,8 +106,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/mint/module.go b/x/mint/module.go index f1434d4205f35..a40a90ff74952 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -26,7 +26,6 @@ import ( const ConsensusVersion = 3 var ( - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.AppModuleSimulation = AppModule{} @@ -77,6 +76,7 @@ func NewAppModule( func (AppModule) IsAppModule() {} // Name returns the mint module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } diff --git a/x/mint/simulation/genesis_test.go b/x/mint/simulation/genesis_test.go index 784f910e326c9..ba31c32e4b2ab 100644 --- a/x/mint/simulation/genesis_test.go +++ b/x/mint/simulation/genesis_test.go @@ -62,7 +62,7 @@ func TestRandomizedGenState(t *testing.T) { require.Equal(t, "0.000000000000000000", mintGenesis.Minter.AnnualProvisions.String()) } -// TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. +// TestRandomizedGenState1 tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { encCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, mint.AppModule{}) diff --git a/x/nft/go.mod b/x/nft/go.mod index 87911b8e4a762..28d524d6d9f55 100644 --- a/x/nft/go.mod +++ b/x/nft/go.mod @@ -5,7 +5,7 @@ go 1.22.2 require ( cosmossdk.io/api v0.7.5 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/log v1.3.1 cosmossdk.io/math v1.3.0 @@ -25,6 +25,7 @@ require ( buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2 // indirect buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2 // indirect cosmossdk.io/collections v0.4.0 // indirect + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/schema v0.1.1 // indirect cosmossdk.io/x/auth v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/x/bank v0.0.0-20240226161501-23359a0b6d91 // indirect @@ -51,7 +52,7 @@ require ( github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -176,7 +177,6 @@ replace ( cosmossdk.io/api => ../../api cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/nft/go.sum b/x/nft/go.sum index 6a2618f159fc5..08da56c9d15ef 100644 --- a/x/nft/go.sum +++ b/x/nft/go.sum @@ -6,6 +6,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -102,8 +104,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/nft/module/module.go b/x/nft/module/module.go index 8c338f41459b5..fefac26c8e039 100644 --- a/x/nft/module/module.go +++ b/x/nft/module/module.go @@ -23,7 +23,6 @@ import ( ) var ( - _ module.HasName = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.AppModuleSimulation = AppModule{} @@ -59,6 +58,7 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak nft.AccountKeeper, b func (AppModule) IsAppModule() {} // Name returns the nft module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return nft.ModuleName } diff --git a/x/nft/proto/cosmos/nft/v1beta1/query.proto b/x/nft/proto/cosmos/nft/v1beta1/query.proto index 3b32094e6d061..92df51459e41b 100644 --- a/x/nft/proto/cosmos/nft/v1beta1/query.proto +++ b/x/nft/proto/cosmos/nft/v1beta1/query.proto @@ -15,7 +15,7 @@ service Query { option (google.api.http).get = "/cosmos/nft/v1beta1/balance/{owner}/{class_id}"; } - // BalancebyQueryString queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 + // BalanceByQueryString queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 rpc BalanceByQueryString(QueryBalanceByQueryStringRequest) returns (QueryBalanceByQueryStringResponse) { option (google.api.http).get = "/cosmos/nft/v1beta1/balance"; option (cosmos_proto.method_added_in) = "nft v0.1.1"; @@ -171,7 +171,7 @@ message QuerySupplyByQueryStringResponse { uint64 amount = 1; } -// QueryNFTstRequest is the request type for the Query/NFTs RPC method +// QueryNFTsRequest is the request type for the Query/NFTs RPC method message QueryNFTsRequest { // class_id associated with the nft string class_id = 1; diff --git a/x/nft/query.pb.go b/x/nft/query.pb.go index 0188d40d5fcba..7b9138320b125 100644 --- a/x/nft/query.pb.go +++ b/x/nft/query.pb.go @@ -618,7 +618,7 @@ func (m *QuerySupplyByQueryStringResponse) GetAmount() uint64 { return 0 } -// QueryNFTstRequest is the request type for the Query/NFTs RPC method +// QueryNFTsRequest is the request type for the Query/NFTs RPC method type QueryNFTsRequest struct { // class_id associated with the nft ClassId string `protobuf:"bytes,1,opt,name=class_id,json=classId,proto3" json:"class_id,omitempty"` @@ -1333,7 +1333,7 @@ const _ = grpc.SupportPackageIsVersion4 type QueryClient interface { // Balance queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 Balance(ctx context.Context, in *QueryBalanceRequest, opts ...grpc.CallOption) (*QueryBalanceResponse, error) - // BalancebyQueryString queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 + // BalanceByQueryString queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 BalanceByQueryString(ctx context.Context, in *QueryBalanceByQueryStringRequest, opts ...grpc.CallOption) (*QueryBalanceByQueryStringResponse, error) // Owner queries the owner of the NFT based on its class and id, same as ownerOf in ERC721 Owner(ctx context.Context, in *QueryOwnerRequest, opts ...grpc.CallOption) (*QueryOwnerResponse, error) @@ -1478,7 +1478,7 @@ func (c *queryClient) Classes(ctx context.Context, in *QueryClassesRequest, opts type QueryServer interface { // Balance queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 Balance(context.Context, *QueryBalanceRequest) (*QueryBalanceResponse, error) - // BalancebyQueryString queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 + // BalanceByQueryString queries the number of NFTs of a given class owned by the owner, same as balanceOf in ERC721 BalanceByQueryString(context.Context, *QueryBalanceByQueryStringRequest) (*QueryBalanceByQueryStringResponse, error) // Owner queries the owner of the NFT based on its class and id, same as ownerOf in ERC721 Owner(context.Context, *QueryOwnerRequest) (*QueryOwnerResponse, error) diff --git a/x/params/go.mod b/x/params/go.mod index c1a10a6023779..ca7924a8fe9f9 100644 --- a/x/params/go.mod +++ b/x/params/go.mod @@ -5,7 +5,7 @@ go 1.22.2 require ( cosmossdk.io/api v0.7.5 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/log v1.3.1 cosmossdk.io/math v1.3.0 @@ -29,6 +29,7 @@ require ( buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2 // indirect buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2 // indirect cosmossdk.io/collections v0.4.0 // indirect + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/schema v0.1.1 // indirect cosmossdk.io/x/auth v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/x/bank v0.0.0-20240226161501-23359a0b6d91 // indirect @@ -53,7 +54,7 @@ require ( github.com/cometbft/cometbft v1.0.0-rc1 // indirect github.com/cometbft/cometbft-db v0.12.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -177,7 +178,6 @@ replace ( cosmossdk.io/api => ../../api cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/params/go.sum b/x/params/go.sum index 6a2618f159fc5..08da56c9d15ef 100644 --- a/x/params/go.sum +++ b/x/params/go.sum @@ -6,6 +6,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -102,8 +104,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/params/module.go b/x/params/module.go index dd36e5a013325..8eda261dd57c7 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -18,7 +18,6 @@ import ( ) var ( - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.AppModuleSimulation = AppModule{} @@ -47,6 +46,7 @@ func NewAppModule(k keeper.Keeper) AppModule { func (am AppModule) IsAppModule() {} // Name returns the params module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return proposal.ModuleName } diff --git a/x/params/types/common_test.go b/x/params/types/common_test.go index 9fd9b1a535af6..bd1d653c86505 100644 --- a/x/params/types/common_test.go +++ b/x/params/types/common_test.go @@ -39,7 +39,7 @@ func validateUnbondingTime(i interface{}) error { } if v < (24 * time.Hour) { - return fmt.Errorf("unbonding time must be at least one day") + return errors.New("unbonding time must be at least one day") } return nil diff --git a/x/protocolpool/go.mod b/x/protocolpool/go.mod index 0fd98601c2158..c0959364d6ad5 100644 --- a/x/protocolpool/go.mod +++ b/x/protocolpool/go.mod @@ -6,7 +6,7 @@ require ( cosmossdk.io/api v0.7.5 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/log v1.3.1 cosmossdk.io/math v1.3.0 @@ -28,6 +28,7 @@ require ( require ( buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2 // indirect buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2 // indirect + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/schema v0.1.1 // indirect cosmossdk.io/x/bank v0.0.0-20240226161501-23359a0b6d91 // indirect cosmossdk.io/x/consensus v0.0.0-00010101000000-000000000000 // indirect @@ -53,7 +54,7 @@ require ( github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -176,7 +177,6 @@ replace ( cosmossdk.io/api => ../../api cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/protocolpool/go.sum b/x/protocolpool/go.sum index 6a2618f159fc5..08da56c9d15ef 100644 --- a/x/protocolpool/go.sum +++ b/x/protocolpool/go.sum @@ -6,6 +6,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -102,8 +104,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/protocolpool/keeper/keeper.go b/x/protocolpool/keeper/keeper.go index 4b5899200c60b..038fd3260d88a 100644 --- a/x/protocolpool/keeper/keeper.go +++ b/x/protocolpool/keeper/keeper.go @@ -196,7 +196,7 @@ func (k Keeper) SetToDistribute(ctx context.Context, amount sdk.Coins, addr stri totalStreamFundsPercentage = totalStreamFundsPercentage.Add(cf.Percentage) if totalStreamFundsPercentage.GT(math.LegacyOneDec()) { - return true, fmt.Errorf("total funds percentage cannot exceed 100") + return true, errors.New("total funds percentage cannot exceed 100") } return false, nil @@ -272,7 +272,7 @@ func (k Keeper) IterateAndUpdateFundsDistribution(ctx context.Context) error { // sanity check for max percentage totalPercentageToBeDistributed = totalPercentageToBeDistributed.Add(cf.Percentage) if totalPercentageToBeDistributed.GT(math.LegacyOneDec()) { - return true, fmt.Errorf("total funds percentage cannot exceed 100") + return true, errors.New("total funds percentage cannot exceed 100") } // Calculate the funds to be distributed based on the percentage @@ -356,7 +356,7 @@ func (k Keeper) getClaimableFunds(ctx context.Context, recipientAddr string) (am // Check if the distribution time has not reached if budget.LastClaimedAt != nil { if currentTime.Before(*budget.LastClaimedAt) { - return sdk.Coin{}, fmt.Errorf("distribution has not started yet") + return sdk.Coin{}, errors.New("distribution has not started yet") } } @@ -374,7 +374,7 @@ func (k Keeper) calculateClaimableFunds(ctx context.Context, recipient sdk.AccAd // Check the time elapsed has passed period length if timeElapsed < *budget.Period { - return sdk.Coin{}, fmt.Errorf("budget period has not passed yet") + return sdk.Coin{}, errors.New("budget period has not passed yet") } // Calculate how many periods have passed @@ -415,7 +415,7 @@ func (k Keeper) calculateClaimableFunds(ctx context.Context, recipient sdk.AccAd func (k Keeper) validateAndUpdateBudgetProposal(ctx context.Context, bp types.MsgSubmitBudgetProposal) (*types.Budget, error) { if bp.BudgetPerTranche.IsZero() { - return nil, fmt.Errorf("invalid budget proposal: budget per tranche cannot be zero") + return nil, errors.New("invalid budget proposal: budget per tranche cannot be zero") } if err := validateAmount(sdk.NewCoins(*bp.BudgetPerTranche)); err != nil { @@ -428,15 +428,15 @@ func (k Keeper) validateAndUpdateBudgetProposal(ctx context.Context, bp types.Ms } if currentTime.After(*bp.StartTime) { - return nil, fmt.Errorf("invalid budget proposal: start time cannot be less than the current block time") + return nil, errors.New("invalid budget proposal: start time cannot be less than the current block time") } if bp.Tranches == 0 { - return nil, fmt.Errorf("invalid budget proposal: tranches must be greater than zero") + return nil, errors.New("invalid budget proposal: tranches must be greater than zero") } if bp.Period == nil || *bp.Period == 0 { - return nil, fmt.Errorf("invalid budget proposal: period length should be greater than zero") + return nil, errors.New("invalid budget proposal: period length should be greater than zero") } // Create and return an updated budget proposal @@ -455,19 +455,19 @@ func (k Keeper) validateAndUpdateBudgetProposal(ctx context.Context, bp types.Ms func (k Keeper) validateContinuousFund(ctx context.Context, msg types.MsgCreateContinuousFund) error { // Validate percentage if msg.Percentage.IsZero() || msg.Percentage.IsNil() { - return fmt.Errorf("percentage cannot be zero or empty") + return errors.New("percentage cannot be zero or empty") } if msg.Percentage.IsNegative() { - return fmt.Errorf("percentage cannot be negative") + return errors.New("percentage cannot be negative") } if msg.Percentage.GTE(math.LegacyOneDec()) { - return fmt.Errorf("percentage cannot be greater than or equal to one") + return errors.New("percentage cannot be greater than or equal to one") } // Validate expiry currentTime := k.HeaderService.HeaderInfo(ctx).Time if msg.Expiry != nil && msg.Expiry.Compare(currentTime) == -1 { - return fmt.Errorf("expiry time cannot be less than the current block time") + return errors.New("expiry time cannot be less than the current block time") } return nil diff --git a/x/protocolpool/module.go b/x/protocolpool/module.go index e8cfd7bde2947..882da6eb6fc89 100644 --- a/x/protocolpool/module.go +++ b/x/protocolpool/module.go @@ -22,7 +22,6 @@ import ( const ConsensusVersion = 1 var ( - _ module.HasName = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.AppModuleSimulation = AppModule{} @@ -55,7 +54,8 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, // IsAppModule implements the appmodule.AppModule interface. func (AppModule) IsAppModule() {} -// Name returns the pool module's name. +// Name returns the protocolpool module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes diff --git a/x/protocolpool/types/genesis.go b/x/protocolpool/types/genesis.go index b16e4ff97e7c0..632a36573469f 100644 --- a/x/protocolpool/types/genesis.go +++ b/x/protocolpool/types/genesis.go @@ -1,9 +1,9 @@ package types import ( - "fmt" + "errors" - "cosmossdk.io/errors" + errorsmod "cosmossdk.io/errors" "cosmossdk.io/math" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -40,41 +40,41 @@ func ValidateGenesis(gs *GenesisState) error { func validateBudget(bp Budget) error { if bp.RecipientAddress == "" { - return fmt.Errorf("recipient cannot be empty") + return errors.New("recipient cannot be empty") } // Validate BudgetPerTranche if bp.BudgetPerTranche == nil || bp.BudgetPerTranche.IsZero() { - return fmt.Errorf("budget per tranche cannot be zero") + return errors.New("budget per tranche cannot be zero") } if err := bp.BudgetPerTranche.Validate(); err != nil { - return errors.Wrap(sdkerrors.ErrInvalidCoins, bp.BudgetPerTranche.String()) + return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, bp.BudgetPerTranche.String()) } if bp.TranchesLeft == 0 { - return fmt.Errorf("invalid budget proposal: tranches must be greater than zero") + return errors.New("invalid budget proposal: tranches must be greater than zero") } if bp.Period == nil || *bp.Period == 0 { - return fmt.Errorf("invalid budget proposal: period length should be greater than zero") + return errors.New("invalid budget proposal: period length should be greater than zero") } return nil } func validateContinuousFund(cf ContinuousFund) error { if cf.Recipient == "" { - return fmt.Errorf("recipient cannot be empty") + return errors.New("recipient cannot be empty") } // Validate percentage if cf.Percentage.IsNil() || cf.Percentage.IsZero() { - return fmt.Errorf("percentage cannot be zero or empty") + return errors.New("percentage cannot be zero or empty") } if cf.Percentage.IsNegative() { - return fmt.Errorf("percentage cannot be negative") + return errors.New("percentage cannot be negative") } if cf.Percentage.GT(math.LegacyOneDec()) { - return fmt.Errorf("percentage cannot be greater than one") + return errors.New("percentage cannot be greater than one") } return nil } diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index f9029759a2cd7..4ffd03a8d826e 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/binary" "encoding/hex" + "errors" "fmt" "io" "math/rand" @@ -118,7 +119,7 @@ func SimulateFromSeedX( // At least 2 accounts must be added here, otherwise when executing SimulateMsgSend // two accounts will be selected to meet the conditions from != to and it will fall into an infinite loop. if len(accs) <= 1 { - return params, fmt.Errorf("at least two genesis accounts are required") + return params, errors.New("at least two genesis accounts are required") } config.ChainID = chainID diff --git a/x/slashing/go.mod b/x/slashing/go.mod index 24ab3a4be0b0e..b60bdb431e11d 100644 --- a/x/slashing/go.mod +++ b/x/slashing/go.mod @@ -6,7 +6,8 @@ require ( cosmossdk.io/api v0.7.5 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/math v1.3.0 cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc @@ -54,7 +55,7 @@ require ( github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -177,7 +178,6 @@ replace ( cosmossdk.io/api => ../../api cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/slashing/go.sum b/x/slashing/go.sum index 3b28ad185a456..283361751656f 100644 --- a/x/slashing/go.sum +++ b/x/slashing/go.sum @@ -6,6 +6,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -104,8 +106,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/slashing/keeper/keeper_test.go b/x/slashing/keeper/keeper_test.go index 93360f66fb552..37878d830cb65 100644 --- a/x/slashing/keeper/keeper_test.go +++ b/x/slashing/keeper/keeper_test.go @@ -10,7 +10,7 @@ import ( st "cosmossdk.io/api/cosmos/staking/v1beta1" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -46,7 +46,7 @@ func (s *KeeperTestSuite) SetupTest() { key := storetypes.NewKVStoreKey(slashingtypes.StoreKey) s.key = key storeService := runtime.NewKVStoreService(key) - env := runtime.NewEnvironment(storeService, log.NewNopLogger()) + env := runtime.NewEnvironment(storeService, coretesting.NewNopLogger()) testCtx := sdktestutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now().Round(0).UTC()}) encCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}) diff --git a/x/slashing/module.go b/x/slashing/module.go index 462f3446a9262..ca06d59ffa3e9 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -28,7 +28,6 @@ import ( const ConsensusVersion = 4 var ( - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.AppModuleSimulation = AppModule{} @@ -72,6 +71,7 @@ func NewAppModule( func (AppModule) IsAppModule() {} // Name returns the slashing module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } diff --git a/x/slashing/simulation/genesis_test.go b/x/slashing/simulation/genesis_test.go index b1bed6f6f803b..1748645ec2500 100644 --- a/x/slashing/simulation/genesis_test.go +++ b/x/slashing/simulation/genesis_test.go @@ -59,7 +59,7 @@ func TestRandomizedGenState(t *testing.T) { require.Len(t, slashingGenesis.SigningInfos, 0) } -// TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. +// TestRandomizedGenState1 tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go new file mode 100644 index 0000000000000..45f61af3a999d --- /dev/null +++ b/x/slashing/simulation/operations.go @@ -0,0 +1,160 @@ +package simulation + +import ( + "errors" + "math/rand" + + "cosmossdk.io/x/slashing/keeper" + "cosmossdk.io/x/slashing/types" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/testutil" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// Simulation operation weights constants +const ( + OpWeightMsgUnjail = "op_weight_msg_unjail" + + DefaultWeightMsgUnjail = 100 +) + +// WeightedOperations returns all the operations from the module with their respective weights +func WeightedOperations( + registry codectypes.InterfaceRegistry, + appParams simtypes.AppParams, + cdc codec.JSONCodec, + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k keeper.Keeper, + sk types.StakingKeeper, +) simulation.WeightedOperations { + var weightMsgUnjail int + appParams.GetOrGenerate(OpWeightMsgUnjail, &weightMsgUnjail, nil, func(_ *rand.Rand) { + weightMsgUnjail = DefaultWeightMsgUnjail + }) + + return simulation.WeightedOperations{ + simulation.NewWeightedOperation( + weightMsgUnjail, + SimulateMsgUnjail(codec.NewProtoCodec(registry), txGen, ak, bk, k, sk), + ), + } +} + +// SimulateMsgUnjail generates a MsgUnjail with random values +func SimulateMsgUnjail( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k keeper.Keeper, + sk types.StakingKeeper, +) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + msgType := sdk.MsgTypeURL(&types.MsgUnjail{}) + + allVals, err := sk.GetAllValidators(ctx) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to get all validators"), nil, err + } + + validator, ok := testutil.RandSliceElem(r, allVals) + if !ok { + return simtypes.NoOpMsg(types.ModuleName, msgType, "validator is not ok"), nil, nil // skip + } + + bz, err := sk.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to convert validator address to bytes"), nil, err + } + + simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(bz)) + if !found { + return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to find account"), nil, nil // skip + } + + if !validator.IsJailed() { + // TODO: due to this condition this message is almost, if not always, skipped ! + return simtypes.NoOpMsg(types.ModuleName, msgType, "validator is not jailed"), nil, nil + } + + consAddr, err := validator.GetConsAddr() + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to get validator consensus key"), nil, err + } + info, _ := k.ValidatorSigningInfo.Get(ctx, consAddr) + + selfDel, _ := sk.Delegation(ctx, simAccount.Address, bz) + if selfDel == nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "self delegation is nil"), nil, nil // skip + } + + account := ak.GetAccount(ctx, sdk.AccAddress(bz)) + spendable := bk.SpendableCoins(ctx, account.GetAddress()) + + fees, err := simtypes.RandomFees(r, spendable) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to generate fees"), nil, nil + } + + msg := types.NewMsgUnjail(validator.GetOperator()) + + tx, err := simtestutil.GenSignedMockTx( + r, + txGen, + []sdk.Msg{msg}, + fees, + simtestutil.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + simAccount.PrivKey, + ) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to generate mock tx"), nil, err + } + + _, res, err := app.SimDeliver(txGen.TxEncoder(), tx) + + // result should fail if: + // - validator cannot be unjailed due to tombstone + // - validator is still in jailed period + // - self delegation too low + if info.Tombstoned || + ctx.HeaderInfo().Time.Before(info.JailedUntil) || + selfDel.GetShares().IsNil() || + validator.TokensFromShares(selfDel.GetShares()).TruncateInt().LT(validator.GetMinSelfDelegation()) { + if res != nil && err == nil { + if info.Tombstoned { + return simtypes.NewOperationMsg(msg, true, ""), nil, errors.New("validator should not have been unjailed if validator tombstoned") + } + if ctx.HeaderInfo().Time.Before(info.JailedUntil) { + return simtypes.NewOperationMsg(msg, true, ""), nil, errors.New("validator unjailed while validator still in jail period") + } + if selfDel.GetShares().IsNil() || + validator.TokensFromShares(selfDel.GetShares()).TruncateInt().LT(validator.GetMinSelfDelegation()) { + return simtypes.NewOperationMsg(msg, true, ""), nil, errors.New("validator unjailed even though self-delegation too low") + } + } + // msg failed as expected + return simtypes.NewOperationMsg(msg, false, ""), nil, nil + } + + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to deliver tx"), nil, errors.New(res.Log) + } + + return simtypes.NewOperationMsg(msg, true, ""), nil, nil + } +} diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index b5d3b20429819..495917167bb34 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -365,7 +365,7 @@ func PrepareConfigForTxCreateValidator(flagSet *flag.FlagSet, moniker, nodeID, c } // BuildCreateValidatorMsg makes a new MsgCreateValidator. -func BuildCreateValidatorMsg(clientCtx client.Context, config TxCreateValidatorConfig, txBldr tx.Factory, generateOnly bool, valCodec address.Codec) (tx.Factory, sdk.Msg, error) { +func BuildCreateValidatorMsg(clientCtx client.Context, config TxCreateValidatorConfig, txBldr tx.Factory, generateOnly bool) (tx.Factory, sdk.Msg, error) { amounstStr := config.Amount amount, err := sdk.ParseCoinNormalized(amounstStr) if err != nil { @@ -398,7 +398,8 @@ func BuildCreateValidatorMsg(clientCtx client.Context, config TxCreateValidatorC return txBldr, nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "minimum self delegation must be a positive integer") } - valStr, err := valCodec.BytesToString(sdk.ValAddress(valAddr)) + valCodec := clientCtx.TxConfig.SigningContext().ValidatorAddressCodec() + valStr, err := valCodec.BytesToString(valAddr) if err != nil { return txBldr, nil, err } diff --git a/x/staking/go.mod b/x/staking/go.mod index 6a05987315dac..5ad5d4f275cf5 100644 --- a/x/staking/go.mod +++ b/x/staking/go.mod @@ -6,7 +6,8 @@ require ( cosmossdk.io/api v0.7.5 cosmossdk.io/collections v0.4.0 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/math v1.3.0 cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc @@ -159,7 +160,7 @@ require ( buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2 // indirect cosmossdk.io/log v1.3.1 // indirect cosmossdk.io/x/consensus v0.0.0-00010101000000-000000000000 - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/dgraph-io/badger/v4 v4.2.0 // indirect github.com/gofrs/uuid v4.4.0+incompatible // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect @@ -182,7 +183,6 @@ replace ( cosmossdk.io/collections => ../../collections cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/staking/go.sum b/x/staking/go.sum index 0b0081734c7bb..4879cfa34550a 100644 --- a/x/staking/go.sum +++ b/x/staking/go.sum @@ -4,6 +4,8 @@ buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88e buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2/go.mod h1:HqcXMSa5qnNuakaMUo+hWhF51mKbcrZxGl9Vp5EeJXc= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -100,8 +102,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 1db3cc99a2fc8..69ad3843ee9c1 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -719,7 +719,7 @@ func (k Keeper) Delegate( // all non bonded if subtractAccount { if tokenSrc == types.Bonded { - return math.LegacyZeroDec(), fmt.Errorf("delegation token source cannot be bonded; expected Unbonded or Unbonding, got Bonded") + return math.LegacyZeroDec(), errors.New("delegation token source cannot be bonded; expected Unbonded or Unbonding, got Bonded") } var sendName string diff --git a/x/staking/keeper/keeper_test.go b/x/staking/keeper/keeper_test.go index ab3b29335b65e..e148a7114ddd9 100644 --- a/x/staking/keeper/keeper_test.go +++ b/x/staking/keeper/keeper_test.go @@ -10,7 +10,7 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -65,7 +65,7 @@ func (s *KeeperTestSuite) SetupTest() { s.baseApp = baseapp.NewBaseApp( "staking", - log.NewNopLogger(), + coretesting.NewNopLogger(), testCtx.DB, encCfg.TxConfig.TxDecoder(), ) @@ -87,7 +87,7 @@ func (s *KeeperTestSuite) SetupTest() { consensustypes.RegisterQueryServer(queryHelper, ck) bankKeeper := stakingtestutil.NewMockBankKeeper(ctrl) - env := runtime.NewEnvironment(storeService, log.NewNopLogger(), runtime.EnvWithQueryRouterService(queryHelper.GRPCQueryRouter), runtime.EnvWithMsgRouterService(s.baseApp.MsgServiceRouter())) + env := runtime.NewEnvironment(storeService, coretesting.NewNopLogger(), runtime.EnvWithQueryRouterService(queryHelper.GRPCQueryRouter), runtime.EnvWithMsgRouterService(s.baseApp.MsgServiceRouter())) authority, err := accountKeeper.AddressCodec().BytesToString(authtypes.NewModuleAddress(stakingtypes.GovModuleName)) s.Require().NoError(err) keeper := stakingkeeper.NewKeeper( diff --git a/x/staking/keeper/migrations.go b/x/staking/keeper/migrations.go index 576b3fbd5b580..1bcf07a1da6ba 100644 --- a/x/staking/keeper/migrations.go +++ b/x/staking/keeper/migrations.go @@ -42,7 +42,7 @@ func (m Migrator) Migrate4to5(ctx context.Context) error { return v5.MigrateStore(ctx, store, m.keeper.cdc, m.keeper.Logger) } -// Migrate4to5 migrates x/staking state from consensus version 5 to 6. +// Migrate5to6 migrates x/staking state from consensus version 5 to 6. func (m Migrator) Migrate5to6(ctx context.Context) error { store := runtime.KVStoreAdapter(m.keeper.KVStoreService.OpenKVStore(ctx)) return v6.MigrateStore(ctx, store, m.keeper.cdc) diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index 3e78cdb949eac..5179752a5b580 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -190,7 +190,7 @@ func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionH return math.NewInt(0), err } default: - return math.NewInt(0), fmt.Errorf("invalid validator status") + return math.NewInt(0), errors.New("invalid validator status") } k.Logger.Info( @@ -415,7 +415,7 @@ func (k Keeper) SlashRedelegation(ctx context.Context, srcValidator types.Valida case dstValidator.IsUnbonded() || dstValidator.IsUnbonding(): notBondedBurnedAmount = notBondedBurnedAmount.Add(tokensToBurn) default: - return math.ZeroInt(), fmt.Errorf("unknown validator status") + return math.ZeroInt(), errors.New("unknown validator status") } } diff --git a/x/staking/keeper/val_state_change.go b/x/staking/keeper/val_state_change.go index ac6d82eb27eea..8d71114c15859 100644 --- a/x/staking/keeper/val_state_change.go +++ b/x/staking/keeper/val_state_change.go @@ -3,6 +3,7 @@ package keeper import ( "bytes" "context" + "errors" "fmt" "sort" @@ -172,7 +173,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx context.Context) ([]appmod } if validator.Jailed { - return nil, fmt.Errorf("should never retrieve a jailed validator from the power store") + return nil, errors.New("should never retrieve a jailed validator from the power store") } // if we get to a zero-power validator (which we don't bond), @@ -198,7 +199,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx context.Context) ([]appmod case validator.IsBonded(): // no state change default: - return nil, fmt.Errorf("unexpected validator status") + return nil, errors.New("unexpected validator status") } // fetch the old power bytes diff --git a/x/staking/keeper/validator.go b/x/staking/keeper/validator.go index 908cff4d8ed99..7ce5cae9822aa 100644 --- a/x/staking/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -542,7 +542,7 @@ func (k Keeper) unbondMatureValidators( } if !val.IsUnbonding() { - return fmt.Errorf("unexpected validator in unbonding queue; status was not unbonding") + return errors.New("unexpected validator in unbonding queue; status was not unbonding") } // if the ref count is not zero, early exit. diff --git a/x/staking/migrations/v5/migrations_test.go b/x/staking/migrations/v5/migrations_test.go index 9238669eedc10..91fe2b397bf4a 100644 --- a/x/staking/migrations/v5/migrations_test.go +++ b/x/staking/migrations/v5/migrations_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/staking" @@ -30,7 +30,7 @@ func TestHistoricalKeysMigration(t *testing.T) { tKey := storetypes.NewTransientStoreKey("transient_test") ctx := testutil.DefaultContext(storeKey, tKey) store := ctx.KVStore(storeKey) - logger := log.NewNopLogger() + logger := coretesting.NewNopLogger() type testCase struct { oldKey, newKey []byte @@ -87,7 +87,7 @@ func TestDelegationsByValidatorMigrations(t *testing.T) { tKey := storetypes.NewTransientStoreKey("transient_test") ctx := testutil.DefaultContext(storeKey, tKey) store := ctx.KVStore(storeKey) - logger := log.NewNopLogger() + logger := coretesting.NewNopLogger() accAddrs := sims.CreateIncrementalAccounts(11) valAddrs := sims.ConvertAddrsToValAddrs(accAddrs[0:1]) diff --git a/x/staking/module.go b/x/staking/module.go index 49a94521c989d..8ffc869274645 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -29,7 +29,6 @@ const ( var ( _ module.AppModuleSimulation = AppModule{} - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} _ module.HasInvariants = AppModule{} @@ -62,6 +61,7 @@ func NewAppModule(cdc codec.Codec, keeper *keeper.Keeper) AppModule { func (am AppModule) IsAppModule() {} // Name returns the staking module's name. +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } diff --git a/x/staking/types/authz.go b/x/staking/types/authz.go index 391a5014811e9..55194c0e28a28 100644 --- a/x/staking/types/authz.go +++ b/x/staking/types/authz.go @@ -2,7 +2,7 @@ package types import ( "context" - "fmt" + "errors" "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" @@ -64,12 +64,12 @@ func (a StakeAuthorization) MsgTypeURL() string { // is unspecified. func (a StakeAuthorization) ValidateBasic() error { if a.MaxTokens != nil && a.MaxTokens.IsNegative() { - return errorsmod.Wrapf(fmt.Errorf("max tokens should be positive"), + return errorsmod.Wrapf(errors.New("max tokens should be positive"), "negative coin amount: %v", a.MaxTokens) } if a.AuthorizationType == AuthorizationType_AUTHORIZATION_TYPE_UNSPECIFIED { - return fmt.Errorf("unknown authorization type") + return errors.New("unknown authorization type") } return nil @@ -220,7 +220,7 @@ func normalizeAuthzType(authzType AuthorizationType) (string, error) { case AuthorizationType_AUTHORIZATION_TYPE_CANCEL_UNBONDING_DELEGATION: return sdk.MsgTypeURL(&MsgCancelUnbondingDelegation{}), nil default: - return "", errorsmod.Wrapf(fmt.Errorf("unknown authorization type"), + return "", errorsmod.Wrapf(errors.New("unknown authorization type"), "cannot normalize authz type with %T", authzType) } } diff --git a/x/staking/types/genesis.go b/x/staking/types/genesis.go index e144661afe558..e3534fc4ea58c 100644 --- a/x/staking/types/genesis.go +++ b/x/staking/types/genesis.go @@ -3,8 +3,9 @@ package types import ( "encoding/json" + gogoprotoany "github.com/cosmos/gogoproto/types/any" + "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" ) // NewGenesisState creates a new GenesisState instance @@ -36,7 +37,7 @@ func GetGenesisStateFromAppState(cdc codec.JSONCodec, appState map[string]json.R } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (g GenesisState) UnpackInterfaces(c codectypes.AnyUnpacker) error { +func (g GenesisState) UnpackInterfaces(c gogoprotoany.AnyUnpacker) error { for i := range g.Validators { if err := g.Validators[i].UnpackInterfaces(c); err != nil { return err diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index 3effad961f14b..782183ff06846 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -1,6 +1,8 @@ package types import ( + gogoprotoany "github.com/cosmos/gogoproto/types/any" + "cosmossdk.io/core/address" coretransaction "cosmossdk.io/core/transaction" errorsmod "cosmossdk.io/errors" @@ -13,14 +15,14 @@ import ( ) var ( - _ coretransaction.Msg = &MsgCreateValidator{} - _ codectypes.UnpackInterfacesMessage = (*MsgCreateValidator)(nil) - _ coretransaction.Msg = &MsgEditValidator{} - _ coretransaction.Msg = &MsgDelegate{} - _ coretransaction.Msg = &MsgUndelegate{} - _ coretransaction.Msg = &MsgBeginRedelegate{} - _ coretransaction.Msg = &MsgCancelUnbondingDelegation{} - _ coretransaction.Msg = &MsgUpdateParams{} + _ coretransaction.Msg = &MsgCreateValidator{} + _ gogoprotoany.UnpackInterfacesMessage = (*MsgCreateValidator)(nil) + _ coretransaction.Msg = &MsgEditValidator{} + _ coretransaction.Msg = &MsgDelegate{} + _ coretransaction.Msg = &MsgUndelegate{} + _ coretransaction.Msg = &MsgBeginRedelegate{} + _ coretransaction.Msg = &MsgCancelUnbondingDelegation{} + _ coretransaction.Msg = &MsgUpdateParams{} ) // NewMsgCreateValidator creates a new MsgCreateValidator instance. @@ -89,7 +91,7 @@ func (msg MsgCreateValidator) Validate(ac address.Codec) error { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (msg MsgCreateValidator) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (msg MsgCreateValidator) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var pubKey cryptotypes.PubKey return unpacker.UnpackAny(msg.Pubkey, &pubKey) } @@ -160,13 +162,13 @@ func NewMsgRotateConsPubKey(valAddr string, pubKey cryptotypes.PubKey) (*MsgRota } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (msg MsgRotateConsPubKey) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (msg MsgRotateConsPubKey) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var pubKey cryptotypes.PubKey return unpacker.UnpackAny(msg.NewPubkey, &pubKey) } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (hi ConsPubKeyRotationHistory) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (hi ConsPubKeyRotationHistory) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var oldPubKey cryptotypes.PubKey err := unpacker.UnpackAny(hi.OldConsPubkey, &oldPubKey) if err != nil { diff --git a/x/staking/types/params.go b/x/staking/types/params.go index 5e27278cda901..bd619ae2c0b24 100644 --- a/x/staking/types/params.go +++ b/x/staking/types/params.go @@ -188,7 +188,7 @@ func ValidatePowerReduction(i interface{}) error { } if v.LT(math.NewInt(1)) { - return fmt.Errorf("power reduction cannot be lower than 1") + return errors.New("power reduction cannot be lower than 1") } return nil diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index 9906bc2b8009d..c2e442d4c55ae 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -7,6 +7,8 @@ import ( "strings" "time" + gogoprotoany "github.com/cosmos/gogoproto/types/any" + "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" "cosmossdk.io/errors" @@ -138,7 +140,7 @@ func (valz ValidatorsByVotingPower) Swap(i, j int) { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (v Validators) UnpackInterfaces(c codectypes.AnyUnpacker) error { +func (v Validators) UnpackInterfaces(c gogoprotoany.AnyUnpacker) error { for i := range v.Validators { if err := v.Validators[i].UnpackInterfaces(c); err != nil { return err @@ -494,7 +496,7 @@ func (v Validator) GetMinSelfDelegation() math.Int { return v.MinSelfDelegat func (v Validator) GetDelegatorShares() math.LegacyDec { return v.DelegatorShares } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (v Validator) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (v Validator) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error { var pk cryptotypes.PubKey return unpacker.UnpackAny(v.ConsensusPubkey, &pk) } diff --git a/x/tx/go.sum b/x/tx/go.sum index 9cc91bbfb20cd..54afc5a8e8edc 100644 --- a/x/tx/go.sum +++ b/x/tx/go.sum @@ -31,8 +31,8 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= -github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= +github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= diff --git a/x/upgrade/go.mod b/x/upgrade/go.mod index 53811cdae25cf..e646726b215bb 100644 --- a/x/upgrade/go.mod +++ b/x/upgrade/go.mod @@ -5,7 +5,8 @@ go 1.22.2 require ( cosmossdk.io/api v0.7.5 cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 - cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 + cosmossdk.io/depinject v1.0.0 cosmossdk.io/errors v1.0.1 cosmossdk.io/log v1.3.1 cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc @@ -68,7 +69,7 @@ require ( github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect github.com/cometbft/cometbft-db v0.12.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect - github.com/cosmos/crypto v0.1.1 // indirect + github.com/cosmos/crypto v0.1.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.2.0 // indirect @@ -207,7 +208,6 @@ replace ( cosmossdk.io/api => ../../api cosmossdk.io/core => ../../core cosmossdk.io/core/testing => ../../core/testing - cosmossdk.io/depinject => ../../depinject cosmossdk.io/log => ../../log cosmossdk.io/x/accounts => ../accounts cosmossdk.io/x/auth => ../auth diff --git a/x/upgrade/go.sum b/x/upgrade/go.sum index 78f068a92eb29..7d486fa36fef9 100644 --- a/x/upgrade/go.sum +++ b/x/upgrade/go.sum @@ -194,6 +194,8 @@ cloud.google.com/go/workflows v1.6.0/go.mod h1:6t9F5h/unJz41YqfBmqSASJSXccBLtD1V cloud.google.com/go/workflows v1.7.0/go.mod h1:JhSrZuVZWuiDfKEFxU0/F1PQjmpnpcoISEXH2bcHC3M= cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= +cosmossdk.io/depinject v1.0.0 h1:dQaTu6+O6askNXO06+jyeUAnF2/ssKwrrszP9t5q050= +cosmossdk.io/depinject v1.0.0/go.mod h1:zxK/h3HgHoA/eJVtiSsoaRaRA2D5U4cJ5thIG4ssbB8= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= @@ -310,8 +312,8 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/crypto v0.1.1 h1:AM0FJULxiDtFl7j3sYawx8smSE42YrxnqBDiZnDTVmM= -github.com/cosmos/crypto v0.1.1/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= +github.com/cosmos/crypto v0.1.2 h1:Yn500sPY+9sKVdhiPUSDtt8JOpBGMB515dOmla4zfls= +github.com/cosmos/crypto v0.1.2/go.mod h1:b6VWz3HczIpBaQPvI7KrbQeF3pXHh0al3T5e0uwMBQw= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/x/upgrade/keeper/abci_test.go b/x/upgrade/keeper/abci_test.go index f0de252394d25..a07f49a7a2825 100644 --- a/x/upgrade/keeper/abci_test.go +++ b/x/upgrade/keeper/abci_test.go @@ -12,7 +12,7 @@ import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" "cosmossdk.io/x/upgrade" @@ -122,13 +122,13 @@ func setupTest(t *testing.T, height int64, skip map[int64]bool) *TestSuite { testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) s.baseApp = baseapp.NewBaseApp( "upgrade", - log.NewNopLogger(), + coretesting.NewNopLogger(), testCtx.DB, s.encCfg.TxConfig.TxDecoder(), ) storeService := runtime.NewKVStoreService(key) - s.env = runtime.NewEnvironment(storeService, log.NewNopLogger(), runtime.EnvWithMsgRouterService(s.baseApp.MsgServiceRouter()), runtime.EnvWithQueryRouterService(s.baseApp.GRPCQueryRouter())) + s.env = runtime.NewEnvironment(storeService, coretesting.NewNopLogger(), runtime.EnvWithMsgRouterService(s.baseApp.MsgServiceRouter()), runtime.EnvWithQueryRouterService(s.baseApp.GRPCQueryRouter())) s.baseApp.SetParamStore(¶mStore{params: cmtproto.ConsensusParams{Version: &cmtproto.VersionParams{App: 1}}}) diff --git a/x/upgrade/keeper/grpc_query_test.go b/x/upgrade/keeper/grpc_query_test.go index 8e28c2ac136a3..7e6042257e170 100644 --- a/x/upgrade/keeper/grpc_query_test.go +++ b/x/upgrade/keeper/grpc_query_test.go @@ -9,7 +9,7 @@ import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" "cosmossdk.io/x/upgrade" @@ -39,7 +39,7 @@ func (suite *UpgradeTestSuite) SetupTest() { suite.encCfg = moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, upgrade.AppModule{}) key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) - env := runtime.NewEnvironment(storeService, log.NewNopLogger()) + env := runtime.NewEnvironment(storeService, coretesting.NewNopLogger()) testCtx := testutil.DefaultContextWithDB(suite.T(), key, storetypes.NewTransientStoreKey("transient_test")) suite.ctx = testCtx.Ctx diff --git a/x/upgrade/keeper/keeper.go b/x/upgrade/keeper/keeper.go index 237ee21fb2029..bafd410e9405f 100644 --- a/x/upgrade/keeper/keeper.go +++ b/x/upgrade/keeper/keeper.go @@ -415,7 +415,7 @@ func (k Keeper) HasHandler(name string) bool { func (k Keeper) ApplyUpgrade(ctx context.Context, plan types.Plan) error { handler := k.upgradeHandlers[plan.Name] if handler == nil { - return fmt.Errorf("ApplyUpgrade should never be called without first checking HasHandler") + return errors.New("ApplyUpgrade should never be called without first checking HasHandler") } vm, err := k.GetModuleVersionMap(ctx) diff --git a/x/upgrade/keeper/keeper_test.go b/x/upgrade/keeper/keeper_test.go index 0135c034fbd20..e26013a1b94b5 100644 --- a/x/upgrade/keeper/keeper_test.go +++ b/x/upgrade/keeper/keeper_test.go @@ -11,7 +11,7 @@ import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/core/header" - "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" "cosmossdk.io/x/upgrade" @@ -47,14 +47,14 @@ func (s *KeeperTestSuite) SetupTest() { s.encCfg = moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, upgrade.AppModule{}) key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) - env := runtime.NewEnvironment(storeService, log.NewNopLogger()) + env := runtime.NewEnvironment(storeService, coretesting.NewNopLogger()) s.key = key testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) s.ctx = testCtx.Ctx.WithHeaderInfo(header.Info{Height: 10}) s.baseApp = baseapp.NewBaseApp( "upgrade", - log.NewNopLogger(), + coretesting.NewNopLogger(), testCtx.DB, s.encCfg.TxConfig.TxDecoder(), ) @@ -253,7 +253,7 @@ func (s *KeeperTestSuite) TestIsSkipHeight() { s.Require().False(ok) skip := map[int64]bool{skipOne: true} storeService := runtime.NewKVStoreService(s.key) - env := runtime.NewEnvironment(storeService, log.NewNopLogger()) + env := runtime.NewEnvironment(storeService, coretesting.NewNopLogger()) upgradeKeeper := keeper.NewKeeper(env, skip, s.encCfg.Codec, s.T().TempDir(), s.baseApp, s.encodedAuthority) s.Require().True(upgradeKeeper.IsSkipHeight(9)) s.Require().False(upgradeKeeper.IsSkipHeight(10)) diff --git a/x/upgrade/keeper/migrations.go b/x/upgrade/keeper/migrations.go index 2cee9df2fe67f..bd257236d8731 100644 --- a/x/upgrade/keeper/migrations.go +++ b/x/upgrade/keeper/migrations.go @@ -3,6 +3,7 @@ package keeper import ( "context" "encoding/binary" + "errors" "fmt" storetypes "cosmossdk.io/core/store" @@ -63,7 +64,7 @@ func (m Migrator) Migrate2to3(ctx context.Context) error { func migrateAppVersion(ctx context.Context, keeper *Keeper) error { if keeper.versionModifier == nil { - return fmt.Errorf("version modifier is not set") + return errors.New("version modifier is not set") } store := keeper.KVStoreService.OpenKVStore(ctx) diff --git a/x/upgrade/module.go b/x/upgrade/module.go index 76c6e4e4ce38c..f18b426c473dd 100644 --- a/x/upgrade/module.go +++ b/x/upgrade/module.go @@ -24,7 +24,6 @@ import ( const ConsensusVersion uint64 = 3 var ( - _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ module.HasGRPCGateway = AppModule{} @@ -52,6 +51,7 @@ func NewAppModule(keeper *keeper.Keeper) AppModule { func (AppModule) IsAppModule() {} // Name returns the ModuleName +// Deprecated: kept for legacy reasons. func (AppModule) Name() string { return types.ModuleName } diff --git a/x/upgrade/types/storeloader_test.go b/x/upgrade/types/storeloader_test.go index e959a971d25f2..41f9e9956a5d5 100644 --- a/x/upgrade/types/storeloader_test.go +++ b/x/upgrade/types/storeloader_test.go @@ -10,7 +10,7 @@ import ( dbm "github.com/cosmos/cosmos-db" "github.com/stretchr/testify/require" - corelog "cosmossdk.io/core/log" + coretesting "cosmossdk.io/core/testing" "cosmossdk.io/log" "cosmossdk.io/store/metrics" pruningtypes "cosmossdk.io/store/pruning/types" @@ -119,7 +119,7 @@ func TestSetLoader(t *testing.T) { // load the app with the existing db opts := []func(*baseapp.BaseApp){baseapp.SetPruning(pruningtypes.NewPruningOptions(pruningtypes.PruningNothing))} - logger := corelog.NewNopLogger() + logger := coretesting.NewNopLogger() oldApp := baseapp.NewBaseApp(t.Name(), logger.With("instance", "orig"), db, nil, opts...) oldApp.MountStores(storetypes.NewKVStoreKey(tc.origStoreKey))