diff --git a/.github/workflows/proto-registry.yml b/.github/workflows/proto-registry.yml index 1175e2c9c260..de9d3f9e62a1 100644 --- a/.github/workflows/proto-registry.yml +++ b/.github/workflows/proto-registry.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - uses: bufbuild/buf-setup-action@v1.25.0 + - uses: bufbuild/buf-setup-action@v1.25.1 - uses: bufbuild/buf-push-action@v1 with: input: "proto" diff --git a/.github/workflows/proto.yml b/.github/workflows/proto.yml index 8d86ea3a80aa..bec887f30fa8 100644 --- a/.github/workflows/proto.yml +++ b/.github/workflows/proto.yml @@ -15,7 +15,7 @@ jobs: timeout-minutes: 5 steps: - uses: actions/checkout@v3 - - uses: bufbuild/buf-setup-action@v1.25.0 + - uses: bufbuild/buf-setup-action@v1.25.1 - uses: bufbuild/buf-lint-action@v1 with: input: "proto" @@ -24,7 +24,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - uses: bufbuild/buf-setup-action@v1.25.0 + - uses: bufbuild/buf-setup-action@v1.25.1 - uses: bufbuild/buf-breaking-action@v1 with: input: "proto" diff --git a/CHANGELOG.md b/CHANGELOG.md index f1e871464d68..78630e85b540 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,28 +44,35 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Improvements +* (x/group, x/gov) [#17220](https://github.com/cosmos/cosmos-sdk/pull/17220) Add `--skip-metadata` flag in `draft-proposal` to skip metadata prompt. * (x/group, x/gov) [#17109](https://github.com/cosmos/cosmos-sdk/pull/17109) Let proposal summary be 40x longer than metadata limit. * (all) [#16537](https://github.com/cosmos/cosmos-sdk/pull/16537) Properly propagated `fmt.Errorf` errors and using `errors.New` where appropriate. * (version) [#17096](https://github.com/cosmos/cosmos-sdk/pull/17096) Improve `getSDKVersion()` to handle module replacements ### Bug Fixes +* (baseapp) [#17251](https://github.com/cosmos/cosmos-sdk/pull/17251) VerifyVoteExtensions and ExtendVote initialize their own contexts/states, allowing VerifyVoteExtensions being called without ExtendVote. * (x/auth) [#17209](https://github.com/cosmos/cosmos-sdk/pull/17209) Internal error on AccountInfo when account's public key is not set. * (baseapp) [#17159](https://github.com/cosmos/cosmos-sdk/pull/17159) Validators can propose blocks that exceed the gas limit. * (x/group) [#17146](https://github.com/cosmos/cosmos-sdk/pull/17146) Rename x/group legacy ORM package's error codespace from "orm" to "legacy_orm", preventing collisions with ORM's error codespace "orm". * (x/bank) [#17170](https://github.com/cosmos/cosmos-sdk/pull/17170) Avoid empty spendable error message on send coins. +* (x/distribution) [#17236](https://github.com/cosmos/cosmos-sdk/pull/17236) Using "validateCommunityTax" in "Params.ValidateBasic", preventing panic when field "CommunityTax" is nil. ### API Breaking Changes +* (x/staking) [#17260](https://github.com/cosmos/cosmos-sdk/pull/17260) Use collections for `ValidatorByConsAddr`: + * remove from `types`: `GetValidatorByConsAddrKey` +* (x/staking) [#17248](https://github.com/cosmos/cosmos-sdk/pull/17248) Use collections for `UnbondingType`. + * remove from `types`: `GetUnbondingTypeKey`. +* (client) [#17259](https://github.com/cosmos/cosmos-sdk/pull/17259) Remove deprecated `clientCtx.PrintObjectLegacy`. Use `clientCtx.PrintProto` or `clientCtx.PrintRaw` instead. * (x/distribution) [#17115](https://github.com/cosmos/cosmos-sdk/pull/17115) Use collections for `PreviousProposer` and `ValidatorSlashEvents`: * remove from `Keeper`: `GetPreviousProposerConsAddr`, `SetPreviousProposerConsAddr`, `GetValidatorHistoricalReferenceCount`, `GetValidatorSlashEvent`, `SetValidatorSlashEvent`. -* (x/slashing) [17063](https://github.com/cosmos/cosmos-sdk/pull/17063) Use collections for `HistoricalInfo`: -* (x/feegrant) [16535](https://github.com/cosmos/cosmos-sdk/pull/16535) Use collections for `FeeAllowance`, `FeeAllowanceQueue`. -* (x/staking) [17063](https://github.com/cosmos/cosmos-sdk/pull/17063) Use collections for `HistoricalInfo`: +* (x/feegrant) [#16535](https://github.com/cosmos/cosmos-sdk/pull/16535) Use collections for `FeeAllowance`, `FeeAllowanceQueue`. +* (x/staking) [#17063](https://github.com/cosmos/cosmos-sdk/pull/17063) Use collections for `HistoricalInfo`: * remove `Keeper`: `GetHistoricalInfo`, `SetHistoricalInfo`, -* (x/staking) [17062](https://github.com/cosmos/cosmos-sdk/pull/17062) Use collections for `ValidatorUpdates`: +* (x/staking) [#17062](https://github.com/cosmos/cosmos-sdk/pull/17062) Use collections for `ValidatorUpdates`: * remove `Keeper`: `SetValidatorUpdates`, `GetValidatorUpdates` -* (x/slashing) [17023](https://github.com/cosmos/cosmos-sdk/pull/17023) Use collections for `ValidatorSigningInfo`: +* (x/slashing) [#17023](https://github.com/cosmos/cosmos-sdk/pull/17023) Use collections for `ValidatorSigningInfo`: * remove `Keeper`: `SetValidatorSigningInfo`, `GetValidatorSigningInfo`, `IterateValidatorSigningInfos` * (x/staking) [#17026](https://github.com/cosmos/cosmos-sdk/pull/17026) Use collections for `LastTotalPower`: * remove `Keeper`: `SetLastTotalPower`, `GetLastTotalPower` @@ -92,11 +99,13 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (x/slashing) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgUnjail` takes a string instead of `sdk.ValAddress` * (x/genutil) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `GenAppStateFromConfig`, AddGenesisAccountCmd and `GenTxCmd` takes an addresscodec to decode addresses * (x/distribution) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgDepositValidatorRewardsPool`, `NewMsgFundCommunityPool`, `NewMsgWithdrawValidatorCommission` and `NewMsgWithdrawDelegatorReward` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress` +* (client) [#17215](https://github.com/cosmos/cosmos-sdk/pull/17215) `server.StartCmd`,`server.ExportCmd`,`server.NewRollbackCmd`,`pruning.Cmd`,`genutilcli.InitCmd`,`genutilcli.GenTxCmd`,`genutilcli.CollectGenTxsCmd`,`genutilcli.AddGenesisAccountCmd`, `genutilcli.GenesisCoreCommand` do not take a home directory anymore. It is inferred from the root command. ### CLI Breaking Changes * (server) [#17177](https://github.com/cosmos/cosmos-sdk/pull/17177) Remove `iavl-lazy-loading` configuration. * (rosetta) [#16276](https://github.com/cosmos/cosmos-sdk/issues/16276) Rosetta migration to standalone repo. +* (cli) [#17184](https://github.com/cosmos/cosmos-sdk/pull/17184) All json keys returned by the `status` command are now snake case instead of pascal case. ### State Machine Breaking diff --git a/Dockerfile b/Dockerfile index 2af186b6ecc5..77483cb5f1e7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -48,5 +48,8 @@ CMD ["simd"] STOPSIGNAL SIGTERM WORKDIR /root +# Install minimum necessary dependencies +RUN apk add --no-cache curl make bash jq sed + # Copy over binaries from the build-env COPY --from=build-env /go/src/github.com/cosmos/cosmos-sdk/build/simd /usr/bin/simd diff --git a/UPGRADING.md b/UPGRADING.md index e470b82de1a5..d1a3ba787b36 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -198,6 +198,40 @@ depinject.Supply( Users manually wiring their chain need to use the new `module.NewBasicManagerFromManager` function, after the module manager creation, and pass a `map[string]module.AppModuleBasic` as argument for optionally overridding some module's `AppModuleBasic`. +#### AutoCLI + +[`AutoCLI`](https://docs.cosmos.network/main/building-modules/autocli) has been implemented by the SDK for all its module CLI queries. This means chains must add the following in their `root.go` to enable `AutoCLI` in their application: + +```go +if err := autoCliOpts.EnhanceRootCommand(rootCmd); err != nil { + panic(err) +} +``` + +Where `autoCliOpts` is the autocli options of the app, containing all modules and codecs. +That value can injected by depinject ([see root_v2.go](https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-beta.0/simapp/simd/cmd/root_v2.go#L49-L67)) or manually provided by the app ([see legacy app.go](https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-beta.0/simapp/app.go#L636-L655)). + +:::warning +Not doing this will result in all core SDK modules queries not to be included in the binary. +::: + +Additionally `AutoCLI` automatically adds the custom modules commands to the root command for all modules implementing the [`appmodule.AppModule`](https://pkg.go.dev/cosmossdk.io/core/appmodule#AppModule) interface. +This means, after ensuring all the used modules implement this interface, the following can be removed from your `root.go`: + +```diff +func txCommand() *cobra.Command { + .... +- appd.ModuleBasics.AddTxCommands(cmd) +} +``` + +```diff +func queryCommand() *cobra.Command { + .... +- appd.ModuleBasics.AddQueryCommands(cmd) +} +``` + ### Packages #### Math diff --git a/baseapp/abci.go b/baseapp/abci.go index 8e5610970d7b..02b2d666c3a2 100644 --- a/baseapp/abci.go +++ b/baseapp/abci.go @@ -548,7 +548,8 @@ func (app *BaseApp) ExtendVote(_ context.Context, req *abci.RequestExtendVote) ( // Always reset state given that ExtendVote and VerifyVoteExtension can timeout // and be called again in a subsequent round. emptyHeader := cmtproto.Header{ChainID: app.chainID, Height: req.Height} - app.setState(execModeVoteExtension, emptyHeader) + ms := app.cms.CacheMultiStore() + ctx := sdk.NewContext(ms, emptyHeader, false, app.logger).WithStreamingManager(app.streamingManager) if app.extendVote == nil { return nil, errors.New("application ExtendVote handler not set") @@ -556,14 +557,14 @@ func (app *BaseApp) ExtendVote(_ context.Context, req *abci.RequestExtendVote) ( // If vote extensions are not enabled, as a safety precaution, we return an // error. - cp := app.GetConsensusParams(app.voteExtensionState.ctx) + cp := app.GetConsensusParams(ctx) extsEnabled := cp.Abci != nil && req.Height >= cp.Abci.VoteExtensionsEnableHeight && cp.Abci.VoteExtensionsEnableHeight != 0 if !extsEnabled { return nil, fmt.Errorf("vote extensions are not enabled; unexpected call to ExtendVote at height %d", req.Height) } - app.voteExtensionState.ctx = app.voteExtensionState.ctx. + ctx = ctx. WithConsensusParams(cp). WithBlockGasMeter(storetypes.NewInfiniteGasMeter()). WithBlockHeight(req.Height). @@ -588,7 +589,7 @@ func (app *BaseApp) ExtendVote(_ context.Context, req *abci.RequestExtendVote) ( } }() - resp, err = app.extendVote(app.voteExtensionState.ctx, req) + resp, err = app.extendVote(ctx, req) if err != nil { app.logger.Error("failed to extend vote", "height", req.Height, "error", err) return &abci.ResponseExtendVote{VoteExtension: []byte{}}, nil @@ -608,9 +609,13 @@ func (app *BaseApp) VerifyVoteExtension(req *abci.RequestVerifyVoteExtension) (r return nil, errors.New("application VerifyVoteExtension handler not set") } + emptyHeader := cmtproto.Header{ChainID: app.chainID, Height: req.Height} + ms := app.cms.CacheMultiStore() + ctx := sdk.NewContext(ms, emptyHeader, false, app.logger).WithStreamingManager(app.streamingManager) + // If vote extensions are not enabled, as a safety precaution, we return an // error. - cp := app.GetConsensusParams(app.voteExtensionState.ctx) + cp := app.GetConsensusParams(ctx) extsEnabled := cp.Abci != nil && req.Height >= cp.Abci.VoteExtensionsEnableHeight && cp.Abci.VoteExtensionsEnableHeight != 0 if !extsEnabled { @@ -631,7 +636,7 @@ func (app *BaseApp) VerifyVoteExtension(req *abci.RequestVerifyVoteExtension) (r } }() - resp, err = app.verifyVoteExt(app.voteExtensionState.ctx, req) + resp, err = app.verifyVoteExt(ctx, req) if err != nil { app.logger.Error("failed to verify vote extension", "height", req.Height, "error", err) return &abci.ResponseVerifyVoteExtension{Status: abci.ResponseVerifyVoteExtension_REJECT}, nil diff --git a/baseapp/abci_test.go b/baseapp/abci_test.go index 4e164b812be0..4f9207924f19 100644 --- a/baseapp/abci_test.go +++ b/baseapp/abci_test.go @@ -364,6 +364,63 @@ func TestABCI_ExtendVote(t *testing.T) { require.Equal(t, abci.ResponseVerifyVoteExtension_REJECT, vres.Status) } +// TestABCI_OnlyVerifyVoteExtension makes sure we can call VerifyVoteExtension +// without having called ExtendVote before. +func TestABCI_OnlyVerifyVoteExtension(t *testing.T) { + name := t.Name() + db := dbm.NewMemDB() + app := baseapp.NewBaseApp(name, log.NewTestLogger(t), db, nil) + + app.SetVerifyVoteExtensionHandler(func(ctx sdk.Context, req *abci.RequestVerifyVoteExtension) (*abci.ResponseVerifyVoteExtension, error) { + // do some kind of verification here + expectedVoteExt := "foo" + hex.EncodeToString(req.Hash) + strconv.FormatInt(req.Height, 10) + if !bytes.Equal(req.VoteExtension, []byte(expectedVoteExt)) { + return &abci.ResponseVerifyVoteExtension{Status: abci.ResponseVerifyVoteExtension_REJECT}, nil + } + + return &abci.ResponseVerifyVoteExtension{Status: abci.ResponseVerifyVoteExtension_ACCEPT}, nil + }) + + app.SetParamStore(¶mStore{db: dbm.NewMemDB()}) + _, err := app.InitChain( + &abci.RequestInitChain{ + InitialHeight: 1, + ConsensusParams: &cmtproto.ConsensusParams{ + Abci: &cmtproto.ABCIParams{ + VoteExtensionsEnableHeight: 200, + }, + }, + }, + ) + require.NoError(t, err) + + // Verify Vote Extensions + _, err = app.VerifyVoteExtension(&abci.RequestVerifyVoteExtension{Height: 123, VoteExtension: []byte("1234567")}) + require.ErrorContains(t, err, "vote extensions are not enabled") + + // First vote on the first enabled height + vres, err := app.VerifyVoteExtension(&abci.RequestVerifyVoteExtension{Height: 200, Hash: []byte("thehash"), VoteExtension: []byte("foo74686568617368200")}) + require.NoError(t, err) + require.Equal(t, abci.ResponseVerifyVoteExtension_ACCEPT, vres.Status) + + vres, err = app.VerifyVoteExtension(&abci.RequestVerifyVoteExtension{Height: 1000, Hash: []byte("thehash"), VoteExtension: []byte("foo746865686173681000")}) + require.NoError(t, err) + require.Equal(t, abci.ResponseVerifyVoteExtension_ACCEPT, vres.Status) + + // Reject because it's just some random bytes + vres, err = app.VerifyVoteExtension(&abci.RequestVerifyVoteExtension{Height: 201, Hash: []byte("thehash"), VoteExtension: []byte("12345678")}) + require.NoError(t, err) + require.Equal(t, abci.ResponseVerifyVoteExtension_REJECT, vres.Status) + + // Reject because the verification failed (no error) + app.SetVerifyVoteExtensionHandler(func(ctx sdk.Context, req *abci.RequestVerifyVoteExtension) (*abci.ResponseVerifyVoteExtension, error) { + return nil, errors.New("some error") + }) + vres, err = app.VerifyVoteExtension(&abci.RequestVerifyVoteExtension{Height: 201, Hash: []byte("thehash"), VoteExtension: []byte("12345678")}) + require.NoError(t, err) + require.Equal(t, abci.ResponseVerifyVoteExtension_REJECT, vres.Status) +} + func TestABCI_GRPCQuery(t *testing.T) { grpcQueryOpt := func(bapp *baseapp.BaseApp) { testdata.RegisterQueryServer( diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 586a83f7b38e..71a297502b88 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -104,11 +104,6 @@ type BaseApp struct { // previous block's state. This state is never committed. In case of multiple // consensus rounds, the state is always reset to the previous block's state. // - // - voteExtensionState: Used for ExtendVote and VerifyVoteExtension, which is - // set based on the previous block's state. This state is never committed. In - // case of multiple rounds, the state is always reset to the previous block's - // state. - // // - processProposalState: Used for ProcessProposal, which is set based on the // the previous block's state. This state is never committed. In case of // multiple rounds, the state is always reset to the previous block's state. @@ -118,7 +113,6 @@ type BaseApp struct { checkState *state prepareProposalState *state processProposalState *state - voteExtensionState *state finalizeBlockState *state // An inter-block write-through cache provided to the context during the ABCI @@ -475,9 +469,6 @@ func (app *BaseApp) setState(mode execMode, header cmtproto.Header) { case execModeProcessProposal: app.processProposalState = baseState - case execModeVoteExtension: - app.voteExtensionState = baseState - case execModeFinalize: app.finalizeBlockState = baseState diff --git a/client/context.go b/client/context.go index d73d72e21543..72ad98a03d17 100644 --- a/client/context.go +++ b/client/context.go @@ -321,17 +321,6 @@ func (ctx Context) PrintProto(toPrint proto.Message) error { return ctx.printOutput(out) } -// PrintObjectLegacy is a variant of PrintProto that doesn't require a proto.Message type -// and uses amino JSON encoding. -// Deprecated: It will be removed in the near future! -func (ctx Context) PrintObjectLegacy(toPrint interface{}) error { - out, err := ctx.LegacyAmino.MarshalJSON(toPrint) - if err != nil { - return err - } - return ctx.printOutput(out) -} - // PrintRaw is a variant of PrintProto that doesn't require a proto.Message type // and uses a raw JSON message. No marshaling is performed. func (ctx Context) PrintRaw(toPrint json.RawMessage) error { diff --git a/client/context_test.go b/client/context_test.go index 9ea673b64f91..34dd381f4cfb 100644 --- a/client/context_test.go +++ b/client/context_test.go @@ -68,52 +68,6 @@ x: "10" `, buf.String()) } -func TestContext_PrintObjectLegacy(t *testing.T) { - ctx := client.Context{} - - animal := &testdata.Dog{ - Size_: "big", - Name: "Spot", - } - anyAnimal, err := types.NewAnyWithValue(animal) - require.NoError(t, err) - hasAnimal := &testdata.HasAnimal{ - Animal: anyAnimal, - X: 10, - } - - // amino - amino := testdata.NewTestAmino() - ctx = ctx.WithLegacyAmino(&codec.LegacyAmino{Amino: amino}) - - // json - buf := &bytes.Buffer{} - ctx = ctx.WithOutput(buf) - ctx.OutputFormat = flags.OutputFormatJSON - err = ctx.PrintObjectLegacy(hasAnimal) - require.NoError(t, err) - require.Equal(t, - `{"type":"testpb/HasAnimal","value":{"animal":{"type":"testpb/Dog","value":{"size":"big","name":"Spot"}},"x":"10"}} -`, buf.String()) - - // yaml - buf = &bytes.Buffer{} - ctx = ctx.WithOutput(buf) - ctx.OutputFormat = flags.OutputFormatText - err = ctx.PrintObjectLegacy(hasAnimal) - require.NoError(t, err) - require.Equal(t, - `type: testpb/HasAnimal -value: - animal: - type: testpb/Dog - value: - name: Spot - size: big - x: "10" -`, buf.String()) -} - func TestContext_PrintRaw(t *testing.T) { ctx := client.Context{} hasAnimal := json.RawMessage(`{"animal":{"@type":"/testpb.Dog","size":"big","name":"Spot"},"x":"10"}`) diff --git a/client/grpc/cmtservice/block.go b/client/grpc/cmtservice/block.go index 9b2ca6bb0c9c..1575626fa629 100644 --- a/client/grpc/cmtservice/block.go +++ b/client/grpc/cmtservice/block.go @@ -9,6 +9,15 @@ import ( "github.com/cosmos/cosmos-sdk/client" ) +func getBlockHeight(ctx context.Context, clientCtx client.Context) (int64, error) { + status, err := getNodeStatus(ctx, clientCtx) + if err != nil { + return 0, err + } + height := status.SyncInfo.LatestBlockHeight + return height, nil +} + func getBlock(ctx context.Context, clientCtx client.Context, height *int64) (*coretypes.ResultBlock, error) { // get the node node, err := clientCtx.GetNode() diff --git a/client/grpc/cmtservice/service.go b/client/grpc/cmtservice/service.go index 8740c0d8f117..39e17ce1a9dc 100644 --- a/client/grpc/cmtservice/service.go +++ b/client/grpc/cmtservice/service.go @@ -11,9 +11,10 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/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" + sdk "github.com/cosmos/cosmos-sdk/types" qtypes "github.com/cosmos/cosmos-sdk/types/query" "github.com/cosmos/cosmos-sdk/version" ) @@ -80,12 +81,12 @@ func (s queryServer) GetLatestBlock(ctx context.Context, _ *GetLatestBlockReques // GetBlockByHeight implements ServiceServer.GetBlockByHeight func (s queryServer) GetBlockByHeight(ctx context.Context, req *GetBlockByHeightRequest) (*GetBlockByHeightResponse, error) { - chainHeight, err := rpc.GetChainHeight(s.clientCtx) + blockHeight, err := getBlockHeight(ctx, s.clientCtx) if err != nil { return nil, err } - if req.Height > chainHeight { + if req.Height > blockHeight { return nil, status.Error(codes.InvalidArgument, "requested block height is bigger then the chain length") } @@ -108,7 +109,7 @@ func (s queryServer) GetLatestValidatorSet(ctx context.Context, req *GetLatestVa return nil, err } - return validatorsOutput(ctx, s.clientCtx, nil, page, limit) + return ValidatorsOutput(ctx, s.clientCtx, nil, page, limit) } func (m *GetLatestValidatorSetResponse) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { @@ -130,16 +131,16 @@ func (s queryServer) GetValidatorSetByHeight(ctx context.Context, req *GetValida return nil, err } - chainHeight, err := rpc.GetChainHeight(s.clientCtx) + blockHeight, err := getBlockHeight(ctx, s.clientCtx) if err != nil { return nil, status.Error(codes.Internal, "failed to parse chain height") } - if req.Height > chainHeight { + if req.Height > blockHeight { return nil, status.Error(codes.InvalidArgument, "requested block height is bigger then the chain length") } - r, err := validatorsOutput(ctx, s.clientCtx, &req.Height, page, limit) + r, err := ValidatorsOutput(ctx, s.clientCtx, &req.Height, page, limit) if err != nil { return nil, err } @@ -151,8 +152,8 @@ func (s queryServer) GetValidatorSetByHeight(ctx context.Context, req *GetValida }, nil } -func validatorsOutput(ctx context.Context, cctx client.Context, height *int64, page, limit int) (*GetLatestValidatorSetResponse, error) { - vs, err := rpc.GetValidators(ctx, cctx, height, &page, &limit) +func ValidatorsOutput(ctx context.Context, clientCtx client.Context, height *int64, page, limit int) (*GetLatestValidatorSetResponse, error) { + vs, err := getValidators(ctx, clientCtx, height, page, limit) if err != nil { return nil, err } @@ -161,18 +162,22 @@ func validatorsOutput(ctx context.Context, cctx client.Context, height *int64, p BlockHeight: vs.BlockHeight, Validators: make([]*Validator, len(vs.Validators)), Pagination: &qtypes.PageResponse{ - Total: vs.Total, + Total: uint64(vs.Total), }, } for i, v := range vs.Validators { - anyPub, err := codectypes.NewAnyWithValue(v.PubKey) + pk, err := cryptocodec.FromCmtPubKeyInterface(v.PubKey) + if err != nil { + return nil, err + } + anyPub, err := codectypes.NewAnyWithValue(pk) if err != nil { return nil, err } resp.Validators[i] = &Validator{ - Address: v.Address.String(), + Address: sdk.ConsAddress(v.Address).String(), ProposerPriority: v.ProposerPriority, PubKey: anyPub, VotingPower: v.VotingPower, diff --git a/client/grpc/cmtservice/validator.go b/client/grpc/cmtservice/validator.go new file mode 100644 index 000000000000..5b81d2bc4cac --- /dev/null +++ b/client/grpc/cmtservice/validator.go @@ -0,0 +1,17 @@ +package cmtservice + +import ( + "context" + + coretypes "github.com/cometbft/cometbft/rpc/core/types" + + "github.com/cosmos/cosmos-sdk/client" +) + +func getValidators(ctx context.Context, clientCtx client.Context, height *int64, page, limit int) (*coretypes.ResultValidators, error) { + node, err := clientCtx.GetNode() + if err != nil { + return nil, err + } + return node.Validators(ctx, height, &page, &limit) +} diff --git a/client/pruning/main.go b/client/pruning/main.go index 51dc5f9c2162..db23564a1d2a 100644 --- a/client/pruning/main.go +++ b/client/pruning/main.go @@ -15,13 +15,14 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server" servertypes "github.com/cosmos/cosmos-sdk/server/types" + "github.com/cosmos/cosmos-sdk/version" ) const FlagAppDBBackend = "app-db-backend" // Cmd prunes the sdk root multi store history versions based on the pruning options // specified by command flags. -func Cmd(appCreator servertypes.AppCreator, defaultNodeHome string) *cobra.Command { +func Cmd(appCreator servertypes.AppCreator) *cobra.Command { cmd := &cobra.Command{ Use: "prune [pruning-method]", Short: "Prune app history states by keeping the recent heights and deleting old heights", @@ -35,7 +36,7 @@ The pruning option is provided via the 'pruning' argument or alternatively with Note: When the --app-db-backend flag is not specified, the default backend type is 'goleveldb'. Supported app-db-backend types include 'goleveldb', 'rocksdb', 'pebbledb'.`, - Example: "prune custom --pruning-keep-recent 100 --app-db-backend 'goleveldb'", + Example: fmt.Sprintf("%s prune custom --pruning-keep-recent 100 --app-db-backend 'goleveldb'", version.AppName), Args: cobra.RangeArgs(0, 1), RunE: func(cmd *cobra.Command, args []string) error { // bind flags to the Context's Viper so we can get pruning options. @@ -43,6 +44,9 @@ Supported app-db-backend types include 'goleveldb', 'rocksdb', 'pebbledb'.`, if err := vp.BindPFlags(cmd.Flags()); err != nil { return err } + if err := vp.BindPFlags(cmd.PersistentFlags()); err != nil { + return err + } // use the first argument if present to set the pruning method if len(args) > 0 { @@ -61,10 +65,6 @@ Supported app-db-backend types include 'goleveldb', 'rocksdb', 'pebbledb'.`, ) home := vp.GetString(flags.FlagHome) - if home == "" { - home = defaultNodeHome - } - db, err := openDB(home, server.GetAppDBBackend(vp)) if err != nil { return err @@ -97,7 +97,6 @@ Supported app-db-backend types include 'goleveldb', 'rocksdb', 'pebbledb'.`, }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().String(FlagAppDBBackend, "", "The type of database for application and snapshots databases") cmd.Flags().Uint64(server.FlagPruningKeepRecent, 0, "Number of recent heights to keep on disk (ignored if pruning is not 'custom')") cmd.Flags().Uint64(server.FlagPruningInterval, 10, diff --git a/client/rpc/status.go b/client/rpc/status.go index 30f59d7c8657..5f50ae36af14 100644 --- a/client/rpc/status.go +++ b/client/rpc/status.go @@ -3,32 +3,14 @@ package rpc import ( "context" - "github.com/cometbft/cometbft/p2p" + cmtjson "github.com/cometbft/cometbft/libs/json" coretypes "github.com/cometbft/cometbft/rpc/core/types" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" ) -// ValidatorInfo is info about the node's validator, same as CometBFT, -// except that we use our own PubKey. -type validatorInfo struct { - Address []byte - PubKey cryptotypes.PubKey - VotingPower int64 -} - -// ResultStatus is node's info, same as CometBFT, except that we use our own -// PubKey. -type resultStatus struct { - NodeInfo p2p.DefaultNodeInfo - SyncInfo coretypes.SyncInfo - ValidatorInfo validatorInfo -} - // StatusCommand returns the command to return the status of the network. func StatusCommand() *cobra.Command { cmd := &cobra.Command{ @@ -45,35 +27,23 @@ func StatusCommand() *cobra.Command { return err } - var pk cryptotypes.PubKey - // `status` has TM pubkeys, we need to convert them to our pubkeys. - if status.ValidatorInfo.PubKey != nil { - pk, err = cryptocodec.FromCmtPubKeyInterface(status.ValidatorInfo.PubKey) - if err != nil { - return err - } - } - statusWithPk := resultStatus{ - NodeInfo: status.NodeInfo, - SyncInfo: status.SyncInfo, - ValidatorInfo: validatorInfo{ - Address: status.ValidatorInfo.Address, - PubKey: pk, - VotingPower: status.ValidatorInfo.VotingPower, - }, - } - - output, err := clientCtx.LegacyAmino.MarshalJSON(statusWithPk) + output, err := cmtjson.Marshal(status) if err != nil { return err } - cmd.Println(string(output)) - return nil + // In order to maintain backwards compatibility, the default json format output + outputFormat, _ := cmd.Flags().GetString(flags.FlagOutput) + if outputFormat == flags.OutputFormatJSON { + clientCtx = clientCtx.WithOutputFormat(flags.OutputFormatJSON) + } + + return clientCtx.PrintRaw(output) }, } cmd.Flags().StringP(flags.FlagNode, "n", "tcp://localhost:26657", "Node to connect to") + cmd.Flags().StringP(flags.FlagOutput, "o", "json", "Output format (text|json)") return cmd } diff --git a/client/rpc/validators.go b/client/rpc/validators.go index 55c2262a8881..7facee4259d4 100644 --- a/client/rpc/validators.go +++ b/client/rpc/validators.go @@ -1,24 +1,16 @@ package rpc import ( - "context" - "fmt" "strconv" - "strings" - cmttypes "github.com/cometbft/cometbft/types" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/client/grpc/cmtservice" "github.com/cosmos/cosmos-sdk/types/query" ) -// TODO these next two functions feel kinda hacky based on their placement - // ValidatorCommand returns the validator set for a given height func ValidatorCommand() *cobra.Command { cmd := &cobra.Command{ @@ -49,12 +41,12 @@ func ValidatorCommand() *cobra.Command { page, _ := cmd.Flags().GetInt(flags.FlagPage) limit, _ := cmd.Flags().GetInt(flags.FlagLimit) - result, err := GetValidators(cmd.Context(), clientCtx, height, &page, &limit) + response, err := cmtservice.ValidatorsOutput(cmd.Context(), clientCtx, height, page, limit) if err != nil { return err } - return clientCtx.PrintObjectLegacy(result) + return clientCtx.PrintProto(response) }, } @@ -65,84 +57,3 @@ func ValidatorCommand() *cobra.Command { return cmd } - -// Validator output -type ValidatorOutput struct { - Address sdk.ConsAddress `json:"address"` - PubKey cryptotypes.PubKey `json:"pub_key"` - ProposerPriority int64 `json:"proposer_priority"` - VotingPower int64 `json:"voting_power"` -} - -// Validators at a certain height output in bech32 format -type ResultValidatorsOutput struct { - BlockHeight int64 `json:"block_height"` - Validators []ValidatorOutput `json:"validators"` - Total uint64 `json:"total"` -} - -func (rvo ResultValidatorsOutput) String() string { - var b strings.Builder - - fmt.Fprintf(&b, "block height: %d\n", rvo.BlockHeight) - fmt.Fprintf(&b, "total count: %d\n", rvo.Total) - - for _, val := range rvo.Validators { - fmt.Fprintf(&b, ` - Address: %s - Pubkey: %s - ProposerPriority: %d - VotingPower: %d - `, - val.Address, val.PubKey, val.ProposerPriority, val.VotingPower, - ) - } - - return b.String() -} - -func validatorOutput(validator *cmttypes.Validator) (ValidatorOutput, error) { - pk, err := cryptocodec.FromCmtPubKeyInterface(validator.PubKey) - if err != nil { - return ValidatorOutput{}, err - } - - return ValidatorOutput{ - Address: sdk.ConsAddress(validator.Address), - PubKey: pk, - ProposerPriority: validator.ProposerPriority, - VotingPower: validator.VotingPower, - }, nil -} - -// GetValidators from client -func GetValidators(ctx context.Context, clientCtx client.Context, height *int64, page, limit *int) (ResultValidatorsOutput, error) { - // get the node - node, err := clientCtx.GetNode() - if err != nil { - return ResultValidatorsOutput{}, err - } - - validatorsRes, err := node.Validators(ctx, height, page, limit) - if err != nil { - return ResultValidatorsOutput{}, err - } - - total := validatorsRes.Total - if validatorsRes.Total < 0 { - total = 0 - } - out := ResultValidatorsOutput{ - BlockHeight: validatorsRes.BlockHeight, - Validators: make([]ValidatorOutput, len(validatorsRes.Validators)), - Total: uint64(total), - } - for i := 0; i < len(validatorsRes.Validators); i++ { - out.Validators[i], err = validatorOutput(validatorsRes.Validators[i]) - if err != nil { - return out, err - } - } - - return out, nil -} diff --git a/client/v2/go.mod b/client/v2/go.mod index 972e43235ac2..5f75af05cfc3 100644 --- a/client/v2/go.mod +++ b/client/v2/go.mod @@ -22,7 +22,7 @@ require ( require ( cosmossdk.io/collections v0.3.0 // indirect cosmossdk.io/errors v1.0.0 // indirect - cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca // indirect + cosmossdk.io/log v1.2.0 // indirect cosmossdk.io/math v1.0.1 // indirect cosmossdk.io/store v1.0.0-alpha.1 // indirect cosmossdk.io/x/tx v0.9.1 // indirect diff --git a/client/v2/go.sum b/client/v2/go.sum index 0b89fd25dfec..3e9f4fe0ce62 100644 --- a/client/v2/go.sum +++ b/client/v2/go.sum @@ -45,8 +45,8 @@ cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca h1:msenprh2BLLRwNT7zN56TbBHOGk/7ARQckXHxXyvjoQ= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca/go.mod h1:PkIAKXZvaxrTRc++z53XMRvFk8AcGGWYHcMIPzVYX9c= +cosmossdk.io/log v1.2.0 h1:BbykkDsutXPSy8RojFB3KZEWyvMsToLy0ykb/ZhsLqQ= +cosmossdk.io/log v1.2.0/go.mod h1:GNSCc/6+DhFIj1aLn/j7Id7PaO8DzNylUZoOYBL9+I4= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= cosmossdk.io/store v1.0.0-alpha.1 h1:/151XxAgm0tiKuYrtJzMG61lf6enpPuP+D/hIN8cRjQ= diff --git a/docs/architecture/adr-064-abci-2.0.md b/docs/architecture/adr-064-abci-2.0.md index 98651a43abfe..f392ccae1e8c 100644 --- a/docs/architecture/adr-064-abci-2.0.md +++ b/docs/architecture/adr-064-abci-2.0.md @@ -106,10 +106,11 @@ type ExtendVoteHandler func(sdk.Context, abci.RequestExtendVote) abci.ResponseEx type VerifyVoteExtensionHandler func(sdk.Context, abci.RequestVerifyVoteExtension) abci.ResponseVerifyVoteExtension ``` -A new execution state, `voteExtensionState`, will be introduced and provided as -the `Context` that is supplied to both handlers. It will contain relevant metadata -such as the block height and block hash. Note, `voteExtensionState` is never -committed and will exist as ephemeral state only in the context of a single block. +An ephemeral context and state will be supplied to both handlers. The +context will contain relevant metadata such as the block height and block hash. +The state will be a cached version of the committed state of the application and +will be discarded after the execution of the handler, this means that both handlers +get a fresh state view and no changes made to it will be written. If an application decides to implement `ExtendVoteHandler`, it must return a non-nil `ResponseExtendVote.VoteExtension`. diff --git a/docs/docs/basics/00-app-anatomy.md b/docs/docs/basics/00-app-anatomy.md index e19e1b5e18a7..005bbafb0ece 100644 --- a/docs/docs/basics/00-app-anatomy.md +++ b/docs/docs/basics/00-app-anatomy.md @@ -182,7 +182,7 @@ Each module should also implement the `RegisterServices` method as part of the [ ### gRPC `Query` Services -gRPC `Query` services allow users to query the state using [gRPC](https://grpc.io). They are enabled by default, and can be configured under the `grpc.enable` and `grpc.address` fields inside [`app.toml`](../run-node/02-interact-node.md#configuring-the-node-using-apptoml). +gRPC `Query` services allow users to query the state using [gRPC](https://grpc.io). They are enabled by default, and can be configured under the `grpc.enable` and `grpc.address` fields inside [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml). gRPC `Query` services are defined in the module's Protobuf definition files, specifically inside `query.proto`. The `query.proto` definition file exposes a single `Query` [Protobuf service](https://developers.google.com/protocol-buffers/docs/proto#services). Each gRPC query endpoint corresponds to a service method, starting with the `rpc` keyword, inside the `Query` service. @@ -230,7 +230,7 @@ Some external clients may not wish to use gRPC. In this case, the Cosmos SDK pro The REST endpoints are defined in the Protobuf files, along with the gRPC services, using Protobuf annotations. Modules that want to expose REST queries should add `google.api.http` annotations to their `rpc` methods. By default, all REST endpoints defined in the SDK have a URL starting with the `/cosmos/` prefix. -The Cosmos SDK also provides a development endpoint to generate [Swagger](https://swagger.io/) definition files for these REST endpoints. This endpoint can be enabled inside the [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml) config file, under the `api.swagger` key. +The Cosmos SDK also provides a development endpoint to generate [Swagger](https://swagger.io/) definition files for these REST endpoints. This endpoint can be enabled inside the [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml) config file, under the `api.swagger` key. ## Application Interface diff --git a/docs/docs/basics/02-query-lifecycle.md b/docs/docs/basics/02-query-lifecycle.md index 502160efd721..29332d802eff 100644 --- a/docs/docs/basics/02-query-lifecycle.md +++ b/docs/docs/basics/02-query-lifecycle.md @@ -35,7 +35,7 @@ Note that the general format is as follows: simd query [moduleName] [command] --flag ``` -To provide values such as `--node` (the full-node the CLI connects to), the user can use the [`app.toml`](../run-node/02-interact-node.md#configuring-the-node-using-apptoml) config file to set them or provide them as flags. +To provide values such as `--node` (the full-node the CLI connects to), the user can use the [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml) config file to set them or provide them as flags. The CLI understands a specific set of commands, defined in a hierarchical structure by the application developer: from the [root command](../core/07-cli.md#root-command) (`simd`), the type of command (`Myquery`), the module that contains the command (`staking`), and command itself (`delegations`). Thus, the CLI knows exactly which module handles this command and directly passes the call there. diff --git a/docs/docs/building-modules/09-module-interfaces.md b/docs/docs/building-modules/09-module-interfaces.md index 01e494bde003..e5d9e6e215b5 100644 --- a/docs/docs/building-modules/09-module-interfaces.md +++ b/docs/docs/building-modules/09-module-interfaces.md @@ -159,6 +159,6 @@ Modules that want to expose REST queries should add `google.api.http` annotation https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/proto/cosmos/auth/v1beta1/query.proto#L14-L89 ``` -gRPC gateway is started in-process along with the application and CometBFT. It can be enabled or disabled by setting gRPC Configuration `enable` in [`app.toml`](../run-node/02-interact-node.md#configuring-the-node-using-apptoml). +gRPC gateway is started in-process along with the application and CometBFT. It can be enabled or disabled by setting gRPC Configuration `enable` in [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml). -The Cosmos SDK provides a command for generating [Swagger](https://swagger.io/) documentation (`protoc-gen-swagger`). Setting `swagger` in [`app.toml`](../run-node/02-interact-node.md#configuring-the-node-using-apptoml) defines if swagger documentation should be automatically registered. +The Cosmos SDK provides a command for generating [Swagger](https://swagger.io/) documentation (`protoc-gen-swagger`). Setting `swagger` in [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml) defines if swagger documentation should be automatically registered. diff --git a/docs/docs/core/00-baseapp.md b/docs/docs/core/00-baseapp.md index adfa6d6b3ead..3a0aa2651d5b 100644 --- a/docs/docs/core/00-baseapp.md +++ b/docs/docs/core/00-baseapp.md @@ -90,7 +90,6 @@ Then, parameters used to define [volatile states](#state-updates) (i.e. cached s [`Commit`](#commit) and gets re-initialized on `FinalizeBlock`. * `processProposalState`: This state is updated during [`ProcessProposal`](#process-proposal). * `prepareProposalState`: This state is updated during [`PrepareProposal`](#prepare-proposal). -* `voteExtensionState`: This state is updated during [`ExtendVote`](#extendvote) & [`VerifyVoteExtension`](#verifyvoteextension). Finally, a few more important parameters: @@ -130,7 +129,7 @@ Naturally, developers can add additional `options` based on their application's ## State Updates The `BaseApp` maintains four primary volatile states and a root or main state. The main state -is the canonical state of the application and the volatile states, `checkState`, `prepareProposalState`, `processProposalState`, `voteExtensionState` and `finalizeBlockState` +is the canonical state of the application and the volatile states, `checkState`, `prepareProposalState`, `processProposalState` and `finalizeBlockState` are used to handle state transitions in-between the main state made during [`Commit`](#commit). Internally, there is only a single `CommitMultiStore` which we refer to as the main or root state. diff --git a/docs/docs/core/06-grpc_rest.md b/docs/docs/core/06-grpc_rest.md index b8ae40f7050b..f78bfa62b346 100644 --- a/docs/docs/core/06-grpc_rest.md +++ b/docs/docs/core/06-grpc_rest.md @@ -78,7 +78,7 @@ The Cosmos SDK's [Swagger generation script](https://github.com/cosmos/cosmos-sd ## CometBFT RPC -Independently from the Cosmos SDK, CometBFT also exposes a RPC server. This RPC server can be configured by tuning parameters under the `rpc` table in the `~/.simapp/config/config.toml`, the default listening address is `tcp://localhost:26657`. An OpenAPI specification of all CometBFT RPC endpoints is available [here](https://docs.cometbft.com/master/rpc/). +Independently from the Cosmos SDK, CometBFT also exposes a RPC server. This RPC server can be configured by tuning parameters under the `rpc` table in the `~/.simapp/config/config.toml`, the default listening address is `tcp://localhost:26657`. An OpenAPI specification of all CometBFT RPC endpoints is available [here](https://docs.cometbft.com/main/rpc/). Some CometBFT RPC endpoints are directly related to the Cosmos SDK: @@ -86,7 +86,8 @@ Some CometBFT RPC endpoints are directly related to the Cosmos SDK: * any Protobuf fully-qualified service method, such as `/cosmos.bank.v1beta1.Query/AllBalances`. The `data` field should then include the method's request parameter(s) encoded as bytes using Protobuf. * `/app/simulate`: this will simulate a transaction, and return some information such as gas used. * `/app/version`: this will return the application's version. - * `/store/{path}`: this will query the store directly. + * `/store/{storeName}/key`: this will directly query the named store for data associated with the key represented in the `data` parameter. + * `/store/{storeName}/subspace`: this will directly query the named store for key/value pairs in which the key has the value of the `data` parameter as a prefix. * `/p2p/filter/addr/{port}`: this will return a filtered list of the node's P2P peers by address port. * `/p2p/filter/id/{id}`: this will return a filtered list of the node's P2P peers by ID. * `/broadcast_tx_{aync,async,commit}`: these 3 endpoint will broadcast a transaction to other peers. CLI, gRPC and REST expose [a way to broadcast transations](./01-transactions.md#broadcasting-the-transaction), but they all use these 3 CometBFT RPCs under the hood. diff --git a/docs/docs/core/07-cli.md b/docs/docs/core/07-cli.md index 42d4f66ed358..a0fc4257e1db 100644 --- a/docs/docs/core/07-cli.md +++ b/docs/docs/core/07-cli.md @@ -145,7 +145,7 @@ Read more about [AutoCLI](https://docs.cosmos.network/main/building-modules/auto ## Flags -Flags are used to modify commands; developers can include them in a `flags.go` file with their CLI. Users can explicitly include them in commands or pre-configure them by inside their [`app.toml`](../run-node/02-interact-node.md#configuring-the-node-using-apptoml). Commonly pre-configured flags include the `--node` to connect to and `--chain-id` of the blockchain the user wishes to interact with. +Flags are used to modify commands; developers can include them in a `flags.go` file with their CLI. Users can explicitly include them in commands or pre-configure them by inside their [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml). Commonly pre-configured flags include the `--node` to connect to and `--chain-id` of the blockchain the user wishes to interact with. A *persistent* flag (as opposed to a *local* flag) added to a command transcends all of its children: subcommands will inherit the configured values for these flags. Additionally, all flags have default values when they are added to commands; some toggle an option off but others are empty values that the user needs to override to create valid commands. A flag can be explicitly marked as *required* so that an error is automatically thrown if the user does not provide a value, but it is also acceptable to handle unexpected missing flags differently. diff --git a/docs/docs/run-node/02-interact-node.md b/docs/docs/run-node/02-interact-node.md index 855aa348be70..90977a61d6ef 100644 --- a/docs/docs/run-node/02-interact-node.md +++ b/docs/docs/run-node/02-interact-node.md @@ -66,7 +66,7 @@ Since the code generation library largely depends on your own tech stack, we wil [grpcurl](https://github.com/fullstorydev/grpcurl) is like `curl` but for gRPC. It is also available as a Go library, but we will use it only as a CLI command for debugging and testing purposes. Follow the instructions in the previous link to install it. -Assuming you have a local node running (either a localnet, or connected a live network), you should be able to run the following command to list the Protobuf services available (you can replace `localhost:9000` by the gRPC server endpoint of another node, which is configured under the `grpc.address` field inside [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml)): +Assuming you have a local node running (either a localnet, or connected a live network), you should be able to run the following command to list the Protobuf services available (you can replace `localhost:9000` by the gRPC server endpoint of another node, which is configured under the `grpc.address` field inside [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml)): ```bash grpcurl -plaintext localhost:9090 list @@ -268,7 +268,7 @@ curl \ Make sure to replace `localhost:1317` with the REST endpoint of your node, configured under the `api.address` field. -The list of all available REST endpoints is available as a Swagger specification file, it can be viewed at `localhost:1317/swagger`. Make sure that the `api.swagger` field is set to true in your [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml) file. +The list of all available REST endpoints is available as a Swagger specification file, it can be viewed at `localhost:1317/swagger`. Make sure that the `api.swagger` field is set to true in your [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml) file. ### Query for historical state using REST @@ -286,4 +286,4 @@ Assuming the state at that block has not yet been pruned by the node, this query ### Cross-Origin Resource Sharing (CORS) -[CORS policies](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) are not enabled by default to help with security. If you would like to use the rest-server in a public environment we recommend you provide a reverse proxy, this can be done with [nginx](https://www.nginx.com/). For testing and development purposes there is an `enabled-unsafe-cors` field inside [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml). +[CORS policies](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) are not enabled by default to help with security. If you would like to use the rest-server in a public environment we recommend you provide a reverse proxy, this can be done with [nginx](https://www.nginx.com/). For testing and development purposes there is an `enabled-unsafe-cors` field inside [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml). diff --git a/docs/docs/tooling/00-protobuf.md b/docs/docs/tooling/00-protobuf.md index 45b241714cd7..332c39f2b7eb 100644 --- a/docs/docs/tooling/00-protobuf.md +++ b/docs/docs/tooling/00-protobuf.md @@ -4,7 +4,7 @@ sidebar_position: 1 # Protocol Buffers -It is known that Cosmos SDK uses protocol buffers extensively, this docuemnt is meant to provide a guide on how it is used in the cosmos-sdk. +It is known that Cosmos SDK uses protocol buffers extensively, this document is meant to provide a guide on how it is used in the cosmos-sdk. To generate the proto file, the Cosmos SDK uses a docker image, this image is provided to all to use as well. The latest version is `ghcr.io/cosmos/proto-builder:0.12.x` diff --git a/go.mod b/go.mod index 7776d01bb8c2..fac866f7e0bc 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( cosmossdk.io/core v0.9.0 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/errors v1.0.0 - cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca + cosmossdk.io/log v1.2.0 cosmossdk.io/math v1.0.1 cosmossdk.io/store v1.0.0-alpha.1.0.20230728080422-54ed7dab3982 cosmossdk.io/x/tx v0.9.1 diff --git a/go.sum b/go.sum index bb4e5b5bfb8b..613734a83200 100644 --- a/go.sum +++ b/go.sum @@ -45,8 +45,8 @@ cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca h1:msenprh2BLLRwNT7zN56TbBHOGk/7ARQckXHxXyvjoQ= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca/go.mod h1:PkIAKXZvaxrTRc++z53XMRvFk8AcGGWYHcMIPzVYX9c= +cosmossdk.io/log v1.2.0 h1:BbykkDsutXPSy8RojFB3KZEWyvMsToLy0ykb/ZhsLqQ= +cosmossdk.io/log v1.2.0/go.mod h1:GNSCc/6+DhFIj1aLn/j7Id7PaO8DzNylUZoOYBL9+I4= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= cosmossdk.io/store v1.0.0-alpha.1.0.20230728080422-54ed7dab3982 h1:61YFeW2AhwwPfoJWzNJWvVubCj32sm5jZkJfraS9pDQ= diff --git a/log/CHANGELOG.md b/log/CHANGELOG.md index 439523bdba5f..9942c4e96473 100644 --- a/log/CHANGELOG.md +++ b/log/CHANGELOG.md @@ -11,35 +11,22 @@ Mention whether you follow Semantic Versioning. Usage: -Change log entries are to be added to the Unreleased section under the -appropriate stanza (see below). Each entry should ideally include a tag and -the Github issue reference in the following format: +Change log entries are to be added to the Unreleased section from newest to oldest. +Each entry must include the Github issue reference in the following format: -* () [#] Changelog message. +* [#] Changelog message. -Types of changes (Stanzas): - -"Features" for new features. -"Improvements" for changes in existing functionality. -"Deprecated" for soon-to-be removed features. -"Bug Fixes" for any bug fixes. -"API Breaking" for breaking exported APIs used by developers building on SDK. -Ref: https://keepachangelog.com/en/1.0.0/ --> # Changelog ## [Unreleased] -* [#15956](https://github.com/cosmos/cosmos-sdk/pull/15956) Introduce an option for enabling error stack trace. - -### Improvements - -* [#17194](https://github.com/cosmos/cosmos-sdk/pull/17194) Avoid repeating parse log level in filterFunc. - -### Bug Fixes +## [v1.2.0](https://github.com/cosmos/cosmos-sdk/releases/tag/log/v1.2.0) - 2023-07-31 +* [#17194](https://github.com/cosmos/cosmos-sdk/pull/17194) Avoid repeating parse log level in `ParseLogLevel`. * [#17205](https://github.com/cosmos/cosmos-sdk/pull/17205) Fix types that do not implement the `json.Marshaler` interface. +* [#15956](https://github.com/cosmos/cosmos-sdk/pull/15956) Introduce an option for enabling error stack trace. ## [v1.1.0](https://github.com/cosmos/cosmos-sdk/releases/tag/log/v1.1.0) - 2023-04-27 diff --git a/log/go.mod b/log/go.mod index d95055b2b493..58b6d0a39b42 100644 --- a/log/go.mod +++ b/log/go.mod @@ -4,7 +4,7 @@ go 1.20 require ( github.com/pkg/errors v0.9.1 - github.com/rs/zerolog v1.29.1 + github.com/rs/zerolog v1.30.0 gotest.tools/v3 v3.5.0 ) diff --git a/log/go.sum b/log/go.sum index 4676af0b692f..4b654436aa69 100644 --- a/log/go.sum +++ b/log/go.sum @@ -11,9 +11,9 @@ github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APP github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= -github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= +github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.30.0 h1:SymVODrcRsaRaSInD9yQtKbtWqwsfoPcRff/oRXLj4c= +github.com/rs/zerolog v1.30.0/go.mod h1:/tk+P47gFdPXq4QYjvCmT5/Gsug2nagsFWBWhAiSi1w= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/server/export.go b/server/export.go index 9b43da0c854e..3c4175315e46 100644 --- a/server/export.go +++ b/server/export.go @@ -23,7 +23,7 @@ const ( ) // ExportCmd dumps app state to JSON. -func ExportCmd(appExporter types.AppExporter, defaultNodeHome string) *cobra.Command { +func ExportCmd(appExporter types.AppExporter) *cobra.Command { cmd := &cobra.Command{ Use: "export", Short: "Export state to JSON", @@ -32,9 +32,6 @@ func ExportCmd(appExporter types.AppExporter, defaultNodeHome string) *cobra.Com serverCtx := GetServerContextFromCmd(cmd) config := serverCtx.Config - homeDir, _ := cmd.Flags().GetString(flags.FlagHome) - config.SetRoot(homeDir) - if _, err := os.Stat(config.GenesisFile()); os.IsNotExist(err) { return err } @@ -115,7 +112,6 @@ func ExportCmd(appExporter types.AppExporter, defaultNodeHome string) *cobra.Com }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().Int64(FlagHeight, -1, "Export state from a particular height (-1 means latest height)") cmd.Flags().Bool(FlagForZeroHeight, false, "Export state to start at height zero (perform preproccessing)") cmd.Flags().StringSlice(FlagJailAllowedAddrs, []string{}, "Comma-separated list of operator addresses of jailed validators to unjail") diff --git a/server/export_test.go b/server/export_test.go index f7c0124f9004..dc400f9c9ed3 100644 --- a/server/export_test.go +++ b/server/export_test.go @@ -58,8 +58,8 @@ func NewExportSystem(t *testing.T, exporter types.AppExporter) *ExportSystem { sys := cmdtest.NewSystem() sys.AddCommands( - server.ExportCmd(exporter, homeDir), - genutilcli.InitCmd(module.NewBasicManager(), homeDir), + server.ExportCmd(exporter), + genutilcli.InitCmd(module.NewBasicManager()), ) tw := zerolog.NewTestWriter(t) diff --git a/server/rollback.go b/server/rollback.go index ccd7e3213902..8c1a637a95ae 100644 --- a/server/rollback.go +++ b/server/rollback.go @@ -6,12 +6,11 @@ import ( cmtcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server/types" ) // NewRollbackCmd creates a command to rollback CometBFT and multistore state by one height. -func NewRollbackCmd(appCreator types.AppCreator, defaultNodeHome string) *cobra.Command { +func NewRollbackCmd(appCreator types.AppCreator) *cobra.Command { var removeBlock bool cmd := &cobra.Command{ @@ -27,9 +26,8 @@ application. `, RunE: func(cmd *cobra.Command, args []string) error { ctx := GetServerContextFromCmd(cmd) - cfg := ctx.Config - home := cfg.RootDir - db, err := openDB(home, GetAppDBBackend(ctx.Viper)) + + db, err := openDB(ctx.Config.RootDir, GetAppDBBackend(ctx.Viper)) if err != nil { return err } @@ -45,12 +43,11 @@ application. return fmt.Errorf("failed to rollback to version: %w", err) } - fmt.Printf("Rolled back state to height %d and hash %X", height, hash) + fmt.Printf("Rolled back state to height %d and hash %X\n", height, hash) return nil }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().BoolVar(&removeBlock, "hard", false, "remove last block as well as state") return cmd } diff --git a/server/start.go b/server/start.go index e5f89ac4691d..b968ca90fd1d 100644 --- a/server/start.go +++ b/server/start.go @@ -29,7 +29,6 @@ import ( pruningtypes "cosmossdk.io/store/pruning/types" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server/api" serverconfig "github.com/cosmos/cosmos-sdk/server/config" @@ -103,13 +102,13 @@ type StartCmdOptions struct { // StartCmd runs the service passed in, either stand-alone or in-process with // CometBFT. -func StartCmd(appCreator types.AppCreator, defaultNodeHome string) *cobra.Command { - return StartCmdWithOptions(appCreator, defaultNodeHome, StartCmdOptions{}) +func StartCmd(appCreator types.AppCreator) *cobra.Command { + return StartCmdWithOptions(appCreator, StartCmdOptions{}) } // StartCmdWithOptions runs the service passed in, either stand-alone or in-process with // CometBFT. -func StartCmdWithOptions(appCreator types.AppCreator, defaultNodeHome string, opts StartCmdOptions) *cobra.Command { +func StartCmdWithOptions(appCreator types.AppCreator, opts StartCmdOptions) *cobra.Command { if opts.DBOpener == nil { opts.DBOpener = openDB } @@ -174,7 +173,6 @@ is performed. Note, when enabled, gRPC will also be automatically enabled. }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().Bool(flagWithComet, true, "Run abci app embedded in-process with CometBFT") cmd.Flags().String(flagAddress, "tcp://0.0.0.0:26658", "Listen address") cmd.Flags().String(flagTransport, "socket", "Transport protocol: socket, grpc") diff --git a/server/util.go b/server/util.go index 40842f4b2c36..fbaf6d0be1d7 100644 --- a/server/util.go +++ b/server/util.go @@ -311,7 +311,7 @@ func interceptConfigs(rootViper *viper.Viper, customAppTemplate string, customCo } // add server commands -func AddCommands(rootCmd *cobra.Command, defaultNodeHome string, appCreator types.AppCreator, appExport types.AppExporter, addStartFlags types.ModuleInitFlags) { +func AddCommands(rootCmd *cobra.Command, appCreator types.AppCreator, appExport types.AppExporter, addStartFlags types.ModuleInitFlags) { cometCmd := &cobra.Command{ Use: "comet", Aliases: []string{"cometbft", "tendermint"}, @@ -328,15 +328,15 @@ func AddCommands(rootCmd *cobra.Command, defaultNodeHome string, appCreator type BootstrapStateCmd(appCreator), ) - startCmd := StartCmd(appCreator, defaultNodeHome) + startCmd := StartCmd(appCreator) addStartFlags(startCmd) rootCmd.AddCommand( startCmd, cometCmd, - ExportCmd(appExport, defaultNodeHome), + ExportCmd(appExport), version.NewVersionCommand(), - NewRollbackCmd(appCreator, defaultNodeHome), + NewRollbackCmd(appCreator), ) } diff --git a/server/util_test.go b/server/util_test.go index 6f9a91ceed21..9f8882380893 100644 --- a/server/util_test.go +++ b/server/util_test.go @@ -39,8 +39,9 @@ func preRunETestImpl(cmd *cobra.Command, args []string) error { func TestInterceptConfigsPreRunHandlerCreatesConfigFilesWhenMissing(t *testing.T) { tempDir := t.TempDir() - cmd := server.StartCmd(nil, "/foobar") - if err := cmd.Flags().Set(flags.FlagHome, tempDir); err != nil { + cmd := server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, "/foobar", "") + if err := cmd.PersistentFlags().Set(flags.FlagHome, tempDir); err != nil { t.Fatalf("Could not set home flag [%T] %v", err, err) } @@ -48,7 +49,7 @@ func TestInterceptConfigsPreRunHandlerCreatesConfigFilesWhenMissing(t *testing.T serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -115,8 +116,9 @@ func TestInterceptConfigsPreRunHandlerReadsConfigToml(t *testing.T) { t.Fatalf("Failed closing config.toml: %v", err) } - cmd := server.StartCmd(nil, "/foobar") - if err := cmd.Flags().Set(flags.FlagHome, tempDir); err != nil { + cmd := server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, "/foobar", "") + if err := cmd.PersistentFlags().Set(flags.FlagHome, tempDir); err != nil { t.Fatalf("Could not set home flag [%T] %v", err, err) } @@ -125,7 +127,7 @@ func TestInterceptConfigsPreRunHandlerReadsConfigToml(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -155,14 +157,15 @@ func TestInterceptConfigsPreRunHandlerReadsAppToml(t *testing.T) { if err := writer.Close(); err != nil { t.Fatalf("Failed closing app.toml: %v", err) } - cmd := server.StartCmd(nil, tempDir) + cmd := server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, tempDir, "") cmd.PreRunE = preRunETestImpl serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -174,9 +177,9 @@ func TestInterceptConfigsPreRunHandlerReadsAppToml(t *testing.T) { func TestInterceptConfigsPreRunHandlerReadsFlags(t *testing.T) { const testAddr = "tcp://127.1.2.3:12345" tempDir := t.TempDir() - cmd := server.StartCmd(nil, "/foobar") - - if err := cmd.Flags().Set(flags.FlagHome, tempDir); err != nil { + cmd := server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, "/foobar", "") + if err := cmd.PersistentFlags().Set(flags.FlagHome, tempDir); err != nil { t.Fatalf("Could not set home flag [%T] %v", err, err) } @@ -190,7 +193,7 @@ func TestInterceptConfigsPreRunHandlerReadsFlags(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -202,8 +205,9 @@ func TestInterceptConfigsPreRunHandlerReadsFlags(t *testing.T) { func TestInterceptConfigsPreRunHandlerReadsEnvVars(t *testing.T) { const testAddr = "tcp://127.1.2.3:12345" tempDir := t.TempDir() - cmd := server.StartCmd(nil, "/foobar") - if err := cmd.Flags().Set(flags.FlagHome, tempDir); err != nil { + cmd := server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, "/foobar", "") + if err := cmd.PersistentFlags().Set(flags.FlagHome, tempDir); err != nil { t.Fatalf("Could not set home flag [%T] %v", err, err) } @@ -225,7 +229,7 @@ func TestInterceptConfigsPreRunHandlerReadsEnvVars(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -289,7 +293,8 @@ func newPrecedenceCommon(t *testing.T) precedenceCommon { }) // Set up the command object that is used in this test - retval.cmd = server.StartCmd(nil, tempDir) + retval.cmd = server.StartCmd(nil) + retval.cmd.PersistentFlags().String(flags.FlagHome, tempDir, "") retval.cmd.PreRunE = preRunETestImpl return retval @@ -331,7 +336,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceFlag(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -347,7 +352,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceEnvVar(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -363,7 +368,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceConfigFile(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -379,7 +384,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceConfigDefault(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -397,8 +402,9 @@ func TestInterceptConfigsWithBadPermissions(t *testing.T) { if err := os.Mkdir(subDir, 0o600); err != nil { t.Fatalf("Failed to create sub directory: %v", err) } - cmd := server.StartCmd(nil, "/foobar") - if err := cmd.Flags().Set(flags.FlagHome, subDir); err != nil { + cmd := server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, "/foobar", "") + if err := cmd.PersistentFlags().Set(flags.FlagHome, subDir); err != nil { t.Fatalf("Could not set home flag [%T] %v", err, err) } @@ -420,9 +426,10 @@ func TestEmptyMinGasPrices(t *testing.T) { // Run InitCmd to create necessary config files. clientCtx := client.Context{}.WithHomeDir(tempDir).WithCodec(encCfg.Codec) serverCtx := server.NewDefaultContext() + serverCtx.Config.SetRoot(tempDir) ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - cmd := genutilcli.InitCmd(module.NewBasicManager(), tempDir) + cmd := genutilcli.InitCmd(module.NewBasicManager()) cmd.SetArgs([]string{"appnode-test"}) err = cmd.ExecuteContext(ctx) require.NoError(t, err) @@ -434,7 +441,8 @@ func TestEmptyMinGasPrices(t *testing.T) { config.WriteConfigFile(appCfgTempFilePath, appConf) // Run StartCmd. - cmd = server.StartCmd(nil, tempDir) + cmd = server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, tempDir, "") cmd.PreRunE = func(cmd *cobra.Command, _ []string) error { ctx, err := server.InterceptConfigsAndCreateContext(cmd, "", nil, cmtcfg.DefaultConfig()) if err != nil { diff --git a/simapp/go.mod b/simapp/go.mod index 430609785ea5..3b0df41b7408 100644 --- a/simapp/go.mod +++ b/simapp/go.mod @@ -8,7 +8,7 @@ require ( cosmossdk.io/collections v0.3.1-0.20230727092431-f0f777fa3cb7 cosmossdk.io/core v0.9.0 cosmossdk.io/depinject v1.0.0-alpha.3 - cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca + cosmossdk.io/log v1.2.0 cosmossdk.io/math v1.0.1 cosmossdk.io/store v1.0.0-alpha.1.0.20230728080422-54ed7dab3982 cosmossdk.io/tools/confix v0.0.0-20230613133644-0a778132a60f diff --git a/simapp/go.sum b/simapp/go.sum index 3fc1c3d874f3..e320ba7e70c6 100644 --- a/simapp/go.sum +++ b/simapp/go.sum @@ -197,8 +197,8 @@ cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca h1:msenprh2BLLRwNT7zN56TbBHOGk/7ARQckXHxXyvjoQ= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca/go.mod h1:PkIAKXZvaxrTRc++z53XMRvFk8AcGGWYHcMIPzVYX9c= +cosmossdk.io/log v1.2.0 h1:BbykkDsutXPSy8RojFB3KZEWyvMsToLy0ykb/ZhsLqQ= +cosmossdk.io/log v1.2.0/go.mod h1:GNSCc/6+DhFIj1aLn/j7Id7PaO8DzNylUZoOYBL9+I4= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= cosmossdk.io/store v1.0.0-alpha.1.0.20230728080422-54ed7dab3982 h1:61YFeW2AhwwPfoJWzNJWvVubCj32sm5jZkJfraS9pDQ= diff --git a/simapp/simd/cmd/commands.go b/simapp/simd/cmd/commands.go new file mode 100644 index 000000000000..d9891f0978ab --- /dev/null +++ b/simapp/simd/cmd/commands.go @@ -0,0 +1,263 @@ +package cmd + +import ( + "errors" + "io" + "os" + + cmtcfg "github.com/cometbft/cometbft/config" + dbm "github.com/cosmos/cosmos-db" + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "cosmossdk.io/log" + "cosmossdk.io/simapp" + confixcmd "cosmossdk.io/tools/confix/cmd" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/debug" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/client/pruning" + "github.com/cosmos/cosmos-sdk/client/rpc" + "github.com/cosmos/cosmos-sdk/client/snapshot" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/server" + serverconfig "github.com/cosmos/cosmos-sdk/server/config" + servertypes "github.com/cosmos/cosmos-sdk/server/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/cosmos/cosmos-sdk/x/crisis" + genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" +) + +// initCometBFTConfig helps to override default CometBFT Config values. +// return cmtcfg.DefaultConfig if no custom configuration is required for the application. +func initCometBFTConfig() *cmtcfg.Config { + cfg := cmtcfg.DefaultConfig() + + // these values put a higher strain on node memory + // cfg.P2P.MaxNumInboundPeers = 100 + // cfg.P2P.MaxNumOutboundPeers = 40 + + return cfg +} + +// initAppConfig helps to override default appConfig template and configs. +// return "", nil if no custom configuration is required for the application. +func initAppConfig() (string, interface{}) { + // The following code snippet is just for reference. + + // WASMConfig defines configuration for the wasm module. + type WASMConfig struct { + // This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries + QueryGasLimit uint64 `mapstructure:"query_gas_limit"` + + // Address defines the gRPC-web server to listen on + LruSize uint64 `mapstructure:"lru_size"` + } + + type CustomAppConfig struct { + serverconfig.Config `mapstructure:",squash"` + + WASM WASMConfig `mapstructure:"wasm"` + } + + // Optionally allow the chain developer to overwrite the SDK's default + // server config. + srvCfg := serverconfig.DefaultConfig() + // The SDK's default minimum gas price is set to "" (empty value) inside + // app.toml. If left empty by validators, the node will halt on startup. + // However, the chain developer can set a default app.toml value for their + // validators here. + // + // In summary: + // - if you leave srvCfg.MinGasPrices = "", all validators MUST tweak their + // own app.toml config, + // - if you set srvCfg.MinGasPrices non-empty, validators CAN tweak their + // own app.toml to override, or use this default value. + // + // In simapp, we set the min gas prices to 0. + srvCfg.MinGasPrices = "0stake" + // srvCfg.BaseConfig.IAVLDisableFastNode = true // disable fastnode by default + + customAppConfig := CustomAppConfig{ + Config: *srvCfg, + WASM: WASMConfig{ + LruSize: 1, + QueryGasLimit: 300000, + }, + } + + customAppTemplate := serverconfig.DefaultConfigTemplate + ` +[wasm] +# This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries +query_gas_limit = 300000 +# This is the number of wasm vm instances we keep cached in memory for speed-up +# Warning: this is currently unstable and may lead to crashes, best to keep for 0 unless testing locally +lru_size = 0` + + return customAppTemplate, customAppConfig +} + +func initRootCmd( + rootCmd *cobra.Command, + txConfig client.TxConfig, + interfaceRegistry codectypes.InterfaceRegistry, + appCodec codec.Codec, + basicManager module.BasicManager, +) { + cfg := sdk.GetConfig() + cfg.Seal() + + rootCmd.AddCommand( + genutilcli.InitCmd(basicManager), + NewTestnetCmd(basicManager, banktypes.GenesisBalancesIterator{}), + debug.Cmd(), + confixcmd.ConfigCommand(), + pruning.Cmd(newApp), + snapshot.Cmd(newApp), + ) + + server.AddCommands(rootCmd, newApp, appExport, addModuleInitFlags) + + // add keybase, auxiliary RPC, query, genesis, and tx child commands + rootCmd.AddCommand( + rpc.StatusCommand(), + genesisCommand(txConfig, basicManager), + queryCommand(), + txCommand(), + keys.Commands(), + ) +} + +func addModuleInitFlags(startCmd *cobra.Command) { + crisis.AddModuleInitFlags(startCmd) +} + +// genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter +func genesisCommand(txConfig client.TxConfig, basicManager module.BasicManager, cmds ...*cobra.Command) *cobra.Command { + cmd := genutilcli.Commands(txConfig, basicManager) + + for _, subCmd := range cmds { + cmd.AddCommand(subCmd) + } + return cmd +} + +func queryCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "query", + Aliases: []string{"q"}, + Short: "Querying subcommands", + DisableFlagParsing: false, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + rpc.ValidatorCommand(), + server.QueryBlockCmd(), + authcmd.QueryTxsByEventsCmd(), + server.QueryBlocksCmd(), + authcmd.QueryTxCmd(), + server.QueryBlockResultsCmd(), + ) + + return cmd +} + +func txCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "tx", + Short: "Transactions subcommands", + DisableFlagParsing: false, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + authcmd.GetSignCommand(), + authcmd.GetSignBatchCommand(), + authcmd.GetMultiSignCommand(), + authcmd.GetMultiSignBatchCmd(), + authcmd.GetValidateSignaturesCommand(), + authcmd.GetBroadcastCommand(), + authcmd.GetEncodeCommand(), + authcmd.GetDecodeCommand(), + authcmd.GetAuxToFeeCommand(), + authcmd.GetSimulateCmd(), + ) + + return cmd +} + +// newApp creates the application +func newApp( + logger log.Logger, + db dbm.DB, + traceStore io.Writer, + appOpts servertypes.AppOptions, +) servertypes.Application { + baseappOptions := server.DefaultBaseappOptions(appOpts) + + return simapp.NewSimApp( + logger, db, traceStore, true, + appOpts, + baseappOptions..., + ) +} + +// appExport creates a new simapp (optionally at a given height) and exports state. +func appExport( + logger log.Logger, + db dbm.DB, + traceStore io.Writer, + height int64, + forZeroHeight bool, + jailAllowedAddrs []string, + appOpts servertypes.AppOptions, + modulesToExport []string, +) (servertypes.ExportedApp, error) { + // this check is necessary as we use the flag in x/upgrade. + // we can exit more gracefully by checking the flag here. + homePath, ok := appOpts.Get(flags.FlagHome).(string) + if !ok || homePath == "" { + return servertypes.ExportedApp{}, errors.New("application home not set") + } + + viperAppOpts, ok := appOpts.(*viper.Viper) + if !ok { + return servertypes.ExportedApp{}, errors.New("appOpts is not viper.Viper") + } + + // overwrite the FlagInvCheckPeriod + viperAppOpts.Set(server.FlagInvCheckPeriod, 1) + appOpts = viperAppOpts + + var simApp *simapp.SimApp + if height != -1 { + simApp = simapp.NewSimApp(logger, db, traceStore, false, appOpts) + + if err := simApp.LoadHeight(height); err != nil { + return servertypes.ExportedApp{}, err + } + } else { + simApp = simapp.NewSimApp(logger, db, traceStore, true, appOpts) + } + + return simApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) +} + +var tempDir = func() string { + dir, err := os.MkdirTemp("", "simapp") + if err != nil { + dir = simapp.DefaultNodeHome + } + defer os.RemoveAll(dir) + + return dir +} diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 70f1cf9f2af1..6ab7f7558262 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -3,42 +3,23 @@ package cmd import ( - "errors" - "io" "os" "cosmossdk.io/log" "cosmossdk.io/simapp" "cosmossdk.io/simapp/params" - confixcmd "cosmossdk.io/tools/confix/cmd" - cmtcfg "github.com/cometbft/cometbft/config" dbm "github.com/cosmos/cosmos-db" "github.com/spf13/cobra" - "github.com/spf13/viper" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/config" - "github.com/cosmos/cosmos-sdk/client/debug" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/pruning" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/client/snapshot" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" - serverconfig "github.com/cosmos/cosmos-sdk/server/config" - servertypes "github.com/cosmos/cosmos-sdk/server/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/tx/signing" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/auth/tx" txmodule "github.com/cosmos/cosmos-sdk/x/auth/tx/config" "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/crisis" - genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" ) // NewRootCmd creates a new root command for simd. It is called once in the @@ -110,7 +91,7 @@ func NewRootCmd() *cobra.Command { }, } - initRootCmd(rootCmd, encodingConfig, tempApp.BasicModuleManager) + initRootCmd(rootCmd, encodingConfig.TxConfig, encodingConfig.InterfaceRegistry, encodingConfig.Codec, tempApp.BasicModuleManager) if err := tempApp.AutoCliOpts().EnhanceRootCommand(rootCmd); err != nil { panic(err) @@ -118,226 +99,3 @@ func NewRootCmd() *cobra.Command { return rootCmd } - -// initCometBFTConfig helps to override default CometBFT Config values. -// return cmtcfg.DefaultConfig if no custom configuration is required for the application. -func initCometBFTConfig() *cmtcfg.Config { - cfg := cmtcfg.DefaultConfig() - - // these values put a higher strain on node memory - // cfg.P2P.MaxNumInboundPeers = 100 - // cfg.P2P.MaxNumOutboundPeers = 40 - - return cfg -} - -// initAppConfig helps to override default appConfig template and configs. -// return "", nil if no custom configuration is required for the application. -func initAppConfig() (string, interface{}) { - // The following code snippet is just for reference. - - // WASMConfig defines configuration for the wasm module. - type WASMConfig struct { - // This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries - QueryGasLimit uint64 `mapstructure:"query_gas_limit"` - - // Address defines the gRPC-web server to listen on - LruSize uint64 `mapstructure:"lru_size"` - } - - type CustomAppConfig struct { - serverconfig.Config `mapstructure:",squash"` - - WASM WASMConfig `mapstructure:"wasm"` - } - - // Optionally allow the chain developer to overwrite the SDK's default - // server config. - srvCfg := serverconfig.DefaultConfig() - // The SDK's default minimum gas price is set to "" (empty value) inside - // app.toml. If left empty by validators, the node will halt on startup. - // However, the chain developer can set a default app.toml value for their - // validators here. - // - // In summary: - // - if you leave srvCfg.MinGasPrices = "", all validators MUST tweak their - // own app.toml config, - // - if you set srvCfg.MinGasPrices non-empty, validators CAN tweak their - // own app.toml to override, or use this default value. - // - // In simapp, we set the min gas prices to 0. - srvCfg.MinGasPrices = "0stake" - // srvCfg.BaseConfig.IAVLDisableFastNode = true // disable fastnode by default - - customAppConfig := CustomAppConfig{ - Config: *srvCfg, - WASM: WASMConfig{ - LruSize: 1, - QueryGasLimit: 300000, - }, - } - - customAppTemplate := serverconfig.DefaultConfigTemplate + ` -[wasm] -# This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries -query_gas_limit = 300000 -# This is the number of wasm vm instances we keep cached in memory for speed-up -# Warning: this is currently unstable and may lead to crashes, best to keep for 0 unless testing locally -lru_size = 0` - - return customAppTemplate, customAppConfig -} - -func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, basicManager module.BasicManager) { - cfg := sdk.GetConfig() - cfg.Seal() - - rootCmd.AddCommand( - genutilcli.InitCmd(basicManager, simapp.DefaultNodeHome), - NewTestnetCmd(basicManager, banktypes.GenesisBalancesIterator{}), - debug.Cmd(), - confixcmd.ConfigCommand(), - pruning.Cmd(newApp, simapp.DefaultNodeHome), - snapshot.Cmd(newApp), - ) - - server.AddCommands(rootCmd, simapp.DefaultNodeHome, newApp, appExport, addModuleInitFlags) - - // add keybase, auxiliary RPC, query, genesis, and tx child commands - rootCmd.AddCommand( - rpc.StatusCommand(), - genesisCommand(encodingConfig, basicManager), - txCommand(), - queryCommand(), - keys.Commands(), - ) -} - -func addModuleInitFlags(startCmd *cobra.Command) { - crisis.AddModuleInitFlags(startCmd) -} - -// genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter -func genesisCommand(encodingConfig params.EncodingConfig, basicManager module.BasicManager, cmds ...*cobra.Command) *cobra.Command { - cmd := genutilcli.Commands(encodingConfig.TxConfig, basicManager, simapp.DefaultNodeHome) - - for _, subCmd := range cmds { - cmd.AddCommand(subCmd) - } - return cmd -} - -func queryCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "query", - Aliases: []string{"q"}, - Short: "Querying subcommands", - DisableFlagParsing: false, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand( - rpc.ValidatorCommand(), - server.QueryBlockCmd(), - authcmd.QueryTxsByEventsCmd(), - server.QueryBlocksCmd(), - authcmd.QueryTxCmd(), - server.QueryBlockResultsCmd(), - ) - - return cmd -} - -func txCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "tx", - Short: "Transactions subcommands", - DisableFlagParsing: false, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand( - authcmd.GetSignCommand(), - authcmd.GetSignBatchCommand(), - authcmd.GetMultiSignCommand(), - authcmd.GetMultiSignBatchCmd(), - authcmd.GetValidateSignaturesCommand(), - authcmd.GetBroadcastCommand(), - authcmd.GetEncodeCommand(), - authcmd.GetDecodeCommand(), - authcmd.GetAuxToFeeCommand(), - authcmd.GetSimulateCmd(), - ) - - return cmd -} - -// newApp creates the application -func newApp( - logger log.Logger, - db dbm.DB, - traceStore io.Writer, - appOpts servertypes.AppOptions, -) servertypes.Application { - baseappOptions := server.DefaultBaseappOptions(appOpts) - - return simapp.NewSimApp( - logger, db, traceStore, true, - appOpts, - baseappOptions..., - ) -} - -// appExport creates a new simapp (optionally at a given height) and exports state. -func appExport( - logger log.Logger, - db dbm.DB, - traceStore io.Writer, - height int64, - forZeroHeight bool, - jailAllowedAddrs []string, - appOpts servertypes.AppOptions, - modulesToExport []string, -) (servertypes.ExportedApp, error) { - var simApp *simapp.SimApp - - // this check is necessary as we use the flag in x/upgrade. - // we can exit more gracefully by checking the flag here. - homePath, ok := appOpts.Get(flags.FlagHome).(string) - if !ok || homePath == "" { - return servertypes.ExportedApp{}, errors.New("application home not set") - } - - viperAppOpts, ok := appOpts.(*viper.Viper) - if !ok { - return servertypes.ExportedApp{}, errors.New("appOpts is not viper.Viper") - } - - // overwrite the FlagInvCheckPeriod - viperAppOpts.Set(server.FlagInvCheckPeriod, 1) - appOpts = viperAppOpts - - if height != -1 { - simApp = simapp.NewSimApp(logger, db, traceStore, false, appOpts) - - if err := simApp.LoadHeight(height); err != nil { - return servertypes.ExportedApp{}, err - } - } else { - simApp = simapp.NewSimApp(logger, db, traceStore, true, appOpts) - } - - return simApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) -} - -var tempDir = func() string { - dir, err := os.MkdirTemp("", "simapp") - if err != nil { - dir = simapp.DefaultNodeHome - } - defer os.RemoveAll(dir) - - return dir -} diff --git a/simapp/simd/cmd/cmd_test.go b/simapp/simd/cmd/root_test.go similarity index 100% rename from simapp/simd/cmd/cmd_test.go rename to simapp/simd/cmd/root_test.go diff --git a/simapp/simd/cmd/root_v2.go b/simapp/simd/cmd/root_v2.go index bdad9390bc23..0d43d1a0cc66 100644 --- a/simapp/simd/cmd/root_v2.go +++ b/simapp/simd/cmd/root_v2.go @@ -3,44 +3,26 @@ package cmd import ( - "errors" - "io" "os" - cmtcfg "github.com/cometbft/cometbft/config" - dbm "github.com/cosmos/cosmos-db" "github.com/spf13/cobra" - "github.com/spf13/viper" "cosmossdk.io/client/v2/autocli" "cosmossdk.io/depinject" "cosmossdk.io/log" "cosmossdk.io/simapp" - confixcmd "cosmossdk.io/tools/confix/cmd" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/config" - "github.com/cosmos/cosmos-sdk/client/debug" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/pruning" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/client/snapshot" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/server" - serverconfig "github.com/cosmos/cosmos-sdk/server/config" - servertypes "github.com/cosmos/cosmos-sdk/server/types" - sdk "github.com/cosmos/cosmos-sdk/types" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/tx/signing" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/auth/tx" txmodule "github.com/cosmos/cosmos-sdk/x/auth/tx/config" "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/crisis" - genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" ) // NewRootCmd creates a new root command for simd. It is called once in the main function. @@ -54,7 +36,13 @@ func NewRootCmd() *cobra.Command { moduleBasicManager module.BasicManager ) - if err := depinject.Inject(depinject.Configs(simapp.AppConfig, depinject.Supply(log.NewNopLogger())), + if err := depinject.Inject( + depinject.Configs(simapp.AppConfig, + depinject.Supply( + log.NewNopLogger(), + simtestutil.NewAppOptionsWithFlagHome(tempDir()), + ), + ), &interfaceRegistry, &appCodec, &txConfig, @@ -128,221 +116,3 @@ func NewRootCmd() *cobra.Command { return rootCmd } - -// initCometBFTConfig helps to override default CometBFT Config values. -// return cmtcfg.DefaultConfig if no custom configuration is required for the application. -func initCometBFTConfig() *cmtcfg.Config { - cfg := cmtcfg.DefaultConfig() - - // these values put a higher strain on node memory - // cfg.P2P.MaxNumInboundPeers = 100 - // cfg.P2P.MaxNumOutboundPeers = 40 - - return cfg -} - -// initAppConfig helps to override default appConfig template and configs. -// return "", nil if no custom configuration is required for the application. -func initAppConfig() (string, interface{}) { - // The following code snippet is just for reference. - - // WASMConfig defines configuration for the wasm module. - type WASMConfig struct { - // This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries - QueryGasLimit uint64 `mapstructure:"query_gas_limit"` - - // Address defines the gRPC-web server to listen on - LruSize uint64 `mapstructure:"lru_size"` - } - - type CustomAppConfig struct { - serverconfig.Config `mapstructure:",squash"` - - WASM WASMConfig `mapstructure:"wasm"` - } - - // Optionally allow the chain developer to overwrite the SDK's default - // server config. - srvCfg := serverconfig.DefaultConfig() - // The SDK's default minimum gas price is set to "" (empty value) inside - // app.toml. If left empty by validators, the node will halt on startup. - // However, the chain developer can set a default app.toml value for their - // validators here. - // - // In summary: - // - if you leave srvCfg.MinGasPrices = "", all validators MUST tweak their - // own app.toml config, - // - if you set srvCfg.MinGasPrices non-empty, validators CAN tweak their - // own app.toml to override, or use this default value. - // - // In simapp, we set the min gas prices to 0. - srvCfg.MinGasPrices = "0stake" - // srvCfg.BaseConfig.IAVLDisableFastNode = true // disable fastnode by default - - customAppConfig := CustomAppConfig{ - Config: *srvCfg, - WASM: WASMConfig{ - LruSize: 1, - QueryGasLimit: 300000, - }, - } - - customAppTemplate := serverconfig.DefaultConfigTemplate + ` -[wasm] -# This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries -query_gas_limit = 300000 -# This is the number of wasm vm instances we keep cached in memory for speed-up -# Warning: this is currently unstable and may lead to crashes, best to keep for 0 unless testing locally -lru_size = 0` - - return customAppTemplate, customAppConfig -} - -func initRootCmd( - rootCmd *cobra.Command, - txConfig client.TxConfig, - interfaceRegistry codectypes.InterfaceRegistry, - appCodec codec.Codec, - basicManager module.BasicManager, -) { - cfg := sdk.GetConfig() - cfg.Seal() - - rootCmd.AddCommand( - genutilcli.InitCmd(basicManager, simapp.DefaultNodeHome), - NewTestnetCmd(basicManager, banktypes.GenesisBalancesIterator{}), - debug.Cmd(), - confixcmd.ConfigCommand(), - pruning.Cmd(newApp, simapp.DefaultNodeHome), - snapshot.Cmd(newApp), - ) - - server.AddCommands(rootCmd, simapp.DefaultNodeHome, newApp, appExport, addModuleInitFlags) - - // add keybase, auxiliary RPC, query, genesis, and tx child commands - rootCmd.AddCommand( - rpc.StatusCommand(), - genesisCommand(txConfig, basicManager), - queryCommand(), - txCommand(), - keys.Commands(), - ) -} - -func addModuleInitFlags(startCmd *cobra.Command) { - crisis.AddModuleInitFlags(startCmd) -} - -// genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter -func genesisCommand(txConfig client.TxConfig, basicManager module.BasicManager, cmds ...*cobra.Command) *cobra.Command { - cmd := genutilcli.Commands(txConfig, basicManager, simapp.DefaultNodeHome) - - for _, subCmd := range cmds { - cmd.AddCommand(subCmd) - } - return cmd -} - -func queryCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "query", - Aliases: []string{"q"}, - Short: "Querying subcommands", - DisableFlagParsing: false, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand( - rpc.ValidatorCommand(), - server.QueryBlockCmd(), - authcmd.QueryTxsByEventsCmd(), - server.QueryBlocksCmd(), - authcmd.QueryTxCmd(), - server.QueryBlockResultsCmd(), - ) - - return cmd -} - -func txCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "tx", - Short: "Transactions subcommands", - DisableFlagParsing: false, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand( - authcmd.GetSignCommand(), - authcmd.GetSignBatchCommand(), - authcmd.GetMultiSignCommand(), - authcmd.GetMultiSignBatchCmd(), - authcmd.GetValidateSignaturesCommand(), - authcmd.GetBroadcastCommand(), - authcmd.GetEncodeCommand(), - authcmd.GetDecodeCommand(), - authcmd.GetAuxToFeeCommand(), - authcmd.GetSimulateCmd(), - ) - - return cmd -} - -// newApp creates the application -func newApp( - logger log.Logger, - db dbm.DB, - traceStore io.Writer, - appOpts servertypes.AppOptions, -) servertypes.Application { - baseappOptions := server.DefaultBaseappOptions(appOpts) - - return simapp.NewSimApp( - logger, db, traceStore, true, - appOpts, - baseappOptions..., - ) -} - -// appExport creates a new simapp (optionally at a given height) and exports state. -func appExport( - logger log.Logger, - db dbm.DB, - traceStore io.Writer, - height int64, - forZeroHeight bool, - jailAllowedAddrs []string, - appOpts servertypes.AppOptions, - modulesToExport []string, -) (servertypes.ExportedApp, error) { - // this check is necessary as we use the flag in x/upgrade. - // we can exit more gracefully by checking the flag here. - homePath, ok := appOpts.Get(flags.FlagHome).(string) - if !ok || homePath == "" { - return servertypes.ExportedApp{}, errors.New("application home not set") - } - - viperAppOpts, ok := appOpts.(*viper.Viper) - if !ok { - return servertypes.ExportedApp{}, errors.New("appOpts is not viper.Viper") - } - - // overwrite the FlagInvCheckPeriod - viperAppOpts.Set(server.FlagInvCheckPeriod, 1) - appOpts = viperAppOpts - - var simApp *simapp.SimApp - if height != -1 { - simApp = simapp.NewSimApp(logger, db, traceStore, false, appOpts) - - if err := simApp.LoadHeight(height); err != nil { - return servertypes.ExportedApp{}, err - } - } else { - simApp = simapp.NewSimApp(logger, db, traceStore, true, appOpts) - } - - return simApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) -} diff --git a/store/go.mod b/store/go.mod index 31fa64330d0d..27bcd4030c9a 100644 --- a/store/go.mod +++ b/store/go.mod @@ -4,7 +4,7 @@ go 1.20 require ( cosmossdk.io/errors v1.0.0 - cosmossdk.io/log v1.1.0 + cosmossdk.io/log v1.2.0 cosmossdk.io/math v1.0.1 github.com/cometbft/cometbft v0.38.0-rc3 github.com/cosmos/cosmos-db v1.0.0 diff --git a/store/go.sum b/store/go.sum index 7ede5c028b3c..47c5cbde6299 100644 --- a/store/go.sum +++ b/store/go.sum @@ -1,7 +1,7 @@ cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= -cosmossdk.io/log v1.1.0 h1:v0ogPHYeTzPcBTcPR1A3j1hkei4pZama8kz8LKlCMv0= -cosmossdk.io/log v1.1.0/go.mod h1:6zjroETlcDs+mm62gd8Ig7mZ+N+fVOZS91V17H+M4N4= +cosmossdk.io/log v1.2.0 h1:BbykkDsutXPSy8RojFB3KZEWyvMsToLy0ykb/ZhsLqQ= +cosmossdk.io/log v1.2.0/go.mod h1:GNSCc/6+DhFIj1aLn/j7Id7PaO8DzNylUZoOYBL9+I4= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= diff --git a/tests/e2e/gov/query.go b/tests/e2e/gov/query.go index 40e3d3aa27a9..a600649d67b2 100644 --- a/tests/e2e/gov/query.go +++ b/tests/e2e/gov/query.go @@ -33,7 +33,7 @@ func (s *E2ETestSuite) TestCmdProposer() { fmt.Sprintf("--%s=json", flags.FlagOutput), }, false, - fmt.Sprintf("{\"proposal_id\":\"%s\",\"proposer\":\"%s\"}", "1", val.Address.String()), + fmt.Sprintf("{\"proposal_id\":%d,\"proposer\":\"%s\"}", 1, val.Address.String()), }, } diff --git a/tests/e2e/server/export_test.go b/tests/e2e/server/export_test.go index 45616e7029b5..9c8922227d4c 100644 --- a/tests/e2e/server/export_test.go +++ b/tests/e2e/server/export_test.go @@ -35,7 +35,6 @@ func TestExportCmd_ConsensusParams(t *testing.T) { output := &bytes.Buffer{} cmd.SetOut(output) - cmd.SetArgs([]string{fmt.Sprintf("--%s=%s", flags.FlagHome, tempDir)}) assert.NilError(t, cmd.ExecuteContext(ctx)) var exportedAppGenesis genutiltypes.AppGenesis @@ -54,7 +53,8 @@ func TestExportCmd_ConsensusParams(t *testing.T) { func TestExportCmd_HomeDir(t *testing.T) { _, ctx, _, cmd := setupApp(t, t.TempDir()) - cmd.SetArgs([]string{fmt.Sprintf("--%s=%s", flags.FlagHome, "foobar")}) + serverCtxPtr := ctx.Value(server.ServerContextKey) + serverCtxPtr.(*server.Context).Config.SetRoot("foobar") err := cmd.ExecuteContext(ctx) assert.ErrorContains(t, err, "stat foobar/config/genesis.json: no such file or directory") @@ -103,8 +103,7 @@ func TestExportCmd_Height(t *testing.T) { output := &bytes.Buffer{} cmd.SetOut(output) - args := append(tc.flags, fmt.Sprintf("--%s=%s", flags.FlagHome, tempDir)) - cmd.SetArgs(args) + cmd.SetArgs(tc.flags) assert.NilError(t, cmd.ExecuteContext(ctx)) var exportedAppGenesis genutiltypes.AppGenesis @@ -137,8 +136,7 @@ func TestExportCmd_Output(t *testing.T) { output := &bytes.Buffer{} cmd.SetOut(output) - args := append(tc.flags, fmt.Sprintf("--%s=%s", flags.FlagHome, tempDir)) - cmd.SetArgs(args) + cmd.SetArgs(tc.flags) assert.NilError(t, cmd.ExecuteContext(ctx)) var exportedAppGenesis genutiltypes.AppGenesis @@ -193,20 +191,19 @@ func setupApp(t *testing.T, tempDir string) (*simapp.SimApp, context.Context, ge }) app.Commit() - cmd := server.ExportCmd( - func(_ log.Logger, _ dbm.DB, _ io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, appOptions types.AppOptions, modulesToExport []string) (types.ExportedApp, error) { - var simApp *simapp.SimApp - if height != -1 { - simApp = simapp.NewSimApp(logger, db, nil, false, appOptions) - if err := simApp.LoadHeight(height); err != nil { - return types.ExportedApp{}, err - } - } else { - simApp = simapp.NewSimApp(logger, db, nil, true, appOptions) + cmd := server.ExportCmd(func(_ log.Logger, _ dbm.DB, _ io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, appOptions types.AppOptions, modulesToExport []string) (types.ExportedApp, error) { + var simApp *simapp.SimApp + if height != -1 { + simApp = simapp.NewSimApp(logger, db, nil, false, appOptions) + if err := simApp.LoadHeight(height); err != nil { + return types.ExportedApp{}, err } + } else { + simApp = simapp.NewSimApp(logger, db, nil, true, appOptions) + } - return simApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) - }, tempDir) + return simApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) + }) ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) diff --git a/tests/go.mod b/tests/go.mod index 5db63af099c2..f64543025097 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -8,7 +8,7 @@ require ( cosmossdk.io/core v0.9.0 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/errors v1.0.0 - cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca + cosmossdk.io/log v1.2.0 cosmossdk.io/math v1.0.1 cosmossdk.io/simapp v0.0.0-20230309163709-87da587416ba cosmossdk.io/store v1.0.0-alpha.1.0.20230728080422-54ed7dab3982 diff --git a/tests/go.sum b/tests/go.sum index 5bd556cd81c4..866d41414b1a 100644 --- a/tests/go.sum +++ b/tests/go.sum @@ -197,8 +197,8 @@ cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca h1:msenprh2BLLRwNT7zN56TbBHOGk/7ARQckXHxXyvjoQ= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca/go.mod h1:PkIAKXZvaxrTRc++z53XMRvFk8AcGGWYHcMIPzVYX9c= +cosmossdk.io/log v1.2.0 h1:BbykkDsutXPSy8RojFB3KZEWyvMsToLy0ykb/ZhsLqQ= +cosmossdk.io/log v1.2.0/go.mod h1:GNSCc/6+DhFIj1aLn/j7Id7PaO8DzNylUZoOYBL9+I4= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= cosmossdk.io/store v1.0.0-alpha.1.0.20230728080422-54ed7dab3982 h1:61YFeW2AhwwPfoJWzNJWvVubCj32sm5jZkJfraS9pDQ= diff --git a/tests/integration/distribution/keeper/msg_server_test.go b/tests/integration/distribution/keeper/msg_server_test.go index 6c17aec04eee..0a32dc847a61 100644 --- a/tests/integration/distribution/keeper/msg_server_test.go +++ b/tests/integration/distribution/keeper/msg_server_test.go @@ -684,6 +684,20 @@ func TestMsgUpdateParams(t *testing.T) { expErr: true, expErrMsg: "invalid authority", }, + { + name: "community tax is nil", + msg: &distrtypes.MsgUpdateParams{ + Authority: f.distrKeeper.GetAuthority(), + Params: distrtypes.Params{ + CommunityTax: math.LegacyDec{}, + WithdrawAddrEnabled: withdrawAddrEnabled, + BaseProposerReward: math.LegacyZeroDec(), + BonusProposerReward: math.LegacyZeroDec(), + }, + }, + expErr: true, + expErrMsg: "community tax must be not nil", + }, { name: "community tax > 1", msg: &distrtypes.MsgUpdateParams{ @@ -696,7 +710,7 @@ func TestMsgUpdateParams(t *testing.T) { }, }, expErr: true, - expErrMsg: "community tax should be non-negative and less than one", + expErrMsg: "community tax too large: 2.000000000000000000", }, { name: "negative community tax", @@ -710,7 +724,7 @@ func TestMsgUpdateParams(t *testing.T) { }, }, expErr: true, - expErrMsg: "community tax should be non-negative and less than one", + expErrMsg: "community tax must be positive: -0.200000000000000000", }, { name: "base proposer reward set", diff --git a/tools/confix/go.mod b/tools/confix/go.mod index 3e1a8a3b14dd..6aa4afca4c21 100644 --- a/tools/confix/go.mod +++ b/tools/confix/go.mod @@ -18,7 +18,7 @@ require ( cosmossdk.io/core v0.9.0 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect cosmossdk.io/errors v1.0.0 // indirect - cosmossdk.io/log v1.1.0 // indirect + cosmossdk.io/log v1.2.0 // indirect cosmossdk.io/math v1.0.1 // indirect cosmossdk.io/store v1.0.0-alpha.1 // indirect cosmossdk.io/x/tx v0.9.1 // indirect diff --git a/tools/confix/go.sum b/tools/confix/go.sum index 879563c49443..d5f1162d656e 100644 --- a/tools/confix/go.sum +++ b/tools/confix/go.sum @@ -45,8 +45,8 @@ cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= -cosmossdk.io/log v1.1.0 h1:v0ogPHYeTzPcBTcPR1A3j1hkei4pZama8kz8LKlCMv0= -cosmossdk.io/log v1.1.0/go.mod h1:6zjroETlcDs+mm62gd8Ig7mZ+N+fVOZS91V17H+M4N4= +cosmossdk.io/log v1.2.0 h1:BbykkDsutXPSy8RojFB3KZEWyvMsToLy0ykb/ZhsLqQ= +cosmossdk.io/log v1.2.0/go.mod h1:GNSCc/6+DhFIj1aLn/j7Id7PaO8DzNylUZoOYBL9+I4= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= cosmossdk.io/store v1.0.0-alpha.1 h1:/151XxAgm0tiKuYrtJzMG61lf6enpPuP+D/hIN8cRjQ= diff --git a/tools/cosmovisor/go.mod b/tools/cosmovisor/go.mod index 24e094a0df8e..efc9438dc4e4 100644 --- a/tools/cosmovisor/go.mod +++ b/tools/cosmovisor/go.mod @@ -3,7 +3,7 @@ module cosmossdk.io/tools/cosmovisor go 1.20 require ( - cosmossdk.io/log v1.1.0 + cosmossdk.io/log v1.2.0 cosmossdk.io/x/upgrade v0.0.0-20230614103911-b3da8bb4e801 github.com/otiai10/copy v1.12.0 github.com/spf13/cobra v1.7.0 diff --git a/tools/cosmovisor/go.sum b/tools/cosmovisor/go.sum index 3c98cb2bdd41..9c9c7906176f 100644 --- a/tools/cosmovisor/go.sum +++ b/tools/cosmovisor/go.sum @@ -197,8 +197,8 @@ cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= -cosmossdk.io/log v1.1.0 h1:v0ogPHYeTzPcBTcPR1A3j1hkei4pZama8kz8LKlCMv0= -cosmossdk.io/log v1.1.0/go.mod h1:6zjroETlcDs+mm62gd8Ig7mZ+N+fVOZS91V17H+M4N4= +cosmossdk.io/log v1.2.0 h1:BbykkDsutXPSy8RojFB3KZEWyvMsToLy0ykb/ZhsLqQ= +cosmossdk.io/log v1.2.0/go.mod h1:GNSCc/6+DhFIj1aLn/j7Id7PaO8DzNylUZoOYBL9+I4= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= cosmossdk.io/store v1.0.0-alpha.1 h1:/151XxAgm0tiKuYrtJzMG61lf6enpPuP+D/hIN8cRjQ= diff --git a/tools/hubl/go.mod b/tools/hubl/go.mod index 36275a37fcc6..0ccc501b04a5 100644 --- a/tools/hubl/go.mod +++ b/tools/hubl/go.mod @@ -19,7 +19,7 @@ require ( cosmossdk.io/collections v0.3.0 // indirect cosmossdk.io/core v0.9.0 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect - cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca // indirect + cosmossdk.io/log v1.2.0 // indirect cosmossdk.io/math v1.0.1 // indirect cosmossdk.io/store v1.0.0-alpha.1 // indirect cosmossdk.io/x/tx v0.9.1 // indirect diff --git a/tools/hubl/go.sum b/tools/hubl/go.sum index 12d96f139a6c..7ad5ef3ab9a4 100644 --- a/tools/hubl/go.sum +++ b/tools/hubl/go.sum @@ -47,8 +47,8 @@ cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca h1:msenprh2BLLRwNT7zN56TbBHOGk/7ARQckXHxXyvjoQ= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca/go.mod h1:PkIAKXZvaxrTRc++z53XMRvFk8AcGGWYHcMIPzVYX9c= +cosmossdk.io/log v1.2.0 h1:BbykkDsutXPSy8RojFB3KZEWyvMsToLy0ykb/ZhsLqQ= +cosmossdk.io/log v1.2.0/go.mod h1:GNSCc/6+DhFIj1aLn/j7Id7PaO8DzNylUZoOYBL9+I4= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= cosmossdk.io/store v1.0.0-alpha.1 h1:/151XxAgm0tiKuYrtJzMG61lf6enpPuP+D/hIN8cRjQ= diff --git a/x/circuit/go.mod b/x/circuit/go.mod index a383329a8994..dc3755b1e5c5 100644 --- a/x/circuit/go.mod +++ b/x/circuit/go.mod @@ -23,7 +23,7 @@ require ( ) require ( - cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca // indirect + cosmossdk.io/log v1.2.0 // indirect cosmossdk.io/x/tx v0.9.1 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect diff --git a/x/circuit/go.sum b/x/circuit/go.sum index 1e3ec663eaa7..c62fbe13c925 100644 --- a/x/circuit/go.sum +++ b/x/circuit/go.sum @@ -45,8 +45,8 @@ cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca h1:msenprh2BLLRwNT7zN56TbBHOGk/7ARQckXHxXyvjoQ= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca/go.mod h1:PkIAKXZvaxrTRc++z53XMRvFk8AcGGWYHcMIPzVYX9c= +cosmossdk.io/log v1.2.0 h1:BbykkDsutXPSy8RojFB3KZEWyvMsToLy0ykb/ZhsLqQ= +cosmossdk.io/log v1.2.0/go.mod h1:GNSCc/6+DhFIj1aLn/j7Id7PaO8DzNylUZoOYBL9+I4= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= cosmossdk.io/store v1.0.0-alpha.1 h1:/151XxAgm0tiKuYrtJzMG61lf6enpPuP+D/hIN8cRjQ= diff --git a/x/distribution/README.md b/x/distribution/README.md index bd7153218291..32858fd696db 100644 --- a/x/distribution/README.md +++ b/x/distribution/README.md @@ -352,15 +352,22 @@ The transaction fails if the amount cannot be transferred from the sender to the ```go func (k Keeper) FundCommunityPool(ctx context.Context, amount sdk.Coins, sender sdk.AccAddress) error { - if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, amount); err != nil { - return err - } + if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, amount); err != nil { + return err + } - feePool := k.GetFeePool(ctx) - feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...) - k.SetFeePool(ctx, feePool) + feePool, err := k.FeePool.Get(ctx) + if err != nil { + return err + } + + feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...) + + if err := k.FeePool.Set(ctx, feePool); err != nil { + return err + } - return nil + return nil } ``` diff --git a/x/distribution/types/params.go b/x/distribution/types/params.go index 395be69d7ea8..f7c980284175 100644 --- a/x/distribution/types/params.go +++ b/x/distribution/types/params.go @@ -18,13 +18,7 @@ func DefaultParams() Params { // ValidateBasic performs basic validation on distribution parameters. func (p Params) ValidateBasic() error { - if p.CommunityTax.IsNegative() || p.CommunityTax.GT(math.LegacyOneDec()) { - return fmt.Errorf( - "community tax should be non-negative and less than one: %s", p.CommunityTax, - ) - } - - return nil + return validateCommunityTax(p.CommunityTax) } func validateCommunityTax(i interface{}) error { diff --git a/x/distribution/types/params_test.go b/x/distribution/types/params_test.go index 4ba9167a0494..dfd68a380ed3 100644 --- a/x/distribution/types/params_test.go +++ b/x/distribution/types/params_test.go @@ -30,6 +30,7 @@ func TestParams_ValidateBasic(t *testing.T) { {"negative bonus proposer reward (must not matter)", fields{toDec("0.1"), toDec("0"), toDec("-0.1"), false}, false}, {"total sum greater than 1 (must not matter)", fields{toDec("0.2"), toDec("0.5"), toDec("0.4"), false}, false}, {"community tax greater than 1", fields{toDec("1.1"), toDec("0"), toDec("0"), false}, true}, + {"community tax nil", fields{sdkmath.LegacyDec{}, toDec("0"), toDec("0"), false}, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/evidence/go.mod b/x/evidence/go.mod index 2b68beb716c8..04e2ec7f1344 100644 --- a/x/evidence/go.mod +++ b/x/evidence/go.mod @@ -8,7 +8,7 @@ require ( cosmossdk.io/core v0.9.0 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/errors v1.0.0 - cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca + cosmossdk.io/log v1.2.0 cosmossdk.io/math v1.0.1 cosmossdk.io/store v1.0.0-alpha.1 github.com/cometbft/cometbft v0.38.0-rc3 diff --git a/x/evidence/go.sum b/x/evidence/go.sum index 9ad69f5c36eb..049ea051e885 100644 --- a/x/evidence/go.sum +++ b/x/evidence/go.sum @@ -45,8 +45,8 @@ cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca h1:msenprh2BLLRwNT7zN56TbBHOGk/7ARQckXHxXyvjoQ= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca/go.mod h1:PkIAKXZvaxrTRc++z53XMRvFk8AcGGWYHcMIPzVYX9c= +cosmossdk.io/log v1.2.0 h1:BbykkDsutXPSy8RojFB3KZEWyvMsToLy0ykb/ZhsLqQ= +cosmossdk.io/log v1.2.0/go.mod h1:GNSCc/6+DhFIj1aLn/j7Id7PaO8DzNylUZoOYBL9+I4= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= cosmossdk.io/store v1.0.0-alpha.1 h1:/151XxAgm0tiKuYrtJzMG61lf6enpPuP+D/hIN8cRjQ= diff --git a/x/feegrant/go.mod b/x/feegrant/go.mod index 8b3b6580a5be..1201cccb38e7 100644 --- a/x/feegrant/go.mod +++ b/x/feegrant/go.mod @@ -8,7 +8,7 @@ require ( cosmossdk.io/core v0.9.0 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/errors v1.0.0 - cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca + cosmossdk.io/log v1.2.0 cosmossdk.io/math v1.0.1 cosmossdk.io/store v1.0.0-alpha.1 github.com/cometbft/cometbft v0.38.0-rc3 diff --git a/x/feegrant/go.sum b/x/feegrant/go.sum index 921658d15ffb..0576a2e50431 100644 --- a/x/feegrant/go.sum +++ b/x/feegrant/go.sum @@ -45,8 +45,8 @@ cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca h1:msenprh2BLLRwNT7zN56TbBHOGk/7ARQckXHxXyvjoQ= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca/go.mod h1:PkIAKXZvaxrTRc++z53XMRvFk8AcGGWYHcMIPzVYX9c= +cosmossdk.io/log v1.2.0 h1:BbykkDsutXPSy8RojFB3KZEWyvMsToLy0ykb/ZhsLqQ= +cosmossdk.io/log v1.2.0/go.mod h1:GNSCc/6+DhFIj1aLn/j7Id7PaO8DzNylUZoOYBL9+I4= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= cosmossdk.io/store v1.0.0-alpha.1 h1:/151XxAgm0tiKuYrtJzMG61lf6enpPuP+D/hIN8cRjQ= diff --git a/x/genutil/client/cli/collect.go b/x/genutil/client/cli/collect.go index 5502445960d7..f164c1ccd922 100644 --- a/x/genutil/client/cli/collect.go +++ b/x/genutil/client/cli/collect.go @@ -9,7 +9,6 @@ import ( "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/x/genutil" @@ -19,7 +18,7 @@ import ( const flagGenTxDir = "gentx-dir" // CollectGenTxsCmd - return the cobra command to collect genesis transactions -func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, defaultNodeHome string, validator types.MessageValidator, valAddrCodec runtime.ValidatorAddressCodec) *cobra.Command { +func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, validator types.MessageValidator, valAddrCodec runtime.ValidatorAddressCodec) *cobra.Command { cmd := &cobra.Command{ Use: "collect-gentxs", Short: "Collect genesis txs and output a genesis.json file", @@ -30,8 +29,6 @@ func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, defaultNodeH clientCtx := client.GetClientContextFromCmd(cmd) cdc := clientCtx.Codec - config.SetRoot(clientCtx.HomeDir) - nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(config) if err != nil { return errors.Wrap(err, "failed to initialize node validator files") @@ -62,7 +59,6 @@ func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, defaultNodeH }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().String(flagGenTxDir, "", "override default \"gentx\" directory from which collect and execute genesis transactions; default [--home]/config/gentx/") return cmd diff --git a/x/genutil/client/cli/commands.go b/x/genutil/client/cli/commands.go index 0db6b39bfba3..bc737886b13d 100644 --- a/x/genutil/client/cli/commands.go +++ b/x/genutil/client/cli/commands.go @@ -12,18 +12,18 @@ import ( // GenesisCoreCommand adds core sdk's sub-commands into genesis command. // Deprecated: use Commands instead. -func GenesisCoreCommand(txConfig client.TxConfig, moduleBasics module.BasicManager, defaultNodeHome string) *cobra.Command { - return Commands(txConfig, moduleBasics, defaultNodeHome) +func GenesisCoreCommand(txConfig client.TxConfig, moduleBasics module.BasicManager) *cobra.Command { + return Commands(txConfig, moduleBasics) } // Commands adds core sdk's sub-commands into genesis command. -func Commands(txConfig client.TxConfig, moduleBasics module.BasicManager, defaultNodeHome string) *cobra.Command { - return CommandsWithCustomMigrationMap(txConfig, moduleBasics, defaultNodeHome, MigrationMap) +func Commands(txConfig client.TxConfig, moduleBasics module.BasicManager) *cobra.Command { + return CommandsWithCustomMigrationMap(txConfig, moduleBasics, 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, moduleBasics module.BasicManager, defaultNodeHome string, migrationMap genutiltypes.MigrationMap) *cobra.Command { +func CommandsWithCustomMigrationMap(txConfig client.TxConfig, moduleBasics module.BasicManager, migrationMap genutiltypes.MigrationMap) *cobra.Command { cmd := &cobra.Command{ Use: "genesis", Short: "Application's genesis-related subcommands", @@ -34,11 +34,11 @@ func CommandsWithCustomMigrationMap(txConfig client.TxConfig, moduleBasics modul gentxModule := moduleBasics[genutiltypes.ModuleName].(genutil.AppModuleBasic) cmd.AddCommand( - GenTxCmd(moduleBasics, txConfig, banktypes.GenesisBalancesIterator{}, defaultNodeHome, txConfig.SigningContext().ValidatorAddressCodec()), + GenTxCmd(moduleBasics, txConfig, banktypes.GenesisBalancesIterator{}, txConfig.SigningContext().ValidatorAddressCodec()), MigrateGenesisCmd(migrationMap), - CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, defaultNodeHome, gentxModule.GenTxValidator, txConfig.SigningContext().ValidatorAddressCodec()), + CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, gentxModule.GenTxValidator, txConfig.SigningContext().ValidatorAddressCodec()), ValidateGenesisCmd(moduleBasics), - AddGenesisAccountCmd(defaultNodeHome, txConfig.SigningContext().AddressCodec()), + AddGenesisAccountCmd(txConfig.SigningContext().AddressCodec()), ) return cmd diff --git a/x/genutil/client/cli/genaccount.go b/x/genutil/client/cli/genaccount.go index 100048751be7..2dfe5e7c7d0b 100644 --- a/x/genutil/client/cli/genaccount.go +++ b/x/genutil/client/cli/genaccount.go @@ -26,7 +26,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(defaultNodeHome string, addressCodec address.Codec) *cobra.Command { +func AddGenesisAccountCmd(addressCodec address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "add-genesis-account [address_or_key_name] [coin][,[coin]]", Short: "Add a genesis account to genesis.json", @@ -41,8 +41,6 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa serverCtx := server.GetServerContextFromCmd(cmd) config := serverCtx.Config - config.SetRoot(clientCtx.HomeDir) - var kr keyring.Keyring addr, err := addressCodec.StringToBytes(args[0]) if err != nil { @@ -80,7 +78,6 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)") cmd.Flags().String(flagVestingAmt, "", "amount of coins for vesting accounts") cmd.Flags().Int64(flagVestingStart, 0, "schedule start time (unix epoch) for vesting accounts") diff --git a/x/genutil/client/cli/genaccount_test.go b/x/genutil/client/cli/genaccount_test.go index 573d9a41bbf8..7bc1a60702e0 100644 --- a/x/genutil/client/cli/genaccount_test.go +++ b/x/genutil/client/cli/genaccount_test.go @@ -2,7 +2,6 @@ package cli_test import ( "context" - "fmt" "testing" "github.com/spf13/viper" @@ -11,7 +10,6 @@ import ( "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" addresscodec "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -91,11 +89,10 @@ func TestAddGenesisAccountCmd(t *testing.T) { ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd := genutilcli.AddGenesisAccountCmd(home, addresscodec.NewBech32Codec("cosmos")) + cmd := genutilcli.AddGenesisAccountCmd(addresscodec.NewBech32Codec("cosmos")) cmd.SetArgs([]string{ tc.addr, tc.denom, - fmt.Sprintf("--%s=home", flags.FlagHome), }) if tc.expectErr { diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 7c5ee6f7f9a7..41410e9cd995 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -11,7 +11,7 @@ import ( "github.com/spf13/cobra" - address "cosmossdk.io/core/address" + "cosmossdk.io/core/address" "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/client" @@ -29,7 +29,7 @@ import ( ) // GenTxCmd builds the application's gentx command. -func GenTxCmd(mbm module.BasicManager, txEncCfg client.TxEncodingConfig, genBalIterator types.GenesisBalancesIterator, defaultNodeHome string, valAdddressCodec address.Codec) *cobra.Command { +func GenTxCmd(mbm module.BasicManager, txEncCfg client.TxEncodingConfig, genBalIterator types.GenesisBalancesIterator, valAdddressCodec address.Codec) *cobra.Command { ipDefault, _ := server.ExternalIP() fsCreateValidator, defaultsDesc := cli.CreateValidatorMsgFlagSet(ipDefault) @@ -61,9 +61,7 @@ $ %s gentx my-key-name 1000000stake --home=/path/to/home/dir --keyring-backend=o return err } cdc := clientCtx.Codec - config := serverCtx.Config - config.SetRoot(clientCtx.HomeDir) nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(serverCtx.Config) if err != nil { @@ -212,7 +210,6 @@ $ %s gentx my-key-name 1000000stake --home=/path/to/home/dir --keyring-backend=o }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().String(flags.FlagOutputDocument, "", "Write the genesis transaction JSON document to the given file instead of the default location") cmd.Flags().AddFlagSet(fsCreateValidator) flags.AddTxFlagsToCmd(cmd) diff --git a/x/genutil/client/cli/gentx_test.go b/x/genutil/client/cli/gentx_test.go index 1f7ffeabce5a..478a536994fb 100644 --- a/x/genutil/client/cli/gentx_test.go +++ b/x/genutil/client/cli/gentx_test.go @@ -123,13 +123,7 @@ func (s *CLITestSuite) TestGenTxCmd() { clientCtx := s.clientCtx ctx := svrcmd.CreateExecuteContext(context.Background()) - cmd := cli.GenTxCmd( - module.NewBasicManager(), - clientCtx.TxConfig, - banktypes.GenesisBalancesIterator{}, - clientCtx.HomeDir, - address.NewBech32Codec("cosmosvaloper"), - ) + cmd := cli.GenTxCmd(module.NewBasicManager(), clientCtx.TxConfig, banktypes.GenesisBalancesIterator{}, address.NewBech32Codec("cosmosvaloper")) cmd.SetContext(ctx) cmd.SetArgs(tc.args) diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 0461713a0e16..999a3dbb0e8a 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -68,7 +68,7 @@ func displayInfo(info printInfo) error { // InitCmd returns a command that initializes all files needed for Tendermint // and the respective application. -func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { +func InitCmd(mbm module.BasicManager) *cobra.Command { cmd := &cobra.Command{ Use: "init [moniker]", Short: "Initialize private validator, p2p, genesis, and application configuration files", @@ -80,7 +80,6 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { serverCtx := server.GetServerContextFromCmd(cmd) config := serverCtx.Config - config.SetRoot(clientCtx.HomeDir) chainID, _ := cmd.Flags().GetString(flags.FlagChainID) switch { @@ -173,7 +172,6 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "node's home directory") cmd.Flags().BoolP(FlagOverwrite, "o", false, "overwrite the genesis.json file") cmd.Flags().Bool(FlagRecover, false, "provide seed phrase to recover existing key instead of creating") cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index 15df1571b899..c73f7d44fb3c 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -78,7 +78,7 @@ func TestInitCmd(t *testing.T) { ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) cmd.SetArgs( tt.flags(home), ) @@ -111,7 +111,7 @@ func TestInitRecover(t *testing.T) { ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) mockIn := testutil.ApplyMockIODiscardOutErr(cmd) cmd.SetArgs([]string{ @@ -142,11 +142,10 @@ func TestInitDefaultBondDenom(t *testing.T) { ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) cmd.SetArgs([]string{ "appnode-test", - fmt.Sprintf("--%s=%s", flags.FlagHome, home), fmt.Sprintf("--%s=testtoken", genutilcli.FlagDefaultBondDenom), }) require.NoError(t, cmd.ExecuteContext(ctx)) @@ -159,6 +158,7 @@ func TestEmptyState(t *testing.T) { require.NoError(t, err) serverCtx := server.NewContext(viper.New(), cfg, logger) + serverCtx.Config.SetRoot(home) interfaceRegistry := types.NewInterfaceRegistry() marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. @@ -170,8 +170,8 @@ func TestEmptyState(t *testing.T) { ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd := genutilcli.InitCmd(testMbm, home) - cmd.SetArgs([]string{"appnode-test", fmt.Sprintf("--%s=%s", flags.FlagHome, home)}) + cmd := genutilcli.InitCmd(testMbm) + cmd.SetArgs([]string{"appnode-test"}) require.NoError(t, cmd.ExecuteContext(ctx)) @@ -179,8 +179,7 @@ func TestEmptyState(t *testing.T) { r, w, _ := os.Pipe() os.Stdout = w - cmd = server.ExportCmd(nil, home) - cmd.SetArgs([]string{fmt.Sprintf("--%s=%s", flags.FlagHome, home)}) + cmd = server.ExportCmd(nil) require.NoError(t, cmd.ExecuteContext(ctx)) outC := make(chan string) @@ -265,7 +264,7 @@ func TestInitConfig(t *testing.T) { ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) cmd.SetArgs([]string{"testnode"}) require.NoError(t, cmd.ExecuteContext(ctx)) @@ -274,7 +273,7 @@ func TestInitConfig(t *testing.T) { r, w, _ := os.Pipe() os.Stdout = w - cmd = server.ExportCmd(nil, home) + cmd = server.ExportCmd(nil) require.NoError(t, cmd.ExecuteContext(ctx)) outC := make(chan string) @@ -313,7 +312,7 @@ func TestInitWithHeight(t *testing.T) { testInitialHeight := int64(333) - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) cmd.SetArgs([]string{"init-height-test", fmt.Sprintf("--%s=%d", flags.FlagInitHeight, testInitialHeight)}) require.NoError(t, cmd.ExecuteContext(ctx)) @@ -345,7 +344,7 @@ func TestInitWithNegativeHeight(t *testing.T) { testInitialHeight := int64(-333) - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) cmd.SetArgs([]string{"init-height-test", fmt.Sprintf("--%s=%d", flags.FlagInitHeight, testInitialHeight)}) require.NoError(t, cmd.ExecuteContext(ctx)) diff --git a/x/genutil/client/testutil/helpers.go b/x/genutil/client/testutil/helpers.go index 7060f6ab243c..3d5e37f99db4 100644 --- a/x/genutil/client/testutil/helpers.go +++ b/x/genutil/client/testutil/helpers.go @@ -10,7 +10,6 @@ import ( "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/testutil" @@ -25,8 +24,9 @@ func ExecInitCmd(testMbm module.BasicManager, home string, cdc codec.Codec) erro return err } - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) serverCtx := server.NewContext(viper.New(), cfg, logger) + serverCtx.Config.SetRoot(home) clientCtx := client.Context{}.WithCodec(cdc).WithHomeDir(home) _, out := testutil.ApplyMockIO(cmd) @@ -36,7 +36,7 @@ func ExecInitCmd(testMbm module.BasicManager, home string, cdc codec.Codec) erro ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd.SetArgs([]string{"appnode-test", fmt.Sprintf("--%s=%s", flags.FlagHome, home)}) + cmd.SetArgs([]string{"appnode-test"}) return cmd.ExecuteContext(ctx) } diff --git a/x/gov/client/cli/prompt.go b/x/gov/client/cli/prompt.go index a75d7c9eda87..2267ddc5052f 100644 --- a/x/gov/client/cli/prompt.go +++ b/x/gov/client/cli/prompt.go @@ -76,15 +76,11 @@ func Prompt[T any](data T, namePrefix string) (T, error) { // create prompts prompt := promptui.Prompt{ - Label: fmt.Sprintf("Enter %s's %s", namePrefix, strings.ToLower(client.CamelCaseToString(v.Type().Field(i).Name))), + Label: fmt.Sprintf("Enter %s %s", namePrefix, strings.ToLower(client.CamelCaseToString(v.Type().Field(i).Name))), Validate: client.ValidatePromptNotEmpty, } fieldName := strings.ToLower(v.Type().Field(i).Name) - // validation per field name - if strings.Contains(fieldName, "url") { - prompt.Validate = client.ValidatePromptURL - } if strings.EqualFold(fieldName, "authority") { // pre-fill with gov address @@ -92,6 +88,7 @@ func Prompt[T any](data T, namePrefix string) (T, error) { prompt.Validate = client.ValidatePromptAddress } + // TODO(@julienrbrt) use scalar annotation instead of dumb string name matching if strings.Contains(fieldName, "addr") || strings.Contains(fieldName, "sender") || strings.Contains(fieldName, "voter") || @@ -150,9 +147,8 @@ type proposalType struct { } // Prompt the proposal type values and return the proposal and its metadata -func (p *proposalType) Prompt(cdc codec.Codec) (*proposal, types.ProposalMetadata, error) { - // set metadata - metadata, err := Prompt(types.ProposalMetadata{}, "proposal") +func (p *proposalType) Prompt(cdc codec.Codec, skipMetadata bool) (*proposal, types.ProposalMetadata, error) { + metadata, err := PromptMetadata(skipMetadata) if err != nil { return nil, metadata, fmt.Errorf("failed to set proposal metadata: %w", err) } @@ -201,8 +197,48 @@ func getProposalSuggestions() []string { return types } +// PromptMetadata prompts for proposal metadata or only title and summary if skip is true +func PromptMetadata(skip bool) (types.ProposalMetadata, error) { + var ( + metadata types.ProposalMetadata + err error + ) + + if !skip { + metadata, err = Prompt(types.ProposalMetadata{}, "proposal") + if err != nil { + return metadata, fmt.Errorf("failed to set proposal metadata: %w", err) + } + } else { + // prompt for title and summary + titlePrompt := promptui.Prompt{ + Label: "Enter proposal title", + Validate: client.ValidatePromptNotEmpty, + } + + metadata.Title, err = titlePrompt.Run() + if err != nil { + return metadata, fmt.Errorf("failed to set proposal title: %w", err) + } + + summaryPrompt := promptui.Prompt{ + Label: "Enter proposal summary", + Validate: client.ValidatePromptNotEmpty, + } + + metadata.Summary, err = summaryPrompt.Run() + if err != nil { + return metadata, fmt.Errorf("failed to set proposal summary: %w", err) + } + } + + return metadata, nil +} + // NewCmdDraftProposal let a user generate a draft proposal. func NewCmdDraftProposal() *cobra.Command { + flagSkipMetadata := "skip-metadata" + cmd := &cobra.Command{ Use: "draft-proposal", Short: "Generate a draft proposal json file. The generated proposal json contains only one message (skeleton).", @@ -260,7 +296,9 @@ func NewCmdDraftProposal() *cobra.Command { } } - result, metadata, err := proposal.Prompt(clientCtx.Codec) + skipMetadataPrompt, _ := cmd.Flags().GetBool(flagSkipMetadata) + + result, metadata, err := proposal.Prompt(clientCtx.Codec, skipMetadataPrompt) if err != nil { return err } @@ -269,17 +307,20 @@ func NewCmdDraftProposal() *cobra.Command { return err } - if err := writeFile(draftMetadataFileName, metadata); err != nil { - return err + if !skipMetadataPrompt { + if err := writeFile(draftMetadataFileName, metadata); err != nil { + return err + } } - fmt.Printf("The draft proposal has successfully been generated.\nProposals should contain off-chain metadata, please upload the metadata JSON to IPFS.\nThen, replace the generated metadata field with the IPFS CID.\n") + cmd.Println("The draft proposal has successfully been generated.\nProposals should contain off-chain metadata, please upload the metadata JSON to IPFS.\nThen, replace the generated metadata field with the IPFS CID.") return nil }, } flags.AddTxFlagsToCmd(cmd) + cmd.Flags().Bool(flagSkipMetadata, false, "skip metadata prompt") return cmd } diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index 9ef1dbf729a9..a6c1538c0ac0 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -1,6 +1,7 @@ package cli import ( + "encoding/json" "fmt" "strconv" @@ -59,7 +60,11 @@ func GetCmdQueryProposer() *cobra.Command { return err } - return clientCtx.PrintObjectLegacy(prop) + output, err := json.Marshal(prop) + if err != nil { + return err + } + return clientCtx.PrintRaw(output) }, } diff --git a/x/gov/testutil/expected_keepers_mocks.go b/x/gov/testutil/expected_keepers_mocks.go index 1a7c78d61df6..0dc0ac0b6365 100644 --- a/x/gov/testutil/expected_keepers_mocks.go +++ b/x/gov/testutil/expected_keepers_mocks.go @@ -1,7 +1,7 @@ // Code generated by MockGen. DO NOT EDIT. // Source: x/gov/testutil/expected_keepers.go -// Package mock_testutil is a generated GoMock package. +// Package testutil is a generated GoMock package. package testutil import ( diff --git a/x/group/client/cli/prompt.go b/x/group/client/cli/prompt.go index 7b4a2fc4507c..79b347f525a3 100644 --- a/x/group/client/cli/prompt.go +++ b/x/group/client/cli/prompt.go @@ -30,9 +30,9 @@ type proposalType struct { } // Prompt the proposal type values and return the proposal and its metadata. -func (p *proposalType) Prompt(cdc codec.Codec) (*Proposal, govtypes.ProposalMetadata, error) { +func (p *proposalType) Prompt(cdc codec.Codec, skipMetadata bool) (*Proposal, govtypes.ProposalMetadata, error) { // set metadata - metadata, err := govcli.Prompt(govtypes.ProposalMetadata{}, "proposal") + metadata, err := govcli.PromptMetadata(skipMetadata) if err != nil { return nil, metadata, fmt.Errorf("failed to set proposal metadata: %w", err) } @@ -86,6 +86,8 @@ func (p *proposalType) Prompt(cdc codec.Codec) (*Proposal, govtypes.ProposalMeta // NewCmdDraftProposal let a user generate a draft proposal. func NewCmdDraftProposal() *cobra.Command { + flagSkipMetadata := "skip-metadata" + cmd := &cobra.Command{ Use: "draft-proposal", Short: "Generate a draft proposal json file. The generated proposal json contains only one message (skeleton).", @@ -137,7 +139,9 @@ func NewCmdDraftProposal() *cobra.Command { panic("unexpected proposal type") } - result, metadata, err := proposal.Prompt(clientCtx.Codec) + skipMetadataPrompt, _ := cmd.Flags().GetBool(flagSkipMetadata) + + result, metadata, err := proposal.Prompt(clientCtx.Codec, skipMetadataPrompt) if err != nil { return err } @@ -146,17 +150,20 @@ func NewCmdDraftProposal() *cobra.Command { return err } - if err := writeFile(draftMetadataFileName, metadata); err != nil { - return err + if !skipMetadataPrompt { + if err := writeFile(draftMetadataFileName, metadata); err != nil { + return err + } } - fmt.Printf("The draft proposal has successfully been generated.\nProposals should contain off-chain metadata, please upload the metadata JSON to IPFS.\nThen, replace the generated metadata field with the IPFS CID.\n") + cmd.Println("The draft proposal has successfully been generated.\nProposals should contain off-chain metadata, please upload the metadata JSON to IPFS.\nThen, replace the generated metadata field with the IPFS CID.") return nil }, } flags.AddTxFlagsToCmd(cmd) + cmd.Flags().Bool(flagSkipMetadata, false, "skip metadata prompt") return cmd } diff --git a/x/nft/go.mod b/x/nft/go.mod index d236c9328ef9..aa9208f908ff 100644 --- a/x/nft/go.mod +++ b/x/nft/go.mod @@ -7,7 +7,7 @@ require ( cosmossdk.io/core v0.9.0 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/errors v1.0.0 - cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca + cosmossdk.io/log v1.2.0 cosmossdk.io/math v1.0.1 cosmossdk.io/store v1.0.0-alpha.1 github.com/cometbft/cometbft v0.38.0-rc3 diff --git a/x/nft/go.sum b/x/nft/go.sum index 69c6988f1a46..85ddbdee6098 100644 --- a/x/nft/go.sum +++ b/x/nft/go.sum @@ -45,8 +45,8 @@ cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca h1:msenprh2BLLRwNT7zN56TbBHOGk/7ARQckXHxXyvjoQ= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca/go.mod h1:PkIAKXZvaxrTRc++z53XMRvFk8AcGGWYHcMIPzVYX9c= +cosmossdk.io/log v1.2.0 h1:BbykkDsutXPSy8RojFB3KZEWyvMsToLy0ykb/ZhsLqQ= +cosmossdk.io/log v1.2.0/go.mod h1:GNSCc/6+DhFIj1aLn/j7Id7PaO8DzNylUZoOYBL9+I4= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= cosmossdk.io/store v1.0.0-alpha.1 h1:/151XxAgm0tiKuYrtJzMG61lf6enpPuP+D/hIN8cRjQ= diff --git a/x/staking/keeper/keeper.go b/x/staking/keeper/keeper.go index 64ad687d1f6f..938dfa855ece 100644 --- a/x/staking/keeper/keeper.go +++ b/x/staking/keeper/keeper.go @@ -5,6 +5,7 @@ import ( "fmt" "cosmossdk.io/collections" + collcodec "cosmossdk.io/collections/codec" addresscodec "cosmossdk.io/core/address" storetypes "cosmossdk.io/core/store" "cosmossdk.io/log" @@ -32,11 +33,13 @@ type Keeper struct { validatorAddressCodec addresscodec.Codec consensusAddressCodec addresscodec.Codec - Schema collections.Schema - HistoricalInfo collections.Map[uint64, types.HistoricalInfo] - LastTotalPower collections.Item[math.Int] - ValidatorUpdates collections.Item[types.ValidatorUpdates] - DelegationsByValidator collections.Map[collections.Pair[sdk.ValAddress, sdk.AccAddress], []byte] + Schema collections.Schema + HistoricalInfo collections.Map[uint64, types.HistoricalInfo] + LastTotalPower collections.Item[math.Int] + ValidatorUpdates collections.Item[types.ValidatorUpdates] + DelegationsByValidator collections.Map[collections.Pair[sdk.ValAddress, sdk.AccAddress], []byte] + ValidatorByConsensusAddress collections.Map[sdk.ConsAddress, sdk.ValAddress] + UnbondingType collections.Map[uint64, uint64] } // NewKeeper creates a new staking Keeper instance @@ -86,6 +89,13 @@ func NewKeeper( collections.PairKeyCodec(sdk.LengthPrefixedAddressKey(sdk.ValAddressKey), sdk.AccAddressKey), // nolint: staticcheck // sdk.LengthPrefixedAddressKey is needed to retain state compatibility collections.BytesValue, ), + ValidatorByConsensusAddress: collections.NewMap( + sb, types.ValidatorsByConsAddrKey, + "validator_by_cons_addr", + sdk.LengthPrefixedAddressKey(sdk.ConsAddressKey), // nolint: staticcheck // sdk.LengthPrefixedAddressKey is needed to retain state compatibility + collcodec.KeyToValueCodec(sdk.ValAddressKey), + ), + UnbondingType: collections.NewMap(sb, types.UnbondingTypeKey, "unbonding_type", collections.Uint64Key, collections.Uint64Value), } schema, err := sb.Build() diff --git a/x/staking/keeper/unbonding.go b/x/staking/keeper/unbonding.go index 1813797b9761..0c457733c869 100644 --- a/x/staking/keeper/unbonding.go +++ b/x/staking/keeper/unbonding.go @@ -3,7 +3,9 @@ package keeper import ( "context" "encoding/binary" + "errors" + "cosmossdk.io/collections" errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" @@ -44,30 +46,17 @@ func (k Keeper) DeleteUnbondingIndex(ctx context.Context, id uint64) error { // GetUnbondingType returns the enum type of unbonding which is any of // {UnbondingDelegation | Redelegation | ValidatorUnbonding} func (k Keeper) GetUnbondingType(ctx context.Context, id uint64) (unbondingType types.UnbondingType, err error) { - store := k.storeService.OpenKVStore(ctx) - - bz, err := store.Get(types.GetUnbondingTypeKey(id)) - if err != nil { - return unbondingType, err - } - - if bz == nil { + ubdType, err := k.UnbondingType.Get(ctx, id) + if errors.Is(err, collections.ErrNotFound) { return unbondingType, types.ErrNoUnbondingType } - - return types.UnbondingType(binary.BigEndian.Uint64(bz)), nil + return types.UnbondingType(ubdType), err } // SetUnbondingType sets the enum type of unbonding which is any of // {UnbondingDelegation | Redelegation | ValidatorUnbonding} func (k Keeper) SetUnbondingType(ctx context.Context, id uint64, unbondingType types.UnbondingType) error { - store := k.storeService.OpenKVStore(ctx) - - // Convert into bytes for storage - bz := make([]byte, 8) - binary.BigEndian.PutUint64(bz, uint64(unbondingType)) - - return store.Set(types.GetUnbondingTypeKey(id), bz) + return k.UnbondingType.Set(ctx, id, uint64(unbondingType)) } // GetUnbondingDelegationByUnbondingID returns a unbonding delegation that has an unbonding delegation entry with a certain ID diff --git a/x/staking/keeper/validator.go b/x/staking/keeper/validator.go index 4db228ec1ecb..e5dd3c85513d 100644 --- a/x/staking/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -9,6 +9,7 @@ import ( gogotypes "github.com/cosmos/gogoproto/types" + "cosmossdk.io/collections" corestore "cosmossdk.io/core/store" errorsmod "cosmossdk.io/errors" "cosmossdk.io/math" @@ -44,9 +45,8 @@ func (k Keeper) mustGetValidator(ctx context.Context, addr sdk.ValAddress) types // GetValidatorByConsAddr gets a single validator by consensus address func (k Keeper) GetValidatorByConsAddr(ctx context.Context, consAddr sdk.ConsAddress) (validator types.Validator, err error) { - store := k.storeService.OpenKVStore(ctx) - opAddr, err := store.Get(types.GetValidatorByConsAddrKey(consAddr)) - if err != nil { + opAddr, err := k.ValidatorByConsensusAddress.Get(ctx, consAddr) + if err != nil && !errors.Is(err, collections.ErrNotFound) { return validator, err } @@ -79,8 +79,8 @@ func (k Keeper) SetValidatorByConsAddr(ctx context.Context, validator types.Vali if err != nil { return err } - store := k.storeService.OpenKVStore(ctx) - return store.Set(types.GetValidatorByConsAddrKey(consPk), validator.GetOperator()) + + return k.ValidatorByConsensusAddress.Set(ctx, consPk, validator.GetOperator()) } // SetValidatorByPowerIndex sets a validator by power index @@ -219,7 +219,7 @@ func (k Keeper) RemoveValidator(ctx context.Context, address sdk.ValAddress) err return err } - if err = store.Delete(types.GetValidatorByConsAddrKey(valConsAddr)); err != nil { + if err = k.ValidatorByConsensusAddress.Remove(ctx, valConsAddr); err != nil { return err } diff --git a/x/staking/migrations/v2/keys.go b/x/staking/migrations/v2/keys.go index 57ccb0aebeea..b115ed5492fd 100644 --- a/x/staking/migrations/v2/keys.go +++ b/x/staking/migrations/v2/keys.go @@ -1,15 +1,29 @@ package v2 -import "strconv" +import ( + "strconv" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/address" +) const ( // ModuleName is the name of the module ModuleName = "staking" ) -var HistoricalInfoKey = []byte{0x50} // prefix for the historical info +var ( + ValidatorsByConsAddrKey = []byte{0x22} // prefix for validators by consensus address + HistoricalInfoKey = []byte{0x50} // prefix for the historical info +) // GetHistoricalInfoKey returns a key prefix for indexing HistoricalInfo objects. func GetHistoricalInfoKey(height int64) []byte { return append(HistoricalInfoKey, []byte(strconv.FormatInt(height, 10))...) } + +// GetValidatorByConsAddrKey creates the key for the validator with pubkey +// VALUE: validator operator address ([]byte) +func GetValidatorByConsAddrKey(addr sdk.ConsAddress) []byte { + return append(ValidatorsByConsAddrKey, address.MustLengthPrefix(addr)...) +} diff --git a/x/staking/migrations/v2/store_test.go b/x/staking/migrations/v2/store_test.go index 20c55e5bfcbb..da808b2a3aa8 100644 --- a/x/staking/migrations/v2/store_test.go +++ b/x/staking/migrations/v2/store_test.go @@ -59,7 +59,7 @@ func TestStoreMigration(t *testing.T) { { "ValidatorsByConsAddrKey", v1.GetValidatorByConsAddrKey(consAddr), - types.GetValidatorByConsAddrKey(consAddr), + v2.GetValidatorByConsAddrKey(consAddr), }, { "ValidatorsByPowerIndexKey", diff --git a/x/staking/testutil/expected_keepers_mocks.go b/x/staking/testutil/expected_keepers_mocks.go index e66027edd2e7..e40bbd84d63e 100644 --- a/x/staking/testutil/expected_keepers_mocks.go +++ b/x/staking/testutil/expected_keepers_mocks.go @@ -15,57 +15,6 @@ import ( gomock "github.com/golang/mock/gomock" ) -// MockDistributionKeeper is a mock of DistributionKeeper interface. -type MockDistributionKeeper struct { - ctrl *gomock.Controller - recorder *MockDistributionKeeperMockRecorder -} - -// MockDistributionKeeperMockRecorder is the mock recorder for MockDistributionKeeper. -type MockDistributionKeeperMockRecorder struct { - mock *MockDistributionKeeper -} - -// NewMockDistributionKeeper creates a new mock instance. -func NewMockDistributionKeeper(ctrl *gomock.Controller) *MockDistributionKeeper { - mock := &MockDistributionKeeper{ctrl: ctrl} - mock.recorder = &MockDistributionKeeperMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockDistributionKeeper) EXPECT() *MockDistributionKeeperMockRecorder { - return m.recorder -} - -// GetFeePoolCommunityCoins mocks base method. -func (m *MockDistributionKeeper) GetFeePoolCommunityCoins(ctx context.Context) types.DecCoins { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetFeePoolCommunityCoins", ctx) - ret0, _ := ret[0].(types.DecCoins) - return ret0 -} - -// GetFeePoolCommunityCoins indicates an expected call of GetFeePoolCommunityCoins. -func (mr *MockDistributionKeeperMockRecorder) GetFeePoolCommunityCoins(ctx interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFeePoolCommunityCoins", reflect.TypeOf((*MockDistributionKeeper)(nil).GetFeePoolCommunityCoins), ctx) -} - -// GetValidatorOutstandingRewardsCoins mocks base method. -func (m *MockDistributionKeeper) GetValidatorOutstandingRewardsCoins(ctx context.Context, val types.ValAddress) types.DecCoins { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetValidatorOutstandingRewardsCoins", ctx, val) - ret0, _ := ret[0].(types.DecCoins) - return ret0 -} - -// GetValidatorOutstandingRewardsCoins indicates an expected call of GetValidatorOutstandingRewardsCoins. -func (mr *MockDistributionKeeperMockRecorder) GetValidatorOutstandingRewardsCoins(ctx, val interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetValidatorOutstandingRewardsCoins", reflect.TypeOf((*MockDistributionKeeper)(nil).GetValidatorOutstandingRewardsCoins), ctx, val) -} - // MockAccountKeeper is a mock of AccountKeeper interface. type MockAccountKeeper struct { ctrl *gomock.Controller diff --git a/x/staking/types/expected_keepers.go b/x/staking/types/expected_keepers.go index 9ab221103179..5e45733d0af7 100644 --- a/x/staking/types/expected_keepers.go +++ b/x/staking/types/expected_keepers.go @@ -9,12 +9,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// DistributionKeeper expected distribution keeper (noalias) -type DistributionKeeper interface { - GetFeePoolCommunityCoins(ctx context.Context) sdk.DecCoins - GetValidatorOutstandingRewardsCoins(ctx context.Context, val sdk.ValAddress) sdk.DecCoins -} - // AccountKeeper defines the expected account keeper (noalias) type AccountKeeper interface { AddressCodec() address.Codec diff --git a/x/staking/types/keys.go b/x/staking/types/keys.go index 067073c1bdff..8572eec7b033 100644 --- a/x/staking/types/keys.go +++ b/x/staking/types/keys.go @@ -34,9 +34,9 @@ var ( LastValidatorPowerKey = []byte{0x11} // prefix for each key to a validator index, for bonded validators LastTotalPowerKey = collections.NewPrefix(18) // prefix for the total power - ValidatorsKey = []byte{0x21} // prefix for each key to a validator - ValidatorsByConsAddrKey = []byte{0x22} // prefix for each key to a validator index, by pubkey - ValidatorsByPowerIndexKey = []byte{0x23} // prefix for each key to a validator index, sorted by power + ValidatorsKey = []byte{0x21} // prefix for each key to a validator + ValidatorsByConsAddrKey = collections.NewPrefix(34) // prefix for each key to a validator index, by pubkey + ValidatorsByPowerIndexKey = []byte{0x23} // prefix for each key to a validator index, sorted by power DelegationKey = []byte{0x31} // key for a delegation UnbondingDelegationKey = []byte{0x32} // key for an unbonding-delegation @@ -45,9 +45,9 @@ var ( RedelegationByValSrcIndexKey = []byte{0x35} // prefix for each key for an redelegation, by source validator operator RedelegationByValDstIndexKey = []byte{0x36} // prefix for each key for an redelegation, by destination validator operator - UnbondingIDKey = []byte{0x37} // key for the counter for the incrementing id for UnbondingOperations - UnbondingIndexKey = []byte{0x38} // prefix for an index for looking up unbonding operations by their IDs - UnbondingTypeKey = []byte{0x39} // prefix for an index containing the type of unbonding operations + UnbondingIDKey = []byte{0x37} // key for the counter for the incrementing id for UnbondingOperations + UnbondingIndexKey = []byte{0x38} // prefix for an index for looking up unbonding operations by their IDs + UnbondingTypeKey = collections.NewPrefix(57) // prefix for an index containing the type of unbonding operations UnbondingQueueKey = []byte{0x41} // prefix for the timestamps in unbonding queue RedelegationQueueKey = []byte{0x42} // prefix for the timestamps in redelegations queue @@ -71,13 +71,6 @@ const ( UnbondingType_ValidatorUnbonding ) -// GetUnbondingTypeKey returns a key for an index containing the type of unbonding operations -func GetUnbondingTypeKey(id uint64) []byte { - bz := make([]byte, 8) - binary.BigEndian.PutUint64(bz, id) - return append(UnbondingTypeKey, bz...) -} - // GetUnbondingIndexKey returns a key for the index for looking up UnbondingDelegations by the UnbondingDelegationEntries they contain func GetUnbondingIndexKey(id uint64) []byte { bz := make([]byte, 8) @@ -91,12 +84,6 @@ func GetValidatorKey(operatorAddr sdk.ValAddress) []byte { return append(ValidatorsKey, address.MustLengthPrefix(operatorAddr)...) } -// GetValidatorByConsAddrKey creates the key for the validator with pubkey -// VALUE: validator operator address ([]byte) -func GetValidatorByConsAddrKey(addr sdk.ConsAddress) []byte { - return append(ValidatorsByConsAddrKey, address.MustLengthPrefix(addr)...) -} - // AddressFromValidatorsKey creates the validator operator address from ValidatorsKey func AddressFromValidatorsKey(key []byte) []byte { kv.AssertKeyAtLeastLength(key, 3) diff --git a/x/upgrade/go.mod b/x/upgrade/go.mod index 998b8fa70449..d757993ad5c3 100644 --- a/x/upgrade/go.mod +++ b/x/upgrade/go.mod @@ -7,7 +7,7 @@ require ( cosmossdk.io/core v0.9.0 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/errors v1.0.0 - cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca + cosmossdk.io/log v1.2.0 cosmossdk.io/store v1.0.0-alpha.1 github.com/cometbft/cometbft v0.38.0-rc3 github.com/cosmos/cosmos-db v1.0.0 diff --git a/x/upgrade/go.sum b/x/upgrade/go.sum index 6615d6b66703..316bef8c5b0a 100644 --- a/x/upgrade/go.sum +++ b/x/upgrade/go.sum @@ -197,8 +197,8 @@ cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca h1:msenprh2BLLRwNT7zN56TbBHOGk/7ARQckXHxXyvjoQ= -cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca/go.mod h1:PkIAKXZvaxrTRc++z53XMRvFk8AcGGWYHcMIPzVYX9c= +cosmossdk.io/log v1.2.0 h1:BbykkDsutXPSy8RojFB3KZEWyvMsToLy0ykb/ZhsLqQ= +cosmossdk.io/log v1.2.0/go.mod h1:GNSCc/6+DhFIj1aLn/j7Id7PaO8DzNylUZoOYBL9+I4= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= cosmossdk.io/store v1.0.0-alpha.1 h1:/151XxAgm0tiKuYrtJzMG61lf6enpPuP+D/hIN8cRjQ=