diff --git a/CHANGELOG.md b/CHANGELOG.md index b674e84db780..39cd7088a8c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -86,6 +86,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### API Breaking Changes * [\#11496](https://github.com/cosmos/cosmos-sdk/pull/11496) refactor abstractions for snapshot and pruning; snapshot intervals eventually pruned; unit tests. +* (types) [\#11689](https://github.com/cosmos/cosmos-sdk/pull/11689) Make `Coins#Sub` and `Coins#SafeSub` consistent with `Coins#Add`. * (store)[\#11152](https://github.com/cosmos/cosmos-sdk/pull/11152) Remove `keep-every` from pruning options. * [\#10950](https://github.com/cosmos/cosmos-sdk/pull/10950) Add `envPrefix` parameter to `cmd.Execute`. * (x/mint) [\#10441](https://github.com/cosmos/cosmos-sdk/pull/10441) The `NewAppModule` function now accepts an inflation calculation function as an argument. @@ -176,6 +177,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Improvements +* [\#11696](https://github.com/cosmos/cosmos-sdk/pull/11696) Rename `helpers.GenTx` to `GenSignedMockTx` to avoid confusion with genutil's `GenTxCmd`. * (x/auth/vesting) [\#11652](https://github.com/cosmos/cosmos-sdk/pull/11652) Add util functions for `Period(s)` * [\#11630](https://github.com/cosmos/cosmos-sdk/pull/11630) Add SafeSub method to sdk.Coin. * [\#11511](https://github.com/cosmos/cosmos-sdk/pull/11511) Add api server flags to start command. @@ -209,6 +211,8 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Bug Fixes +* [\#11693](https://github.com/cosmos/cosmos-sdk/pull/11693) Add validation for gentx cmd. +* [\#11645](https://github.com/cosmos/cosmos-sdk/pull/11645) Fix `--home` flag ignored when running help. * [\#11558](https://github.com/cosmos/cosmos-sdk/pull/11558) Fix `--dry-run` not working when using tx command. * [\#11354](https://github.com/cosmos/cosmos-sdk/pull/11355) Added missing pagination flag for `bank q total` query. * [\#11197](https://github.com/cosmos/cosmos-sdk/pull/11197) Signing with multisig now works with multisig address which is not in the keyring. diff --git a/Dockerfile b/Dockerfile index ffcbeccbc15f..026f222c594a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,7 +10,7 @@ # > docker run -it -p 26657:26657 -p 26656:26656 -v ~/.simappcli:/root/.simapp simapp simd keys add foo # > docker run -it -p 26657:26657 -p 26656:26656 -v ~/.simappcli:/root/.simapp simapp simd keys list # TODO: demo connecting rest-server (or is this in server now?) -FROM golang:alpine AS build-env +FROM golang:1.18-alpine AS build-env # Install minimum necessary dependencies ENV PACKAGES curl make git libc-dev bash gcc linux-headers eudev-dev python3 diff --git a/client/cmd_test.go b/client/cmd_test.go index 65161fe4752b..81d5719ccfb6 100644 --- a/client/cmd_test.go +++ b/client/cmd_test.go @@ -70,6 +70,7 @@ func TestSetCmdClientContextHandler(t *testing.T) { } c.Flags().String(flags.FlagChainID, "", "network chain ID") + c.Flags().String(flags.FlagHome, "", "home dir") return c } @@ -91,6 +92,14 @@ func TestSetCmdClientContextHandler(t *testing.T) { fmt.Sprintf("--%s=new-chain-id", flags.FlagChainID), }, }, + { + "flags set with space", + initClientCtx.WithHomeDir("/tmp/dir"), + []string{ + fmt.Sprintf("--%s", flags.FlagHome), + "/tmp/dir", + }, + }, } for _, tc := range testCases { diff --git a/contrib/devtools/Dockerfile b/contrib/devtools/Dockerfile index 8c4bdcd1452b..f94cd50d8044 100644 --- a/contrib/devtools/Dockerfile +++ b/contrib/devtools/Dockerfile @@ -4,7 +4,7 @@ FROM bufbuild/buf:1.1.0 as BUILDER -FROM golang:alpine +FROM golang:1.18-alpine RUN apk add --no-cache \ nodejs \ diff --git a/contrib/devtools/Makefile b/contrib/devtools/Makefile index 2e3741fd852f..f8a5de4edd37 100644 --- a/contrib/devtools/Makefile +++ b/contrib/devtools/Makefile @@ -57,28 +57,20 @@ tools-stamp: statik runsim # in a row. touch $@ -# Install the runsim binary with a temporary workaround of entering an outside -# directory as the "go get" command ignores the -mod option and will polute the -# go.{mod, sum} files. -# -# ref: https://github.com/golang/go/issues/30515 +# Install the runsim binary statik: $(STATIK) $(STATIK): @echo "Installing statik..." - @(cd /tmp && go get github.com/rakyll/statik@v0.1.6) + @go install github.com/rakyll/statik@v0.1.6 -# Install the runsim binary with a temporary workaround of entering an outside -# directory as the "go get" command ignores the -mod option and will polute the -# go.{mod, sum} files. -# -# ref: https://github.com/golang/go/issues/30515 +# Install the runsim binary runsim: $(RUNSIM) $(RUNSIM): @echo "Installing runsim..." - @(cd /tmp && go get github.com/cosmos/tools/cmd/runsim@v1.0.0) + @go install github.com/cosmos/tools/cmd/runsim@v1.0.0 tools-clean: rm -f $(STATIK) $(GOLANGCI_LINT) $(RUNSIM) rm -f tools-stamp -.PHONY: tools-clean statik runsim +.PHONY: tools-clean statik runsim \ No newline at end of file diff --git a/contrib/images/simd-dlv/Dockerfile b/contrib/images/simd-dlv/Dockerfile index 35680f21f415..30ed840fcb63 100644 --- a/contrib/images/simd-dlv/Dockerfile +++ b/contrib/images/simd-dlv/Dockerfile @@ -1,4 +1,5 @@ -FROM golang:alpine AS build +FROM golang:1.18-alpine AS build + RUN apk add build-base git linux-headers libc-dev RUN go install github.com/go-delve/delve/cmd/dlv@latest WORKDIR /work @@ -20,4 +21,4 @@ WORKDIR /simd EXPOSE 26656 26657 2345 ENTRYPOINT ["/usr/bin/wrapper.sh"] CMD ["start", "--log_format", "plain"] -STOPSIGNAL SIGTERM \ No newline at end of file +STOPSIGNAL SIGTERM diff --git a/contrib/images/simd-env/Dockerfile b/contrib/images/simd-env/Dockerfile index 83b86dce7101..d32fdfe82614 100644 --- a/contrib/images/simd-env/Dockerfile +++ b/contrib/images/simd-env/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:alpine AS build +FROM golang:1.18-alpine AS build RUN apk add build-base git linux-headers WORKDIR /work COPY go.mod go.sum /work/ diff --git a/contrib/rosetta/rosetta-ci/Dockerfile b/contrib/rosetta/rosetta-ci/Dockerfile index 34cc6512e989..d4cfc58528e9 100644 --- a/contrib/rosetta/rosetta-ci/Dockerfile +++ b/contrib/rosetta/rosetta-ci/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:alpine as build +FROM golang:1.18-alpine as build RUN apk add --no-cache tar git diff --git a/contrib/rosetta/rosetta-cli/Dockerfile b/contrib/rosetta/rosetta-cli/Dockerfile index aa1f16146f14..da6ef2879239 100644 --- a/contrib/rosetta/rosetta-cli/Dockerfile +++ b/contrib/rosetta/rosetta-cli/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:alpine as build +FROM golang:1.18-alpine as build RUN apk add git gcc libc-dev --no-cache @@ -15,4 +15,4 @@ RUN apk add gcc libc-dev python3 --no-cache ENV PATH=$PATH:/bin -COPY --from=build /rosetta/rosetta-cli /bin/rosetta-cli \ No newline at end of file +COPY --from=build /rosetta/rosetta-cli /bin/rosetta-cli diff --git a/docs/architecture/adr-030-authz-module.md b/docs/architecture/adr-030-authz-module.md index b9c0720e10f0..1390d0f6b4c5 100644 --- a/docs/architecture/adr-030-authz-module.md +++ b/docs/architecture/adr-030-authz-module.md @@ -6,6 +6,7 @@ * 2020-10-12: Updated Draft * 2020-11-13: Accepted * 2020-05-06: proto API updates, use `sdk.Msg` instead of `sdk.ServiceMsg` (the latter concept was removed from Cosmos SDK) +* 2022-04-20: Updated the `SendAuthorization` proto docs to clarify the `SpendLimit` is a required field. (Generic authorization can be used with bank msg type url to create limit less bank authorization) ## Status @@ -87,8 +88,8 @@ a `SpendLimit` and updates it down to zero: ```go type SendAuthorization struct { // SpendLimit specifies the maximum amount of tokens that can be spent - // by this authorization and will be updated as tokens are spent. If it is - // empty, there is no spend limit and any amount of coins can be spent. + // by this authorization and will be updated as tokens are spent. This field is required. (Generic authorization + // can be used with bank msg type url to create limit less bank authorization). SpendLimit sdk.Coins } diff --git a/docs/core/encoding.md b/docs/core/encoding.md index 9e71968c26cd..e7a9e330f048 100644 --- a/docs/core/encoding.md +++ b/docs/core/encoding.md @@ -73,12 +73,12 @@ Since the `MsgExec` message type can contain different messages instances, it is add the following code inside the `init` method of their module's `codec.go` file: ```go -import "github.com/cosmos/cosmos-sdk/codec/legacy" +import authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" init() { - // Register all Amino interfaces and concrete types on the global Amino codec so that this can later be - // used to properly serialize x/authz MsgExec instances - RegisterLegacyAminoCodec(legacy.Cdc) + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } ``` diff --git a/go.mod b/go.mod index 62e25f28ea8d..0a5b61dc8a46 100644 --- a/go.mod +++ b/go.mod @@ -37,7 +37,7 @@ require ( github.com/mattn/go-isatty v0.0.14 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.12.1 - github.com/prometheus/common v0.33.0 + github.com/prometheus/common v0.34.0 github.com/rakyll/statik v0.1.7 github.com/regen-network/cosmos-proto v0.3.1 github.com/rs/zerolog v1.26.1 diff --git a/go.sum b/go.sum index 0cafef3401a8..cf953e024344 100644 --- a/go.sum +++ b/go.sum @@ -970,8 +970,8 @@ github.com/prometheus/common v0.15.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16 github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= github.com/prometheus/common v0.30.0/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= -github.com/prometheus/common v0.33.0 h1:rHgav/0a6+uYgGdNt3jwz8FNSesO/Hsang3O0T9A5SE= -github.com/prometheus/common v0.33.0/go.mod h1:gB3sOl7P0TvJabZpLY5uQMpUqRCPPCyRLCZYc7JZTNE= +github.com/prometheus/common v0.34.0 h1:RBmGO9d/FVjqHT0yUGQwBJhkwKV+wPCn7KGpvfab0uE= +github.com/prometheus/common v0.34.0/go.mod h1:gB3sOl7P0TvJabZpLY5uQMpUqRCPPCyRLCZYc7JZTNE= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index 2d02d58dedd3..0dc88f9b4623 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -18,8 +18,8 @@ const ( SimAppChainID = "simulation-app" ) -// GenTx generates a signed mock transaction. -func GenTx(gen client.TxConfig, msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accNums, accSeqs []uint64, priv ...cryptotypes.PrivKey) (sdk.Tx, error) { +// GenSignedMockTx generates a signed mock transaction. +func GenSignedMockTx(gen client.TxConfig, msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accNums, accSeqs []uint64, priv ...cryptotypes.PrivKey) (sdk.Tx, error) { sigs := make([]signing.SignatureV2, len(priv)) // create a random length memo diff --git a/simapp/simd/cmd/cmd_test.go b/simapp/simd/cmd/cmd_test.go index 0e2a291e9c74..ab9d8de71064 100644 --- a/simapp/simd/cmd/cmd_test.go +++ b/simapp/simd/cmd/cmd_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/client/flags" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/simapp/simd/cmd" @@ -22,3 +23,21 @@ func TestInitCmd(t *testing.T) { require.NoError(t, svrcmd.Execute(rootCmd, "", simapp.DefaultNodeHome)) } + +func TestHomeFlagRegistration(t *testing.T) { + homeDir := "/tmp/foo" + + rootCmd, _ := cmd.NewRootCmd() + + rootCmd.SetArgs([]string{ + "query", + fmt.Sprintf("--%s", flags.FlagHome), + homeDir, + }) + + require.NoError(t, svrcmd.Execute(rootCmd, "", simapp.DefaultNodeHome)) + + result, err := rootCmd.Flags().GetString(flags.FlagHome) + require.NoError(t, err) + require.Equal(t, result, homeDir) +} diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 354c00b8c5fa..373b7d40e24a 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -193,7 +193,7 @@ func queryCommand() *cobra.Command { Use: "query", Aliases: []string{"q"}, Short: "Querying subcommands", - DisableFlagParsing: true, + DisableFlagParsing: false, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } @@ -216,7 +216,7 @@ func txCommand() *cobra.Command { cmd := &cobra.Command{ Use: "tx", Short: "Transactions subcommands", - DisableFlagParsing: true, + DisableFlagParsing: false, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 364891a5f0c9..4fe0c2b4d87f 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -412,7 +412,7 @@ func SignCheckDeliver( chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey, ) (sdk.GasInfo, *sdk.Result, error) { - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txCfg, msgs, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, @@ -462,7 +462,7 @@ func GenSequenceOfTxs(txGen client.TxConfig, msgs []sdk.Msg, accNums []uint64, i txs := make([]sdk.Tx, numToGenerate) var err error for i := 0; i < numToGenerate; i++ { - txs[i], err = helpers.GenTx( + txs[i], err = helpers.GenSignedMockTx( txGen, msgs, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, diff --git a/types/coin.go b/types/coin.go index ffffa5a6685e..1b8e465c1d81 100644 --- a/types/coin.go +++ b/types/coin.go @@ -393,8 +393,8 @@ func (coins Coins) DenomsSubsetOf(coinsB Coins) bool { // // CONTRACT: Sub will never return Coins where one Coin has a non-positive // amount. In otherwords, IsValid will always return true. -func (coins Coins) Sub(coinsB Coins) Coins { - diff, hasNeg := coins.SafeSub(coinsB) +func (coins Coins) Sub(coinsB ...Coin) Coins { + diff, hasNeg := coins.SafeSub(coinsB...) if hasNeg { panic("negative coin amount") } @@ -405,8 +405,8 @@ func (coins Coins) Sub(coinsB Coins) Coins { // SafeSub performs the same arithmetic as Sub but returns a boolean if any // negative coin amount was returned. // The function panics if `coins` or `coinsB` are not sorted (ascending). -func (coins Coins) SafeSub(coinsB Coins) (Coins, bool) { - diff := coins.safeAdd(coinsB.negative()) +func (coins Coins) SafeSub(coinsB ...Coin) (Coins, bool) { + diff := coins.safeAdd(NewCoins(coinsB...).negative()) return diff, diff.IsAnyNegative() } @@ -834,13 +834,13 @@ func ParseCoinNormalized(coinStr string) (coin Coin, err error) { return coin, nil } -// ParseCoinsNormalized will parse out a list of coins separated by commas, and normalize them by converting to smallest -// unit. If the parsing is successuful, the provided coins will be sanitized by removing zero coins and sorting the coin +// ParseCoinsNormalized will parse out a list of coins separated by commas, and normalize them by converting to the smallest +// unit. If the parsing is successful, the provided coins will be sanitized by removing zero coins and sorting the coin // set. Lastly a validation of the coin set is executed. If the check passes, ParseCoinsNormalized will return the // sanitized coins. -// Otherwise it will return an error. +// Otherwise, it will return an error. // If an empty string is provided to ParseCoinsNormalized, it returns nil Coins. -// ParseCoinsNormalized supports decimal coins as inputs, and truncate them to int after converted to smallest unit. +// ParseCoinsNormalized supports decimal coins as inputs, and truncate them to int after converted to the smallest unit. // Expected format: "{amount0}{denomination},...,{amountN}{denominationN}" func ParseCoinsNormalized(coinStr string) (Coins, error) { coins, err := ParseDecCoins(coinStr) diff --git a/types/coin_test.go b/types/coin_test.go index 4ede386e3d49..64a39c813e09 100644 --- a/types/coin_test.go +++ b/types/coin_test.go @@ -496,9 +496,9 @@ func (s *coinTestSuite) TestSubCoins() { for i, tc := range testCases { tc := tc if tc.shouldPanic { - assert.Panics(func() { tc.inputOne.Sub(tc.inputTwo) }) + assert.Panics(func() { tc.inputOne.Sub(tc.inputTwo...) }) } else { - res := tc.inputOne.Sub(tc.inputTwo) + res := tc.inputOne.Sub(tc.inputTwo...) assert.True(res.IsValid()) assert.Equal(tc.expected, res, "sum of coins is incorrect, tc #%d", i) } diff --git a/x/auth/client/testutil/suite.go b/x/auth/client/testutil/suite.go index 4bf61146b717..40aa258dd5e6 100644 --- a/x/auth/client/testutil/suite.go +++ b/x/auth/client/testutil/suite.go @@ -917,7 +917,7 @@ func (s *IntegrationTestSuite) TestCLIMultisignSortSignatures() { err = val1.ClientCtx.Codec.UnmarshalJSON(resp.Bytes(), &balRes) s.Require().NoError(err) - diff, _ := balRes.Balances.SafeSub(intialCoins) + diff, _ := balRes.Balances.SafeSub(intialCoins...) s.Require().Equal(sendTokens.Amount, diff.AmountOf(s.cfg.BondDenom)) // Generate multisig transaction. diff --git a/x/auth/middleware/basic_test.go b/x/auth/middleware/basic_test.go index 1c44e292eb93..7bc583ed8d75 100644 --- a/x/auth/middleware/basic_test.go +++ b/x/auth/middleware/basic_test.go @@ -33,22 +33,37 @@ func (s *MWTestSuite) TestValidateBasic() { invalidTx, _, err := s.createTestTx(txBuilder, privs, accNums, accSeqs, ctx.ChainID()) s.Require().NoError(err) + // DeliverTx _, err = txHandler.DeliverTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: invalidTx}) s.Require().NotNil(err, "Did not error on invalid tx") + // SimulateTx + _, err = txHandler.SimulateTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: invalidTx}) + s.Require().NotNil(err, "Did not error on invalid tx") + privs, accNums, accSeqs = []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} validTx, _, err := s.createTestTx(txBuilder, privs, accNums, accSeqs, ctx.ChainID()) s.Require().NoError(err) + // DeliverTx _, err = txHandler.DeliverTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: validTx}) s.Require().Nil(err, "ValidateBasicMiddleware returned error on valid tx. err: %v", err) + // SimulateTx + _, err = txHandler.SimulateTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: validTx}) + s.Require().Nil(err, "ValidateBasicMiddleware returned error on valid tx. err: %v", err) + // test middleware skips on recheck ctx = ctx.WithIsReCheckTx(true) // middleware should skip processing invalidTx on recheck and thus return nil-error + // DeliverTx _, err = txHandler.DeliverTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: invalidTx}) s.Require().Nil(err, "ValidateBasicMiddleware ran on ReCheck") + + // SimulateTx + _, err = txHandler.SimulateTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: invalidTx}) + s.Require().Nil(err, "ValidateBasicMiddleware ran on ReCheck") } func (s *MWTestSuite) TestValidateMemo() { @@ -73,8 +88,12 @@ func (s *MWTestSuite) TestValidateMemo() { s.Require().NoError(err) // require that long memos get rejected + // DeliverTx _, err = txHandler.DeliverTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: invalidTx}) + s.Require().NotNil(err, "Did not error on tx with high memo") + // SimulateTx + _, err = txHandler.SimulateTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: invalidTx}) s.Require().NotNil(err, "Did not error on tx with high memo") txBuilder.SetMemo(strings.Repeat("01234567890", 10)) @@ -82,8 +101,13 @@ func (s *MWTestSuite) TestValidateMemo() { s.Require().NoError(err) // require small memos pass ValidateMemo middleware + // DeliverTx _, err = txHandler.DeliverTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: validTx}) s.Require().Nil(err, "ValidateBasicMiddleware returned error on valid tx. err: %v", err) + + // SimulateTx + _, err = txHandler.SimulateTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: validTx}) + s.Require().Nil(err, "ValidateBasicMiddleware returned error on valid tx. err: %v", err) } func (s *MWTestSuite) TestConsumeGasForTxSize() { @@ -214,8 +238,15 @@ func (s *MWTestSuite) TestTxHeightTimeoutMiddleware() { s.Require().NoError(err) ctx := ctx.WithBlockHeight(tc.height) + + // DeliverTx + _, err = txHandler.DeliverTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: testTx}) + s.Require().Equal(tc.expectErr, err != nil, err) + + // SimulateTx _, err = txHandler.SimulateTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: testTx}) s.Require().Equal(tc.expectErr, err != nil, err) + }) } } diff --git a/x/auth/middleware/fee_test.go b/x/auth/middleware/fee_test.go index 7c1f54463fff..9899e2aa63c3 100644 --- a/x/auth/middleware/fee_test.go +++ b/x/auth/middleware/fee_test.go @@ -100,15 +100,27 @@ func (s *MWTestSuite) TestDeductFees() { err = testutil.FundAccount(s.app.BankKeeper, ctx, addr1, coins) s.Require().NoError(err) + // DeliverTx _, err = txHandler.DeliverTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: testTx}) - s.Require().NotNil(err, "Tx did not error when fee payer had insufficient funds") + s.Require().NotNil(err, "Tx errored when fee payer had insufficient funds") + + // SimulateTx + _, err = txHandler.SimulateTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: testTx}) + s.Require().NotNil(err, "Tx errored when fee payer had insufficient funds") // Set account with sufficient funds s.app.AccountKeeper.SetAccount(ctx, acc) err = testutil.FundAccount(s.app.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewCoin("atom", sdk.NewInt(200)))) s.Require().NoError(err) + // DeliverTx _, err = txHandler.DeliverTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: testTx}) + s.Require().Nil(err, "Tx did not error after account has been set with sufficient funds") + + err = testutil.FundAccount(s.app.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewCoin("atom", sdk.NewInt(200)))) + s.Require().NoError(err) - s.Require().Nil(err, "Tx errored after account has been set with sufficient funds") + // SimulateTx + _, err = txHandler.SimulateTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: testTx}) + s.Require().Nil(err, "Tx did not error after account has been set with sufficient funds") } diff --git a/x/auth/middleware/gas_test.go b/x/auth/middleware/gas_test.go index 78685fa6c766..480077762149 100644 --- a/x/auth/middleware/gas_test.go +++ b/x/auth/middleware/gas_test.go @@ -65,10 +65,13 @@ func (s *MWTestSuite) TestSetup() { for _, tc := range testcases { s.Run(tc.name, func() { res, _, err := txHandler.CheckTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: tc.tx}, tx.RequestCheckTx{}) + _, simErr := txHandler.SimulateTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: tc.tx}) if tc.expErr { s.Require().EqualError(err, tc.errorStr) + s.Require().EqualError(simErr, tc.errorStr) } else { s.Require().Nil(err, "SetUpContextMiddleware returned error") + s.Require().Nil(simErr, "SetUpContextMiddleware returned error") s.Require().Equal(tc.expGasLimit, uint64(res.GasWanted)) } }) diff --git a/x/auth/middleware/run_msgs_test.go b/x/auth/middleware/run_msgs_test.go index 6278d5c023d2..143a21975380 100644 --- a/x/auth/middleware/run_msgs_test.go +++ b/x/auth/middleware/run_msgs_test.go @@ -28,8 +28,13 @@ func (s *MWTestSuite) TestRunMsgs() { txBytes, err := s.clientCtx.TxConfig.TxEncoder()(testTx) s.Require().NoError(err) + // DeliverTx res, err := txHandler.DeliverTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: testTx, TxBytes: txBytes}) s.Require().NoError(err) s.Require().Len(res.MsgResponses, 1) s.Require().Equal(fmt.Sprintf("/%s", proto.MessageName(&testdata.MsgCreateDogResponse{})), res.MsgResponses[0].TypeUrl) + + // SimulateTx + _, err = txHandler.SimulateTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: testTx, TxBytes: txBytes}) + s.Require().NoError(err) } diff --git a/x/auth/middleware/sigverify_test.go b/x/auth/middleware/sigverify_test.go index a0c68062a968..fd4fc5622041 100644 --- a/x/auth/middleware/sigverify_test.go +++ b/x/auth/middleware/sigverify_test.go @@ -55,6 +55,7 @@ func (s *MWTestSuite) TestSetPubKey() { testTx, _, err := s.createTestTx(txBuilder, privs, accNums, accSeqs, ctx.ChainID()) require.NoError(err) + // DeliverTx _, err = txHandler.DeliverTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: testTx}) require.NoError(err) @@ -65,6 +66,10 @@ func (s *MWTestSuite) TestSetPubKey() { require.True(pubs[i].Equals(pk), "Wrong Pubkey retrieved from AccountKeeper, idx=%d\nexpected=%s\n got=%s", i, pubs[i], pk) } + + // SimulateTx + _, err = txHandler.SimulateTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: testTx}) + require.NoError(err) } func (s *MWTestSuite) TestConsumeSignatureVerificationGas() { diff --git a/x/auth/middleware/tips_test.go b/x/auth/middleware/tips_test.go index 769aa0c4194a..7fb50f7e0f0f 100644 --- a/x/auth/middleware/tips_test.go +++ b/x/auth/middleware/tips_test.go @@ -115,9 +115,9 @@ func (s *MWTestSuite) TestTips() { s.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: ctx.BlockHeight()}}) // Make sure tip is correctly transferred to feepayer, and fee is paid. - expTipperRegens := initialRegens.Sub(tc.tip) + expTipperRegens := initialRegens.Sub(tc.tip...) expFeePayerRegens := initialRegens.Add(tc.tip...) - expFeePayerAtoms := initialAtoms.Sub(tc.fee) + expFeePayerAtoms := initialAtoms.Sub(tc.fee...) s.Require().True(expTipperRegens.AmountOf("regen").Equal(s.app.BankKeeper.GetBalance(ctx, tipper.acc.GetAddress(), "regen").Amount)) s.Require().True(expFeePayerRegens.AmountOf("regen").Equal(s.app.BankKeeper.GetBalance(ctx, feePayer.acc.GetAddress(), "regen").Amount)) s.Require().True(expFeePayerAtoms.AmountOf("atom").Equal(s.app.BankKeeper.GetBalance(ctx, feePayer.acc.GetAddress(), "atom").Amount)) diff --git a/x/auth/middleware/tx_test.go b/x/auth/middleware/tx_test.go index 8624aadbfea2..9e4ce65ed648 100644 --- a/x/auth/middleware/tx_test.go +++ b/x/auth/middleware/tx_test.go @@ -46,11 +46,18 @@ func (s *MWTestSuite) TestTxDecoderMiddleware() { txReqChecker, middleware.NewTxDecoderMiddleware(s.clientCtx.TxConfig.TxDecoder()), ) + + // DeliverTx _, err := txHandler.DeliverTx(sdk.WrapSDKContext(ctx), tc.req) + + // SimulateTx + _, simErr := txHandler.SimulateTx(sdk.WrapSDKContext(ctx), tc.req) if tc.expErr { require.Error(err) + require.Error(simErr) } else { require.NoError(err) + require.NoError(simErr) } }) } diff --git a/x/auth/types/codec.go b/x/auth/types/codec.go index fa8f0589fcfb..29561dfe018c 100644 --- a/x/auth/types/codec.go +++ b/x/auth/types/codec.go @@ -2,9 +2,11 @@ package types import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" ) // RegisterLegacyAminoCodec registers the account interfaces and concrete types on the @@ -37,6 +39,17 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { ) } +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + func init() { - RegisterLegacyAminoCodec(legacy.Cdc) + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } diff --git a/x/auth/vesting/types/codec.go b/x/auth/vesting/types/codec.go index 318c1ceea238..270116671e91 100644 --- a/x/auth/vesting/types/codec.go +++ b/x/auth/vesting/types/codec.go @@ -4,10 +4,12 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" ) // RegisterLegacyAminoCodec registers the vesting interfaces and concrete types on the @@ -62,6 +64,17 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + func init() { - RegisterLegacyAminoCodec(legacy.Cdc) + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } diff --git a/x/auth/vesting/types/msgs.go b/x/auth/vesting/types/msgs.go index 0948daac702b..6c56ab3208d0 100644 --- a/x/auth/vesting/types/msgs.go +++ b/x/auth/vesting/types/msgs.go @@ -2,8 +2,6 @@ package types import ( "fmt" - "github.com/cosmos/cosmos-sdk/codec/legacy" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -68,7 +66,7 @@ func (msg MsgCreateVestingAccount) ValidateBasic() error { // GetSignBytes returns the bytes all expected signers must sign over for a // MsgCreateVestingAccount. func (msg MsgCreateVestingAccount) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) } // GetSigners returns the expected signers for a MsgCreateVestingAccount. @@ -116,7 +114,7 @@ func (msg MsgCreatePermanentLockedAccount) ValidateBasic() error { // GetSignBytes returns the bytes all expected signers must sign over for a // MsgCreatePermanentLockedAccount. func (msg MsgCreatePermanentLockedAccount) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) } // GetSigners returns the expected signers for a MsgCreatePermanentLockedAccount. @@ -154,7 +152,7 @@ func (msg MsgCreatePeriodicVestingAccount) GetSigners() []sdk.AccAddress { // GetSignBytes returns the bytes all expected signers must sign over for a // MsgCreatePeriodicVestingAccount. func (msg MsgCreatePeriodicVestingAccount) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) } // ValidateBasic Implements Msg. diff --git a/x/auth/vesting/types/vesting_account.go b/x/auth/vesting/types/vesting_account.go index 1b21e882f0a9..7316e6afd5b7 100644 --- a/x/auth/vesting/types/vesting_account.go +++ b/x/auth/vesting/types/vesting_account.go @@ -41,7 +41,7 @@ func NewBaseVestingAccount(baseAccount *authtypes.BaseAccount, originalVesting s // // CONTRACT: Delegated vesting coins and vestingCoins must be sorted. func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins { - lockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting)) + lockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting)...) if lockedCoins == nil { return sdk.Coins{} } @@ -111,12 +111,12 @@ func (bva *BaseVestingAccount) TrackUndelegation(amount sdk.Coins) { if !x.IsZero() { xCoin := sdk.NewCoin(coin.Denom, x) - bva.DelegatedFree = bva.DelegatedFree.Sub(sdk.Coins{xCoin}) + bva.DelegatedFree = bva.DelegatedFree.Sub(xCoin) } if !y.IsZero() { yCoin := sdk.NewCoin(coin.Denom, y) - bva.DelegatedVesting = bva.DelegatedVesting.Sub(sdk.Coins{yCoin}) + bva.DelegatedVesting = bva.DelegatedVesting.Sub(yCoin) } } } @@ -248,7 +248,7 @@ func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coin // GetVestingCoins returns the total number of vesting coins. If no coins are // vesting, nil is returned. func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins { - return cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime)) + return cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime)...) } // LockedCoins returns the set of coins that are not spendable (i.e. locked), @@ -374,7 +374,7 @@ func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins // GetVestingCoins returns the total number of vesting coins. If no coins are // vesting, nil is returned. func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins { - return pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime)) + return pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime)...) } // LockedCoins returns the set of coins that are not spendable (i.e. locked), @@ -485,7 +485,7 @@ func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins { // GetVestingCoins returns the total number of vesting coins for a delayed // vesting account. func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins { - return dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime)) + return dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime)...) } // LockedCoins returns the set of coins that are not spendable (i.e. locked), diff --git a/x/auth/vesting/types/vesting_account_test.go b/x/auth/vesting/types/vesting_account_test.go index 6d85b8e7580d..db2d52141014 100644 --- a/x/auth/vesting/types/vesting_account_test.go +++ b/x/auth/vesting/types/vesting_account_test.go @@ -242,7 +242,7 @@ func TestSpendableCoinsDelVestingAcc(t *testing.T) { delegatedAmount := sdk.NewCoins(sdk.NewInt64Coin(stakeDenom, 50)) dva.TrackDelegation(now.Add(12*time.Hour), origCoins, delegatedAmount) lockedCoins = dva.LockedCoins(now.Add(12 * time.Hour)) - require.True(t, lockedCoins.IsEqual(origCoins.Sub(delegatedAmount))) + require.True(t, lockedCoins.IsEqual(origCoins.Sub(delegatedAmount...))) } func TestTrackDelegationDelVestingAcc(t *testing.T) { @@ -600,7 +600,7 @@ func TestSpendableCoinsPermLockedVestingAcc(t *testing.T) { delegatedAmount := sdk.NewCoins(sdk.NewInt64Coin(stakeDenom, 50)) plva.TrackDelegation(now.Add(12*time.Hour), origCoins, delegatedAmount) lockedCoins = plva.LockedCoins(now.Add(12 * time.Hour)) - require.True(t, lockedCoins.IsEqual(origCoins.Sub(delegatedAmount))) + require.True(t, lockedCoins.IsEqual(origCoins.Sub(delegatedAmount...))) } func TestTrackDelegationPermLockedVestingAcc(t *testing.T) { diff --git a/x/authz/codec.go b/x/authz/codec.go index 8d44c4f41f9e..da8222c8ec45 100644 --- a/x/authz/codec.go +++ b/x/authz/codec.go @@ -6,6 +6,7 @@ import ( types "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" ) // RegisterLegacyAminoCodec registers the necessary x/authz interfaces and concrete types @@ -36,7 +37,7 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, MsgServiceDesc()) } func init() { - // Register all Amino interfaces and concrete types on the global Amino codec so that this can later be + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(legacy.Cdc) + RegisterLegacyAminoCodec(authzcodec.Amino) } diff --git a/x/authz/codec/cdc.go b/x/authz/codec/cdc.go new file mode 100644 index 000000000000..520e435afd69 --- /dev/null +++ b/x/authz/codec/cdc.go @@ -0,0 +1,18 @@ +package codec + +import ( + "github.com/cosmos/cosmos-sdk/codec" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ( + Amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(Amino) +) + +func init() { + cryptocodec.RegisterCrypto(Amino) + codec.RegisterEvidences(Amino) + sdk.RegisterLegacyAminoCodec(Amino) +} diff --git a/x/authz/codec/doc.go b/x/authz/codec/doc.go new file mode 100644 index 000000000000..ecc365a2211b --- /dev/null +++ b/x/authz/codec/doc.go @@ -0,0 +1,18 @@ +/* +Package codec provides a singleton instance of Amino codec that should be used to register +any concrete type that can later be referenced inside a MsgGrant or MsgExec instance so that they +can be (de)serialized properly. + +Amino types should be ideally registered inside this codec within the init function of each module's +codec.go file as follows: + +func init() { + // ... + + RegisterLegacyAminoCodec(authzcodec.Amino) +} + +The codec instance is put inside this package and not the x/authz package in order to avoid any dependency cycle. + +*/ +package codec diff --git a/x/authz/keeper/keeper_test.go b/x/authz/keeper/keeper_test.go index de57acf71c10..223e3ad32617 100644 --- a/x/authz/keeper/keeper_test.go +++ b/x/authz/keeper/keeper_test.go @@ -220,7 +220,7 @@ func (s *TestSuite) TestDispatchAction() { require.Len(authzs, 1) authorization := authzs[0].(*banktypes.SendAuthorization) require.NotNil(authorization) - require.Equal(authorization.SpendLimit, coins100.Sub(coins10)) + require.Equal(authorization.SpendLimit, coins100.Sub(coins10...)) }, }, { diff --git a/x/authz/msgs.go b/x/authz/msgs.go index 3aa145bd7d12..60961d51a4c2 100644 --- a/x/authz/msgs.go +++ b/x/authz/msgs.go @@ -1,10 +1,9 @@ package authz import ( + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" "time" - "github.com/cosmos/cosmos-sdk/codec/legacy" - "github.com/gogo/protobuf/proto" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -77,7 +76,7 @@ func (msg MsgGrant) Route() string { // GetSignBytes implements the LegacyMsg.GetSignBytes method. func (msg MsgGrant) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&msg)) + return sdk.MustSortJSON(authzcodec.ModuleCdc.MustMarshalJSON(&msg)) } // GetAuthorization returns the cache value from the MsgGrant.Authorization if present. @@ -167,7 +166,7 @@ func (msg MsgRevoke) Route() string { // GetSignBytes implements the LegacyMsg.GetSignBytes method. func (msg MsgRevoke) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&msg)) + return sdk.MustSortJSON(authzcodec.ModuleCdc.MustMarshalJSON(&msg)) } // NewMsgExec creates a new MsgExecAuthorized @@ -234,5 +233,5 @@ func (msg MsgExec) Route() string { // GetSignBytes implements the LegacyMsg.GetSignBytes method. func (msg MsgExec) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&msg)) + return sdk.MustSortJSON(authzcodec.ModuleCdc.MustMarshalJSON(&msg)) } diff --git a/x/authz/simulation/operations.go b/x/authz/simulation/operations.go index ef5db52fdcc5..a20c7f276ca9 100644 --- a/x/authz/simulation/operations.go +++ b/x/authz/simulation/operations.go @@ -102,7 +102,7 @@ func SimulateMsgGrant(ak authz.AccountKeeper, bk authz.BankKeeper, _ keeper.Keep return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, err.Error()), nil, err } - spendLimit := spendableCoins.Sub(fees) + spendLimit := spendableCoins.Sub(fees...) if spendLimit == nil { return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, "spend limit is nil"), nil, nil } @@ -117,7 +117,7 @@ func SimulateMsgGrant(ak authz.AccountKeeper, bk authz.BankKeeper, _ keeper.Keep return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, err.Error()), nil, err } txCfg := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txCfg, []sdk.Msg{msg}, fees, @@ -187,7 +187,7 @@ func SimulateMsgRevoke(ak authz.AccountKeeper, bk authz.BankKeeper, k keeper.Kee msg := authz.NewMsgRevoke(granterAddr, granteeAddr, a.MsgTypeURL()) txCfg := simappparams.MakeTestEncodingConfig().TxConfig account := ak.GetAccount(ctx, granterAddr) - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txCfg, []sdk.Msg{&msg}, fees, @@ -276,7 +276,7 @@ func SimulateMsgExec(ak authz.AccountKeeper, bk authz.BankKeeper, k keeper.Keepe txCfg := simappparams.MakeTestEncodingConfig().TxConfig granteeAcc := ak.GetAccount(ctx, granteeAddr) - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txCfg, []sdk.Msg{&msgExec}, fees, diff --git a/x/authz/spec/01_concepts.md b/x/authz/spec/01_concepts.md index c4cc63acc4e3..9fa522ae5c10 100644 --- a/x/authz/spec/01_concepts.md +++ b/x/authz/spec/01_concepts.md @@ -42,7 +42,7 @@ The Cosmos SDK `x/authz` module comes with following authorization types: ### StakeAuthorization -`StakeAuthorization` implements the `Authorization` interface for messages in the [staking module](https://docs.cosmos.network/v0.44/modules/staking/). It takes an `AuthorizationType` to specify whether you want to authorise delegating, undelegating or redelegating (i.e. these have to be authorised seperately). It also takes a `MaxTokens` that keeps track of a limit to the amount of tokens that can be delegated/undelegated/redelegated. If left empty, the amount is unlimited. Additionally, this Msg takes an `AllowList` and a `DenyList`, which allows you to select which validators you allow grantees to stake with. +`StakeAuthorization` implements the `Authorization` interface for messages in the [staking module](https://docs.cosmos.network/v0.44/modules/staking/). It takes an `AuthorizationType` to specify whether you want to authorise delegating, undelegating or redelegating (i.e. these have to be authorised seperately). It also takes a required `MaxTokens` that keeps track of a limit to the amount of tokens that can be delegated/undelegated/redelegated. If left empty, the amount is unlimited. Additionally, this Msg takes an `AllowList` or a `DenyList`, which allows you to select which validators you allow or deny grantees to stake with. +++ https://github.com/cosmos/cosmos-sdk/blob/v0.43.0-beta1/proto/cosmos/staking/v1beta1/authz.proto#L11-L31 @@ -51,3 +51,5 @@ The Cosmos SDK `x/authz` module comes with following authorization types: ## Gas In order to prevent DoS attacks, granting `StakeAuthorization`s with `x/authz` incurs gas. `StakeAuthorization` allows you to authorize another account to delegate, undelegate, or redelegate to validators. The authorizer can define a list of validators they allow or deny delegations to. The Cosmos SDK iterates over these lists and charge 10 gas for each validator in both of the lists. + +Since the state maintaining a list for granter, grantee pair with same expiration, we are iterating over the list to remove the grant (incase of any revoke of paritcular `msgType`) from the list and we are charging 20 gas per iteration. diff --git a/x/authz/spec/02_state.md b/x/authz/spec/02_state.md index 4aa7ac143234..4bd35e94f714 100644 --- a/x/authz/spec/02_state.md +++ b/x/authz/spec/02_state.md @@ -12,4 +12,12 @@ Grants are identified by combining granter address (the address bytes of the gra The grant object encapsulates an `Authorization` type and an expiration timestamp: -+++ https://github.com/cosmos/cosmos-sdk/blob/v0.43.0-beta1/proto/cosmos/authz/v1beta1/authz.proto#L21-L26 ++++ https://github.com/cosmos/cosmos-sdk/blob/v0.46.0-beta2/proto/cosmos/authz/v1beta1/authz.proto#L22-L30 + +## GrantQueue + +We are maintaining a queue for authz pruning, whenever a grant created an item will be added to `GrantQueue` with a key of granter, grantee, expiration and value added as array of msg type urls. + +* GrantQueue: `0x02 | granter_address_len (1 byte) | granter_address_bytes | grantee_address_len (1 byte) | grantee_address_bytes | expiration_bytes -> ProtocalBuffer([]string{msgTypeUrls})` + ++++ https://github.com/cosmos/cosmos-sdk/blob/v0.46.0-beta2/x/authz/keeper/keys.go#L86-L102 \ No newline at end of file diff --git a/x/authz/spec/03_messages.md b/x/authz/spec/03_messages.md index 22007980a226..8afdcf187c4d 100644 --- a/x/authz/spec/03_messages.md +++ b/x/authz/spec/03_messages.md @@ -16,7 +16,7 @@ If there is already a grant for the `(granter, grantee, Authorization)` triple, The message handling should fail if: * both granter and grantee have the same address. -* provided `Expiration` time is less than current unix timestamp. +* provided `Expiration` time is less than current unix timestamp (but a grant will be created if no `expiration` time is provided since `expiration` is optional). * provided `Grant.Authorization` is not implemented. * `Authorization.MsgTypeURL()` is not defined in the router (there is no defined handler in the app router to handle that Msg types). diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index 3c181d65d9fd..7c3feb4c1c2f 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -287,7 +287,7 @@ func (suite *IntegrationTestSuite) TestSupply_BurnCoins() { supplyAfterBurn, _, err := keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) suite.Require().NoError(err) suite.Require().Equal(sdk.NewCoins().String(), getCoinsByName(ctx, keeper, authKeeper, authtypes.Burner).String()) - suite.Require().Equal(supplyAfterInflation.Sub(initCoins), supplyAfterBurn) + suite.Require().Equal(supplyAfterInflation.Sub(initCoins...), supplyAfterBurn) // test same functionality on module account with multiple permissions suite. @@ -304,7 +304,7 @@ func (suite *IntegrationTestSuite) TestSupply_BurnCoins() { suite.Require().NoError(err) suite.Require().NoError(err) suite.Require().Equal(sdk.NewCoins().String(), getCoinsByName(ctx, keeper, authKeeper, multiPermAcc.GetName()).String()) - suite.Require().Equal(supplyAfterInflation.Sub(initCoins), supplyAfterBurn) + suite.Require().Equal(supplyAfterInflation.Sub(initCoins...), supplyAfterBurn) } func (suite *IntegrationTestSuite) TestSendCoinsNewAccount() { @@ -331,7 +331,7 @@ func (suite *IntegrationTestSuite) TestSendCoinsNewAccount() { acc2Balances := app.BankKeeper.GetAllBalances(ctx, addr2) acc1Balances = app.BankKeeper.GetAllBalances(ctx, addr1) suite.Require().Equal(sendAmt, acc2Balances) - updatedAcc1Bal := balances.Sub(sendAmt) + updatedAcc1Bal := balances.Sub(sendAmt...) suite.Require().Len(acc1Balances, len(updatedAcc1Bal)) suite.Require().Equal(acc1Balances, updatedAcc1Bal) suite.Require().NotNil(app.AccountKeeper.GetAccount(ctx, addr2)) @@ -713,7 +713,7 @@ func (suite *IntegrationTestSuite) TestSpendableCoins() { ctx = ctx.WithBlockTime(now.Add(12 * time.Hour)) suite.Require().NoError(app.BankKeeper.DelegateCoins(ctx, addr2, addrModule, delCoins)) - suite.Require().Equal(origCoins.Sub(delCoins), app.BankKeeper.SpendableCoins(ctx, addr1)) + suite.Require().Equal(origCoins.Sub(delCoins...), app.BankKeeper.SpendableCoins(ctx, addr1)) } func (suite *IntegrationTestSuite) TestVestingAccountSend() { @@ -806,10 +806,10 @@ func (suite *IntegrationTestSuite) TestVestingAccountReceive() { vacc = app.AccountKeeper.GetAccount(ctx, addr1).(*vesting.ContinuousVestingAccount) balances := app.BankKeeper.GetAllBalances(ctx, addr1) suite.Require().Equal(origCoins.Add(sendCoins...), balances) - suite.Require().Equal(balances.Sub(vacc.LockedCoins(now)), sendCoins) + suite.Require().Equal(balances.Sub(vacc.LockedCoins(now)...), sendCoins) // require coins are spendable plus any that have vested - suite.Require().Equal(balances.Sub(vacc.LockedCoins(now.Add(12*time.Hour))), origCoins) + suite.Require().Equal(balances.Sub(vacc.LockedCoins(now.Add(12*time.Hour))...), origCoins) } func (suite *IntegrationTestSuite) TestPeriodicVestingAccountReceive() { @@ -845,10 +845,10 @@ func (suite *IntegrationTestSuite) TestPeriodicVestingAccountReceive() { vacc = app.AccountKeeper.GetAccount(ctx, addr1).(*vesting.PeriodicVestingAccount) balances := app.BankKeeper.GetAllBalances(ctx, addr1) suite.Require().Equal(origCoins.Add(sendCoins...), balances) - suite.Require().Equal(balances.Sub(vacc.LockedCoins(now)), sendCoins) + suite.Require().Equal(balances.Sub(vacc.LockedCoins(now)...), sendCoins) // require coins are spendable plus any that have vested - suite.Require().Equal(balances.Sub(vacc.LockedCoins(now.Add(12*time.Hour))), origCoins) + suite.Require().Equal(balances.Sub(vacc.LockedCoins(now.Add(12*time.Hour))...), origCoins) } func (suite *IntegrationTestSuite) TestDelegateCoins() { @@ -879,7 +879,7 @@ func (suite *IntegrationTestSuite) TestDelegateCoins() { // require the ability for a non-vesting account to delegate suite.Require().NoError(app.BankKeeper.DelegateCoins(ctx, addr2, addrModule, delCoins)) - suite.Require().Equal(origCoins.Sub(delCoins), app.BankKeeper.GetAllBalances(ctx, addr2)) + suite.Require().Equal(origCoins.Sub(delCoins...), app.BankKeeper.GetAllBalances(ctx, addr2)) suite.Require().Equal(delCoins, app.BankKeeper.GetAllBalances(ctx, addrModule)) // require the ability for a vesting account to delegate @@ -945,7 +945,7 @@ func (suite *IntegrationTestSuite) TestUndelegateCoins() { err := app.BankKeeper.DelegateCoins(ctx, addr2, addrModule, delCoins) suite.Require().NoError(err) - suite.Require().Equal(origCoins.Sub(delCoins), app.BankKeeper.GetAllBalances(ctx, addr2)) + suite.Require().Equal(origCoins.Sub(delCoins...), app.BankKeeper.GetAllBalances(ctx, addr2)) suite.Require().Equal(delCoins, app.BankKeeper.GetAllBalances(ctx, addrModule)) // require the ability for a non-vesting account to undelegate @@ -957,7 +957,7 @@ func (suite *IntegrationTestSuite) TestUndelegateCoins() { // require the ability for a vesting account to delegate suite.Require().NoError(app.BankKeeper.DelegateCoins(ctx, addr1, addrModule, delCoins)) - suite.Require().Equal(origCoins.Sub(delCoins), app.BankKeeper.GetAllBalances(ctx, addr1)) + suite.Require().Equal(origCoins.Sub(delCoins...), app.BankKeeper.GetAllBalances(ctx, addr1)) suite.Require().Equal(delCoins, app.BankKeeper.GetAllBalances(ctx, addrModule)) // require the ability for a vesting account to undelegate @@ -1095,7 +1095,7 @@ func (suite *IntegrationTestSuite) TestBalanceTrackingEvents() { case types.EventTypeCoinBurn: burnedCoins, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) suite.Require().NoError(err) - supply = supply.Sub(burnedCoins) + supply = supply.Sub(burnedCoins...) case types.EventTypeCoinMint: mintedCoins, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) @@ -1107,7 +1107,7 @@ func (suite *IntegrationTestSuite) TestBalanceTrackingEvents() { suite.Require().NoError(err) spender, err := sdk.AccAddressFromBech32((string)(e.Attributes[0].Value)) suite.Require().NoError(err) - balances[spender.String()] = balances[spender.String()].Sub(coinsSpent) + balances[spender.String()] = balances[spender.String()].Sub(coinsSpent...) case types.EventTypeCoinReceived: coinsRecv, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) diff --git a/x/bank/keeper/send.go b/x/bank/keeper/send.go index fb68fc9c4a03..109b33bc08e9 100644 --- a/x/bank/keeper/send.go +++ b/x/bank/keeper/send.go @@ -187,7 +187,7 @@ func (k BaseSendKeeper) subUnlockedCoins(ctx sdk.Context, addr sdk.AccAddress, a locked := sdk.NewCoin(coin.Denom, lockedCoins.AmountOf(coin.Denom)) spendable := balance.Sub(locked) - _, hasNeg := sdk.Coins{spendable}.SafeSub(sdk.Coins{coin}) + _, hasNeg := sdk.Coins{spendable}.SafeSub(coin) if hasNeg { return sdkerrors.Wrapf(sdkerrors.ErrInsufficientFunds, "%s is smaller than %s", spendable, coin) } diff --git a/x/bank/keeper/view.go b/x/bank/keeper/view.go index c6feb72786dc..cf66c1962002 100644 --- a/x/bank/keeper/view.go +++ b/x/bank/keeper/view.go @@ -192,7 +192,7 @@ func (k BaseViewKeeper) spendableCoins(ctx sdk.Context, addr sdk.AccAddress) (sp total = k.GetAllBalances(ctx, addr) locked := k.LockedCoins(ctx, addr) - spendable, hasNeg := total.SafeSub(locked) + spendable, hasNeg := total.SafeSub(locked...) if hasNeg { spendable = sdk.NewCoins() return diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 05d14a7375f7..8c0c94f0e62b 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -130,7 +130,7 @@ func sendMsgSend( account := ak.GetAccount(ctx, from) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - coins, hasNeg := spendable.SafeSub(msg.Amount) + coins, hasNeg := spendable.SafeSub(msg.Amount...) if !hasNeg { fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { @@ -138,7 +138,7 @@ func sendMsgSend( } } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{msg}, fees, @@ -219,7 +219,7 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Ope // take random subset of remaining coins for output // and update remaining coins outCoins = simtypes.RandSubsetCoins(r, totalSentCoins) - totalSentCoins = totalSentCoins.Sub(outCoins) + totalSentCoins = totalSentCoins.Sub(outCoins...) } outputs[o] = types.NewOutput(outAddr.Address, outCoins) @@ -286,7 +286,7 @@ func SimulateMsgMultiSendToModuleAccount(ak types.AccountKeeper, bk keeper.Keepe // take random subset of remaining coins for output // and update remaining coins outCoins = simtypes.RandSubsetCoins(r, totalSentCoins) - totalSentCoins = totalSentCoins.Sub(outCoins) + totalSentCoins = totalSentCoins.Sub(outCoins...) } outputs[i] = types.NewOutput(moduleAccounts[i].Address, outCoins) @@ -351,7 +351,7 @@ func sendMsgMultiSend( feePayer := ak.GetAccount(ctx, addr) spendable := bk.SpendableCoins(ctx, feePayer.GetAddress()) - coins, hasNeg := spendable.SafeSub(msg.Inputs[0].Coins) + coins, hasNeg := spendable.SafeSub(msg.Inputs[0].Coins...) if !hasNeg { fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { @@ -360,7 +360,7 @@ func sendMsgMultiSend( } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{msg}, fees, diff --git a/x/bank/simulation/operations_test.go b/x/bank/simulation/operations_test.go index 77ad02ff2c76..f50c2b944885 100644 --- a/x/bank/simulation/operations_test.go +++ b/x/bank/simulation/operations_test.go @@ -1,7 +1,6 @@ package simulation_test import ( - "github.com/cosmos/cosmos-sdk/codec/legacy" "math/rand" "testing" @@ -81,7 +80,7 @@ func (suite *SimTestSuite) TestSimulateMsgSend() { suite.Require().NoError(err) var msg types.MsgSend - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().True(operationMsg.OK) suite.Require().Equal("65337742stake", msg.Amount.String()) @@ -110,7 +109,7 @@ func (suite *SimTestSuite) TestSimulateMsgMultiSend() { require.NoError(err) var msg types.MsgMultiSend - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) require.True(operationMsg.OK) require.Len(msg.Inputs, 3) @@ -147,7 +146,7 @@ func (suite *SimTestSuite) TestSimulateModuleAccountMsgSend() { suite.Require().Error(err) var msg types.MsgSend - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().False(operationMsg.OK) suite.Require().Equal(operationMsg.Comment, "invalid transfers") @@ -176,7 +175,7 @@ func (suite *SimTestSuite) TestSimulateMsgMultiSendToModuleAccount() { suite.Require().Error(err) var msg types.MsgMultiSend - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().False(operationMsg.OK) // sending tokens to a module account should fail suite.Require().Equal(operationMsg.Comment, "invalid transfers") diff --git a/x/bank/types/codec.go b/x/bank/types/codec.go index 498fb3272e0f..a4107c1cfdb6 100644 --- a/x/bank/types/codec.go +++ b/x/bank/types/codec.go @@ -4,9 +4,11 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" "github.com/cosmos/cosmos-sdk/x/authz" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" ) // RegisterLegacyAminoCodec registers the necessary x/bank interfaces and concrete types @@ -30,6 +32,17 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + func init() { - RegisterLegacyAminoCodec(legacy.Cdc) + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } diff --git a/x/bank/types/msgs.go b/x/bank/types/msgs.go index f04433a6bb14..8030e04519f3 100644 --- a/x/bank/types/msgs.go +++ b/x/bank/types/msgs.go @@ -1,7 +1,6 @@ package types import ( - "github.com/cosmos/cosmos-sdk/codec/legacy" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -49,7 +48,7 @@ func (msg MsgSend) ValidateBasic() error { // GetSignBytes Implements Msg. func (msg MsgSend) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) } // GetSigners Implements Msg. @@ -88,7 +87,7 @@ func (msg MsgMultiSend) ValidateBasic() error { // GetSignBytes Implements Msg. func (msg MsgMultiSend) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) } // GetSigners Implements Msg. diff --git a/x/bank/types/send_authorization.go b/x/bank/types/send_authorization.go index 08a7b641fe48..a8a7855948d5 100644 --- a/x/bank/types/send_authorization.go +++ b/x/bank/types/send_authorization.go @@ -28,7 +28,7 @@ func (a SendAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (authz.AcceptRes if !ok { return authz.AcceptResponse{}, sdkerrors.ErrInvalidType.Wrap("type mismatch") } - limitLeft, isNegative := a.SpendLimit.SafeSub(mSend.Amount) + limitLeft, isNegative := a.SpendLimit.SafeSub(mSend.Amount...) if isNegative { return authz.AcceptResponse{}, sdkerrors.ErrInsufficientFunds.Wrapf("requested amount is more than spend limit") } diff --git a/x/crisis/types/codec.go b/x/crisis/types/codec.go index 868ebaa919bb..324ef56891ea 100644 --- a/x/crisis/types/codec.go +++ b/x/crisis/types/codec.go @@ -4,8 +4,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" ) // RegisterLegacyAminoCodec registers the necessary x/crisis interfaces and concrete types @@ -22,6 +24,17 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + func init() { - RegisterLegacyAminoCodec(legacy.Cdc) + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } diff --git a/x/crisis/types/msgs.go b/x/crisis/types/msgs.go index bd9c60e936d9..a5450b010e7f 100644 --- a/x/crisis/types/msgs.go +++ b/x/crisis/types/msgs.go @@ -1,7 +1,6 @@ package types import ( - "github.com/cosmos/cosmos-sdk/codec/legacy" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -30,7 +29,7 @@ func (msg MsgVerifyInvariant) GetSigners() []sdk.AccAddress { // GetSignBytes gets the sign bytes for the msg MsgVerifyInvariant func (msg MsgVerifyInvariant) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index f82e921290b4..9c1976cc2e28 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -222,7 +222,7 @@ func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k err error ) - coins, hasNeg := spendable.SafeSub(fundAmount) + coins, hasNeg := spendable.SafeSub(fundAmount...) if !hasNeg { fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { diff --git a/x/distribution/simulation/operations_test.go b/x/distribution/simulation/operations_test.go index bc902a0f1f6b..4d70aab2eacf 100644 --- a/x/distribution/simulation/operations_test.go +++ b/x/distribution/simulation/operations_test.go @@ -1,7 +1,6 @@ package simulation_test import ( - "github.com/cosmos/cosmos-sdk/codec/legacy" "math/rand" "testing" @@ -74,7 +73,7 @@ func (suite *SimTestSuite) TestSimulateMsgSetWithdrawAddress() { suite.Require().NoError(err) var msg types.MsgSetWithdrawAddress - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().True(operationMsg.OK) suite.Require().Equal("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", msg.DelegatorAddress) @@ -115,7 +114,7 @@ func (suite *SimTestSuite) TestSimulateMsgWithdrawDelegatorReward() { suite.Require().NoError(err) var msg types.MsgWithdrawDelegatorReward - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().True(operationMsg.OK) suite.Require().Equal("cosmosvaloper1l4s054098kk9hmr5753c6k3m2kw65h686d3mhr", msg.ValidatorAddress) @@ -176,7 +175,7 @@ func (suite *SimTestSuite) testSimulateMsgWithdrawValidatorCommission(tokenName suite.Require().NoError(err) var msg types.MsgWithdrawValidatorCommission - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().True(operationMsg.OK) suite.Require().Equal("cosmosvaloper1tnh2q55v8wyygtt9srz5safamzdengsn9dsd7z", msg.ValidatorAddress) @@ -203,7 +202,7 @@ func (suite *SimTestSuite) TestSimulateMsgFundCommunityPool() { suite.Require().NoError(err) var msg types.MsgFundCommunityPool - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().True(operationMsg.OK) suite.Require().Equal("4896096stake", msg.Amount.String()) diff --git a/x/distribution/types/codec.go b/x/distribution/types/codec.go index 6fe51998e4d3..0bff07d87340 100644 --- a/x/distribution/types/codec.go +++ b/x/distribution/types/codec.go @@ -4,8 +4,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) @@ -35,6 +37,17 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + func init() { - RegisterLegacyAminoCodec(legacy.Cdc) + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } diff --git a/x/distribution/types/msg.go b/x/distribution/types/msg.go index 5f7b9b371075..2071ca0282e8 100644 --- a/x/distribution/types/msg.go +++ b/x/distribution/types/msg.go @@ -1,7 +1,6 @@ package types import ( - "github.com/cosmos/cosmos-sdk/codec/legacy" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -35,7 +34,7 @@ func (msg MsgSetWithdrawAddress) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgSetWithdrawAddress) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -69,7 +68,7 @@ func (msg MsgWithdrawDelegatorReward) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgWithdrawDelegatorReward) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -101,7 +100,7 @@ func (msg MsgWithdrawValidatorCommission) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgWithdrawValidatorCommission) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -138,7 +137,7 @@ func (msg MsgFundCommunityPool) GetSigners() []sdk.AccAddress { // GetSignBytes returns the raw bytes for a MsgFundCommunityPool message that // the expected signer needs to sign. func (msg MsgFundCommunityPool) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } diff --git a/x/evidence/types/codec.go b/x/evidence/types/codec.go index 559a119f81db..19dcd12cbee9 100644 --- a/x/evidence/types/codec.go +++ b/x/evidence/types/codec.go @@ -4,8 +4,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" "github.com/cosmos/cosmos-sdk/x/evidence/exported" ) @@ -28,6 +30,17 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + func init() { - RegisterLegacyAminoCodec(legacy.Cdc) + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } diff --git a/x/evidence/types/msgs.go b/x/evidence/types/msgs.go index 6227040fd4e9..94a7546167ee 100644 --- a/x/evidence/types/msgs.go +++ b/x/evidence/types/msgs.go @@ -2,8 +2,6 @@ package types import ( "fmt" - "github.com/cosmos/cosmos-sdk/codec/legacy" - "github.com/gogo/protobuf/proto" "github.com/cosmos/cosmos-sdk/codec/types" @@ -63,7 +61,7 @@ func (m MsgSubmitEvidence) ValidateBasic() error { // GetSignBytes returns the raw bytes a signer is expected to sign when submitting // a MsgSubmitEvidence message. func (m MsgSubmitEvidence) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the single expected signer for a MsgSubmitEvidence. diff --git a/x/feegrant/basic_fee.go b/x/feegrant/basic_fee.go index 703b509b3a68..81419b6d5764 100644 --- a/x/feegrant/basic_fee.go +++ b/x/feegrant/basic_fee.go @@ -25,7 +25,7 @@ func (a *BasicAllowance) Accept(ctx sdk.Context, fee sdk.Coins, _ []sdk.Msg) (bo } if a.SpendLimit != nil { - left, invalid := a.SpendLimit.SafeSub(fee) + left, invalid := a.SpendLimit.SafeSub(fee...) if invalid { return false, sdkerrors.Wrap(ErrFeeLimitExceeded, "basic allowance") } diff --git a/x/feegrant/codec.go b/x/feegrant/codec.go index 238c5f05f7ea..0fd6eaeb9e7f 100644 --- a/x/feegrant/codec.go +++ b/x/feegrant/codec.go @@ -4,8 +4,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" ) // RegisterLegacyAminoCodec registers the necessary x/feegrant interfaces and concrete types @@ -52,8 +54,10 @@ var ( func init() { RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) - // Register all Amino interfaces and concrete types on the global Amino codec so that this can later be - // used to properly serialize x/authz MsgExec instances - RegisterLegacyAminoCodec(legacy.Cdc) + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } diff --git a/x/feegrant/periodic_fee.go b/x/feegrant/periodic_fee.go index 43229247ff0c..0e496ce5a93b 100644 --- a/x/feegrant/periodic_fee.go +++ b/x/feegrant/periodic_fee.go @@ -30,13 +30,13 @@ func (a *PeriodicAllowance) Accept(ctx sdk.Context, fee sdk.Coins, _ []sdk.Msg) // deduct from both the current period and the max amount var isNeg bool - a.PeriodCanSpend, isNeg = a.PeriodCanSpend.SafeSub(fee) + a.PeriodCanSpend, isNeg = a.PeriodCanSpend.SafeSub(fee...) if isNeg { return false, sdkerrors.Wrap(ErrFeeLimitExceeded, "period limit") } if a.Basic.SpendLimit != nil { - a.Basic.SpendLimit, isNeg = a.Basic.SpendLimit.SafeSub(fee) + a.Basic.SpendLimit, isNeg = a.Basic.SpendLimit.SafeSub(fee...) if isNeg { return false, sdkerrors.Wrap(ErrFeeLimitExceeded, "absolute limit") } @@ -59,7 +59,7 @@ func (a *PeriodicAllowance) tryResetPeriod(blockTime time.Time) { } // set PeriodCanSpend to the lesser of Basic.SpendLimit and PeriodSpendLimit - if _, isNeg := a.Basic.SpendLimit.SafeSub(a.PeriodSpendLimit); isNeg && !a.Basic.SpendLimit.Empty() { + if _, isNeg := a.Basic.SpendLimit.SafeSub(a.PeriodSpendLimit...); isNeg && !a.Basic.SpendLimit.Empty() { a.PeriodCanSpend = a.Basic.SpendLimit } else { a.PeriodCanSpend = a.PeriodSpendLimit diff --git a/x/feegrant/periodic_fee_test.go b/x/feegrant/periodic_fee_test.go index b6a8d39bd9dc..439ef19a0195 100644 --- a/x/feegrant/periodic_fee_test.go +++ b/x/feegrant/periodic_fee_test.go @@ -131,8 +131,8 @@ func TestPeriodicFeeValidAllow(t *testing.T) { blockTime: oneHour, accept: true, remove: false, - remainsPeriod: smallAtom.Sub(oneAtom), - remains: smallAtom.Sub(oneAtom), + remainsPeriod: smallAtom.Sub(oneAtom...), + remains: smallAtom.Sub(oneAtom...), periodReset: oneHour.Add(tenMinutes), // one step from last reset, not now }, "period reset no spend limit": { diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 00ff11ab6f98..9f01d3445b4f 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -167,6 +167,10 @@ $ %s gentx my-key-name 1000000stake --home=/path/to/home/dir --keyring-backend=o w := bytes.NewBuffer([]byte{}) clientCtx = clientCtx.WithOutput(w) + if err = msg.ValidateBasic(); err != nil { + return err + } + if err = txBldr.PrintUnsignedTx(clientCtx, msg); err != nil { return errors.Wrap(err, "failed to print unsigned std tx") } diff --git a/x/genutil/client/testutil/suite.go b/x/genutil/client/testutil/suite.go index f025160da6c7..755d20154eb3 100644 --- a/x/genutil/client/testutil/suite.go +++ b/x/genutil/client/testutil/suite.go @@ -1,7 +1,6 @@ package testutil import ( - "context" "fmt" "io" "os" @@ -9,10 +8,9 @@ import ( "github.com/stretchr/testify/suite" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/testutil" + clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/testutil/network" sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -50,84 +48,97 @@ func (s *IntegrationTestSuite) TearDownSuite() { func (s *IntegrationTestSuite) TestGenTxCmd() { val := s.network.Validators[0] - dir := s.T().TempDir() - - cmd := cli.GenTxCmd( - simapp.ModuleBasics, - val.ClientCtx.TxConfig, banktypes.GenesisBalancesIterator{}, val.ClientCtx.HomeDir) - - _, out := testutil.ApplyMockIO(cmd) - clientCtx := val.ClientCtx.WithOutput(out) - - ctx := context.Background() - ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - + clientCtx := val.ClientCtx amount := sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(12)) - genTxFile := filepath.Join(dir, "myTx") - cmd.SetArgs([]string{ - fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), - fmt.Sprintf("--%s=%s", flags.FlagOutputDocument, genTxFile), - val.Moniker, - amount.String(), - }) - - err := cmd.ExecuteContext(ctx) - s.Require().NoError(err) - - // validate generated transaction. - open, err := os.Open(genTxFile) - s.Require().NoError(err) - - all, err := io.ReadAll(open) - s.Require().NoError(err) - - tx, err := val.ClientCtx.TxConfig.TxJSONDecoder()(all) - s.Require().NoError(err) - - msgs := tx.GetMsgs() - s.Require().Len(msgs, 1) - - s.Require().Equal(sdk.MsgTypeURL(&types.MsgCreateValidator{}), sdk.MsgTypeURL(msgs[0])) - s.Require().True(val.Address.Equals(msgs[0].GetSigners()[0])) - s.Require().Equal(amount, msgs[0].(*types.MsgCreateValidator).Value) - s.Require().NoError(tx.ValidateBasic()) -} - -func (s *IntegrationTestSuite) TestGenTxCmdPubkey() { - val := s.network.Validators[0] - dir := s.T().TempDir() - - cmd := cli.GenTxCmd( - simapp.ModuleBasics, - val.ClientCtx.TxConfig, - banktypes.GenesisBalancesIterator{}, - val.ClientCtx.HomeDir, - ) - - _, out := testutil.ApplyMockIO(cmd) - clientCtx := val.ClientCtx.WithOutput(out) - ctx := context.Background() - ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - - amount := sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(12)) - genTxFile := filepath.Join(dir, "myTx") - - cmd.SetArgs([]string{ - fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), - fmt.Sprintf("--%s=%s", flags.FlagOutputDocument, genTxFile), - fmt.Sprintf("--%s={\"key\":\"BOIkjkFruMpfOFC9oNPhiJGfmY2pHF/gwHdLDLnrnS0=\"}", stakingcli.FlagPubKey), - val.Moniker, - amount.String(), - }) - s.Require().Error(cmd.ExecuteContext(ctx)) - - cmd.SetArgs([]string{ - fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), - fmt.Sprintf("--%s=%s", flags.FlagOutputDocument, genTxFile), - fmt.Sprintf("--%s={\"@type\":\"/cosmos.crypto.ed25519.PubKey\",\"key\":\"BOIkjkFruMpfOFC9oNPhiJGfmY2pHF/gwHdLDLnrnS0=\"}", stakingcli.FlagPubKey), - val.Moniker, - amount.String(), - }) - s.Require().NoError(cmd.ExecuteContext(ctx)) + tests := []struct { + name string + args []string + expError bool + }{ + { + name: "invalid commission rate returns error", + args: []string{ + fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), + fmt.Sprintf("--%s=1", stakingcli.FlagCommissionRate), + val.Moniker, + amount.String(), + }, + expError: true, + }, + { + name: "valid gentx", + args: []string{ + fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), + val.Moniker, + amount.String(), + }, + expError: false, + }, + { + name: "invalid pubkey", + args: []string{ + fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), + fmt.Sprintf("--%s={\"key\":\"BOIkjkFruMpfOFC9oNPhiJGfmY2pHF/gwHdLDLnrnS0=\"}", stakingcli.FlagPubKey), + val.Moniker, + amount.String(), + }, + expError: true, + }, + { + name: "valid pubkey flag", + args: []string{ + fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), + fmt.Sprintf("--%s={\"@type\":\"/cosmos.crypto.ed25519.PubKey\",\"key\":\"BOIkjkFruMpfOFC9oNPhiJGfmY2pHF/gwHdLDLnrnS0=\"}", stakingcli.FlagPubKey), + val.Moniker, + amount.String(), + }, + expError: false, + }, + } + + for _, tc := range tests { + tc := tc + + dir := s.T().TempDir() + genTxFile := filepath.Join(dir, "myTx") + tc.args = append(tc.args, fmt.Sprintf("--%s=%s", flags.FlagOutputDocument, genTxFile)) + + s.Run(tc.name, func() { + cmd := cli.GenTxCmd( + simapp.ModuleBasics, + val.ClientCtx.TxConfig, + banktypes.GenesisBalancesIterator{}, + val.ClientCtx.HomeDir) + + out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) + + if tc.expError { + s.Require().Error(err) + + _, err = os.Open(genTxFile) + s.Require().Error(err) + } else { + s.Require().NoError(err, "test: %s\noutput: %s", tc.name, out.String()) + + // validate generated transaction. + open, err := os.Open(genTxFile) + s.Require().NoError(err) + + all, err := io.ReadAll(open) + s.Require().NoError(err) + + tx, err := val.ClientCtx.TxConfig.TxJSONDecoder()(all) + s.Require().NoError(err) + + msgs := tx.GetMsgs() + s.Require().Len(msgs, 1) + + s.Require().Equal(sdk.MsgTypeURL(&types.MsgCreateValidator{}), sdk.MsgTypeURL(msgs[0])) + s.Require().True(val.Address.Equals(msgs[0].GetSigners()[0])) + s.Require().Equal(amount, msgs[0].(*types.MsgCreateValidator).Value) + s.Require().NoError(tx.ValidateBasic()) + } + }) + } } diff --git a/x/genutil/gentx_test.go b/x/genutil/gentx_test.go index b08ecb9750f2..510c04d8d1e4 100644 --- a/x/genutil/gentx_test.go +++ b/x/genutil/gentx_test.go @@ -65,7 +65,7 @@ func (suite *GenTxTestSuite) setAccountBalance(addr sdk.AccAddress, amount int64 acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr) suite.app.AccountKeeper.SetAccount(suite.ctx, acc) - err := testutil.FundAccount(suite.app.BankKeeper, suite.ctx, addr, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 25)}) + err := testutil.FundAccount(suite.app.BankKeeper, suite.ctx, addr, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, amount)}) suite.Require().NoError(err) bankGenesisState := suite.app.BankKeeper.ExportGenesis(suite.ctx) @@ -231,10 +231,10 @@ func (suite *GenTxTestSuite) TestDeliverGenTxs() { "success", func() { _ = suite.setAccountBalance(addr1, 50) - _ = suite.setAccountBalance(addr2, 0) + _ = suite.setAccountBalance(addr2, 1) msg := banktypes.NewMsgSend(addr1, addr2, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1)}) - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( suite.encodingConfig.TxConfig, []sdk.Msg{msg}, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 10)}, diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go index 9183f16deb55..8d0a1986aae0 100644 --- a/x/gov/keeper/deposit_test.go +++ b/x/gov/keeper/deposit_test.go @@ -47,7 +47,7 @@ func TestDeposits(t *testing.T) { proposal, ok = app.GovKeeper.GetProposal(ctx, proposalID) require.True(t, ok) require.Equal(t, fourStake, sdk.NewCoins(proposal.TotalDeposit...)) - require.Equal(t, addr0Initial.Sub(fourStake), app.BankKeeper.GetAllBalances(ctx, TestAddrs[0])) + require.Equal(t, addr0Initial.Sub(fourStake...), app.BankKeeper.GetAllBalances(ctx, TestAddrs[0])) // Check a second deposit from same address votingStarted, err = app.GovKeeper.AddDeposit(ctx, proposalID, TestAddrs[0], fiveStake) @@ -60,7 +60,7 @@ func TestDeposits(t *testing.T) { proposal, ok = app.GovKeeper.GetProposal(ctx, proposalID) require.True(t, ok) require.Equal(t, fourStake.Add(fiveStake...), sdk.NewCoins(proposal.TotalDeposit...)) - require.Equal(t, addr0Initial.Sub(fourStake).Sub(fiveStake), app.BankKeeper.GetAllBalances(ctx, TestAddrs[0])) + require.Equal(t, addr0Initial.Sub(fourStake...).Sub(fiveStake...), app.BankKeeper.GetAllBalances(ctx, TestAddrs[0])) // Check third deposit from a new address votingStarted, err = app.GovKeeper.AddDeposit(ctx, proposalID, TestAddrs[1], fourStake) @@ -73,7 +73,7 @@ func TestDeposits(t *testing.T) { proposal, ok = app.GovKeeper.GetProposal(ctx, proposalID) require.True(t, ok) require.Equal(t, fourStake.Add(fiveStake...).Add(fourStake...), sdk.NewCoins(proposal.TotalDeposit...)) - require.Equal(t, addr1Initial.Sub(fourStake), app.BankKeeper.GetAllBalances(ctx, TestAddrs[1])) + require.Equal(t, addr1Initial.Sub(fourStake...), app.BankKeeper.GetAllBalances(ctx, TestAddrs[1])) // Check that proposal moved to voting period proposal, ok = app.GovKeeper.GetProposal(ctx, proposalID) @@ -109,5 +109,5 @@ func TestDeposits(t *testing.T) { app.GovKeeper.DeleteAndBurnDeposits(ctx, proposalID) deposits = app.GovKeeper.GetDeposits(ctx, proposalID) require.Len(t, deposits, 0) - require.Equal(t, addr0Initial.Sub(fourStake), app.BankKeeper.GetAllBalances(ctx, TestAddrs[0])) + require.Equal(t, addr0Initial.Sub(fourStake...), app.BankKeeper.GetAllBalances(ctx, TestAddrs[0])) } diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index e619dfabc96e..5963a2d2e6b7 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -161,7 +161,7 @@ func SimulateMsgSubmitProposal( spendable := bk.SpendableCoins(ctx, account.GetAddress()) var fees sdk.Coins - coins, hasNeg := spendable.SafeSub(deposit) + coins, hasNeg := spendable.SafeSub(deposit...) if !hasNeg { fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { @@ -170,7 +170,7 @@ func SimulateMsgSubmitProposal( } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{msg}, fees, @@ -248,7 +248,7 @@ func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Ke spendable := bk.SpendableCoins(ctx, account.GetAddress()) var fees sdk.Coins - coins, hasNeg := spendable.SafeSub(deposit) + coins, hasNeg := spendable.SafeSub(deposit...) if !hasNeg { fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { diff --git a/x/gov/simulation/operations_test.go b/x/gov/simulation/operations_test.go index 1d0ac256b49d..3ef0acb9bd49 100644 --- a/x/gov/simulation/operations_test.go +++ b/x/gov/simulation/operations_test.go @@ -10,7 +10,6 @@ import ( abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/simapp" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" @@ -117,7 +116,7 @@ func TestSimulateMsgSubmitProposal(t *testing.T) { require.NoError(t, err) var msg v1.MsgSubmitProposal - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = v1.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) require.NoError(t, err) require.True(t, operationMsg.OK) @@ -164,7 +163,7 @@ func TestSimulateMsgDeposit(t *testing.T) { require.NoError(t, err) var msg v1.MsgDeposit - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = v1.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) require.NoError(t, err) require.True(t, operationMsg.OK) @@ -210,7 +209,7 @@ func TestSimulateMsgVote(t *testing.T) { require.NoError(t, err) var msg v1.MsgVote - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + v1.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) require.True(t, operationMsg.OK) require.Equal(t, uint64(1), msg.ProposalId) @@ -253,7 +252,7 @@ func TestSimulateMsgVoteWeighted(t *testing.T) { require.NoError(t, err) var msg v1.MsgVoteWeighted - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + v1.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) require.True(t, operationMsg.OK) require.Equal(t, uint64(1), msg.ProposalId) diff --git a/x/gov/types/v1/codec.go b/x/gov/types/v1/codec.go index 3f113e3b0095..327094960d7b 100644 --- a/x/gov/types/v1/codec.go +++ b/x/gov/types/v1/codec.go @@ -4,8 +4,11 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" + "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) // RegisterLegacyAminoCodec registers all the necessary types and interfaces for the @@ -30,6 +33,18 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + func init() { - RegisterLegacyAminoCodec(legacy.Cdc) + RegisterLegacyAminoCodec(amino) + v1beta1.RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } diff --git a/x/gov/types/v1/msgs.go b/x/gov/types/v1/msgs.go index 6404d824ffba..1391cbf4c673 100644 --- a/x/gov/types/v1/msgs.go +++ b/x/gov/types/v1/msgs.go @@ -3,7 +3,6 @@ package v1 import ( "fmt" - "github.com/cosmos/cosmos-sdk/codec/legacy" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -83,7 +82,7 @@ func (m MsgSubmitProposal) ValidateBasic() error { // GetSignBytes implements Msg func (m MsgSubmitProposal) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&m) + bz := ModuleCdc.MustMarshalJSON(&m) return sdk.MustSortJSON(bz) } @@ -128,7 +127,7 @@ func (msg MsgDeposit) ValidateBasic() error { // GetSignBytes implements Msg func (msg MsgDeposit) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -164,7 +163,7 @@ func (msg MsgVote) ValidateBasic() error { // GetSignBytes implements Msg func (msg MsgVote) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -225,7 +224,7 @@ func (msg MsgVoteWeighted) ValidateBasic() error { // GetSignBytes implements Msg func (msg MsgVoteWeighted) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } diff --git a/x/gov/types/v1beta1/codec.go b/x/gov/types/v1beta1/codec.go index 583ab48963a8..f73f1082c5cd 100644 --- a/x/gov/types/v1beta1/codec.go +++ b/x/gov/types/v1beta1/codec.go @@ -4,8 +4,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" ) // RegisterLegacyAminoCodec registers all the necessary types and interfaces for the @@ -35,6 +37,17 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + func init() { - RegisterLegacyAminoCodec(legacy.Cdc) + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } diff --git a/x/gov/types/v1beta1/msgs.go b/x/gov/types/v1beta1/msgs.go index 3fc309577b3c..cd5d886aed9c 100644 --- a/x/gov/types/v1beta1/msgs.go +++ b/x/gov/types/v1beta1/msgs.go @@ -2,8 +2,6 @@ package v1beta1 import ( "fmt" - "github.com/cosmos/cosmos-sdk/codec/legacy" - "github.com/gogo/protobuf/proto" "sigs.k8s.io/yaml" @@ -110,7 +108,7 @@ func (m MsgSubmitProposal) ValidateBasic() error { // GetSignBytes implements Msg func (m MsgSubmitProposal) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&m) + bz := ModuleCdc.MustMarshalJSON(&m) return sdk.MustSortJSON(bz) } @@ -167,7 +165,7 @@ func (msg MsgDeposit) String() string { // GetSignBytes implements Msg func (msg MsgDeposit) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -209,7 +207,7 @@ func (msg MsgVote) String() string { // GetSignBytes implements Msg func (msg MsgVote) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -272,7 +270,7 @@ func (msg MsgVoteWeighted) String() string { // GetSignBytes implements Msg func (msg MsgVoteWeighted) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } diff --git a/x/group/codec.go b/x/group/codec.go index 8e89e4ea0b30..32e1ec15c7cb 100644 --- a/x/group/codec.go +++ b/x/group/codec.go @@ -4,8 +4,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" ) // RegisterLegacyAminoCodec registers all the necessary group module concrete @@ -60,6 +62,17 @@ func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { ) } +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + func init() { - RegisterLegacyAminoCodec(legacy.Cdc) + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } diff --git a/x/group/msgs.go b/x/group/msgs.go index 0042ed4a4761..93c7793ffa1a 100644 --- a/x/group/msgs.go +++ b/x/group/msgs.go @@ -1,8 +1,6 @@ package group import ( - "github.com/cosmos/cosmos-sdk/codec/legacy" - proto "github.com/gogo/protobuf/proto" "github.com/cosmos/cosmos-sdk/codec/types" @@ -23,7 +21,7 @@ func (m MsgCreateGroup) Type() string { return sdk.MsgTypeURL(&m) } // GetSignBytes Implements Msg. func (m MsgCreateGroup) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the expected signers for a MsgCreateGroup. @@ -75,7 +73,7 @@ func (m MsgUpdateGroupAdmin) Type() string { return sdk.MsgTypeURL(&m) } // GetSignBytes Implements Msg. func (m MsgUpdateGroupAdmin) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the expected signers for a MsgUpdateGroupAdmin. @@ -125,7 +123,7 @@ func (m MsgUpdateGroupMetadata) Type() string { return sdk.MsgTypeURL(&m) } // GetSignBytes Implements Msg. func (m MsgUpdateGroupMetadata) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the expected signers for a MsgUpdateGroupMetadata. @@ -167,7 +165,7 @@ func (m MsgUpdateGroupMembers) Type() string { return sdk.MsgTypeURL(&m) } // GetSignBytes Implements Msg. func (m MsgUpdateGroupMembers) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } var _ sdk.Msg = &MsgUpdateGroupMembers{} @@ -260,7 +258,7 @@ func (m MsgCreateGroupWithPolicy) Type() string { // GetSignBytes Implements Msg. func (m MsgCreateGroupWithPolicy) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the expected signers for a MsgCreateGroupWithPolicy. @@ -301,7 +299,7 @@ func (m MsgCreateGroupPolicy) Type() string { return sdk.MsgTypeURL(&m) } // GetSignBytes Implements Msg. func (m MsgCreateGroupPolicy) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the expected signers for a MsgCreateGroupPolicy. @@ -346,7 +344,7 @@ func (m MsgUpdateGroupPolicyAdmin) Type() string { return sdk.MsgTypeURL(&m) } // GetSignBytes Implements Msg. func (m MsgUpdateGroupPolicyAdmin) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the expected signers for a MsgUpdateGroupPolicyAdmin. @@ -422,7 +420,7 @@ func (m MsgUpdateGroupPolicyDecisionPolicy) Type() string { // GetSignBytes Implements Msg. func (m MsgUpdateGroupPolicyDecisionPolicy) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the expected signers for a MsgUpdateGroupPolicyDecisionPolicy. @@ -485,7 +483,7 @@ func (m MsgUpdateGroupPolicyMetadata) Type() string { return sdk.MsgTypeURL(&m) // GetSignBytes Implements Msg. func (m MsgUpdateGroupPolicyMetadata) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the expected signers for a MsgUpdateGroupPolicyMetadata. @@ -591,7 +589,7 @@ func (m MsgSubmitProposal) Type() string { return sdk.MsgTypeURL(&m) } // GetSignBytes Implements Msg. func (m MsgSubmitProposal) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the expected signers for a MsgSubmitProposal. @@ -683,7 +681,7 @@ func (m MsgWithdrawProposal) Type() string { return sdk.MsgTypeURL(&m) } // GetSignBytes Implements Msg. func (m MsgWithdrawProposal) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the expected signers for a MsgWithdrawProposal. @@ -721,7 +719,7 @@ func (m MsgVote) Type() string { return sdk.MsgTypeURL(&m) } // GetSignBytes Implements Msg. func (m MsgVote) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the expected signers for a MsgVote. @@ -763,7 +761,7 @@ func (m MsgExec) Type() string { return sdk.MsgTypeURL(&m) } // GetSignBytes Implements Msg. func (m MsgExec) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the expected signers for a MsgExec. @@ -799,7 +797,7 @@ func (m MsgLeaveGroup) Type() string { return sdk.MsgTypeURL(&m) } // GetSignBytes Implements Msg func (m MsgLeaveGroup) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the expected signers for a MsgLeaveGroup diff --git a/x/group/simulation/operations.go b/x/group/simulation/operations.go index 98e04352bc2f..a81bf4925fb4 100644 --- a/x/group/simulation/operations.go +++ b/x/group/simulation/operations.go @@ -258,7 +258,7 @@ func SimulateMsgCreateGroup(ak group.AccountKeeper, bk group.BankKeeper) simtype msg := &group.MsgCreateGroup{Admin: accAddr, Members: members, Metadata: simtypes.RandStringOfLength(r, 10)} txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{msg}, fees, @@ -316,7 +316,7 @@ func SimulateMsgCreateGroupWithPolicy(ak group.AccountKeeper, bk group.BankKeepe } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{msg}, fees, @@ -374,7 +374,7 @@ func SimulateMsgCreateGroupPolicy(ak group.AccountKeeper, bk group.BankKeeper, k } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{msg}, fees, @@ -448,7 +448,7 @@ func SimulateMsgSubmitProposal(ak group.AccountKeeper, bk group.BankKeeper, k ke } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{&msg}, fees, @@ -506,7 +506,7 @@ func SimulateMsgUpdateGroupAdmin(ak group.AccountKeeper, bk group.BankKeeper, k } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{&msg}, fees, @@ -555,7 +555,7 @@ func SimulateMsgUpdateGroupMetadata(ak group.AccountKeeper, bk group.BankKeeper, } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{&msg}, fees, @@ -632,7 +632,7 @@ func SimulateMsgUpdateGroupMembers(ak group.AccountKeeper, } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{&msg}, fees, @@ -690,7 +690,7 @@ func SimulateMsgUpdateGroupPolicyAdmin(ak group.AccountKeeper, bk group.BankKeep } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{&msg}, fees, @@ -749,7 +749,7 @@ func SimulateMsgUpdateGroupPolicyDecisionPolicy(ak group.AccountKeeper, } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{msg}, fees, @@ -798,7 +798,7 @@ func SimulateMsgUpdateGroupPolicyMetadata(ak group.AccountKeeper, } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{&msg}, fees, @@ -898,7 +898,7 @@ func SimulateMsgWithdrawProposal(ak group.AccountKeeper, } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{&msg}, fees, @@ -1002,7 +1002,7 @@ func SimulateMsgVote(ak group.AccountKeeper, Metadata: simtypes.RandStringOfLength(r, 10), } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{&msg}, fees, @@ -1078,7 +1078,7 @@ func SimulateMsgExec(ak group.AccountKeeper, Executor: acc.Address.String(), } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{&msg}, fees, @@ -1140,7 +1140,7 @@ func SimulateMsgLeaveGroup(k keeper.Keeper, ak group.AccountKeeper, bk group.Ban } txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{msg}, fees, diff --git a/x/group/simulation/operations_test.go b/x/group/simulation/operations_test.go index 8631bb76836c..29e985809ffd 100644 --- a/x/group/simulation/operations_test.go +++ b/x/group/simulation/operations_test.go @@ -5,8 +5,6 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/codec/legacy" - "github.com/stretchr/testify/suite" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -117,7 +115,7 @@ func (suite *SimTestSuite) TestSimulateCreateGroup() { suite.Require().NoError(err) var msg group.MsgCreateGroup - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(acc.Address.String(), msg.Admin) @@ -146,7 +144,7 @@ func (suite *SimTestSuite) TestSimulateCreateGroupWithPolicy() { suite.Require().NoError(err) var msg group.MsgCreateGroupWithPolicy - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(acc.Address.String(), msg.Admin) @@ -188,7 +186,7 @@ func (suite *SimTestSuite) TestSimulateCreateGroupPolicy() { suite.Require().NoError(err) var msg group.MsgCreateGroupPolicy - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(acc.Address.String(), msg.Admin) @@ -241,7 +239,7 @@ func (suite *SimTestSuite) TestSimulateSubmitProposal() { suite.Require().NoError(err) var msg group.MsgSubmitProposal - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(groupPolicyRes.Address, msg.GroupPolicyAddress) @@ -307,7 +305,7 @@ func (suite *SimTestSuite) TestWithdrawProposal() { suite.Require().NoError(err) var msg group.MsgWithdrawProposal - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(addr, msg.Address) @@ -374,7 +372,7 @@ func (suite *SimTestSuite) TestSimulateVote() { suite.Require().NoError(err) var msg group.MsgVote - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(addr, msg.Voter) @@ -449,7 +447,7 @@ func (suite *SimTestSuite) TestSimulateExec() { suite.Require().NoError(err) var msg group.MsgExec - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(addr, msg.Executor) @@ -491,7 +489,7 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupAdmin() { suite.Require().NoError(err) var msg group.MsgUpdateGroupAdmin - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(acc.Address.String(), msg.Admin) @@ -533,7 +531,7 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupMetadata() { suite.Require().NoError(err) var msg group.MsgUpdateGroupMetadata - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(acc.Address.String(), msg.Admin) @@ -575,7 +573,7 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupMembers() { suite.Require().NoError(err) var msg group.MsgUpdateGroupMembers - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(acc.Address.String(), msg.Admin) @@ -628,7 +626,7 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupPolicyAdmin() { suite.Require().NoError(err) var msg group.MsgUpdateGroupPolicyAdmin - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(groupPolicyRes.Address, msg.GroupPolicyAddress) @@ -681,7 +679,7 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupPolicyDecisionPolicy() { suite.Require().NoError(err) var msg group.MsgUpdateGroupPolicyDecisionPolicy - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(groupPolicyRes.Address, msg.GroupPolicyAddress) @@ -734,7 +732,7 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupPolicyMetadata() { suite.Require().NoError(err) var msg group.MsgUpdateGroupPolicyMetadata - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(groupPolicyRes.Address, msg.GroupPolicyAddress) @@ -800,7 +798,7 @@ func (suite *SimTestSuite) TestSimulateLeaveGroup() { suite.Require().NoError(err) var msg group.MsgLeaveGroup - err = legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = group.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(groupRes.GroupId, msg.GroupId) diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index d430c3c12e78..975fa57133ea 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -81,7 +81,7 @@ func SimulateMsgSend( return simtypes.NoOpMsg(nft.ModuleName, TypeMsgSend, err.Error()), nil, err } - spendLimit := spendableCoins.Sub(fees) + spendLimit := spendableCoins.Sub(fees...) if spendLimit == nil { return simtypes.NoOpMsg(nft.ModuleName, TypeMsgSend, "spend limit is nil"), nil, nil } @@ -99,7 +99,7 @@ func SimulateMsgSend( } txCfg := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txCfg, []sdk.Msg{msg}, fees, diff --git a/x/simulation/util.go b/x/simulation/util.go index 498c056ebdab..4b752609f093 100644 --- a/x/simulation/util.go +++ b/x/simulation/util.go @@ -85,7 +85,7 @@ func GenAndDeliverTxWithRandFees(txCtx OperationInput) (simtypes.OperationMsg, [ var fees sdk.Coins var err error - coins, hasNeg := spendable.SafeSub(txCtx.CoinsSpentInMsg) + coins, hasNeg := spendable.SafeSub(txCtx.CoinsSpentInMsg...) if hasNeg { return simtypes.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "message doesn't leave room for fees"), nil, err } @@ -100,7 +100,7 @@ func GenAndDeliverTxWithRandFees(txCtx OperationInput) (simtypes.OperationMsg, [ // GenAndDeliverTx generates a transactions and delivers it. func GenAndDeliverTx(txCtx OperationInput, fees sdk.Coins) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { account := txCtx.AccountKeeper.GetAccount(txCtx.Context, txCtx.SimAccount.Address) - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txCtx.TxGen, []sdk.Msg{txCtx.Msg}, fees, diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index a4c82e0f4af4..e2f3efd02848 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -89,7 +89,7 @@ func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Kee msg := types.NewMsgUnjail(validator.GetOperator()) txGen := simappparams.MakeTestEncodingConfig().TxConfig - tx, err := helpers.GenTx( + tx, err := helpers.GenSignedMockTx( txGen, []sdk.Msg{msg}, fees, diff --git a/x/slashing/simulation/operations_test.go b/x/slashing/simulation/operations_test.go index 25b1473e4b1b..a0dbffb1f360 100644 --- a/x/slashing/simulation/operations_test.go +++ b/x/slashing/simulation/operations_test.go @@ -1,7 +1,6 @@ package simulation_test import ( - "github.com/cosmos/cosmos-sdk/codec/legacy" "math/rand" "testing" "time" @@ -100,7 +99,7 @@ func TestSimulateMsgUnjail(t *testing.T) { require.NoError(t, err) var msg types.MsgUnjail - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) require.True(t, operationMsg.OK) require.Equal(t, types.TypeMsgUnjail, msg.Type()) diff --git a/x/slashing/types/codec.go b/x/slashing/types/codec.go index ec1b44ec559d..d1b54a969ee1 100644 --- a/x/slashing/types/codec.go +++ b/x/slashing/types/codec.go @@ -4,8 +4,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" ) // RegisterLegacyAminoCodec registers concrete types on LegacyAmino codec @@ -21,6 +23,17 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + func init() { - RegisterLegacyAminoCodec(legacy.Cdc) + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } diff --git a/x/slashing/types/msg.go b/x/slashing/types/msg.go index 374f0c3dd32c..91a15f72dbd4 100644 --- a/x/slashing/types/msg.go +++ b/x/slashing/types/msg.go @@ -1,7 +1,6 @@ package types import ( - "github.com/cosmos/cosmos-sdk/codec/legacy" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -31,7 +30,7 @@ func (msg MsgUnjail) GetSigners() []sdk.AccAddress { // GetSignBytes gets the bytes for the message signer to sign on func (msg MsgUnjail) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } diff --git a/x/staking/keeper/slash_test.go b/x/staking/keeper/slash_test.go index 8b987d0e8d5e..014173d9d075 100644 --- a/x/staking/keeper/slash_test.go +++ b/x/staking/keeper/slash_test.go @@ -112,7 +112,7 @@ func TestSlashUnbondingDelegation(t *testing.T) { // balance decreased require.Equal(t, sdk.NewInt(5), ubd.Entries[0].Balance) newUnbondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, notBondedPool.GetAddress()) - diffTokens := oldUnbondedPoolBalances.Sub(newUnbondedPoolBalances) + diffTokens := oldUnbondedPoolBalances.Sub(newUnbondedPoolBalances...) require.True(t, diffTokens.AmountOf(app.StakingKeeper.BondDenom(ctx)).Equal(sdk.NewInt(5))) } @@ -180,7 +180,7 @@ func TestSlashRedelegation(t *testing.T) { // pool bonded tokens should decrease burnedCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), slashAmount)) - require.Equal(t, balances.Sub(burnedCoins), app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())) + require.Equal(t, balances.Sub(burnedCoins...), app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())) } // tests Slash at a future height (must panic) @@ -220,7 +220,7 @@ func TestSlashAtNegativeHeight(t *testing.T) { // pool bonded shares decreased newBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()) - diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx)) + diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(app.StakingKeeper.BondDenom(ctx)) require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 5).String(), diffTokens.String()) } @@ -251,7 +251,7 @@ func TestSlashValidatorAtCurrentHeight(t *testing.T) { // pool bonded shares decreased newBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()) - diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx)) + diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(app.StakingKeeper.BondDenom(ctx)) require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 5).String(), diffTokens.String()) } @@ -290,7 +290,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // bonded tokens burned newBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()) - diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx)) + diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(app.StakingKeeper.BondDenom(ctx)) require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 3), diffTokens) // read updated validator @@ -316,7 +316,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // bonded tokens burned again newBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()) - diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx)) + diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(app.StakingKeeper.BondDenom(ctx)) require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 6), diffTokens) // read updated validator @@ -342,7 +342,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // bonded tokens burned again newBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()) - diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx)) + diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(app.StakingKeeper.BondDenom(ctx)) require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 9), diffTokens) // read updated validator @@ -368,7 +368,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // just 1 bonded token burned again since that's all the validator now has newBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()) - diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx)) + diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(app.StakingKeeper.BondDenom(ctx)) require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 10), diffTokens) // apply TM updates diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 1a702b150c35..7cff6459db18 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -135,7 +135,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k var fees sdk.Coins - coins, hasNeg := spendable.SafeSub(sdk.Coins{selfDelegation}) + coins, hasNeg := spendable.SafeSub(selfDelegation) if !hasNeg { fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { @@ -277,7 +277,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.K var fees sdk.Coins - coins, hasNeg := spendable.SafeSub(sdk.Coins{bondAmt}) + coins, hasNeg := spendable.SafeSub(bondAmt) if !hasNeg { fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { @@ -419,10 +419,7 @@ func SimulateMsgCancelUnbondingDelegate(ak types.AccountKeeper, bk types.BankKee return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgCancelUnbondingDelegation, "delegator receiving balance is negative"), nil, nil } - cancelBondAmt, err := simtypes.RandPositiveInt(r, unbondingDelegationEntry.Balance) - if err != nil { - return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgCancelUnbondingDelegation, "invalid cancelBondAmt amount"), nil, err - } + cancelBondAmt := simtypes.RandomAmount(r, unbondingDelegationEntry.Balance) if cancelBondAmt.IsZero() { return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgCancelUnbondingDelegation, "cancelBondAmt amount is zero"), nil, nil diff --git a/x/staking/simulation/operations_test.go b/x/staking/simulation/operations_test.go index 7ab52ee1a5b3..2c04abe875a8 100644 --- a/x/staking/simulation/operations_test.go +++ b/x/staking/simulation/operations_test.go @@ -6,8 +6,6 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/codec/legacy" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" @@ -83,7 +81,7 @@ func TestSimulateMsgCreateValidator(t *testing.T) { require.NoError(t, err) var msg types.MsgCreateValidator - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) require.True(t, operationMsg.OK) require.Equal(t, "0.080000000000000000", msg.Commission.MaxChangeRate.String()) @@ -137,7 +135,7 @@ func TestSimulateMsgCancelUnbondingDelegation(t *testing.T) { require.NoError(t, err) var msg types.MsgCancelUnbondingDelegation - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) require.True(t, operationMsg.OK) require.Equal(t, types.TypeMsgCancelUnbondingDelegation, msg.Type()) @@ -170,7 +168,7 @@ func TestSimulateMsgEditValidator(t *testing.T) { require.NoError(t, err) var msg types.MsgEditValidator - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) require.True(t, operationMsg.OK) require.Equal(t, "0.280623462081924936", msg.CommissionRate.String()) @@ -199,7 +197,7 @@ func TestSimulateMsgDelegate(t *testing.T) { require.NoError(t, err) var msg types.MsgDelegate - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) require.True(t, operationMsg.OK) require.Equal(t, "cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", msg.DelegatorAddress) @@ -245,7 +243,7 @@ func TestSimulateMsgUndelegate(t *testing.T) { require.NoError(t, err) var msg types.MsgUndelegate - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) require.True(t, operationMsg.OK) require.Equal(t, "cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", msg.DelegatorAddress) @@ -294,7 +292,7 @@ func TestSimulateMsgBeginRedelegate(t *testing.T) { require.NoError(t, err) var msg types.MsgBeginRedelegate - legacy.Cdc.UnmarshalJSON(operationMsg.Msg, &msg) + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) require.True(t, operationMsg.OK) require.Equal(t, "cosmos1092v0qgulpejj8y8hs6dmlw82x9gv8f7jfc7jl", msg.DelegatorAddress) diff --git a/x/staking/types/codec.go b/x/staking/types/codec.go index ccc6ac358331..558f2eb038ad 100644 --- a/x/staking/types/codec.go +++ b/x/staking/types/codec.go @@ -4,9 +4,11 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" "github.com/cosmos/cosmos-sdk/x/authz" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" ) // RegisterLegacyAminoCodec registers the necessary x/staking interfaces and concrete types @@ -43,6 +45,17 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + func init() { - RegisterLegacyAminoCodec(legacy.Cdc) + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index 2113f96207e5..a1ae89d15751 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -1,7 +1,6 @@ package types import ( - "github.com/cosmos/cosmos-sdk/codec/legacy" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -79,7 +78,7 @@ func (msg MsgCreateValidator) GetSigners() []sdk.AccAddress { // GetSignBytes returns the message bytes to sign over. func (msg MsgCreateValidator) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -163,7 +162,7 @@ func (msg MsgEditValidator) GetSigners() []sdk.AccAddress { // GetSignBytes implements the sdk.Msg interface. func (msg MsgEditValidator) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -217,7 +216,7 @@ func (msg MsgDelegate) GetSigners() []sdk.AccAddress { // GetSignBytes implements the sdk.Msg interface. func (msg MsgDelegate) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -267,7 +266,7 @@ func (msg MsgBeginRedelegate) GetSigners() []sdk.AccAddress { // GetSignBytes implements the sdk.Msg interface. func (msg MsgBeginRedelegate) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -317,7 +316,7 @@ func (msg MsgUndelegate) GetSigners() []sdk.AccAddress { // GetSignBytes implements the sdk.Msg interface. func (msg MsgUndelegate) GetSignBytes() []byte { - bz := legacy.Cdc.MustMarshalJSON(&msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -365,7 +364,7 @@ func (msg MsgCancelUnbondingDelegation) GetSigners() []sdk.AccAddress { // GetSignBytes implements the sdk.Msg interface. func (msg MsgCancelUnbondingDelegation) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) } // ValidateBasic implements the sdk.Msg interface. diff --git a/x/upgrade/types/codec.go b/x/upgrade/types/codec.go index 4acdc05944ab..0f852cc9a2a9 100644 --- a/x/upgrade/types/codec.go +++ b/x/upgrade/types/codec.go @@ -4,15 +4,13 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) -func init() { - RegisterLegacyAminoCodec(legacy.Cdc) -} - // RegisterLegacyAminoCodec registers concrete types on the LegacyAmino codec func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { cdc.RegisterConcrete(Plan{}, "cosmos-sdk/Plan", nil) @@ -36,3 +34,18 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } + +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + +func init() { + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) +} diff --git a/x/upgrade/types/msgs.go b/x/upgrade/types/msgs.go index 5ecc2830f5be..c0e4e810f8a3 100644 --- a/x/upgrade/types/msgs.go +++ b/x/upgrade/types/msgs.go @@ -1,7 +1,6 @@ package types import ( - "github.com/cosmos/cosmos-sdk/codec/legacy" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" @@ -20,7 +19,7 @@ func (m MsgSoftwareUpgrade) Type() string { return sdk.MsgTypeURL(&m) } // GetSignBytes implements the LegacyMsg interface. func (m MsgSoftwareUpgrade) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // ValidateBasic does a sanity check on the provided data. @@ -50,7 +49,7 @@ func (m MsgCancelUpgrade) Type() string { return sdk.MsgTypeURL(&m) } // GetSignBytes implements the LegacyMsg interface. func (m MsgCancelUpgrade) GetSignBytes() []byte { - return sdk.MustSortJSON(legacy.Cdc.MustMarshalJSON(&m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // ValidateBasic does a sanity check on the provided data.