From 7f59723d889b69ca19966167f0b3a7fec7a39e53 Mon Sep 17 00:00:00 2001 From: Marie Date: Wed, 26 Aug 2020 11:39:38 +0200 Subject: [PATCH] Make JSONMarshaler methods require proto.Message (#7054) * Make JSONMarshaler require proto.Message * Use &msg with MarshalJSON * Use *LegacyAmino in queriers instead of JSONMarshaler * Revert ABCIMessageLogs String() and coins tests * Use LegacyAmino in client/debug and fix subspace tests * Use LegacyAmino in all legacy queriers and adapt simulation * Make AminoCodec implement Marshaler and some godoc fixes * Test fixes * Remove unrelevant comment * Use TxConfig.TxJSONEncoder * Use encoding/json in genutil cli migrate/validate genesis cmds * Address simulation related comments * Use JSONMarshaler in cli tests * Use proto.Message as respType in cli tests * Use tmjson for tm GenesisDoc * Update types/module/simulation.go Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update types/module/module_test.go Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Add godoc comments * Remove unused InsertKeyJSON * Fix tests Co-authored-by: Aaron Craelius Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com> --- client/context.go | 29 ++++++----- client/context_test.go | 6 +-- client/debug/main.go | 2 +- codec/amino.go | 12 ++--- codec/amino_codec.go | 35 +++++++++++++ codec/amino_codec_test.go | 6 +-- codec/codec.go | 10 ++-- codec/proto_codec.go | 29 +++++++++-- codec/proto_codec_test.go | 20 -------- go.sum | 3 -- server/start.go | 1 - server/util.go | 20 -------- server/util_test.go | 41 --------------- simapp/app.go | 4 +- simapp/simd/cmd/genaccounts.go | 2 +- simapp/state.go | 17 +++++-- tests/mocks/types_module_module.go | 2 +- types/module/module.go | 6 +-- types/module/module_test.go | 21 +++++--- types/rest/rest.go | 8 +-- types/rest/rest_test.go | 3 +- types/simulation/types.go | 7 ++- x/auth/client/cli/query.go | 2 +- x/auth/client/rest/broadcast.go | 2 - x/auth/client/rest/decode.go | 2 - x/auth/keeper/querier.go | 6 +-- x/auth/keeper/querier_test.go | 8 +-- x/auth/module.go | 2 +- x/auth/simulation/genesis.go | 8 ++- x/auth/simulation/genesis_test.go | 8 +-- x/bank/client/cli/cli_test.go | 23 ++++++--- x/bank/client/rest/grpc_query_test.go | 6 ++- x/bank/client/rest/query.go | 6 +-- x/bank/client/rest/tx.go | 2 +- x/bank/keeper/querier.go | 10 ++-- x/bank/keeper/querier_test.go | 43 ++++++++-------- x/bank/module.go | 2 +- x/bank/simulation/genesis.go | 8 ++- x/bank/simulation/genesis_test.go | 7 ++- x/bank/simulation/params.go | 7 ++- x/bank/types/codec.go | 2 +- x/bank/types/msgs.go | 4 +- x/capability/module.go | 2 +- x/capability/simulation/genesis.go | 9 ++-- x/capability/simulation/genesis_test.go | 7 ++- x/crisis/client/cli/cli_test.go | 3 +- x/crisis/module.go | 2 +- x/crisis/types/msgs.go | 2 +- x/distribution/client/cli/cli_test.go | 11 ++-- x/distribution/client/common/common.go | 4 +- x/distribution/client/common/common_test.go | 2 +- x/distribution/client/rest/query.go | 14 +++--- x/distribution/keeper/querier.go | 20 ++++---- x/distribution/keeper/querier_test.go | 3 +- x/distribution/module.go | 2 +- x/distribution/simulation/genesis.go | 9 ++-- x/distribution/simulation/genesis_test.go | 7 ++- x/distribution/types/msg.go | 8 +-- x/evidence/client/rest/query.go | 2 +- x/evidence/keeper/keeper_test.go | 4 +- x/evidence/keeper/querier.go | 6 +-- x/evidence/module.go | 2 +- x/evidence/simulation/genesis.go | 9 ++-- x/evidence/simulation/genesis_test.go | 4 +- x/evidence/types/msgs.go | 2 +- x/genutil/client/cli/init_test.go | 19 +++++-- x/genutil/client/cli/migrate.go | 8 +-- x/genutil/client/cli/migrate_test.go | 2 +- x/genutil/client/cli/validate_genesis.go | 2 +- x/genutil/client/rest/query.go | 4 +- x/genutil/types/genesis_state.go | 2 +- x/genutil/types/genesis_state_test.go | 2 +- x/gov/client/cli/cli_test.go | 3 +- x/gov/client/cli/query.go | 8 ++- x/gov/client/rest/query.go | 26 +++++----- x/gov/client/utils/query.go | 10 ++-- x/gov/client/utils/query_test.go | 3 +- x/gov/keeper/querier.go | 18 +++---- x/gov/keeper/querier_test.go | 50 +++++++++---------- x/gov/module.go | 2 +- x/gov/simulation/genesis.go | 9 ++-- x/gov/simulation/genesis_test.go | 20 +++++--- x/gov/types/msgs.go | 6 +-- x/ibc-transfer/module.go | 2 +- x/ibc-transfer/simulation/genesis.go | 8 ++- x/ibc-transfer/simulation/genesis_test.go | 8 ++- x/ibc/03-connection/types/msgs.go | 8 +-- x/ibc/07-tendermint/client/cli/tx.go | 21 +++++--- x/ibc/09-localhost/types/msgs.go | 2 +- .../solomachine/client/cli/tx.go | 12 ++--- x/ibc/light-clients/solomachine/types/msgs.go | 6 +-- x/ibc/module.go | 2 +- x/ibc/simulation/genesis.go | 9 ++-- x/ibc/simulation/genesis_test.go | 18 +++---- x/mint/keeper/querier.go | 8 +-- x/mint/keeper/querier_test.go | 8 +-- x/mint/module.go | 2 +- x/mint/simulation/genesis.go | 9 ++-- x/mint/simulation/genesis_test.go | 8 ++- x/params/client/cli/tx.go | 2 +- x/params/client/utils/utils.go | 2 +- x/params/keeper/querier.go | 4 +- x/params/module.go | 2 +- x/simulation/params.go | 13 +++-- x/slashing/client/cli/cli_test.go | 3 +- x/slashing/client/rest/query.go | 4 +- x/slashing/client/rest/tx.go | 2 +- x/slashing/keeper/querier.go | 8 +-- x/slashing/keeper/querier_test.go | 4 +- x/slashing/module.go | 2 +- x/slashing/simulation/genesis.go | 9 ++-- x/slashing/simulation/genesis_test.go | 8 ++- x/slashing/types/msg.go | 2 +- x/staking/client/cli/cli_test.go | 4 +- x/staking/client/rest/query.go | 8 +-- x/staking/client/rest/utils.go | 6 +-- x/staking/keeper/querier.go | 30 +++++------ x/staking/keeper/querier_test.go | 16 +++--- x/staking/module.go | 2 +- x/staking/simulation/genesis.go | 9 ++-- x/staking/simulation/genesis_test.go | 8 ++- x/staking/types/msg.go | 10 ++-- x/upgrade/abci_test.go | 3 +- x/upgrade/client/rest/query.go | 2 +- x/upgrade/keeper/querier.go | 6 +-- x/upgrade/module.go | 2 +- 126 files changed, 580 insertions(+), 492 deletions(-) delete mode 100644 server/util_test.go diff --git a/client/context.go b/client/context.go index ade34161e..56133fbcb 100644 --- a/client/context.go +++ b/client/context.go @@ -66,7 +66,7 @@ func (ctx Context) WithJSONMarshaler(m codec.JSONMarshaler) Context { return ctx } -// WithCodec returns a copy of the context with an updated codec. +// WithLegacyAmino returns a copy of the context with an updated LegacyAmino codec. // TODO: Deprecated (remove). func (ctx Context) WithLegacyAmino(cdc *codec.LegacyAmino) Context { ctx.LegacyAmino = cdc @@ -212,27 +212,30 @@ func (ctx Context) PrintString(str string) error { // either text or json. If text, toPrint will be YAML encoded. Otherwise, toPrint // will be JSON encoded using ctx.JSONMarshaler. An error is returned upon failure. func (ctx Context) PrintOutput(toPrint proto.Message) error { - return ctx.printOutput(toPrint) -} - -// PrintOutputLegacy is a variant of PrintOutput that doesn't require a proto type -// and uses amino JSON encoding. It will be removed in the near future! -func (ctx Context) PrintOutputLegacy(toPrint interface{}) error { - return ctx.WithJSONMarshaler(ctx.LegacyAmino).printOutput(toPrint) -} - -func (ctx Context) printOutput(toPrint interface{}) error { // always serialize JSON initially because proto json can't be directly YAML encoded out, err := ctx.JSONMarshaler.MarshalJSON(toPrint) if err != nil { return err } + return ctx.printOutput(out) +} +// PrintOutputLegacy is a variant of PrintOutput that doesn't require a proto type +// and uses amino JSON encoding. It will be removed in the near future! +func (ctx Context) PrintOutputLegacy(toPrint interface{}) error { + out, err := ctx.LegacyAmino.MarshalJSON(toPrint) + if err != nil { + return err + } + return ctx.printOutput(out) +} + +func (ctx Context) printOutput(out []byte) error { if ctx.OutputFormat == "text" { // handle text format by decoding and re-encoding JSON as YAML var j interface{} - err = json.Unmarshal(out, &j) + err := json.Unmarshal(out, &j) if err != nil { return err } @@ -248,7 +251,7 @@ func (ctx Context) printOutput(toPrint interface{}) error { writer = os.Stdout } - _, err = writer.Write(out) + _, err := writer.Write(out) if err != nil { return err } diff --git a/client/context_test.go b/client/context_test.go index 7d879e1b4..79f6de5d0 100644 --- a/client/context_test.go +++ b/client/context_test.go @@ -71,13 +71,13 @@ x: "10" // amino // amino := testdata.NewTestAmino() - ctx = ctx.WithJSONMarshaler(codec.NewAminoCodec(&codec.LegacyAmino{Amino: amino})) + ctx = ctx.WithLegacyAmino(&codec.LegacyAmino{Amino: amino}) // json buf = &bytes.Buffer{} ctx = ctx.WithOutput(buf) ctx.OutputFormat = "json" - err = ctx.PrintOutput(hasAnimal) + err = ctx.PrintOutputLegacy(hasAnimal) require.NoError(t, err) require.Equal(t, `{"type":"testdata/HasAnimal","value":{"animal":{"type":"testdata/Dog","value":{"size":"big","name":"Spot"}},"x":"10"}} @@ -87,7 +87,7 @@ x: "10" buf = &bytes.Buffer{} ctx = ctx.WithOutput(buf) ctx.OutputFormat = "text" - err = ctx.PrintOutput(hasAnimal) + err = ctx.PrintOutputLegacy(hasAnimal) require.NoError(t, err) require.Equal(t, `type: testdata/HasAnimal diff --git a/client/debug/main.go b/client/debug/main.go index 5ce659721..a35fdecf0 100644 --- a/client/debug/main.go +++ b/client/debug/main.go @@ -90,7 +90,7 @@ $ %s debug pubkey cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg return fmt.Errorf("invalid pubkey type; expected ED25519") } - pubKeyJSONBytes, err := clientCtx.JSONMarshaler.MarshalJSON(edPK) + pubKeyJSONBytes, err := clientCtx.LegacyAmino.MarshalJSON(edPK) if err != nil { return err } diff --git a/codec/amino.go b/codec/amino.go index bb16b89e9..2c19667f6 100644 --- a/codec/amino.go +++ b/codec/amino.go @@ -13,14 +13,12 @@ import ( "github.com/cosmos/cosmos-sdk/codec/types" ) -// deprecated: Codec defines a wrapper for an Amino codec that properly handles protobuf +// deprecated: LegacyAmino defines a wrapper for an Amino codec that properly handles protobuf // types with Any's type LegacyAmino struct { Amino *amino.Codec } -var _ JSONMarshaler = &LegacyAmino{} - func (cdc *LegacyAmino) Seal() { cdc.Amino.Seal() } @@ -43,8 +41,8 @@ func RegisterEvidences(cdc *LegacyAmino) { // MarshalJSONIndent provides a utility for indented JSON encoding of an object // via an Amino codec. It returns an error if it cannot serialize or indent as // JSON. -func MarshalJSONIndent(m JSONMarshaler, obj interface{}) ([]byte, error) { - bz, err := m.MarshalJSON(obj) +func MarshalJSONIndent(cdc *LegacyAmino, obj interface{}) ([]byte, error) { + bz, err := cdc.MarshalJSON(obj) if err != nil { return nil, err } @@ -58,8 +56,8 @@ func MarshalJSONIndent(m JSONMarshaler, obj interface{}) ([]byte, error) { } // MustMarshalJSONIndent executes MarshalJSONIndent except it panics upon failure. -func MustMarshalJSONIndent(m JSONMarshaler, obj interface{}) []byte { - bz, err := MarshalJSONIndent(m, obj) +func MustMarshalJSONIndent(cdc *LegacyAmino, obj interface{}) []byte { + bz, err := MarshalJSONIndent(cdc, obj) if err != nil { panic(fmt.Sprintf("failed to marshal JSON: %s", err)) } diff --git a/codec/amino_codec.go b/codec/amino_codec.go index 79b58fa81..21b751e8d 100644 --- a/codec/amino_codec.go +++ b/codec/amino_codec.go @@ -1,5 +1,7 @@ package codec +import "github.com/gogo/protobuf/proto" + // AminoCodec defines a codec that utilizes Codec for both binary and JSON // encoding. type AminoCodec struct { @@ -8,38 +10,71 @@ type AminoCodec struct { var _ Marshaler = &AminoCodec{} +// NewAminoCodec returns a reference to a new AminoCodec func NewAminoCodec(codec *LegacyAmino) *AminoCodec { return &AminoCodec{LegacyAmino: codec} } +// MarshalBinaryBare implements BinaryMarshaler.MarshalBinaryBare method. func (ac *AminoCodec) MarshalBinaryBare(o ProtoMarshaler) ([]byte, error) { return ac.LegacyAmino.MarshalBinaryBare(o) } +// MustMarshalBinaryBare implements BinaryMarshaler.MustMarshalBinaryBare method. func (ac *AminoCodec) MustMarshalBinaryBare(o ProtoMarshaler) []byte { return ac.LegacyAmino.MustMarshalBinaryBare(o) } +// MarshalBinaryLengthPrefixed implements BinaryMarshaler.MarshalBinaryLengthPrefixed method. func (ac *AminoCodec) MarshalBinaryLengthPrefixed(o ProtoMarshaler) ([]byte, error) { return ac.LegacyAmino.MarshalBinaryLengthPrefixed(o) } +// MustMarshalBinaryLengthPrefixed implements BinaryMarshaler.MustMarshalBinaryLengthPrefixed method. func (ac *AminoCodec) MustMarshalBinaryLengthPrefixed(o ProtoMarshaler) []byte { return ac.LegacyAmino.MustMarshalBinaryLengthPrefixed(o) } +// UnmarshalBinaryBare implements BinaryMarshaler.UnmarshalBinaryBare method. func (ac *AminoCodec) UnmarshalBinaryBare(bz []byte, ptr ProtoMarshaler) error { return ac.LegacyAmino.UnmarshalBinaryBare(bz, ptr) } +// MustUnmarshalBinaryBare implements BinaryMarshaler.MustUnmarshalBinaryBare method. func (ac *AminoCodec) MustUnmarshalBinaryBare(bz []byte, ptr ProtoMarshaler) { ac.LegacyAmino.MustUnmarshalBinaryBare(bz, ptr) } +// UnmarshalBinaryLengthPrefixed implements BinaryMarshaler.UnmarshalBinaryLengthPrefixed method. func (ac *AminoCodec) UnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) error { return ac.LegacyAmino.UnmarshalBinaryLengthPrefixed(bz, ptr) } +// MustUnmarshalBinaryLengthPrefixed implements BinaryMarshaler.MustUnmarshalBinaryLengthPrefixed method. func (ac *AminoCodec) MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) { ac.LegacyAmino.MustUnmarshalBinaryLengthPrefixed(bz, ptr) } + +// MarshalJSON implements JSONMarshaler.MarshalJSON method, +// it marshals to JSON using legacy amino codec. +func (ac *AminoCodec) MarshalJSON(o proto.Message) ([]byte, error) { + return ac.LegacyAmino.MarshalJSON(o) +} + +// MustMarshalJSON implements JSONMarshaler.MustMarshalJSON method, +// it executes MarshalJSON except it panics upon failure. +func (ac *AminoCodec) MustMarshalJSON(o proto.Message) []byte { + return ac.LegacyAmino.MustMarshalJSON(o) +} + +// UnmarshalJSON implements JSONMarshaler.UnmarshalJSON method, +// it unmarshals from JSON using legacy amino codec. +func (ac *AminoCodec) UnmarshalJSON(bz []byte, ptr proto.Message) error { + return ac.LegacyAmino.UnmarshalJSON(bz, ptr) +} + +// MustUnmarshalJSON implements JSONMarshaler.MustUnmarshalJSON method, +// it executes UnmarshalJSON except it panics upon failure. +func (ac *AminoCodec) MustUnmarshalJSON(bz []byte, ptr proto.Message) { + ac.LegacyAmino.MustUnmarshalJSON(bz, ptr) +} diff --git a/codec/amino_codec_test.go b/codec/amino_codec_test.go index cc8e0fac1..7c683d6f0 100644 --- a/codec/amino_codec_test.go +++ b/codec/amino_codec_test.go @@ -29,7 +29,7 @@ func TestAminoCodec(t *testing.T) { testCases := []struct { name string - codec codec.Marshaler + codec *codec.AminoCodec input codec.ProtoMarshaler recv codec.ProtoMarshaler marshalErr bool @@ -175,7 +175,7 @@ func TestAminoCodecMarshalJSONIndent(t *testing.T) { if tc.marshalErr { require.Error(t, err) - require.Panics(t, func() { codec.MustMarshalJSONIndent(cdc, tc.input) }) + require.Panics(t, func() { codec.MustMarshalJSONIndent(cdc.LegacyAmino, tc.input) }) return } @@ -184,7 +184,7 @@ func TestAminoCodecMarshalJSONIndent(t *testing.T) { require.Equal(t, bz, []byte(tc.wantJSON)) var bz2 []byte - require.NotPanics(t, func() { bz2 = codec.MustMarshalJSONIndent(cdc, tc.input) }) + require.NotPanics(t, func() { bz2 = codec.MustMarshalJSONIndent(cdc.LegacyAmino, tc.input) }) require.Equal(t, bz2, []byte(tc.wantJSON)) }) } diff --git a/codec/codec.go b/codec/codec.go index a65231261..a0bf5a598 100644 --- a/codec/codec.go +++ b/codec/codec.go @@ -10,7 +10,7 @@ type ( // Marshaler defines the interface module codecs must implement in order to support // backwards compatibility with Amino while allowing custom Protobuf-based // serialization. Note, Amino can still be used without any dependency on - // Protobuf. There are three typical implementations that fulfill this contract: + // Protobuf. There are two typical implementations that fulfill this contract: // // 1. AminoCodec: Provides full Amino serialization compatibility. // 2. ProtoCodec: Provides full Protobuf serialization compatibility. @@ -36,11 +36,11 @@ type ( } JSONMarshaler interface { - MarshalJSON(o interface{}) ([]byte, error) - MustMarshalJSON(o interface{}) []byte + MarshalJSON(o proto.Message) ([]byte, error) + MustMarshalJSON(o proto.Message) []byte - UnmarshalJSON(bz []byte, ptr interface{}) error - MustUnmarshalJSON(bz []byte, ptr interface{}) + UnmarshalJSON(bz []byte, ptr proto.Message) error + MustUnmarshalJSON(bz []byte, ptr proto.Message) } // ProtoMarshaler defines an interface a type must implement as protocol buffer diff --git a/codec/proto_codec.go b/codec/proto_codec.go index c38a5c7fe..02677af36 100644 --- a/codec/proto_codec.go +++ b/codec/proto_codec.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec/types" "github.com/gogo/protobuf/jsonpb" + "github.com/gogo/protobuf/proto" ) // ProtoCodec defines a codec that utilizes Protobuf for both binary and JSON @@ -18,14 +19,17 @@ type ProtoCodec struct { var _ Marshaler = &ProtoCodec{} +// NewProtoCodec returns a reference to a new ProtoCodec func NewProtoCodec(anyUnpacker types.AnyUnpacker) *ProtoCodec { return &ProtoCodec{anyUnpacker: anyUnpacker} } +// MarshalBinaryBare implements BinaryMarshaler.MarshalBinaryBare method. func (pc *ProtoCodec) MarshalBinaryBare(o ProtoMarshaler) ([]byte, error) { return o.Marshal() } +// MustMarshalBinaryBare implements BinaryMarshaler.MustMarshalBinaryBare method. func (pc *ProtoCodec) MustMarshalBinaryBare(o ProtoMarshaler) []byte { bz, err := pc.MarshalBinaryBare(o) if err != nil { @@ -35,6 +39,7 @@ func (pc *ProtoCodec) MustMarshalBinaryBare(o ProtoMarshaler) []byte { return bz } +// MarshalBinaryLengthPrefixed implements BinaryMarshaler.MarshalBinaryLengthPrefixed method. func (pc *ProtoCodec) MarshalBinaryLengthPrefixed(o ProtoMarshaler) ([]byte, error) { bz, err := pc.MarshalBinaryBare(o) if err != nil { @@ -46,6 +51,7 @@ func (pc *ProtoCodec) MarshalBinaryLengthPrefixed(o ProtoMarshaler) ([]byte, err return append(sizeBuf[:n], bz...), nil } +// MustMarshalBinaryLengthPrefixed implements BinaryMarshaler.MustMarshalBinaryLengthPrefixed method. func (pc *ProtoCodec) MustMarshalBinaryLengthPrefixed(o ProtoMarshaler) []byte { bz, err := pc.MarshalBinaryLengthPrefixed(o) if err != nil { @@ -55,6 +61,7 @@ func (pc *ProtoCodec) MustMarshalBinaryLengthPrefixed(o ProtoMarshaler) []byte { return bz } +// UnmarshalBinaryBare implements BinaryMarshaler.UnmarshalBinaryBare method. func (pc *ProtoCodec) UnmarshalBinaryBare(bz []byte, ptr ProtoMarshaler) error { err := ptr.Unmarshal(bz) if err != nil { @@ -67,12 +74,14 @@ func (pc *ProtoCodec) UnmarshalBinaryBare(bz []byte, ptr ProtoMarshaler) error { return nil } +// MustUnmarshalBinaryBare implements BinaryMarshaler.MustUnmarshalBinaryBare method. func (pc *ProtoCodec) MustUnmarshalBinaryBare(bz []byte, ptr ProtoMarshaler) { if err := pc.UnmarshalBinaryBare(bz, ptr); err != nil { panic(err) } } +// UnmarshalBinaryLengthPrefixed implements BinaryMarshaler.UnmarshalBinaryLengthPrefixed method. func (pc *ProtoCodec) UnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) error { size, n := binary.Uvarint(bz) if n < 0 { @@ -89,13 +98,16 @@ func (pc *ProtoCodec) UnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshale return pc.UnmarshalBinaryBare(bz, ptr) } +// MustUnmarshalBinaryLengthPrefixed implements BinaryMarshaler.MustUnmarshalBinaryLengthPrefixed method. func (pc *ProtoCodec) MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) { if err := pc.UnmarshalBinaryLengthPrefixed(bz, ptr); err != nil { panic(err) } } -func (pc *ProtoCodec) MarshalJSON(o interface{}) ([]byte, error) { +// MarshalJSON implements JSONMarshaler.MarshalJSON method, +// it marshals to JSON using proto codec. +func (pc *ProtoCodec) MarshalJSON(o proto.Message) ([]byte, error) { m, ok := o.(ProtoMarshaler) if !ok { return nil, fmt.Errorf("cannot protobuf JSON encode unsupported type: %T", o) @@ -104,7 +116,9 @@ func (pc *ProtoCodec) MarshalJSON(o interface{}) ([]byte, error) { return ProtoMarshalJSON(m) } -func (pc *ProtoCodec) MustMarshalJSON(o interface{}) []byte { +// MustMarshalJSON implements JSONMarshaler.MustMarshalJSON method, +// it executes MarshalJSON except it panics upon failure. +func (pc *ProtoCodec) MustMarshalJSON(o proto.Message) []byte { bz, err := pc.MarshalJSON(o) if err != nil { panic(err) @@ -113,7 +127,9 @@ func (pc *ProtoCodec) MustMarshalJSON(o interface{}) []byte { return bz } -func (pc *ProtoCodec) UnmarshalJSON(bz []byte, ptr interface{}) error { +// UnmarshalJSON implements JSONMarshaler.UnmarshalJSON method, +// it unmarshals from JSON using proto codec. +func (pc *ProtoCodec) UnmarshalJSON(bz []byte, ptr proto.Message) error { m, ok := ptr.(ProtoMarshaler) if !ok { return fmt.Errorf("cannot protobuf JSON decode unsupported type: %T", ptr) @@ -127,12 +143,17 @@ func (pc *ProtoCodec) UnmarshalJSON(bz []byte, ptr interface{}) error { return types.UnpackInterfaces(ptr, pc.anyUnpacker) } -func (pc *ProtoCodec) MustUnmarshalJSON(bz []byte, ptr interface{}) { +// MustUnmarshalJSON implements JSONMarshaler.MustUnmarshalJSON method, +// it executes UnmarshalJSON except it panics upon failure. +func (pc *ProtoCodec) MustUnmarshalJSON(bz []byte, ptr proto.Message) { if err := pc.UnmarshalJSON(bz, ptr); err != nil { panic(err) } } +// UnpackAny implements AnyUnpacker.UnpackAny method, +// it unpacks the value in any to the interface pointer passed in as +// iface. func (pc *ProtoCodec) UnpackAny(any *types.Any, iface interface{}) error { return pc.anyUnpacker.UnpackAny(any, iface) } diff --git a/codec/proto_codec_test.go b/codec/proto_codec_test.go index 522c80c4e..734bf1320 100644 --- a/codec/proto_codec_test.go +++ b/codec/proto_codec_test.go @@ -122,26 +122,6 @@ func TestProtoCodec(t *testing.T) { } } -func TestProtoCodecMarshalAnyNonProtoErrors(t *testing.T) { - cdc := codec.NewProtoCodec(createTestInterfaceRegistry()) - - input := "this one that one" - _, err := cdc.MarshalJSON(input) - require.Error(t, err) - require.Equal(t, err, errors.New("cannot protobuf JSON encode unsupported type: string")) - - require.Panics(t, func() { cdc.MustMarshalJSON(input) }) -} - -func TestProtoCodecUnmarshalAnyNonProtoErrors(t *testing.T) { - cdc := codec.NewProtoCodec(createTestInterfaceRegistry()) - - recv := new(int) - err := cdc.UnmarshalJSON([]byte("foo"), recv) - require.Error(t, err) - require.Equal(t, err, errors.New("cannot protobuf JSON decode unsupported type: *int")) -} - type lyingProtoMarshaler struct { codec.ProtoMarshaler falseSize int diff --git a/go.sum b/go.sum index 404f49abe..512a0c040 100644 --- a/go.sum +++ b/go.sum @@ -775,17 +775,14 @@ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLks gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= diff --git a/server/start.go b/server/start.go index f4571e06e..59d3261fa 100644 --- a/server/start.go +++ b/server/start.go @@ -233,7 +233,6 @@ func startInProcess(ctx *Context, legacyAminoCdc *codec.LegacyAmino, appCreator clientCtx := client.Context{}. WithHomeDir(home). WithChainID(genDoc.ChainID). - WithJSONMarshaler(legacyAminoCdc). // amino is needed here for backwards compatibility of REST routes WithLegacyAmino(legacyAminoCdc). WithClient(local.New(tmNode)) diff --git a/server/util.go b/server/util.go index b19f7942b..6e34dcfe5 100644 --- a/server/util.go +++ b/server/util.go @@ -1,7 +1,6 @@ package server import ( - "encoding/json" "errors" "fmt" "io" @@ -21,7 +20,6 @@ import ( dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server/config" "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -191,24 +189,6 @@ func AddCommands(rootCmd *cobra.Command, defaultNodeHome string, appCreator type ) } -// InsertKeyJSON inserts a new JSON field/key with a given value to an existing -// JSON message. An error is returned if any serialization operation fails. -// -// NOTE: The ordering of the keys returned as the resulting JSON message is -// non-deterministic, so the client should not rely on key ordering. -func InsertKeyJSON(cdc codec.JSONMarshaler, baseJSON []byte, key string, value json.RawMessage) ([]byte, error) { - var jsonMap map[string]json.RawMessage - - if err := cdc.UnmarshalJSON(baseJSON, &jsonMap); err != nil { - return nil, err - } - - jsonMap[key] = value - bz, err := codec.MarshalJSONIndent(cdc, jsonMap) - - return json.RawMessage(bz), err -} - // https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go // TODO there must be a better way to get external IP func ExternalIP() (string, error) { diff --git a/server/util_test.go b/server/util_test.go deleted file mode 100644 index fb4e73259..000000000 --- a/server/util_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package server - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/codec" -) - -func TestInsertKeyJSON(t *testing.T) { - cdc := codec.New() - - foo := map[string]string{"foo": "foofoo"} - bar := map[string]string{"barInner": "barbar"} - - // create raw messages - bz, err := cdc.MarshalJSON(foo) - require.NoError(t, err) - fooRaw := json.RawMessage(bz) - - bz, err = cdc.MarshalJSON(bar) - require.NoError(t, err) - barRaw := json.RawMessage(bz) - - // make the append - appBz, err := InsertKeyJSON(cdc, fooRaw, "barOuter", barRaw) - require.NoError(t, err) - - // test the append - var appended map[string]json.RawMessage - err = cdc.UnmarshalJSON(appBz, &appended) - require.NoError(t, err) - - var resBar map[string]string - err = cdc.UnmarshalJSON(appended["barOuter"], &resBar) - require.NoError(t, err) - - require.Equal(t, bar, resBar, "appended: %v", appended) -} diff --git a/simapp/app.go b/simapp/app.go index 6b21ef8cf..48c25ecbb 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -331,7 +331,7 @@ func NewSimApp( ) app.mm.RegisterInvariants(&app.CrisisKeeper) - app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), codec.NewAminoCodec(encodingConfig.Amino)) + app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino) app.mm.RegisterQueryServices(app.GRPCQueryRouter()) // add test gRPC service for testing gRPC queries in isolation @@ -507,8 +507,6 @@ func (app *SimApp) SimulationManager() *module.SimulationManager { // API server. func (app *SimApp) RegisterAPIRoutes(apiSvr *api.Server) { clientCtx := apiSvr.ClientCtx - // amino is needed here for backwards compatibility of REST routes - clientCtx = clientCtx.WithJSONMarshaler(clientCtx.LegacyAmino) rpc.RegisterRoutes(clientCtx, apiSvr.Router) authrest.RegisterTxRoutes(clientCtx, apiSvr.Router) ModuleBasics.RegisterRESTRoutes(clientCtx, apiSvr.Router) diff --git a/simapp/simd/cmd/genaccounts.go b/simapp/simd/cmd/genaccounts.go index 67ffb88e2..bda0fcba5 100644 --- a/simapp/simd/cmd/genaccounts.go +++ b/simapp/simd/cmd/genaccounts.go @@ -114,7 +114,7 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa } genFile := config.GenesisFile() - appState, genDoc, err := genutiltypes.GenesisStateFromGenFile(depCdc, genFile) + appState, genDoc, err := genutiltypes.GenesisStateFromGenFile(genFile) if err != nil { return fmt.Errorf("failed to unmarshal genesis state: %w", err) } diff --git a/simapp/state.go b/simapp/state.go index 54629441c..921aac590 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -9,6 +9,7 @@ import ( "time" "github.com/tendermint/tendermint/crypto/secp256k1" + tmjson "github.com/tendermint/tendermint/libs/json" tmtypes "github.com/tendermint/tendermint/types" "github.com/cosmos/cosmos-sdk/codec" @@ -56,7 +57,10 @@ func AppStateFn(cdc codec.JSONMarshaler, simManager *module.SimulationManager) s panic(err) } - cdc.MustUnmarshalJSON(bz, &appParams) + err = json.Unmarshal(bz, &appParams) + if err != nil { + panic(err) + } appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) default: @@ -132,10 +136,17 @@ func AppStateFromGenesisFileFn(r io.Reader, cdc codec.JSONMarshaler, genesisFile } var genesis tmtypes.GenesisDoc - cdc.MustUnmarshalJSON(bytes, &genesis) + // NOTE: Tendermint uses a custom JSON decoder for GenesisDoc + err = tmjson.Unmarshal(bytes, &genesis) + if err != nil { + panic(err) + } var appState GenesisState - cdc.MustUnmarshalJSON(genesis.AppState, &appState) + err = json.Unmarshal(genesis.AppState, &appState) + if err != nil { + panic(err) + } var authGenesis authtypes.GenesisState if appState[authtypes.ModuleName] != nil { diff --git a/tests/mocks/types_module_module.go b/tests/mocks/types_module_module.go index 2d18a9b9c..d674a8ba3 100644 --- a/tests/mocks/types_module_module.go +++ b/tests/mocks/types_module_module.go @@ -540,7 +540,7 @@ func (mr *MockAppModuleMockRecorder) QuerierRoute() *gomock.Call { } // LegacyQuerierHandler mocks base method -func (m *MockAppModule) LegacyQuerierHandler(codec.JSONMarshaler) types0.Querier { +func (m *MockAppModule) LegacyQuerierHandler(*codec.LegacyAmino) types0.Querier { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "LegacyQuerierHandler") ret0, _ := ret[0].(types0.Querier) diff --git a/types/module/module.go b/types/module/module.go index aa88a80bc..34904f5d7 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -169,7 +169,7 @@ type AppModule interface { // Deprecated: use RegisterQueryService QuerierRoute() string // Deprecated: use RegisterQueryService - LegacyQuerierHandler(codec.JSONMarshaler) sdk.Querier + LegacyQuerierHandler(*codec.LegacyAmino) sdk.Querier // RegisterQueryService allows a module to register a gRPC query service RegisterQueryService(grpc.Server) @@ -202,7 +202,7 @@ func (GenesisOnlyAppModule) Route() sdk.Route { return sdk.Route{} } func (GenesisOnlyAppModule) QuerierRoute() string { return "" } // LegacyQuerierHandler returns an empty module querier -func (gam GenesisOnlyAppModule) LegacyQuerierHandler(codec.JSONMarshaler) sdk.Querier { return nil } +func (gam GenesisOnlyAppModule) LegacyQuerierHandler(*codec.LegacyAmino) sdk.Querier { return nil } // RegisterQueryService registers all gRPC query services. func (gam GenesisOnlyAppModule) RegisterQueryService(grpc.Server) {} @@ -274,7 +274,7 @@ func (m *Manager) RegisterInvariants(ir sdk.InvariantRegistry) { } // RegisterRoutes registers all module routes and module querier routes -func (m *Manager) RegisterRoutes(router sdk.Router, queryRouter sdk.QueryRouter, legacyQuerierCdc codec.JSONMarshaler) { +func (m *Manager) RegisterRoutes(router sdk.Router, queryRouter sdk.QueryRouter, legacyQuerierCdc *codec.LegacyAmino) { for _, module := range m.Modules { if !module.Route().Empty() { router.AddRoute(module.Route()) diff --git a/types/module/module_test.go b/types/module/module_test.go index 0826a76bb..6472370b4 100644 --- a/types/module/module_test.go +++ b/types/module/module_test.go @@ -25,10 +25,12 @@ var errFoo = errors.New("dummy") func TestBasicManager(t *testing.T) { mockCtrl := gomock.NewController(t) t.Cleanup(mockCtrl.Finish) - cdc := codec.New() + legacyAmino := codec.New() interfaceRegistry := types.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) + clientCtx := client.Context{} - clientCtx = clientCtx.WithLegacyAmino(cdc) + clientCtx = clientCtx.WithLegacyAmino(legacyAmino) wantDefaultGenesis := map[string]json.RawMessage{"mockAppModuleBasic1": json.RawMessage(``)} mockAppModuleBasic1 := mocks.NewMockAppModuleBasic(mockCtrl) @@ -37,7 +39,7 @@ func TestBasicManager(t *testing.T) { mockAppModuleBasic1.EXPECT().DefaultGenesis(gomock.Eq(cdc)).Times(1).Return(json.RawMessage(``)) mockAppModuleBasic1.EXPECT().ValidateGenesis(gomock.Eq(cdc), gomock.Eq(nil), gomock.Eq(wantDefaultGenesis["mockAppModuleBasic1"])).Times(1).Return(errFoo) mockAppModuleBasic1.EXPECT().RegisterRESTRoutes(gomock.Eq(client.Context{}), gomock.Eq(&mux.Router{})).Times(1) - mockAppModuleBasic1.EXPECT().RegisterCodec(gomock.Eq(cdc)).Times(1) + mockAppModuleBasic1.EXPECT().RegisterCodec(gomock.Eq(legacyAmino)).Times(1) mockAppModuleBasic1.EXPECT().RegisterInterfaces(gomock.Eq(interfaceRegistry)).Times(1) mockAppModuleBasic1.EXPECT().GetTxCmd().Times(1).Return(nil) mockAppModuleBasic1.EXPECT().GetQueryCmd().Times(1).Return(nil) @@ -45,7 +47,7 @@ func TestBasicManager(t *testing.T) { mm := module.NewBasicManager(mockAppModuleBasic1) require.Equal(t, mm["mockAppModuleBasic1"], mockAppModuleBasic1) - mm.RegisterCodec(cdc) + mm.RegisterCodec(legacyAmino) mm.RegisterInterfaces(interfaceRegistry) require.Equal(t, wantDefaultGenesis, mm.DefaultGenesis(cdc)) @@ -164,8 +166,7 @@ func TestManager_RegisterRoutes(t *testing.T) { queryRouter.EXPECT().AddRoute(gomock.Eq("querierRoute1"), gomock.Eq(handler3)).Times(1) amino := codec.New() - jsonCdc := codec.NewAminoCodec(amino) - mm.RegisterRoutes(router, queryRouter, jsonCdc) + mm.RegisterRoutes(router, queryRouter, amino) } func TestManager_RegisterQueryServices(t *testing.T) { @@ -199,7 +200,9 @@ func TestManager_InitGenesis(t *testing.T) { require.NotNil(t, mm) require.Equal(t, 2, len(mm.Modules)) - cdc, ctx := codec.New(), sdk.Context{} + ctx := sdk.Context{} + interfaceRegistry := types.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) genesisData := map[string]json.RawMessage{"module1": json.RawMessage(`{"key": "value"}`)} mockAppModule1.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(cdc), gomock.Eq(genesisData["module1"])).Times(1).Return(nil) @@ -226,7 +229,9 @@ func TestManager_ExportGenesis(t *testing.T) { require.NotNil(t, mm) require.Equal(t, 2, len(mm.Modules)) - cdc, ctx := codec.New(), sdk.Context{} + ctx := sdk.Context{} + interfaceRegistry := types.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) mockAppModule1.EXPECT().ExportGenesis(gomock.Eq(ctx), gomock.Eq(cdc)).Times(1).Return(json.RawMessage(`{"key1": "value1"}`)) mockAppModule2.EXPECT().ExportGenesis(gomock.Eq(ctx), gomock.Eq(cdc)).Times(1).Return(json.RawMessage(`{"key2": "value2"}`)) diff --git a/types/rest/rest.go b/types/rest/rest.go index 66ed3e5d3..80afe2fb6 100644 --- a/types/rest/rest.go +++ b/types/rest/rest.go @@ -134,13 +134,13 @@ func (br BaseReq) ValidateBasic(w http.ResponseWriter) bool { // ReadRESTReq reads and unmarshals a Request's body to the the BaseReq struct. // Writes an error response to ResponseWriter and returns true if errors occurred. -func ReadRESTReq(w http.ResponseWriter, r *http.Request, m codec.JSONMarshaler, req interface{}) bool { +func ReadRESTReq(w http.ResponseWriter, r *http.Request, cdc *codec.LegacyAmino, req interface{}) bool { body, err := ioutil.ReadAll(r.Body) if CheckBadRequestError(w, err) { return false } - err = m.UnmarshalJSON(body, req) + err = cdc.UnmarshalJSON(body, req) if err != nil { WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("failed to decode JSON payload: %s", err)) return false @@ -199,10 +199,10 @@ func WriteErrorResponse(w http.ResponseWriter, status int, err string) { // WriteSimulationResponse prepares and writes an HTTP // response for transactions simulations. -func WriteSimulationResponse(w http.ResponseWriter, m codec.JSONMarshaler, gas uint64) { +func WriteSimulationResponse(w http.ResponseWriter, cdc *codec.LegacyAmino, gas uint64) { gasEst := GasEstimateResponse{GasEstimate: gas} - resp, err := m.MarshalJSON(gasEst) + resp, err := cdc.MarshalJSON(gasEst) if CheckInternalServerError(w, err) { return } diff --git a/types/rest/rest_test.go b/types/rest/rest_test.go index e05deb187..5116593ca 100644 --- a/types/rest/rest_test.go +++ b/types/rest/rest_test.go @@ -310,8 +310,7 @@ func TestPostProcessResponseBare(t *testing.T) { encodingConfig := simappparams.MakeEncodingConfig() clientCtx := client.Context{}. WithTxConfig(encodingConfig.TxConfig). - WithJSONMarshaler(encodingConfig.Amino). // amino used intentionally here - WithLegacyAmino(encodingConfig.Amino) // amino used intentionally here + WithLegacyAmino(encodingConfig.Amino) // amino used intentionally here // write bytes w := httptest.NewRecorder() bs := []byte("text string") diff --git a/types/simulation/types.go b/types/simulation/types.go index 8778611af..f541b1d76 100644 --- a/types/simulation/types.go +++ b/types/simulation/types.go @@ -135,9 +135,12 @@ type AppParams map[string]json.RawMessage // object. If it exists, it'll be decoded and returned. Otherwise, the provided // ParamSimulator is used to generate a random value or default value (eg: in the // case of operation weights where Rand is not used). -func (sp AppParams) GetOrGenerate(cdc codec.JSONMarshaler, key string, ptr interface{}, r *rand.Rand, ps ParamSimulator) { +func (sp AppParams) GetOrGenerate(_ codec.JSONMarshaler, key string, ptr interface{}, r *rand.Rand, ps ParamSimulator) { if v, ok := sp[key]; ok && v != nil { - cdc.MustUnmarshalJSON(v, ptr) + err := json.Unmarshal(v, ptr) + if err != nil { + panic(err) + } return } diff --git a/x/auth/client/cli/query.go b/x/auth/client/cli/query.go index d58a303ca..3706a3a47 100644 --- a/x/auth/client/cli/query.go +++ b/x/auth/client/cli/query.go @@ -167,7 +167,7 @@ $ %s query txs --%s 'message.sender=cosmos1...&message.action=withdraw_delegator return err } - output, err := clientCtx.JSONMarshaler.MarshalJSON(txs) + output, err := clientCtx.LegacyAmino.MarshalJSON(txs) if err != nil { return err } diff --git a/x/auth/client/rest/broadcast.go b/x/auth/client/rest/broadcast.go index 632c10c3a..37daf5084 100644 --- a/x/auth/client/rest/broadcast.go +++ b/x/auth/client/rest/broadcast.go @@ -46,8 +46,6 @@ func BroadcastTxRequest(clientCtx client.Context) http.HandlerFunc { return } - // NOTE: amino is set intentionally here, don't migrate it! - clientCtx = clientCtx.WithJSONMarshaler(clientCtx.LegacyAmino) rest.PostProcessResponseBare(w, clientCtx, res) } } diff --git a/x/auth/client/rest/decode.go b/x/auth/client/rest/decode.go index 5081412b6..ed327a78e 100644 --- a/x/auth/client/rest/decode.go +++ b/x/auth/client/rest/decode.go @@ -65,8 +65,6 @@ func DecodeTxRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { response := DecodeResp(stdTx) - // NOTE: amino is set intentionally here, don't migrate it - clientCtx = clientCtx.WithJSONMarshaler(clientCtx.LegacyAmino) rest.PostProcessResponse(w, clientCtx, response) } } diff --git a/x/auth/keeper/querier.go b/x/auth/keeper/querier.go index ac2ab3984..0a654867d 100644 --- a/x/auth/keeper/querier.go +++ b/x/auth/keeper/querier.go @@ -10,7 +10,7 @@ import ( ) // NewQuerier creates a querier for auth REST endpoints -func NewQuerier(k AccountKeeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func NewQuerier(k AccountKeeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { switch path[0] { case types.QueryAccount: @@ -25,7 +25,7 @@ func NewQuerier(k AccountKeeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Queri } } -func queryAccount(ctx sdk.Context, req abci.RequestQuery, k AccountKeeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryAccount(ctx sdk.Context, req abci.RequestQuery, k AccountKeeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryAccountRequest if err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) @@ -44,7 +44,7 @@ func queryAccount(ctx sdk.Context, req abci.RequestQuery, k AccountKeeper, legac return bz, nil } -func queryParams(ctx sdk.Context, k AccountKeeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryParams(ctx sdk.Context, k AccountKeeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { params := k.GetParams(ctx) res, err := codec.MarshalJSONIndent(legacyQuerierCdc, params) diff --git a/x/auth/keeper/querier_test.go b/x/auth/keeper/querier_test.go index 470ebb826..55bb20ca7 100644 --- a/x/auth/keeper/querier_test.go +++ b/x/auth/keeper/querier_test.go @@ -25,7 +25,7 @@ func TestQueryAccount(t *testing.T) { } path := []string{types.QueryAccount} - querier := keep.NewQuerier(app.AccountKeeper, legacyQuerierCdc) + querier := keep.NewQuerier(app.AccountKeeper, legacyQuerierCdc.LegacyAmino) bz, err := querier(ctx, []string{"other"}, req) require.Error(t, err) @@ -39,13 +39,13 @@ func TestQueryAccount(t *testing.T) { require.Error(t, err) require.Nil(t, res) - req.Data = legacyQuerierCdc.MustMarshalJSON(types.QueryAccountRequest{Address: []byte("")}) + req.Data = legacyQuerierCdc.MustMarshalJSON(&types.QueryAccountRequest{Address: []byte("")}) res, err = querier(ctx, path, req) require.Error(t, err) require.Nil(t, res) _, _, addr := testdata.KeyTestPubAddr() - req.Data = legacyQuerierCdc.MustMarshalJSON(types.QueryAccountRequest{Address: addr}) + req.Data = legacyQuerierCdc.MustMarshalJSON(&types.QueryAccountRequest{Address: addr}) res, err = querier(ctx, path, req) require.Error(t, err) require.Nil(t, res) @@ -60,6 +60,6 @@ func TestQueryAccount(t *testing.T) { require.NotNil(t, res) var account types.AccountI - err2 := legacyQuerierCdc.UnmarshalJSON(res, &account) + err2 := legacyQuerierCdc.LegacyAmino.UnmarshalJSON(res, &account) require.Nil(t, err2) } diff --git a/x/auth/module.go b/x/auth/module.go index 78b84bb22..6e5253984 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -120,7 +120,7 @@ func (AppModule) QuerierRoute() string { } // LegacyQuerierHandler returns the auth module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return keeper.NewQuerier(am.accountKeeper, legacyQuerierCdc) } diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 98148cb6c..f04ca34ba 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -1,10 +1,10 @@ package simulation import ( + "encoding/json" "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/simulation" @@ -129,6 +129,10 @@ func RandomizedGenState(simState *module.SimulationState, randGenAccountsFn Rand authGenesis := types.NewGenesisState(params, genesisAccs) - fmt.Printf("Selected randomly generated auth parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.Cdc, &authGenesis.Params)) + bz, err := json.MarshalIndent(&authGenesis.Params, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("Selected randomly generated auth parameters:\n%s\n", bz) simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(authGenesis) } diff --git a/x/auth/simulation/genesis_test.go b/x/auth/simulation/genesis_test.go index 8894010d6..830a264ff 100644 --- a/x/auth/simulation/genesis_test.go +++ b/x/auth/simulation/genesis_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/auth/simulation" @@ -17,10 +18,9 @@ import ( // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. // Abonormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { - cdc := codec.New() - // Make sure to register cdc. - // otherwise the test will panic - types.RegisterCodec(cdc) + registry := codectypes.NewInterfaceRegistry() + types.RegisterInterfaces(registry) + cdc := codec.NewProtoCodec(registry) s := rand.NewSource(1) r := rand.New(s) diff --git a/x/bank/client/cli/cli_test.go b/x/bank/client/cli/cli_test.go index 620cb265f..a1f129653 100644 --- a/x/bank/client/cli/cli_test.go +++ b/x/bank/client/cli/cli_test.go @@ -55,8 +55,8 @@ func (s *IntegrationTestSuite) TestGetBalancesCmd() { name string args []string expectErr bool - respType fmt.Stringer - expected fmt.Stringer + respType proto.Message + expected proto.Message }{ {"no address provided", []string{}, true, nil, nil}, { @@ -86,14 +86,18 @@ func (s *IntegrationTestSuite) TestGetBalancesCmd() { }, false, &sdk.Coin{}, - sdk.NewCoin(s.cfg.BondDenom, s.cfg.StakingTokens.Sub(s.cfg.BondedTokens)), + NewCoin(s.cfg.BondDenom, s.cfg.StakingTokens.Sub(s.cfg.BondedTokens)), }, { "total account balance of a bogus denom", - []string{val.Address.String(), fmt.Sprintf("--%s=foobar", cli.FlagDenom), fmt.Sprintf("--%s=json", tmcli.OutputFlag)}, + []string{ + val.Address.String(), + fmt.Sprintf("--%s=foobar", cli.FlagDenom), + fmt.Sprintf("--%s=json", tmcli.OutputFlag), + }, false, &sdk.Coin{}, - sdk.NewCoin("foobar", sdk.ZeroInt()), + NewCoin("foobar", sdk.ZeroInt()), }, } @@ -216,7 +220,7 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { amount sdk.Coins args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -284,8 +288,8 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(bz.Bytes(), tc.respType), bz.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(bz.Bytes(), tc.respType), bz.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) } @@ -296,3 +300,8 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { func TestIntegrationTestSuite(t *testing.T) { suite.Run(t, new(IntegrationTestSuite)) } + +func NewCoin(denom string, amount sdk.Int) *sdk.Coin { + coin := sdk.NewCoin(denom, amount) + return &coin +} diff --git a/x/bank/client/rest/grpc_query_test.go b/x/bank/client/rest/grpc_query_test.go index 1ca5946b1..e1b4384ef 100644 --- a/x/bank/client/rest/grpc_query_test.go +++ b/x/bank/client/rest/grpc_query_test.go @@ -3,6 +3,8 @@ package rest_test import ( "fmt" + "github.com/gogo/protobuf/proto" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" @@ -17,8 +19,8 @@ func (s *IntegrationTestSuite) TestTotalSupplyGRPCHandler() { name string url string headers map[string]string - respType fmt.Stringer - expected fmt.Stringer + respType proto.Message + expected proto.Message }{ { "test GRPC total supply", diff --git a/x/bank/client/rest/query.go b/x/bank/client/rest/query.go index b8e258225..7c88c790f 100644 --- a/x/bank/client/rest/query.go +++ b/x/bank/client/rest/query.go @@ -45,7 +45,7 @@ func QueryBalancesRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { route = fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryBalance) } - bz, err := ctx.JSONMarshaler.MarshalJSON(params) + bz, err := ctx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } @@ -74,7 +74,7 @@ func totalSupplyHandlerFn(clientCtx client.Context) http.HandlerFunc { } params := types.NewQueryTotalSupplyParams(page, limit) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return @@ -101,7 +101,7 @@ func supplyOfHandlerFn(clientCtx client.Context) http.HandlerFunc { } params := types.NewQuerySupplyOfParams(denom) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return diff --git a/x/bank/client/rest/tx.go b/x/bank/client/rest/tx.go index a59450c3f..e630710df 100644 --- a/x/bank/client/rest/tx.go +++ b/x/bank/client/rest/tx.go @@ -31,7 +31,7 @@ func NewSendRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { } var req SendReq - if !rest.ReadRESTReq(w, r, clientCtx.JSONMarshaler, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.LegacyAmino, &req) { return } diff --git a/x/bank/keeper/querier.go b/x/bank/keeper/querier.go index 8acc5a3c5..88bfac373 100644 --- a/x/bank/keeper/querier.go +++ b/x/bank/keeper/querier.go @@ -11,7 +11,7 @@ import ( ) // NewQuerier returns a new sdk.Keeper instance. -func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { switch path[0] { case types.QueryBalance: @@ -32,7 +32,7 @@ func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { } } -func queryBalance(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryBalance(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryBalanceRequest if err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { @@ -49,7 +49,7 @@ func queryBalance(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerie return bz, nil } -func queryAllBalance(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryAllBalance(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryAllBalancesRequest if err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { @@ -66,7 +66,7 @@ func queryAllBalance(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQue return bz, nil } -func queryTotalSupply(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryTotalSupply(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryTotalSupplyParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -91,7 +91,7 @@ func queryTotalSupply(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQu return res, nil } -func querySupplyOf(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func querySupplyOf(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QuerySupplyOfParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) diff --git a/x/bank/keeper/querier_test.go b/x/bank/keeper/querier_test.go index 0e1ba93d0..84ec3d095 100644 --- a/x/bank/keeper/querier_test.go +++ b/x/bank/keeper/querier_test.go @@ -3,8 +3,6 @@ package keeper_test import ( "fmt" - "github.com/cosmos/cosmos-sdk/codec" - abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/testutil/testdata" @@ -15,26 +13,26 @@ import ( func (suite *IntegrationTestSuite) TestQuerier_QueryBalance() { app, ctx := suite.app, suite.ctx - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) + legacyAmino := app.LegacyAmino() _, _, addr := testdata.KeyTestPubAddr() req := abci.RequestQuery{ Path: fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QueryBalance), Data: []byte{}, } - querier := keeper.NewQuerier(app.BankKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.BankKeeper, legacyAmino) res, err := querier(ctx, []string{types.QueryBalance}, req) suite.Require().NotNil(err) suite.Require().Nil(res) - req.Data = app.LegacyAmino().MustMarshalJSON(types.NewQueryBalanceRequest(addr, fooDenom)) + req.Data = legacyAmino.MustMarshalJSON(types.NewQueryBalanceRequest(addr, fooDenom)) res, err = querier(ctx, []string{types.QueryBalance}, req) suite.Require().NoError(err) suite.Require().NotNil(res) var balance sdk.Coin - suite.Require().NoError(app.LegacyAmino().UnmarshalJSON(res, &balance)) + suite.Require().NoError(legacyAmino.UnmarshalJSON(res, &balance)) suite.True(balance.IsZero()) origCoins := sdk.NewCoins(newFooCoin(50), newBarCoin(30)) @@ -46,32 +44,32 @@ func (suite *IntegrationTestSuite) TestQuerier_QueryBalance() { res, err = querier(ctx, []string{types.QueryBalance}, req) suite.Require().NoError(err) suite.Require().NotNil(res) - suite.Require().NoError(app.LegacyAmino().UnmarshalJSON(res, &balance)) + suite.Require().NoError(legacyAmino.UnmarshalJSON(res, &balance)) suite.True(balance.IsEqual(newFooCoin(50))) } func (suite *IntegrationTestSuite) TestQuerier_QueryAllBalances() { app, ctx := suite.app, suite.ctx - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) + legacyAmino := app.LegacyAmino() _, _, addr := testdata.KeyTestPubAddr() req := abci.RequestQuery{ Path: fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QueryAllBalances), Data: []byte{}, } - querier := keeper.NewQuerier(app.BankKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.BankKeeper, legacyAmino) res, err := querier(ctx, []string{types.QueryAllBalances}, req) suite.Require().NotNil(err) suite.Require().Nil(res) - req.Data = app.LegacyAmino().MustMarshalJSON(types.NewQueryAllBalancesRequest(addr, nil)) + req.Data = legacyAmino.MustMarshalJSON(types.NewQueryAllBalancesRequest(addr, nil)) res, err = querier(ctx, []string{types.QueryAllBalances}, req) suite.Require().NoError(err) suite.Require().NotNil(res) var balances sdk.Coins - suite.Require().NoError(app.LegacyAmino().UnmarshalJSON(res, &balances)) + suite.Require().NoError(legacyAmino.UnmarshalJSON(res, &balances)) suite.True(balances.IsZero()) origCoins := sdk.NewCoins(newFooCoin(50), newBarCoin(30)) @@ -83,13 +81,13 @@ func (suite *IntegrationTestSuite) TestQuerier_QueryAllBalances() { res, err = querier(ctx, []string{types.QueryAllBalances}, req) suite.Require().NoError(err) suite.Require().NotNil(res) - suite.Require().NoError(app.LegacyAmino().UnmarshalJSON(res, &balances)) + suite.Require().NoError(legacyAmino.UnmarshalJSON(res, &balances)) suite.True(balances.IsEqual(origCoins)) } func (suite *IntegrationTestSuite) TestQuerier_QueryTotalSupply() { app, ctx := suite.app, suite.ctx - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) + legacyAmino := app.LegacyAmino() expectedTotalSupply := types.NewSupply(sdk.NewCoins(sdk.NewInt64Coin("test", 400000000))) app.BankKeeper.SetSupply(ctx, expectedTotalSupply) @@ -98,26 +96,25 @@ func (suite *IntegrationTestSuite) TestQuerier_QueryTotalSupply() { Data: []byte{}, } - querier := keeper.NewQuerier(app.BankKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.BankKeeper, legacyAmino) res, err := querier(ctx, []string{types.QueryTotalSupply}, req) suite.Require().NotNil(err) suite.Require().Nil(res) - req.Data = app.LegacyAmino().MustMarshalJSON(types.NewQueryTotalSupplyParams(1, 100)) + req.Data = legacyAmino.MustMarshalJSON(types.NewQueryTotalSupplyParams(1, 100)) res, err = querier(ctx, []string{types.QueryTotalSupply}, req) suite.Require().NoError(err) suite.Require().NotNil(res) var resp sdk.Coins - suite.Require().NoError(app.LegacyAmino().UnmarshalJSON(res, &resp)) + suite.Require().NoError(legacyAmino.UnmarshalJSON(res, &resp)) suite.Require().Equal(expectedTotalSupply.Total, resp) } func (suite *IntegrationTestSuite) TestQuerier_QueryTotalSupplyOf() { app, ctx := suite.app, suite.ctx - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - + legacyAmino := app.LegacyAmino() test1Supply := sdk.NewInt64Coin("test1", 4000000) test2Supply := sdk.NewInt64Coin("test2", 700000000) expectedTotalSupply := types.NewSupply(sdk.NewCoins(test1Supply, test2Supply)) @@ -128,31 +125,31 @@ func (suite *IntegrationTestSuite) TestQuerier_QueryTotalSupplyOf() { Data: []byte{}, } - querier := keeper.NewQuerier(app.BankKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.BankKeeper, legacyAmino) res, err := querier(ctx, []string{types.QuerySupplyOf}, req) suite.Require().NotNil(err) suite.Require().Nil(res) - req.Data = app.LegacyAmino().MustMarshalJSON(types.NewQuerySupplyOfParams(test1Supply.Denom)) + req.Data = legacyAmino.MustMarshalJSON(types.NewQuerySupplyOfParams(test1Supply.Denom)) res, err = querier(ctx, []string{types.QuerySupplyOf}, req) suite.Require().NoError(err) suite.Require().NotNil(res) var resp sdk.Coin - suite.Require().NoError(app.LegacyAmino().UnmarshalJSON(res, &resp)) + suite.Require().NoError(legacyAmino.UnmarshalJSON(res, &resp)) suite.Require().Equal(test1Supply, resp) } func (suite *IntegrationTestSuite) TestQuerierRouteNotFound() { app, ctx := suite.app, suite.ctx - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) + legacyAmino := app.LegacyAmino() req := abci.RequestQuery{ Path: fmt.Sprintf("custom/%s/invalid", types.ModuleName), Data: []byte{}, } - querier := keeper.NewQuerier(app.BankKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.BankKeeper, legacyAmino) _, err := querier(ctx, []string{"invalid"}, req) suite.Error(err) } diff --git a/x/bank/module.go b/x/bank/module.go index 0d7e33b1c..1dee965d2 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -125,7 +125,7 @@ func (am AppModule) Route() sdk.Route { func (AppModule) QuerierRoute() string { return types.RouterKey } // LegacyQuerierHandler returns the bank module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return keeper.NewQuerier(am.keeper, legacyQuerierCdc) } diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index 21b298d63..2d6384d06 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -3,10 +3,10 @@ package simulation // DONTCOVER import ( + "encoding/json" "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -77,6 +77,10 @@ func RandomizedGenState(simState *module.SimulationState) { Supply: supply, } - fmt.Printf("Selected randomly generated bank parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.Cdc, &bankGenesis.Params)) + paramsBytes, err := json.MarshalIndent(&bankGenesis.Params, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("Selected randomly generated bank parameters:\n%s\n", paramsBytes) simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&bankGenesis) } diff --git a/x/bank/simulation/genesis_test.go b/x/bank/simulation/genesis_test.go index 8bc2d8d44..fc31ca38e 100644 --- a/x/bank/simulation/genesis_test.go +++ b/x/bank/simulation/genesis_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/bank/simulation" @@ -17,7 +18,8 @@ import ( // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. // Abonormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) s := rand.NewSource(1) r := rand.New(s) @@ -46,7 +48,8 @@ func TestRandomizedGenState(t *testing.T) { // TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) s := rand.NewSource(1) r := rand.New(s) diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go index a2699659f..c3da18220 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -3,6 +3,7 @@ package simulation // DONTCOVER import ( + "encoding/json" "fmt" "math/rand" @@ -18,7 +19,11 @@ func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ simulation.NewSimParamChange(types.ModuleName, string(types.KeySendEnabled), func(r *rand.Rand) string { - return fmt.Sprintf("%s", types.ModuleCdc.MustMarshalJSON(RandomGenesisSendParams(r))) + paramsBytes, err := json.Marshal(RandomGenesisSendParams(r)) + if err != nil { + panic(err) + } + return fmt.Sprintf("%s", paramsBytes) }, ), simulation.NewSimParamChange(types.ModuleName, string(types.KeyDefaultSendEnabled), diff --git a/x/bank/types/codec.go b/x/bank/types/codec.go index 5b869df74..b0acd6b7c 100644 --- a/x/bank/types/codec.go +++ b/x/bank/types/codec.go @@ -33,7 +33,7 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { var ( amino = codec.New() - // ModuleCdc references the global x/staking module codec. Note, the codec should + // ModuleCdc references the global x/bank module codec. Note, the codec should // ONLY be used in certain instances of tests and for JSON encoding as Amino is // still used for that purpose. // diff --git a/x/bank/types/msgs.go b/x/bank/types/msgs.go index 4c3f7faea..6fada6e0a 100644 --- a/x/bank/types/msgs.go +++ b/x/bank/types/msgs.go @@ -47,7 +47,7 @@ func (msg MsgSend) ValidateBasic() error { // GetSignBytes Implements Msg. func (msg MsgSend) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) } // GetSigners Implements Msg. @@ -85,7 +85,7 @@ func (msg MsgMultiSend) ValidateBasic() error { // GetSignBytes Implements Msg. func (msg MsgMultiSend) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) } // GetSigners Implements Msg. diff --git a/x/capability/module.go b/x/capability/module.go index ed081a649..e1bd4c99c 100644 --- a/x/capability/module.go +++ b/x/capability/module.go @@ -112,7 +112,7 @@ func (AppModule) Route() sdk.Route { return sdk.Route{} } func (AppModule) QuerierRoute() string { return "" } // LegacyQuerierHandler returns the capability module's Querier. -func (am AppModule) LegacyQuerierHandler(codec.JSONMarshaler) sdk.Querier { return nil } +func (am AppModule) LegacyQuerierHandler(*codec.LegacyAmino) sdk.Querier { return nil } // RegisterQueryService registers a GRPC query service to respond to the // module-specific GRPC queries. diff --git a/x/capability/simulation/genesis.go b/x/capability/simulation/genesis.go index 465a9aa47..ab1d11fb3 100644 --- a/x/capability/simulation/genesis.go +++ b/x/capability/simulation/genesis.go @@ -3,11 +3,10 @@ package simulation // DONTCOVER import ( + "encoding/json" "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/capability/types" ) @@ -31,6 +30,10 @@ func RandomizedGenState(simState *module.SimulationState) { capabilityGenesis := types.GenesisState{Index: idx} - fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, codec.MustMarshalJSONIndent(simState.Cdc, &capabilityGenesis)) + bz, err := json.MarshalIndent(&capabilityGenesis, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, bz) simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&capabilityGenesis) } diff --git a/x/capability/simulation/genesis_test.go b/x/capability/simulation/genesis_test.go index 5c255e2f7..16d54c177 100644 --- a/x/capability/simulation/genesis_test.go +++ b/x/capability/simulation/genesis_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/capability/simulation" @@ -17,7 +18,8 @@ import ( // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. // Abonormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) s := rand.NewSource(1) r := rand.New(s) @@ -42,7 +44,8 @@ func TestRandomizedGenState(t *testing.T) { // TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) s := rand.NewSource(1) r := rand.New(s) diff --git a/x/crisis/client/cli/cli_test.go b/x/crisis/client/cli/cli_test.go index bea5d5b5b..ef135b2de 100644 --- a/x/crisis/client/cli/cli_test.go +++ b/x/crisis/client/cli/cli_test.go @@ -4,6 +4,7 @@ import ( "fmt" "testing" + "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" "github.com/cosmos/cosmos-sdk/client/flags" @@ -45,7 +46,7 @@ func (s *IntegrationTestSuite) TestNewMsgVerifyInvariantTxCmd() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { diff --git a/x/crisis/module.go b/x/crisis/module.go index 2e0cf6c65..76acb86e4 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -111,7 +111,7 @@ func (am AppModule) Route() sdk.Route { func (AppModule) QuerierRoute() string { return "" } // LegacyQuerierHandler returns no sdk.Querier. -func (AppModule) LegacyQuerierHandler(codec.JSONMarshaler) sdk.Querier { return nil } +func (AppModule) LegacyQuerierHandler(*codec.LegacyAmino) sdk.Querier { return nil } // RegisterQueryService registers a GRPC query service to respond to the // module-specific GRPC queries. diff --git a/x/crisis/types/msgs.go b/x/crisis/types/msgs.go index 97446f07d..3487d229d 100644 --- a/x/crisis/types/msgs.go +++ b/x/crisis/types/msgs.go @@ -24,7 +24,7 @@ func (msg MsgVerifyInvariant) GetSigners() []sdk.AccAddress { return []sdk.AccAd // GetSignBytes gets the sign bytes for the msg MsgVerifyInvariant func (msg MsgVerifyInvariant) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } diff --git a/x/distribution/client/cli/cli_test.go b/x/distribution/client/cli/cli_test.go index e565e0913..0b6fea8c6 100644 --- a/x/distribution/client/cli/cli_test.go +++ b/x/distribution/client/cli/cli_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" tmcli "github.com/tendermint/tendermint/libs/cli" @@ -456,7 +457,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawRewardsCmd() { valAddr fmt.Stringer args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -525,7 +526,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawAllRewardsCmd() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -578,7 +579,7 @@ func (s *IntegrationTestSuite) TestNewSetWithdrawAddrCmd() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -633,7 +634,7 @@ func (s *IntegrationTestSuite) TestNewFundCommunityPoolCmd() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -718,7 +719,7 @@ func (s *IntegrationTestSuite) TestGetCmdSubmitProposal() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { diff --git a/x/distribution/client/common/common.go b/x/distribution/client/common/common.go index c7034a876..a2d5fceda 100644 --- a/x/distribution/client/common/common.go +++ b/x/distribution/client/common/common.go @@ -22,7 +22,7 @@ func QueryDelegationRewards(clientCtx client.Context, delAddr, valAddr string) ( } params := types.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if err != nil { return nil, 0, fmt.Errorf("failed to marshal params: %w", err) } @@ -45,7 +45,7 @@ func QueryDelegatorValidators(clientCtx client.Context, delegatorAddr sdk.AccAdd func QueryValidatorCommission(clientCtx client.Context, validatorAddr sdk.ValAddress) ([]byte, error) { res, _, err := clientCtx.QueryWithData( fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidatorCommission), - clientCtx.JSONMarshaler.MustMarshalJSON(types.NewQueryValidatorCommissionParams(validatorAddr)), + clientCtx.LegacyAmino.MustMarshalJSON(types.NewQueryValidatorCommissionParams(validatorAddr)), ) return res, err } diff --git a/x/distribution/client/common/common_test.go b/x/distribution/client/common/common_test.go index 9adef2662..6b3ecdd5c 100644 --- a/x/distribution/client/common/common_test.go +++ b/x/distribution/client/common/common_test.go @@ -10,7 +10,7 @@ import ( ) func TestQueryDelegationRewardsAddrValidation(t *testing.T) { - clientCtx := client.Context{}.WithJSONMarshaler(types.ModuleCdc) + clientCtx := client.Context{}.WithLegacyAmino(types.ModuleCdc.LegacyAmino) type args struct { delAddr string diff --git a/x/distribution/client/rest/query.go b/x/distribution/client/rest/query.go index 9f90e31f5..0fb923afc 100644 --- a/x/distribution/client/rest/query.go +++ b/x/distribution/client/rest/query.go @@ -79,7 +79,7 @@ func delegatorRewardsHandlerFn(clientCtx client.Context) http.HandlerFunc { } params := types.NewQueryDelegatorParams(delegatorAddr) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("failed to marshal params: %s", err)) return @@ -131,7 +131,7 @@ func delegatorWithdrawalAddrHandlerFn(clientCtx client.Context) http.HandlerFunc return } - bz := clientCtx.JSONMarshaler.MustMarshalJSON(types.NewQueryDelegatorWithdrawAddrParams(delegatorAddr)) + bz := clientCtx.LegacyAmino.MustMarshalJSON(types.NewQueryDelegatorWithdrawAddrParams(delegatorAddr)) res, height, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/withdraw_addr", types.QuerierRoute), bz) if rest.CheckInternalServerError(w, err) { return @@ -180,7 +180,7 @@ func validatorInfoHandlerFn(clientCtx client.Context) http.HandlerFunc { } var commission types.ValidatorAccumulatedCommission - if rest.CheckInternalServerError(w, clientCtx.JSONMarshaler.UnmarshalJSON(bz, &commission)) { + if rest.CheckInternalServerError(w, clientCtx.LegacyAmino.UnmarshalJSON(bz, &commission)) { return } @@ -192,11 +192,11 @@ func validatorInfoHandlerFn(clientCtx client.Context) http.HandlerFunc { } var rewards sdk.DecCoins - if rest.CheckInternalServerError(w, clientCtx.JSONMarshaler.UnmarshalJSON(bz, &rewards)) { + if rest.CheckInternalServerError(w, clientCtx.LegacyAmino.UnmarshalJSON(bz, &rewards)) { return } - bz, err = clientCtx.JSONMarshaler.MarshalJSON(NewValidatorDistInfo(delAddr, rewards, commission)) + bz, err = clientCtx.LegacyAmino.MarshalJSON(NewValidatorDistInfo(delAddr, rewards, commission)) if rest.CheckInternalServerError(w, err) { return } @@ -263,7 +263,7 @@ func communityPoolHandler(clientCtx client.Context) http.HandlerFunc { } var result sdk.DecCoins - if rest.CheckInternalServerError(w, clientCtx.JSONMarshaler.UnmarshalJSON(res, &result)) { + if rest.CheckInternalServerError(w, clientCtx.LegacyAmino.UnmarshalJSON(res, &result)) { return } @@ -285,7 +285,7 @@ func outstandingRewardsHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - bin := clientCtx.JSONMarshaler.MustMarshalJSON(types.NewQueryValidatorOutstandingRewardsParams(validatorAddr)) + bin := clientCtx.LegacyAmino.MustMarshalJSON(types.NewQueryValidatorOutstandingRewardsParams(validatorAddr)) res, height, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/validator_outstanding_rewards", types.QuerierRoute), bin) if rest.CheckInternalServerError(w, err) { return diff --git a/x/distribution/keeper/querier.go b/x/distribution/keeper/querier.go index 78662796c..e2621eec2 100644 --- a/x/distribution/keeper/querier.go +++ b/x/distribution/keeper/querier.go @@ -12,7 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/exported" ) -func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { switch path[0] { case types.QueryParams: @@ -48,7 +48,7 @@ func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { } } -func queryParams(ctx sdk.Context, _ []string, _ abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryParams(ctx sdk.Context, _ []string, _ abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { params := k.GetParams(ctx) res, err := codec.MarshalJSONIndent(legacyQuerierCdc, params) @@ -59,7 +59,7 @@ func queryParams(ctx sdk.Context, _ []string, _ abci.RequestQuery, k Keeper, leg return res, nil } -func queryValidatorOutstandingRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryValidatorOutstandingRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryValidatorOutstandingRewardsParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -79,7 +79,7 @@ func queryValidatorOutstandingRewards(ctx sdk.Context, _ []string, req abci.Requ return bz, nil } -func queryValidatorCommission(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryValidatorCommission(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryValidatorCommissionParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -99,7 +99,7 @@ func queryValidatorCommission(ctx sdk.Context, _ []string, req abci.RequestQuery return bz, nil } -func queryValidatorSlashes(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryValidatorSlashes(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryValidatorSlashesParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -122,7 +122,7 @@ func queryValidatorSlashes(ctx sdk.Context, _ []string, req abci.RequestQuery, k return bz, nil } -func queryDelegationRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryDelegationRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDelegationRewardsParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -156,7 +156,7 @@ func queryDelegationRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, return bz, nil } -func queryDelegatorTotalRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryDelegatorTotalRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDelegatorParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -194,7 +194,7 @@ func queryDelegatorTotalRewards(ctx sdk.Context, _ []string, req abci.RequestQue return bz, nil } -func queryDelegatorValidators(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryDelegatorValidators(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDelegatorParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -222,7 +222,7 @@ func queryDelegatorValidators(ctx sdk.Context, _ []string, req abci.RequestQuery return bz, nil } -func queryDelegatorWithdrawAddress(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryDelegatorWithdrawAddress(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDelegatorWithdrawAddrParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -241,7 +241,7 @@ func queryDelegatorWithdrawAddress(ctx sdk.Context, _ []string, req abci.Request return bz, nil } -func queryCommunityPool(ctx sdk.Context, _ []string, _ abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryCommunityPool(ctx sdk.Context, _ []string, _ abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { pool := k.GetFeePoolCommunityCoins(ctx) if pool == nil { pool = sdk.DecCoins{} diff --git a/x/distribution/keeper/querier_test.go b/x/distribution/keeper/querier_test.go index 39cddc2a1..2a30c7bc9 100644 --- a/x/distribution/keeper/querier_test.go +++ b/x/distribution/keeper/querier_test.go @@ -114,7 +114,6 @@ func TestQueries(t *testing.T) { cdc := codec.New() types.RegisterCodec(cdc) banktypes.RegisterCodec(cdc) - legacyQuerierCdc := codec.NewAminoCodec(cdc) app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) @@ -123,7 +122,7 @@ func TestQueries(t *testing.T) { valAddrs := simapp.ConvertAddrsToValAddrs(addr) valOpAddr1 := valAddrs[0] - querier := keeper.NewQuerier(app.DistrKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.DistrKeeper, cdc) // test param queries params := types.Params{ diff --git a/x/distribution/module.go b/x/distribution/module.go index d33fc0ef3..16072f5b5 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -133,7 +133,7 @@ func (AppModule) QuerierRoute() string { } // LegacyQuerierHandler returns the distribution module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return keeper.NewQuerier(am.keeper, legacyQuerierCdc) } diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index e4b79bdbb..3f64d5c01 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -3,11 +3,10 @@ package simulation // DONTCOVER import ( + "encoding/json" "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/distribution/types" @@ -77,6 +76,10 @@ func RandomizedGenState(simState *module.SimulationState) { }, } - fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.Cdc, &distrGenesis)) + bz, err := json.MarshalIndent(&distrGenesis, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", bz) simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&distrGenesis) } diff --git a/x/distribution/simulation/genesis_test.go b/x/distribution/simulation/genesis_test.go index 2ee2464b6..e923fbd4c 100644 --- a/x/distribution/simulation/genesis_test.go +++ b/x/distribution/simulation/genesis_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -18,7 +19,8 @@ import ( // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. // Abonormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) s := rand.NewSource(1) r := rand.New(s) @@ -52,7 +54,8 @@ func TestRandomizedGenState(t *testing.T) { // TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) s := rand.NewSource(1) r := rand.New(s) diff --git a/x/distribution/types/msg.go b/x/distribution/types/msg.go index 8fa3aa4ce..1ba548a7b 100644 --- a/x/distribution/types/msg.go +++ b/x/distribution/types/msg.go @@ -34,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 := ModuleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -67,7 +67,7 @@ func (msg MsgWithdrawDelegatorReward) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgWithdrawDelegatorReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -98,7 +98,7 @@ func (msg MsgWithdrawValidatorCommission) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgWithdrawValidatorCommission) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -134,7 +134,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 := ModuleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } diff --git a/x/evidence/client/rest/query.go b/x/evidence/client/rest/query.go index bc74cd300..21ae8b7bb 100644 --- a/x/evidence/client/rest/query.go +++ b/x/evidence/client/rest/query.go @@ -77,7 +77,7 @@ func queryAllEvidenceHandler(clientCtx client.Context) http.HandlerFunc { } params := types.NewQueryAllEvidenceParams(page, limit) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("failed to marshal query params: %s", err)) return diff --git a/x/evidence/keeper/keeper_test.go b/x/evidence/keeper/keeper_test.go index 849676e38..664ea9595 100644 --- a/x/evidence/keeper/keeper_test.go +++ b/x/evidence/keeper/keeper_test.go @@ -12,7 +12,6 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -82,7 +81,6 @@ type KeeperTestSuite struct { func (suite *KeeperTestSuite) SetupTest() { checkTx := false app := simapp.Setup(checkTx) - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) // recreate keeper in order to use custom testing types evidenceKeeper := keeper.NewKeeper( @@ -95,7 +93,7 @@ func (suite *KeeperTestSuite) SetupTest() { app.EvidenceKeeper = *evidenceKeeper suite.ctx = app.BaseApp.NewContext(checkTx, tmproto.Header{Height: 1}) - suite.querier = keeper.NewQuerier(*evidenceKeeper, legacyQuerierCdc) + suite.querier = keeper.NewQuerier(*evidenceKeeper, app.LegacyAmino()) suite.app = app for i, addr := range valAddresses { diff --git a/x/evidence/keeper/querier.go b/x/evidence/keeper/querier.go index a07576b32..c1ae20d4d 100644 --- a/x/evidence/keeper/querier.go +++ b/x/evidence/keeper/querier.go @@ -11,7 +11,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) -func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { var ( res []byte @@ -33,7 +33,7 @@ func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { } } -func queryEvidence(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryEvidence(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryEvidenceRequest err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -54,7 +54,7 @@ func queryEvidence(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQueri return res, nil } -func queryAllEvidence(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryAllEvidence(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryAllEvidenceParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) diff --git a/x/evidence/module.go b/x/evidence/module.go index e9997a5e2..27ed4812d 100644 --- a/x/evidence/module.go +++ b/x/evidence/module.go @@ -143,7 +143,7 @@ func (AppModule) QuerierRoute() string { } // LegacyQuerierHandler returns the evidence module's Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return keeper.NewQuerier(am.keeper, legacyQuerierCdc) } diff --git a/x/evidence/simulation/genesis.go b/x/evidence/simulation/genesis.go index 9d1aa4c6c..640670ebe 100644 --- a/x/evidence/simulation/genesis.go +++ b/x/evidence/simulation/genesis.go @@ -3,11 +3,10 @@ package simulation // DONTCOVER import ( + "encoding/json" "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/evidence/exported" @@ -33,6 +32,10 @@ func RandomizedGenState(simState *module.SimulationState) { evidenceGenesis := types.NewGenesisState(ev) - fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, codec.MustMarshalJSONIndent(simState.Cdc, evidenceGenesis)) + bz, err := json.MarshalIndent(&evidenceGenesis, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, bz) simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(evidenceGenesis) } diff --git a/x/evidence/simulation/genesis_test.go b/x/evidence/simulation/genesis_test.go index 633f7a8e0..8cfa086ad 100644 --- a/x/evidence/simulation/genesis_test.go +++ b/x/evidence/simulation/genesis_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/evidence/simulation" @@ -17,7 +18,8 @@ import ( // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. // Abonormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) s := rand.NewSource(1) r := rand.New(s) diff --git a/x/evidence/types/msgs.go b/x/evidence/types/msgs.go index aca411ef9..c7ec4a8be 100644 --- a/x/evidence/types/msgs.go +++ b/x/evidence/types/msgs.go @@ -61,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(ModuleCdc.MustMarshalJSON(m)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } // GetSigners returns the single expected signer for a MsgSubmitEvidence. diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index 4cba36598..2adaf4a62 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -17,6 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/mock" @@ -61,7 +62,12 @@ func TestInitCmd(t *testing.T) { require.NoError(t, err) serverCtx := server.NewContext(viper.New(), cfg, logger) - clientCtx := client.Context{}.WithJSONMarshaler(makeCodec()).WithHomeDir(home) + interfaceRegistry := types.NewInterfaceRegistry() + marshaler := codec.NewProtoCodec(interfaceRegistry) + clientCtx := client.Context{}. + WithJSONMarshaler(marshaler). + WithLegacyAmino(makeCodec()). + WithHomeDir(home) ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) @@ -99,7 +105,12 @@ func TestEmptyState(t *testing.T) { require.NoError(t, err) serverCtx := server.NewContext(viper.New(), cfg, logger) - clientCtx := client.Context{}.WithJSONMarshaler(makeCodec()).WithHomeDir(home) + interfaceRegistry := types.NewInterfaceRegistry() + marshaler := codec.NewProtoCodec(interfaceRegistry) + clientCtx := client.Context{}. + WithJSONMarshaler(marshaler). + WithLegacyAmino(makeCodec()). + WithHomeDir(home) ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) @@ -142,7 +153,9 @@ func TestStartStandAlone(t *testing.T) { t.Cleanup(setupClientHome(t)) logger := log.NewNopLogger() - err := genutiltest.ExecInitCmd(testMbm, home, makeCodec()) + interfaceRegistry := types.NewInterfaceRegistry() + marshaler := codec.NewProtoCodec(interfaceRegistry) + err := genutiltest.ExecInitCmd(testMbm, home, marshaler) require.NoError(t, err) app, err := mock.NewApp(home, logger) diff --git a/x/genutil/client/cli/migrate.go b/x/genutil/client/cli/migrate.go index 675e55c7c..151beef12 100644 --- a/x/genutil/client/cli/migrate.go +++ b/x/genutil/client/cli/migrate.go @@ -10,7 +10,6 @@ import ( "github.com/spf13/cobra" tmtypes "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" @@ -66,9 +65,6 @@ $ %s migrate v0.36 /path/to/genesis.json --chain-id=cosmoshub-3 --genesis-time=2 `, version.AppName), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - clientCtx := client.GetClientContextFromCmd(cmd) - cdc := clientCtx.JSONMarshaler - var err error target := args[0] @@ -80,7 +76,7 @@ $ %s migrate v0.36 /path/to/genesis.json --chain-id=cosmoshub-3 --genesis-time=2 } var initialState types.AppMap - if err := cdc.UnmarshalJSON(genDoc.AppState, &initialState); err != nil { + if err := json.Unmarshal(genDoc.AppState, &initialState); err != nil { return errors.Wrap(err, "failed to JSON unmarshal initial genesis state") } @@ -92,7 +88,7 @@ $ %s migrate v0.36 /path/to/genesis.json --chain-id=cosmoshub-3 --genesis-time=2 // TODO: handler error from migrationFunc call newGenState := migrationFunc(initialState) - genDoc.AppState, err = cdc.MarshalJSON(newGenState) + genDoc.AppState, err = json.Marshal(newGenState) if err != nil { return errors.Wrap(err, "failed to JSON marshal migrated genesis state") } diff --git a/x/genutil/client/cli/migrate_test.go b/x/genutil/client/cli/migrate_test.go index 941721d22..95506fb3c 100644 --- a/x/genutil/client/cli/migrate_test.go +++ b/x/genutil/client/cli/migrate_test.go @@ -31,7 +31,7 @@ func TestMigrateGenesis(t *testing.T) { cmd := cli.MigrateGenesisCmd() _ = testutil.ApplyMockIODiscardOutErr(cmd) - clientCtx := client.Context{}.WithJSONMarshaler(cdc) + clientCtx := client.Context{}.WithLegacyAmino(cdc) ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) diff --git a/x/genutil/client/cli/validate_genesis.go b/x/genutil/client/cli/validate_genesis.go index 756b06a26..a2e148b24 100644 --- a/x/genutil/client/cli/validate_genesis.go +++ b/x/genutil/client/cli/validate_genesis.go @@ -41,7 +41,7 @@ func ValidateGenesisCmd(mbm module.BasicManager, txEncCfg client.TxEncodingConfi } var genState map[string]json.RawMessage - if err = cdc.UnmarshalJSON(genDoc.AppState, &genState); err != nil { + if err = json.Unmarshal(genDoc.AppState, &genState); err != nil { return fmt.Errorf("error unmarshalling genesis doc %s: %s", genesis, err.Error()) } diff --git a/x/genutil/client/rest/query.go b/x/genutil/client/rest/query.go index e66071a87..7361c4672 100644 --- a/x/genutil/client/rest/query.go +++ b/x/genutil/client/rest/query.go @@ -31,10 +31,10 @@ func QueryGenesisTxs(clientCtx client.Context, w http.ResponseWriter) { return } - genState := types.GetGenesisStateFromAppState(clientCtx.LegacyAmino, appState) + genState := types.GetGenesisStateFromAppState(clientCtx.JSONMarshaler, appState) genTxs := make([]sdk.Tx, len(genState.GenTxs)) for i, tx := range genState.GenTxs { - err := clientCtx.JSONMarshaler.UnmarshalJSON(tx, &genTxs[i]) + err := clientCtx.LegacyAmino.UnmarshalJSON(tx, &genTxs[i]) if err != nil { rest.WriteErrorResponse( w, http.StatusInternalServerError, diff --git a/x/genutil/types/genesis_state.go b/x/genutil/types/genesis_state.go index a7915b717..b3e28bb6d 100644 --- a/x/genutil/types/genesis_state.go +++ b/x/genutil/types/genesis_state.go @@ -80,7 +80,7 @@ func GenesisStateFromGenDoc(genDoc tmtypes.GenesisDoc) (genesisState map[string] // for the application. // // NOTE: The pubkey input is this machines pubkey. -func GenesisStateFromGenFile(cdc codec.JSONMarshaler, genFile string) (genesisState map[string]json.RawMessage, genDoc *tmtypes.GenesisDoc, err error) { +func GenesisStateFromGenFile(genFile string) (genesisState map[string]json.RawMessage, genDoc *tmtypes.GenesisDoc, err error) { if !tmos.FileExists(genFile) { return genesisState, genDoc, fmt.Errorf("%s does not exist, run `init` first", genFile) diff --git a/x/genutil/types/genesis_state_test.go b/x/genutil/types/genesis_state_test.go index adb771548..5d2b2d862 100644 --- a/x/genutil/types/genesis_state_test.go +++ b/x/genutil/types/genesis_state_test.go @@ -76,7 +76,7 @@ func TestGenesisStateFromGenFile(t *testing.T) { cdc := codec.New() genFile := "../../../tests/fixtures/adr-024-coin-metadata_genesis.json" - genesisState, _, err := types.GenesisStateFromGenFile(cdc, genFile) + genesisState, _, err := types.GenesisStateFromGenFile(genFile) require.NoError(t, err) var bankGenesis banktypes.GenesisState diff --git a/x/gov/client/cli/cli_test.go b/x/gov/client/cli/cli_test.go index b3cb6165a..ae60494ff 100644 --- a/x/gov/client/cli/cli_test.go +++ b/x/gov/client/cli/cli_test.go @@ -6,6 +6,7 @@ import ( "os" "testing" + "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" "github.com/cosmos/cosmos-sdk/client/flags" @@ -76,7 +77,7 @@ func (s *IntegrationTestSuite) TestNewCmdSubmitProposal() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index 48af66a62..26a2efd6a 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -297,7 +297,9 @@ $ %[1]s query gov votes 1 --page=2 --limit=100 } var votes types.Votes - clientCtx.JSONMarshaler.MustUnmarshalJSON(resByTxQuery, &votes) + // TODO migrate to use JSONMarshaler (implement MarshalJSONArray + // or wrap lists of proto.Message in some other message) + clientCtx.LegacyAmino.MustUnmarshalJSON(resByTxQuery, &votes) return clientCtx.PrintOutputLegacy(votes) } @@ -446,7 +448,9 @@ $ %s query gov deposits 1 } var dep types.Deposits - clientCtx.JSONMarshaler.MustUnmarshalJSON(resByTxQuery, &dep) + // TODO migrate to use JSONMarshaler (implement MarshalJSONArray + // or wrap lists of proto.Message in some other message) + clientCtx.LegacyAmino.MustUnmarshalJSON(resByTxQuery, &dep) return clientCtx.PrintOutputLegacy(dep) } diff --git a/x/gov/client/rest/query.go b/x/gov/client/rest/query.go index 7c7228a3b..d526629be 100644 --- a/x/gov/client/rest/query.go +++ b/x/gov/client/rest/query.go @@ -69,7 +69,7 @@ func queryProposalHandlerFn(clientCtx client.Context) http.HandlerFunc { params := types.NewQueryProposalParams(proposalID) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } @@ -101,7 +101,7 @@ func queryDepositsHandlerFn(clientCtx client.Context) http.HandlerFunc { params := types.NewQueryProposalParams(proposalID) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } @@ -112,7 +112,7 @@ func queryDepositsHandlerFn(clientCtx client.Context) http.HandlerFunc { } var proposal types.Proposal - if rest.CheckInternalServerError(w, clientCtx.JSONMarshaler.UnmarshalJSON(res, &proposal)) { + if rest.CheckInternalServerError(w, clientCtx.LegacyAmino.UnmarshalJSON(res, &proposal)) { return } @@ -192,7 +192,7 @@ func queryDepositHandlerFn(clientCtx client.Context) http.HandlerFunc { params := types.NewQueryDepositParams(proposalID, depositorAddr) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } @@ -203,7 +203,7 @@ func queryDepositHandlerFn(clientCtx client.Context) http.HandlerFunc { } var deposit types.Deposit - if rest.CheckBadRequestError(w, clientCtx.JSONMarshaler.UnmarshalJSON(res, &deposit)) { + if rest.CheckBadRequestError(w, clientCtx.LegacyAmino.UnmarshalJSON(res, &deposit)) { return } @@ -211,7 +211,7 @@ func queryDepositHandlerFn(clientCtx client.Context) http.HandlerFunc { // which case the deposit would be removed from state and should be queried // for directly via a txs query. if deposit.Empty() { - bz, err := clientCtx.JSONMarshaler.MarshalJSON(types.NewQueryProposalParams(proposalID)) + bz, err := clientCtx.LegacyAmino.MarshalJSON(types.NewQueryProposalParams(proposalID)) if rest.CheckBadRequestError(w, err) { return } @@ -269,7 +269,7 @@ func queryVoteHandlerFn(clientCtx client.Context) http.HandlerFunc { params := types.NewQueryVoteParams(proposalID, voterAddr) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } @@ -280,7 +280,7 @@ func queryVoteHandlerFn(clientCtx client.Context) http.HandlerFunc { } var vote types.Vote - if rest.CheckBadRequestError(w, clientCtx.JSONMarshaler.UnmarshalJSON(res, &vote)) { + if rest.CheckBadRequestError(w, clientCtx.LegacyAmino.UnmarshalJSON(res, &vote)) { return } @@ -288,7 +288,7 @@ func queryVoteHandlerFn(clientCtx client.Context) http.HandlerFunc { // which case the vote would be removed from state and should be queried for // directly via a txs query. if vote.Empty() { - bz, err := clientCtx.JSONMarshaler.MarshalJSON(types.NewQueryProposalParams(proposalID)) + bz, err := clientCtx.LegacyAmino.MarshalJSON(types.NewQueryProposalParams(proposalID)) if rest.CheckBadRequestError(w, err) { return } @@ -339,7 +339,7 @@ func queryVotesOnProposalHandlerFn(clientCtx client.Context) http.HandlerFunc { params := types.NewQueryProposalVotesParams(proposalID, page, limit) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } @@ -350,7 +350,7 @@ func queryVotesOnProposalHandlerFn(clientCtx client.Context) http.HandlerFunc { } var proposal types.Proposal - if rest.CheckInternalServerError(w, clientCtx.JSONMarshaler.UnmarshalJSON(res, &proposal)) { + if rest.CheckInternalServerError(w, clientCtx.LegacyAmino.UnmarshalJSON(res, &proposal)) { return } @@ -412,7 +412,7 @@ func queryProposalsWithParameterFn(clientCtx client.Context) http.HandlerFunc { } params := types.NewQueryProposalsParams(page, limit, proposalStatus, voterAddr, depositorAddr) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } @@ -452,7 +452,7 @@ func queryTallyOnProposalHandlerFn(clientCtx client.Context) http.HandlerFunc { params := types.NewQueryProposalParams(proposalID) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } diff --git a/x/gov/client/utils/query.go b/x/gov/client/utils/query.go index ced02a9e3..9c62ac865 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -65,7 +65,7 @@ func QueryDepositsByTxQuery(clientCtx client.Context, params types.QueryProposal } } - bz, err := clientCtx.JSONMarshaler.MarshalJSON(deposits) + bz, err := clientCtx.LegacyAmino.MarshalJSON(deposits) if err != nil { return nil, err } @@ -117,7 +117,7 @@ func QueryVotesByTxQuery(clientCtx client.Context, params types.QueryProposalVot votes = votes[start:end] } - bz, err := clientCtx.JSONMarshaler.MarshalJSON(votes) + bz, err := clientCtx.LegacyAmino.MarshalJSON(votes) if err != nil { return nil, err } @@ -151,7 +151,7 @@ func QueryVoteByTxQuery(clientCtx client.Context, params types.QueryVoteParams) Option: voteMsg.Option, } - bz, err := clientCtx.JSONMarshaler.MarshalJSON(vote) + bz, err := clientCtx.JSONMarshaler.MarshalJSON(&vote) if err != nil { return nil, err } @@ -192,7 +192,7 @@ func QueryDepositByTxQuery(clientCtx client.Context, params types.QueryDepositPa Amount: depMsg.Amount, } - bz, err := clientCtx.JSONMarshaler.MarshalJSON(deposit) + bz, err := clientCtx.JSONMarshaler.MarshalJSON(&deposit) if err != nil { return nil, err } @@ -236,7 +236,7 @@ func QueryProposerByTxQuery(clientCtx client.Context, proposalID uint64) (Propos // QueryProposalByID takes a proposalID and returns a proposal func QueryProposalByID(proposalID uint64, clientCtx client.Context, queryRoute string) ([]byte, error) { params := types.NewQueryProposalParams(proposalID) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if err != nil { return nil, err } diff --git a/x/gov/client/utils/query_test.go b/x/gov/client/utils/query_test.go index 272251538..3a448c2f5 100644 --- a/x/gov/client/utils/query_test.go +++ b/x/gov/client/utils/query_test.go @@ -154,7 +154,6 @@ func TestGetPaginatedVotes(t *testing.T) { cli := TxSearchMock{txs: marshalled} clientCtx := client.Context{}. - WithJSONMarshaler(cdc). WithLegacyAmino(cdc). WithClient(cli) @@ -162,7 +161,7 @@ func TestGetPaginatedVotes(t *testing.T) { votesData, err := QueryVotesByTxQuery(clientCtx, params) require.NoError(t, err) votes := []types.Vote{} - require.NoError(t, clientCtx.JSONMarshaler.UnmarshalJSON(votesData, &votes)) + require.NoError(t, clientCtx.LegacyAmino.UnmarshalJSON(votesData, &votes)) require.Equal(t, len(tc.votes), len(votes)) for i := range votes { require.Equal(t, tc.votes[i], votes[i]) diff --git a/x/gov/keeper/querier.go b/x/gov/keeper/querier.go index af1a20270..6eb343d07 100644 --- a/x/gov/keeper/querier.go +++ b/x/gov/keeper/querier.go @@ -11,7 +11,7 @@ import ( ) // NewQuerier creates a new gov Querier instance -func NewQuerier(keeper Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func NewQuerier(keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { switch path[0] { case types.QueryParams: @@ -44,7 +44,7 @@ func NewQuerier(keeper Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier } } -func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { switch path[0] { case types.ParamDeposit: bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, keeper.GetDepositParams(ctx)) @@ -73,7 +73,7 @@ func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, keeper K } // nolint: unparam -func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -94,7 +94,7 @@ func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper } // nolint: unparam -func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDepositParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -111,7 +111,7 @@ func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper } // nolint: unparam -func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryVoteParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -128,7 +128,7 @@ func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Kee } // nolint: unparam -func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -149,7 +149,7 @@ func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper } // nolint: unparam -func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -186,7 +186,7 @@ func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Ke } // nolint: unparam -func queryVotes(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryVotes(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryProposalVotesParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -213,7 +213,7 @@ func queryVotes(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Ke return bz, nil } -func queryProposals(ctx sdk.Context, _ []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryProposals(ctx sdk.Context, _ []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryProposalsParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index bb984959f..ea529c61f 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -19,7 +19,7 @@ import ( const custom = "custom" -func getQueriedParams(t *testing.T, ctx sdk.Context, cdc codec.JSONMarshaler, querier sdk.Querier) (types.DepositParams, types.VotingParams, types.TallyParams) { +func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier) (types.DepositParams, types.VotingParams, types.TallyParams) { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamDeposit}, "/"), Data: []byte{}, @@ -60,7 +60,7 @@ func getQueriedParams(t *testing.T, ctx sdk.Context, cdc codec.JSONMarshaler, qu } func getQueriedProposals( - t *testing.T, ctx sdk.Context, cdc codec.JSONMarshaler, querier sdk.Querier, + t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, depositor, voter sdk.AccAddress, status types.ProposalStatus, page, limit int, ) []types.Proposal { @@ -79,7 +79,7 @@ func getQueriedProposals( return proposals } -func getQueriedDeposit(t *testing.T, ctx sdk.Context, cdc codec.JSONMarshaler, querier sdk.Querier, proposalID uint64, depositor sdk.AccAddress) types.Deposit { +func getQueriedDeposit(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, proposalID uint64, depositor sdk.AccAddress) types.Deposit { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDeposit}, "/"), Data: cdc.MustMarshalJSON(types.NewQueryDepositParams(proposalID, depositor)), @@ -95,7 +95,7 @@ func getQueriedDeposit(t *testing.T, ctx sdk.Context, cdc codec.JSONMarshaler, q return deposit } -func getQueriedDeposits(t *testing.T, ctx sdk.Context, cdc codec.JSONMarshaler, querier sdk.Querier, proposalID uint64) []types.Deposit { +func getQueriedDeposits(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, proposalID uint64) []types.Deposit { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDeposits}, "/"), Data: cdc.MustMarshalJSON(types.NewQueryProposalParams(proposalID)), @@ -111,7 +111,7 @@ func getQueriedDeposits(t *testing.T, ctx sdk.Context, cdc codec.JSONMarshaler, return deposits } -func getQueriedVote(t *testing.T, ctx sdk.Context, cdc codec.JSONMarshaler, querier sdk.Querier, proposalID uint64, voter sdk.AccAddress) types.Vote { +func getQueriedVote(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, proposalID uint64, voter sdk.AccAddress) types.Vote { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryVote}, "/"), Data: cdc.MustMarshalJSON(types.NewQueryVoteParams(proposalID, voter)), @@ -127,7 +127,7 @@ func getQueriedVote(t *testing.T, ctx sdk.Context, cdc codec.JSONMarshaler, quer return vote } -func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc codec.JSONMarshaler, querier sdk.Querier, +func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, proposalID uint64, page, limit int) []types.Vote { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryVote}, "/"), @@ -147,8 +147,7 @@ func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc codec.JSONMarshaler, que func TestQueries(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - appCodec := legacyQuerierCdc + legacyQuerierCdc := app.LegacyAmino() querier := keeper.NewQuerier(app.GovKeeper, legacyQuerierCdc) TestAddrs := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(20000001)) @@ -158,7 +157,7 @@ func TestQueries(t *testing.T) { tp := TestProposal - depositParams, _, _ := getQueriedParams(t, ctx, appCodec, querier) + depositParams, _, _ := getQueriedParams(t, ctx, legacyQuerierCdc, querier) // TestAddrs[0] proposes (and deposits) proposals #1 and #2 proposal1, err := app.GovKeeper.SubmitProposal(ctx, tp) @@ -206,35 +205,36 @@ func TestQueries(t *testing.T) { deposit5.Amount = deposit5.Amount.Add(deposit3.Amount...) // check deposits on proposal1 match individual deposits - deposits := getQueriedDeposits(t, ctx, appCodec, querier, proposal1.ProposalId) + + deposits := getQueriedDeposits(t, ctx, legacyQuerierCdc, querier, proposal1.ProposalId) require.Len(t, deposits, 1) require.Equal(t, deposit1, deposits[0]) - deposit := getQueriedDeposit(t, ctx, appCodec, querier, proposal1.ProposalId, TestAddrs[0]) + deposit := getQueriedDeposit(t, ctx, legacyQuerierCdc, querier, proposal1.ProposalId, TestAddrs[0]) require.Equal(t, deposit1, deposit) // check deposits on proposal2 match individual deposits - deposits = getQueriedDeposits(t, ctx, appCodec, querier, proposal2.ProposalId) + deposits = getQueriedDeposits(t, ctx, legacyQuerierCdc, querier, proposal2.ProposalId) require.Len(t, deposits, 2) // NOTE order of deposits is determined by the addresses require.Equal(t, deposit2, deposits[0]) require.Equal(t, deposit4, deposits[1]) // check deposits on proposal3 match individual deposits - deposits = getQueriedDeposits(t, ctx, appCodec, querier, proposal3.ProposalId) + deposits = getQueriedDeposits(t, ctx, legacyQuerierCdc, querier, proposal3.ProposalId) require.Len(t, deposits, 1) require.Equal(t, deposit5, deposits[0]) - deposit = getQueriedDeposit(t, ctx, appCodec, querier, proposal3.ProposalId, TestAddrs[1]) + deposit = getQueriedDeposit(t, ctx, legacyQuerierCdc, querier, proposal3.ProposalId, TestAddrs[1]) require.Equal(t, deposit5, deposit) // Only proposal #1 should be in types.Deposit Period - proposals := getQueriedProposals(t, ctx, appCodec, querier, nil, nil, types.StatusDepositPeriod, 1, 0) + proposals := getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, nil, types.StatusDepositPeriod, 1, 0) require.Len(t, proposals, 1) require.Equal(t, proposal1, proposals[0]) // Only proposals #2 and #3 should be in Voting Period - proposals = getQueriedProposals(t, ctx, appCodec, querier, nil, nil, types.StatusVotingPeriod, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, nil, types.StatusVotingPeriod, 1, 0) require.Len(t, proposals, 2) require.Equal(t, proposal2, proposals[0]) require.Equal(t, proposal3, proposals[1]) @@ -250,45 +250,45 @@ func TestQueries(t *testing.T) { app.GovKeeper.SetVote(ctx, vote3) // Test query voted by TestAddrs[0] - proposals = getQueriedProposals(t, ctx, appCodec, querier, nil, TestAddrs[0], types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, TestAddrs[0], types.StatusNil, 1, 0) require.Equal(t, proposal2, proposals[0]) require.Equal(t, proposal3, proposals[1]) // Test query votes on types.Proposal 2 - votes := getQueriedVotes(t, ctx, appCodec, querier, proposal2.ProposalId, 1, 0) + votes := getQueriedVotes(t, ctx, legacyQuerierCdc, querier, proposal2.ProposalId, 1, 0) require.Len(t, votes, 1) require.Equal(t, vote1, votes[0]) - vote := getQueriedVote(t, ctx, appCodec, querier, proposal2.ProposalId, TestAddrs[0]) + vote := getQueriedVote(t, ctx, legacyQuerierCdc, querier, proposal2.ProposalId, TestAddrs[0]) require.Equal(t, vote1, vote) // Test query votes on types.Proposal 3 - votes = getQueriedVotes(t, ctx, appCodec, querier, proposal3.ProposalId, 1, 0) + votes = getQueriedVotes(t, ctx, legacyQuerierCdc, querier, proposal3.ProposalId, 1, 0) require.Len(t, votes, 2) require.Equal(t, vote2, votes[0]) require.Equal(t, vote3, votes[1]) // Test query all proposals - proposals = getQueriedProposals(t, ctx, appCodec, querier, nil, nil, types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, nil, types.StatusNil, 1, 0) require.Equal(t, proposal1, proposals[0]) require.Equal(t, proposal2, proposals[1]) require.Equal(t, proposal3, proposals[2]) // Test query voted by TestAddrs[1] - proposals = getQueriedProposals(t, ctx, appCodec, querier, nil, TestAddrs[1], types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, TestAddrs[1], types.StatusNil, 1, 0) require.Equal(t, proposal3.ProposalId, proposals[0].ProposalId) // Test query deposited by TestAddrs[0] - proposals = getQueriedProposals(t, ctx, appCodec, querier, TestAddrs[0], nil, types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, TestAddrs[0], nil, types.StatusNil, 1, 0) require.Equal(t, proposal1.ProposalId, proposals[0].ProposalId) // Test query deposited by addr2 - proposals = getQueriedProposals(t, ctx, appCodec, querier, TestAddrs[1], nil, types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, TestAddrs[1], nil, types.StatusNil, 1, 0) require.Equal(t, proposal2.ProposalId, proposals[0].ProposalId) require.Equal(t, proposal3.ProposalId, proposals[1].ProposalId) // Test query voted AND deposited by addr1 - proposals = getQueriedProposals(t, ctx, appCodec, querier, TestAddrs[0], TestAddrs[0], types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, TestAddrs[0], TestAddrs[0], types.StatusNil, 1, 0) require.Equal(t, proposal2.ProposalId, proposals[0].ProposalId) } diff --git a/x/gov/module.go b/x/gov/module.go index 7616eaee6..b0f43fb6e 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -150,7 +150,7 @@ func (AppModule) QuerierRoute() string { } // LegacyQuerierHandler returns no sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return keeper.NewQuerier(am.keeper, legacyQuerierCdc) } diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index 694c54e65..3f9ed2d08 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -3,12 +3,11 @@ package simulation // DONTCOVER import ( + "encoding/json" "fmt" "math/rand" "time" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/simulation" @@ -102,6 +101,10 @@ func RandomizedGenState(simState *module.SimulationState) { types.NewTallyParams(quorum, threshold, veto), ) - fmt.Printf("Selected randomly generated governance parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.Cdc, govGenesis)) + bz, err := json.MarshalIndent(&govGenesis, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("Selected randomly generated governance parameters:\n%s\n", bz) simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(govGenesis) } diff --git a/x/gov/simulation/genesis_test.go b/x/gov/simulation/genesis_test.go index 1df3202dd..46c86febb 100644 --- a/x/gov/simulation/genesis_test.go +++ b/x/gov/simulation/genesis_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -18,7 +19,9 @@ import ( // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. // Abonormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) + s := rand.NewSource(1) r := rand.New(s) @@ -48,14 +51,15 @@ func TestRandomizedGenState(t *testing.T) { require.Equal(t, dec2, govGenesis.TallyParams.Threshold) require.Equal(t, dec3, govGenesis.TallyParams.VetoThreshold) require.Equal(t, uint64(0x28), govGenesis.StartingProposalId) - require.Equal(t, types.Deposits(nil), govGenesis.Deposits) - require.Equal(t, types.Votes(nil), govGenesis.Votes) - require.Equal(t, types.Proposals(nil), govGenesis.Proposals) + require.Equal(t, types.Deposits{}, govGenesis.Deposits) + require.Equal(t, types.Votes{}, govGenesis.Votes) + require.Equal(t, types.Proposals{}, govGenesis.Proposals) } // TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) s := rand.NewSource(1) r := rand.New(s) @@ -68,9 +72,9 @@ func TestRandomizedGenState1(t *testing.T) { module.SimulationState{}, "invalid memory address or nil pointer dereference"}, { // panic => reason: incomplete initialization of the simState module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - Rand: r, + AppParams: make(simtypes.AppParams), + Cdc: cdc, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/gov/types/msgs.go b/x/gov/types/msgs.go index c6d57b87d..1770f1d74 100644 --- a/x/gov/types/msgs.go +++ b/x/gov/types/msgs.go @@ -121,7 +121,7 @@ func (m MsgSubmitProposal) ValidateBasic() error { // GetSignBytes implements Msg func (m MsgSubmitProposal) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(m) + bz := ModuleCdc.MustMarshalJSON(&m) return sdk.MustSortJSON(bz) } @@ -176,7 +176,7 @@ func (msg MsgDeposit) String() string { // GetSignBytes implements Msg func (msg MsgDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -216,7 +216,7 @@ func (msg MsgVote) String() string { // GetSignBytes implements Msg func (msg MsgVote) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } diff --git a/x/ibc-transfer/module.go b/x/ibc-transfer/module.go index 6ec3d81f4..6dcb3f47f 100644 --- a/x/ibc-transfer/module.go +++ b/x/ibc-transfer/module.go @@ -115,7 +115,7 @@ func (AppModule) QuerierRoute() string { } // LegacyQuerierHandler implements the AppModule interface -func (am AppModule) LegacyQuerierHandler(codec.JSONMarshaler) sdk.Querier { +func (am AppModule) LegacyQuerierHandler(*codec.LegacyAmino) sdk.Querier { return nil } diff --git a/x/ibc-transfer/simulation/genesis.go b/x/ibc-transfer/simulation/genesis.go index a0a5485ba..78db91c3e 100644 --- a/x/ibc-transfer/simulation/genesis.go +++ b/x/ibc-transfer/simulation/genesis.go @@ -1,11 +1,11 @@ package simulation import ( + "encoding/json" "fmt" "math/rand" "strings" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/ibc-transfer/types" @@ -45,6 +45,10 @@ func RandomizedGenState(simState *module.SimulationState) { Params: types.NewParams(sendEnabled, receiveEnabled), } - fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, codec.MustMarshalJSONIndent(simState.Cdc, &transferGenesis)) + bz, err := json.MarshalIndent(&transferGenesis, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, bz) simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&transferGenesis) } diff --git a/x/ibc-transfer/simulation/genesis_test.go b/x/ibc-transfer/simulation/genesis_test.go index 093997c94..c84cb4263 100644 --- a/x/ibc-transfer/simulation/genesis_test.go +++ b/x/ibc-transfer/simulation/genesis_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/ibc-transfer/simulation" @@ -17,7 +18,9 @@ import ( // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. // Abonormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) + s := rand.NewSource(1) r := rand.New(s) @@ -45,7 +48,8 @@ func TestRandomizedGenState(t *testing.T) { // TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) s := rand.NewSource(1) r := rand.New(s) diff --git a/x/ibc/03-connection/types/msgs.go b/x/ibc/03-connection/types/msgs.go index 8daf3a271..e4b8d0b6a 100644 --- a/x/ibc/03-connection/types/msgs.go +++ b/x/ibc/03-connection/types/msgs.go @@ -52,7 +52,7 @@ func (msg MsgConnectionOpenInit) ValidateBasic() error { // GetSignBytes implements sdk.Msg func (msg MsgConnectionOpenInit) GetSignBytes() []byte { - return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(&msg)) } // GetSigners implements sdk.Msg @@ -146,7 +146,7 @@ func (msg MsgConnectionOpenTry) ValidateBasic() error { // GetSignBytes implements sdk.Msg func (msg MsgConnectionOpenTry) GetSignBytes() []byte { - return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(&msg)) } // GetSigners implements sdk.Msg @@ -228,7 +228,7 @@ func (msg MsgConnectionOpenAck) ValidateBasic() error { // GetSignBytes implements sdk.Msg func (msg MsgConnectionOpenAck) GetSignBytes() []byte { - return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(&msg)) } // GetSigners implements sdk.Msg @@ -280,7 +280,7 @@ func (msg MsgConnectionOpenConfirm) ValidateBasic() error { // GetSignBytes implements sdk.Msg func (msg MsgConnectionOpenConfirm) GetSignBytes() []byte { - return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(&msg)) } // GetSigners implements sdk.Msg diff --git a/x/ibc/07-tendermint/client/cli/tx.go b/x/ibc/07-tendermint/client/cli/tx.go index a8fbe0c98..6e6c4b399 100644 --- a/x/ibc/07-tendermint/client/cli/tx.go +++ b/x/ibc/07-tendermint/client/cli/tx.go @@ -47,15 +47,16 @@ func NewCreateClientCmd() *cobra.Command { clientID := args[0] cdc := codec.NewProtoCodec(clientCtx.InterfaceRegistry) + legacyAmino := codec.New() var header *types.Header - if err := cdc.UnmarshalJSON([]byte(args[1]), &header); err != nil { + if err := cdc.UnmarshalJSON([]byte(args[1]), header); err != nil { // check for file path if JSON input is not provided contents, err := ioutil.ReadFile(args[1]) if err != nil { return errors.New("neither JSON input nor path to .json file were provided for consensus header") } - if err := cdc.UnmarshalJSON(contents, &header); err != nil { + if err := cdc.UnmarshalJSON(contents, header); err != nil { return errors.Wrap(err, "error unmarshalling consensus header file") } } @@ -94,13 +95,17 @@ func NewCreateClientCmd() *cobra.Command { spc, _ := cmd.Flags().GetString(flagProofSpecs) if spc == "default" { specs = commitmenttypes.GetSDKSpecs() - } else if err := cdc.UnmarshalJSON([]byte(spc), &specs); err != nil { + // TODO migrate to use JSONMarshaler (implement MarshalJSONArray + // or wrap lists of proto.Message in some other message) + } else if err := legacyAmino.UnmarshalJSON([]byte(spc), &specs); err != nil { // check for file path if JSON input not provided contents, err := ioutil.ReadFile(spc) if err != nil { return errors.New("neither JSON input nor path to .json file was provided for proof specs flag") } - if err := cdc.UnmarshalJSON(contents, &specs); err != nil { + // TODO migrate to use JSONMarshaler (implement MarshalJSONArray + // or wrap lists of proto.Message in some other message) + if err := legacyAmino.UnmarshalJSON(contents, &specs); err != nil { return errors.Wrap(err, "error unmarshalling proof specs file") } } @@ -148,13 +153,13 @@ func NewUpdateClientCmd() *cobra.Command { cdc := codec.NewProtoCodec(clientCtx.InterfaceRegistry) var header *types.Header - if err := cdc.UnmarshalJSON([]byte(args[1]), &header); err != nil { + if err := cdc.UnmarshalJSON([]byte(args[1]), header); err != nil { // check for file path if JSON input is not provided contents, err := ioutil.ReadFile(args[1]) if err != nil { return errors.New("neither JSON input nor path to .json file were provided") } - if err := cdc.UnmarshalJSON(contents, &header); err != nil { + if err := cdc.UnmarshalJSON(contents, header); err != nil { return errors.Wrap(err, "error unmarshalling header file") } } @@ -196,13 +201,13 @@ func NewSubmitMisbehaviourCmd() *cobra.Command { cdc := codec.NewProtoCodec(clientCtx.InterfaceRegistry) var ev *types.Evidence - if err := cdc.UnmarshalJSON([]byte(args[0]), &ev); err != nil { + if err := cdc.UnmarshalJSON([]byte(args[0]), ev); err != nil { // check for file path if JSON input is not provided contents, err := ioutil.ReadFile(args[0]) if err != nil { return errors.New("neither JSON input nor path to .json file were provided") } - if err := cdc.UnmarshalJSON(contents, &ev); err != nil { + if err := cdc.UnmarshalJSON(contents, ev); err != nil { return errors.Wrap(err, "error unmarshalling evidence file") } } diff --git a/x/ibc/09-localhost/types/msgs.go b/x/ibc/09-localhost/types/msgs.go index 00a97893c..b43d02c0e 100644 --- a/x/ibc/09-localhost/types/msgs.go +++ b/x/ibc/09-localhost/types/msgs.go @@ -38,7 +38,7 @@ func (msg MsgCreateClient) ValidateBasic() error { // GetSignBytes implements sdk.Msg func (msg MsgCreateClient) GetSignBytes() []byte { - return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(&msg)) } // GetSigners implements sdk.Msg diff --git a/x/ibc/light-clients/solomachine/client/cli/tx.go b/x/ibc/light-clients/solomachine/client/cli/tx.go index 54bdfb2b2..678e33499 100644 --- a/x/ibc/light-clients/solomachine/client/cli/tx.go +++ b/x/ibc/light-clients/solomachine/client/cli/tx.go @@ -35,13 +35,13 @@ func NewCreateClientCmd() *cobra.Command { cdc := codec.NewProtoCodec(clientCtx.InterfaceRegistry) var consensusState *types.ConsensusState - if err := cdc.UnmarshalJSON([]byte(args[1]), &consensusState); err != nil { + if err := cdc.UnmarshalJSON([]byte(args[1]), consensusState); err != nil { // check for file path if JSON input is not provided contents, err := ioutil.ReadFile(args[1]) if err != nil { return errors.New("neither JSON input nor path to .json file were provided") } - if err := cdc.UnmarshalJSON(contents, &consensusState); err != nil { + if err := cdc.UnmarshalJSON(contents, consensusState); err != nil { return errors.Wrap(err, "error unmarshalling consensus state file") } } @@ -77,13 +77,13 @@ func NewUpdateClientCmd() *cobra.Command { cdc := codec.NewProtoCodec(clientCtx.InterfaceRegistry) var header *types.Header - if err := cdc.UnmarshalJSON([]byte(args[1]), &header); err != nil { + if err := cdc.UnmarshalJSON([]byte(args[1]), header); err != nil { // check for file path if JSON input is not provided contents, err := ioutil.ReadFile(args[1]) if err != nil { return errors.New("neither JSON input nor path to .json file were provided") } - if err := cdc.UnmarshalJSON(contents, &header); err != nil { + if err := cdc.UnmarshalJSON(contents, header); err != nil { return errors.Wrap(err, "error unmarshalling header file") } } @@ -117,13 +117,13 @@ func NewSubmitMisbehaviourCmd() *cobra.Command { cdc := codec.NewProtoCodec(clientCtx.InterfaceRegistry) var ev *types.Evidence - if err := cdc.UnmarshalJSON([]byte(args[0]), &ev); err != nil { + if err := cdc.UnmarshalJSON([]byte(args[0]), ev); err != nil { // check for file path if JSON input is not provided contents, err := ioutil.ReadFile(args[0]) if err != nil { return errors.New("neither JSON input nor path to .json file were provided") } - if err := cdc.UnmarshalJSON(contents, &ev); err != nil { + if err := cdc.UnmarshalJSON(contents, ev); err != nil { return errors.Wrap(err, "error unmarshalling evidence file") } } diff --git a/x/ibc/light-clients/solomachine/types/msgs.go b/x/ibc/light-clients/solomachine/types/msgs.go index e75380511..76713e88c 100644 --- a/x/ibc/light-clients/solomachine/types/msgs.go +++ b/x/ibc/light-clients/solomachine/types/msgs.go @@ -47,7 +47,7 @@ func (msg MsgCreateClient) ValidateBasic() error { // GetSignBytes implements sdk.Msg func (msg MsgCreateClient) GetSignBytes() []byte { - return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(&msg)) } // GetSigners implements sdk.Msg @@ -106,7 +106,7 @@ func (msg MsgUpdateClient) ValidateBasic() error { // GetSignBytes implements sdk.Msg func (msg MsgUpdateClient) GetSignBytes() []byte { - return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(&msg)) } // GetSigners implements sdk.Msg @@ -153,7 +153,7 @@ func (msg MsgSubmitClientMisbehaviour) ValidateBasic() error { // GetSignBytes returns the raw bytes a signer is expected to sign when submitting // a MsgSubmitClientMisbehaviour message. func (msg MsgSubmitClientMisbehaviour) GetSignBytes() []byte { - return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(SubModuleCdc.MustMarshalJSON(&msg)) } // GetSigners returns the single expected signer for a MsgSubmitClientMisbehaviour. diff --git a/x/ibc/module.go b/x/ibc/module.go index fc15814e4..62a00fd65 100644 --- a/x/ibc/module.go +++ b/x/ibc/module.go @@ -120,7 +120,7 @@ func (AppModule) QuerierRoute() string { } // LegacyQuerierHandler returns nil. IBC does not support the legacy querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return nil } diff --git a/x/ibc/simulation/genesis.go b/x/ibc/simulation/genesis.go index 3aff7ff62..1cc142e53 100644 --- a/x/ibc/simulation/genesis.go +++ b/x/ibc/simulation/genesis.go @@ -3,11 +3,10 @@ package simulation // DONTCOVER import ( + "encoding/json" "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/types/module" clientsims "github.com/cosmos/cosmos-sdk/x/ibc/02-client/simulation" clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/02-client/types" @@ -55,6 +54,10 @@ func RandomizedGenState(simState *module.SimulationState) { ChannelGenesis: channelGenesisState, } - fmt.Printf("Selected randomly generated %s parameters:\n%s\n", host.ModuleName, codec.MustMarshalJSONIndent(simState.Cdc, &ibcGenesis)) + bz, err := json.MarshalIndent(&ibcGenesis, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("Selected randomly generated %s parameters:\n%s\n", host.ModuleName, bz) simState.GenState[host.ModuleName] = simState.Cdc.MustMarshalJSON(&ibcGenesis) } diff --git a/x/ibc/simulation/genesis_test.go b/x/ibc/simulation/genesis_test.go index d52f5391e..9ef3f4824 100644 --- a/x/ibc/simulation/genesis_test.go +++ b/x/ibc/simulation/genesis_test.go @@ -8,17 +8,20 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/ibc/02-client/types" host "github.com/cosmos/cosmos-sdk/x/ibc/24-host" "github.com/cosmos/cosmos-sdk/x/ibc/simulation" + "github.com/cosmos/cosmos-sdk/x/ibc/types" ) // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. // Abonormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) + s := rand.NewSource(1) r := rand.New(s) @@ -40,12 +43,7 @@ func TestRandomizedGenState(t *testing.T) { var ibcGenesis types.GenesisState simState.Cdc.MustUnmarshalJSON(simState.GenState[host.ModuleName], &ibcGenesis) - require.Len(t, ibcGenesis.Clients, 0) - require.Len(t, ibcGenesis.ClientsConsensus, 0) - require.False(t, ibcGenesis.CreateLocalhost) - - // Note: ibcGenesis.ChannelGenesis is missing because the ChannelGenesis - // interface is not register in RegisterCodec. (Not sure if is a feature - // or a bug.) - + require.NotNil(t, ibcGenesis.ClientGenesis) + require.NotNil(t, ibcGenesis.ConnectionGenesis) + require.NotNil(t, ibcGenesis.ChannelGenesis) } diff --git a/x/mint/keeper/querier.go b/x/mint/keeper/querier.go index 4b88ab6ff..294445614 100644 --- a/x/mint/keeper/querier.go +++ b/x/mint/keeper/querier.go @@ -10,7 +10,7 @@ import ( ) // NewQuerier returns a minting Querier handler. -func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return func(ctx sdk.Context, path []string, _ abci.RequestQuery) ([]byte, error) { switch path[0] { case types.QueryParameters: @@ -28,7 +28,7 @@ func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { } } -func queryParams(ctx sdk.Context, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryParams(ctx sdk.Context, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { params := k.GetParams(ctx) res, err := codec.MarshalJSONIndent(legacyQuerierCdc, params) @@ -39,7 +39,7 @@ func queryParams(ctx sdk.Context, k Keeper, legacyQuerierCdc codec.JSONMarshaler return res, nil } -func queryInflation(ctx sdk.Context, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryInflation(ctx sdk.Context, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { minter := k.GetMinter(ctx) res, err := codec.MarshalJSONIndent(legacyQuerierCdc, minter.Inflation) @@ -50,7 +50,7 @@ func queryInflation(ctx sdk.Context, k Keeper, legacyQuerierCdc codec.JSONMarsha return res, nil } -func queryAnnualProvisions(ctx sdk.Context, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryAnnualProvisions(ctx sdk.Context, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { minter := k.GetMinter(ctx) res, err := codec.MarshalJSONIndent(legacyQuerierCdc, minter.AnnualProvisions) diff --git a/x/mint/keeper/querier_test.go b/x/mint/keeper/querier_test.go index d2f1b223a..2e987aa04 100644 --- a/x/mint/keeper/querier_test.go +++ b/x/mint/keeper/querier_test.go @@ -17,7 +17,7 @@ import ( func TestNewQuerier(t *testing.T) { app, ctx := createTestApp(true) legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keep.NewQuerier(app.MintKeeper, legacyQuerierCdc) + querier := keep.NewQuerier(app.MintKeeper, legacyQuerierCdc.LegacyAmino) query := abci.RequestQuery{ Path: "", @@ -40,7 +40,7 @@ func TestNewQuerier(t *testing.T) { func TestQueryParams(t *testing.T) { app, ctx := createTestApp(true) legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keep.NewQuerier(app.MintKeeper, legacyQuerierCdc) + querier := keep.NewQuerier(app.MintKeeper, legacyQuerierCdc.LegacyAmino) var params types.Params @@ -56,7 +56,7 @@ func TestQueryParams(t *testing.T) { func TestQueryInflation(t *testing.T) { app, ctx := createTestApp(true) legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keep.NewQuerier(app.MintKeeper, legacyQuerierCdc) + querier := keep.NewQuerier(app.MintKeeper, legacyQuerierCdc.LegacyAmino) var inflation sdk.Dec @@ -72,7 +72,7 @@ func TestQueryInflation(t *testing.T) { func TestQueryAnnualProvisions(t *testing.T) { app, ctx := createTestApp(true) legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keep.NewQuerier(app.MintKeeper, legacyQuerierCdc) + querier := keep.NewQuerier(app.MintKeeper, legacyQuerierCdc.LegacyAmino) var annualProvisions sdk.Dec diff --git a/x/mint/module.go b/x/mint/module.go index e7b18307d..431504b56 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -117,7 +117,7 @@ func (AppModule) QuerierRoute() string { } // LegacyQuerierHandler returns the mint module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return keeper.NewQuerier(am.keeper, legacyQuerierCdc) } diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index b4b3e1534..77d506441 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -3,11 +3,10 @@ package simulation // DONTCOVER import ( + "encoding/json" "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/mint/types" @@ -87,6 +86,10 @@ func RandomizedGenState(simState *module.SimulationState) { mintGenesis := types.NewGenesisState(types.InitialMinter(inflation), params) - fmt.Printf("Selected randomly generated minting parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.Cdc, mintGenesis)) + bz, err := json.MarshalIndent(&mintGenesis, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("Selected randomly generated minting parameters:\n%s\n", bz) simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(mintGenesis) } diff --git a/x/mint/simulation/genesis_test.go b/x/mint/simulation/genesis_test.go index e6dbf4221..ac57da7ac 100644 --- a/x/mint/simulation/genesis_test.go +++ b/x/mint/simulation/genesis_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -18,7 +19,9 @@ import ( // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. // Abonormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) + s := rand.NewSource(1) r := rand.New(s) @@ -55,7 +58,8 @@ func TestRandomizedGenState(t *testing.T) { // TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) s := rand.NewSource(1) r := rand.New(s) diff --git a/x/params/client/cli/tx.go b/x/params/client/cli/tx.go index 739fadd39..fcc808043 100644 --- a/x/params/client/cli/tx.go +++ b/x/params/client/cli/tx.go @@ -63,7 +63,7 @@ Where proposal.json contains: return err } - proposal, err := paramscutils.ParseParamChangeProposalJSON(clientCtx.JSONMarshaler, args[0]) + proposal, err := paramscutils.ParseParamChangeProposalJSON(clientCtx.LegacyAmino, args[0]) if err != nil { return err } diff --git a/x/params/client/utils/utils.go b/x/params/client/utils/utils.go index cb3199bef..b4c680fdd 100644 --- a/x/params/client/utils/utils.go +++ b/x/params/client/utils/utils.go @@ -65,7 +65,7 @@ func (pcj ParamChangesJSON) ToParamChanges() []proposal.ParamChange { // ParseParamChangeProposalJSON reads and parses a ParamChangeProposalJSON from // file. -func ParseParamChangeProposalJSON(cdc codec.JSONMarshaler, proposalFile string) (ParamChangeProposalJSON, error) { +func ParseParamChangeProposalJSON(cdc *codec.LegacyAmino, proposalFile string) (ParamChangeProposalJSON, error) { proposal := ParamChangeProposalJSON{} contents, err := ioutil.ReadFile(proposalFile) diff --git a/x/params/keeper/querier.go b/x/params/keeper/querier.go index 29a8ab637..9d6f3c3da 100644 --- a/x/params/keeper/querier.go +++ b/x/params/keeper/querier.go @@ -11,7 +11,7 @@ import ( ) // NewQuerier returns a new querier handler for the x/params module. -func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { switch path[0] { case types.QueryParams: @@ -23,7 +23,7 @@ func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { } } -func queryParams(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryParams(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QuerySubspaceParams if err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { diff --git a/x/params/module.go b/x/params/module.go index b056fc3be..56eb8afc3 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -103,7 +103,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) {} func (AppModule) QuerierRoute() string { return types.QuerierRoute } // LegacyQuerierHandler returns the x/params querier handler. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return keeper.NewQuerier(am.keeper, legacyQuerierCdc) } diff --git a/x/simulation/params.go b/x/simulation/params.go index 0aae67753..f7fc798e6 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -9,7 +9,6 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/params" "github.com/cosmos/cosmos-sdk/types/simulation" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -160,7 +159,10 @@ func RandomConsensusParams(r *rand.Rand, appState json.RawMessage) *abci.Consens var genesisState map[string]json.RawMessage - cdc.UnmarshalJSON(appState, &genesisState) + err := json.Unmarshal(appState, &genesisState) + if err != nil { + panic(err) + } stakingGenesisState := stakingtypes.GetGenesisStateFromAppState(cdc, genesisState) @@ -177,7 +179,12 @@ func RandomConsensusParams(r *rand.Rand, appState json.RawMessage) *abci.Consens MaxAgeDuration: stakingGenesisState.Params.UnbondingTime, }, } - fmt.Printf("Selected randomly generated consensus parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, consensusParams)) + + bz, err := json.MarshalIndent(&consensusParams, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("Selected randomly generated consensus parameters:\n%s\n", bz) return consensusParams } diff --git a/x/slashing/client/cli/cli_test.go b/x/slashing/client/cli/cli_test.go index 59d10e98c..e925e6433 100644 --- a/x/slashing/client/cli/cli_test.go +++ b/x/slashing/client/cli/cli_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" tmcli "github.com/tendermint/tendermint/libs/cli" @@ -147,7 +148,7 @@ func (s *IntegrationTestSuite) TestNewUnjailTxCmd() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { diff --git a/x/slashing/client/rest/query.go b/x/slashing/client/rest/query.go index 3fb4278f2..3cb65d81e 100644 --- a/x/slashing/client/rest/query.go +++ b/x/slashing/client/rest/query.go @@ -45,7 +45,7 @@ func signingInfoHandlerFn(clientCtx client.Context) http.HandlerFunc { params := types.QuerySigningInfoRequest{ConsAddress: sdk.ConsAddress(pk.Address())} - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } @@ -75,7 +75,7 @@ func signingInfoHandlerListFn(clientCtx client.Context) http.HandlerFunc { } params := types.NewQuerySigningInfosParams(page, limit) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckInternalServerError(w, err) { return } diff --git a/x/slashing/client/rest/tx.go b/x/slashing/client/rest/tx.go index ffe7023b0..eaac614fa 100644 --- a/x/slashing/client/rest/tx.go +++ b/x/slashing/client/rest/tx.go @@ -30,7 +30,7 @@ func NewUnjailRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { bech32Validator := vars["validatorAddr"] var req UnjailReq - if !rest.ReadRESTReq(w, r, clientCtx.JSONMarshaler, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.LegacyAmino, &req) { return } diff --git a/x/slashing/keeper/querier.go b/x/slashing/keeper/querier.go index d2eea2fab..b168c4e62 100644 --- a/x/slashing/keeper/querier.go +++ b/x/slashing/keeper/querier.go @@ -11,7 +11,7 @@ import ( ) // NewQuerier creates a new querier for slashing clients. -func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { switch path[0] { case types.QueryParameters: @@ -29,7 +29,7 @@ func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { } } -func queryParams(ctx sdk.Context, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryParams(ctx sdk.Context, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { params := k.GetParams(ctx) res, err := codec.MarshalJSONIndent(legacyQuerierCdc, params) @@ -40,7 +40,7 @@ func queryParams(ctx sdk.Context, k Keeper, legacyQuerierCdc codec.JSONMarshaler return res, nil } -func querySigningInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func querySigningInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QuerySigningInfoRequest err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -61,7 +61,7 @@ func querySigningInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQu return res, nil } -func querySigningInfos(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func querySigningInfos(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QuerySigningInfosParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) diff --git a/x/slashing/keeper/querier_test.go b/x/slashing/keeper/querier_test.go index 785d5d4c3..d3305eb9f 100644 --- a/x/slashing/keeper/querier_test.go +++ b/x/slashing/keeper/querier_test.go @@ -19,7 +19,7 @@ func TestNewQuerier(t *testing.T) { ctx := app.BaseApp.NewContext(false, tmproto.Header{}) app.SlashingKeeper.SetParams(ctx, keeper.TestParams()) legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.SlashingKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.SlashingKeeper, legacyQuerierCdc.LegacyAmino) query := abci.RequestQuery{ Path: "", @@ -37,7 +37,7 @@ func TestQueryParams(t *testing.T) { ctx := app.BaseApp.NewContext(false, tmproto.Header{}) app.SlashingKeeper.SetParams(ctx, keeper.TestParams()) - querier := keeper.NewQuerier(app.SlashingKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.SlashingKeeper, legacyQuerierCdc.LegacyAmino) query := abci.RequestQuery{ Path: "", diff --git a/x/slashing/module.go b/x/slashing/module.go index 0adc2ee92..6a0a2b29f 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -132,7 +132,7 @@ func (AppModule) QuerierRoute() string { } // LegacyQuerierHandler returns the slashing module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return keeper.NewQuerier(am.keeper, legacyQuerierCdc) } diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index 5d60c5a5d..2c1eba7db 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -3,12 +3,11 @@ package simulation // DONTCOVER import ( + "encoding/json" "fmt" "math/rand" "time" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/simulation" @@ -88,6 +87,10 @@ func RandomizedGenState(simState *module.SimulationState) { slashingGenesis := types.NewGenesisState(params, []types.SigningInfo{}, []types.ValidatorMissedBlocks{}) - fmt.Printf("Selected randomly generated slashing parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.Cdc, &slashingGenesis.Params)) + bz, err := json.MarshalIndent(&slashingGenesis, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("Selected randomly generated slashing parameters:\n%s\n", bz) simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(slashingGenesis) } diff --git a/x/slashing/simulation/genesis_test.go b/x/slashing/simulation/genesis_test.go index e9604dad7..a386588d8 100644 --- a/x/slashing/simulation/genesis_test.go +++ b/x/slashing/simulation/genesis_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -19,7 +20,9 @@ import ( // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. // Abonormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) + s := rand.NewSource(1) r := rand.New(s) @@ -54,7 +57,8 @@ func TestRandomizedGenState(t *testing.T) { // TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) s := rand.NewSource(1) r := rand.New(s) diff --git a/x/slashing/types/msg.go b/x/slashing/types/msg.go index e67a849a2..da691dffc 100644 --- a/x/slashing/types/msg.go +++ b/x/slashing/types/msg.go @@ -27,7 +27,7 @@ func (msg MsgUnjail) GetSigners() []sdk.AccAddress { // GetSignBytes gets the bytes for the message signer to sign on func (msg MsgUnjail) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } diff --git a/x/staking/client/cli/cli_test.go b/x/staking/client/cli/cli_test.go index faae76132..ea809ee03 100644 --- a/x/staking/client/cli/cli_test.go +++ b/x/staking/client/cli/cli_test.go @@ -4,7 +4,9 @@ import ( "fmt" "testing" + "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" + "github.com/tendermint/tendermint/crypto/ed25519" "github.com/cosmos/cosmos-sdk/client/flags" @@ -68,7 +70,7 @@ func (s *IntegrationTestSuite) TestNewCreateValidatorCmd() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { diff --git a/x/staking/client/rest/query.go b/x/staking/client/rest/query.go index 27e458d9b..8a326c93b 100644 --- a/x/staking/client/rest/query.go +++ b/x/staking/client/rest/query.go @@ -179,7 +179,7 @@ func delegatorTxsHandlerFn(clientCtx client.Context) http.HandlerFunc { txs = append(txs, foundTxs) } - res, err := clientCtx.JSONMarshaler.MarshalJSON(txs) + res, err := clientCtx.LegacyAmino.MarshalJSON(txs) if rest.CheckInternalServerError(w, err) { return } @@ -234,7 +234,7 @@ func redelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { params.DstValidatorAddr = dstValidatorAddr } - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } @@ -284,7 +284,7 @@ func validatorsHandlerFn(clientCtx client.Context) http.HandlerFunc { params := types.NewQueryValidatorsParams(page, limit, status) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } @@ -330,7 +330,7 @@ func historicalInfoHandlerFn(clientCtx client.Context) http.HandlerFunc { params := types.QueryHistoricalInfoRequest{Height: height} - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckInternalServerError(w, err) { return } diff --git a/x/staking/client/rest/utils.go b/x/staking/client/rest/utils.go index 6cc30499b..cacba533d 100644 --- a/x/staking/client/rest/utils.go +++ b/x/staking/client/rest/utils.go @@ -59,7 +59,7 @@ func queryBonds(clientCtx client.Context, endpoint string) http.HandlerFunc { params := types.QueryDelegatorValidatorRequest{DelegatorAddr: delegatorAddr, ValidatorAddr: validatorAddr} - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } @@ -91,7 +91,7 @@ func queryDelegator(clientCtx client.Context, endpoint string) http.HandlerFunc params := types.NewQueryDelegatorParams(delegatorAddr) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } @@ -128,7 +128,7 @@ func queryValidator(clientCtx client.Context, endpoint string) http.HandlerFunc params := types.NewQueryValidatorParams(validatorAddr, page, limit) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } diff --git a/x/staking/keeper/querier.go b/x/staking/keeper/querier.go index 2b637e0c5..ebe6ab79b 100644 --- a/x/staking/keeper/querier.go +++ b/x/staking/keeper/querier.go @@ -14,7 +14,7 @@ import ( ) // creates a querier for staking REST endpoints -func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { switch path[0] { case types.QueryValidators: @@ -65,7 +65,7 @@ func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { } } -func queryValidators(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryValidators(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryValidatorsParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -97,7 +97,7 @@ func queryValidators(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQue return res, nil } -func queryValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryValidatorParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -118,7 +118,7 @@ func queryValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuer return res, nil } -func queryValidatorDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryValidatorDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryValidatorParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -152,7 +152,7 @@ func queryValidatorDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, return res, nil } -func queryValidatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryValidatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryValidatorParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -180,7 +180,7 @@ func queryValidatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, return res, nil } -func queryDelegatorDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryDelegatorDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDelegatorParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -207,7 +207,7 @@ func queryDelegatorDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, return res, nil } -func queryDelegatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryDelegatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDelegatorParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -228,7 +228,7 @@ func queryDelegatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, return res, nil } -func queryDelegatorValidators(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryDelegatorValidators(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDelegatorParams stakingParams := k.GetParams(ctx) @@ -251,7 +251,7 @@ func queryDelegatorValidators(ctx sdk.Context, req abci.RequestQuery, k Keeper, return res, nil } -func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDelegatorValidatorRequest err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -272,7 +272,7 @@ func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper, l return res, nil } -func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDelegatorValidatorRequest err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -298,7 +298,7 @@ func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQue return res, nil } -func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDelegatorValidatorRequest err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -319,7 +319,7 @@ func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, return res, nil } -func queryRedelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryRedelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryRedelegationParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -360,7 +360,7 @@ func queryRedelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacy return res, nil } -func queryHistoricalInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryHistoricalInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryHistoricalInfoRequest err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -381,7 +381,7 @@ func queryHistoricalInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper, legac return res, nil } -func queryPool(ctx sdk.Context, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryPool(ctx sdk.Context, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { bondDenom := k.BondDenom(ctx) bondedPool := k.GetBondedPool(ctx) notBondedPool := k.GetNotBondedPool(ctx) @@ -403,7 +403,7 @@ func queryPool(ctx sdk.Context, k Keeper, legacyQuerierCdc codec.JSONMarshaler) return res, nil } -func queryParameters(ctx sdk.Context, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryParameters(ctx sdk.Context, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { params := k.GetParams(ctx) res, err := codec.MarshalJSONIndent(legacyQuerierCdc, params) diff --git a/x/staking/keeper/querier_test.go b/x/staking/keeper/querier_test.go index 25214fd06..54ae2b501 100644 --- a/x/staking/keeper/querier_test.go +++ b/x/staking/keeper/querier_test.go @@ -45,7 +45,7 @@ func TestNewQuerier(t *testing.T) { } legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) bz, err := querier(ctx, []string{"other"}, query) require.Error(t, err) @@ -110,7 +110,7 @@ func TestNewQuerier(t *testing.T) { func TestQueryParametersPool(t *testing.T) { cdc, app, ctx := createTestInput() legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) bondDenom := sdk.DefaultBondDenom @@ -137,7 +137,7 @@ func TestQueryValidators(t *testing.T) { cdc, app, ctx := createTestInput() params := app.StakingKeeper.GetParams(ctx) legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) addrs := simapp.AddTestAddrs(app, ctx, 500, sdk.TokensFromConsensusPower(10000)) @@ -205,7 +205,7 @@ func TestQueryDelegation(t *testing.T) { cdc, app, ctx := createTestInput() params := app.StakingKeeper.GetParams(ctx) legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.TokensFromConsensusPower(10000)) addrAcc1, addrAcc2 := addrs[0], addrs[1] @@ -454,7 +454,7 @@ func TestQueryValidatorDelegations_Pagination(t *testing.T) { cdc, app, ctx := createTestInput() legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) addrs := simapp.AddTestAddrs(app, ctx, 100, sdk.TokensFromConsensusPower(10000)) pubKeys := simapp.CreateTestPubKeys(1) @@ -539,7 +539,7 @@ func TestQueryValidatorDelegations_Pagination(t *testing.T) { func TestQueryRedelegations(t *testing.T) { cdc, app, ctx := createTestInput() legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.TokensFromConsensusPower(10000)) addrAcc1, addrAcc2 := addrs[0], addrs[1] @@ -611,7 +611,7 @@ func TestQueryRedelegations(t *testing.T) { func TestQueryUnbondingDelegation(t *testing.T) { cdc, app, ctx := createTestInput() legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.TokensFromConsensusPower(10000)) addrAcc1, addrAcc2 := addrs[0], addrs[1] @@ -707,7 +707,7 @@ func TestQueryUnbondingDelegation(t *testing.T) { func TestQueryHistoricalInfo(t *testing.T) { cdc, app, ctx := createTestInput() legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc) + querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.TokensFromConsensusPower(10000)) addrAcc1, addrAcc2 := addrs[0], addrs[1] diff --git a/x/staking/module.go b/x/staking/module.go index 24d3b0530..03480080a 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -130,7 +130,7 @@ func (AppModule) QuerierRoute() string { } // LegacyQuerierHandler returns the staking module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return keeper.NewQuerier(am.keeper, legacyQuerierCdc) } diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index d30f19b07..e4ed7d348 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -3,12 +3,11 @@ package simulation // DONTCOVER import ( + "encoding/json" "fmt" "math/rand" "time" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/simulation" @@ -98,6 +97,10 @@ func RandomizedGenState(simState *module.SimulationState) { stakingGenesis := types.NewGenesisState(params, validators, delegations) - fmt.Printf("Selected randomly generated staking parameters:\n%s\n", codec.MustMarshalJSONIndent(types.ModuleCdc, stakingGenesis.Params)) + bz, err := json.MarshalIndent(&stakingGenesis, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("Selected randomly generated staking parameters:\n%s\n", bz) simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(stakingGenesis) } diff --git a/x/staking/simulation/genesis_test.go b/x/staking/simulation/genesis_test.go index 66acafb52..b32a9c411 100644 --- a/x/staking/simulation/genesis_test.go +++ b/x/staking/simulation/genesis_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/staking/simulation" @@ -17,7 +18,9 @@ import ( // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. // Abonormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) + s := rand.NewSource(1) r := rand.New(s) @@ -63,7 +66,8 @@ func TestRandomizedGenState(t *testing.T) { // TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { - cdc := codec.New() + interfaceRegistry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) s := rand.NewSource(1) r := rand.New(s) diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index 10a9373eb..75d8c2476 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -71,7 +71,7 @@ func (msg MsgCreateValidator) GetSigners() []sdk.AccAddress { // GetSignBytes returns the message bytes to sign over. func (msg MsgCreateValidator) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -144,7 +144,7 @@ func (msg MsgEditValidator) GetSigners() []sdk.AccAddress { // GetSignBytes implements the sdk.Msg interface. func (msg MsgEditValidator) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -193,7 +193,7 @@ func (msg MsgDelegate) GetSigners() []sdk.AccAddress { // GetSignBytes implements the sdk.Msg interface. func (msg MsgDelegate) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -239,7 +239,7 @@ func (msg MsgBeginRedelegate) GetSigners() []sdk.AccAddress { // GetSignBytes implements the sdk.Msg interface. func (msg MsgBeginRedelegate) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -284,7 +284,7 @@ func (msg MsgUndelegate) GetSigners() []sdk.AccAddress { return []sdk.AccAddress // GetSignBytes implements the sdk.Msg interface. func (msg MsgUndelegate) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } diff --git a/x/upgrade/abci_test.go b/x/upgrade/abci_test.go index de2d629de..1c3d65224 100644 --- a/x/upgrade/abci_test.go +++ b/x/upgrade/abci_test.go @@ -14,7 +14,6 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -55,7 +54,7 @@ func setupTest(height int64, skip map[int64]bool) TestSuite { s.ctx = app.BaseApp.NewContext(false, tmproto.Header{Height: height, Time: time.Now()}) s.module = upgrade.NewAppModule(s.keeper) - s.querier = s.module.LegacyQuerierHandler(codec.NewAminoCodec(app.LegacyAmino())) + s.querier = s.module.LegacyQuerierHandler(app.LegacyAmino()) s.handler = upgrade.NewSoftwareUpgradeProposalHandler(s.keeper) return s } diff --git a/x/upgrade/client/rest/query.go b/x/upgrade/client/rest/query.go index 2df7b86b9..946430634 100644 --- a/x/upgrade/client/rest/query.go +++ b/x/upgrade/client/rest/query.go @@ -48,7 +48,7 @@ func getDonePlanHandler(clientCtx client.Context) func(http.ResponseWriter, *htt name := mux.Vars(r)["name"] params := types.QueryAppliedPlanRequest{Name: name} - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } diff --git a/x/upgrade/keeper/querier.go b/x/upgrade/keeper/querier.go index 9d0fffa65..227d770f2 100644 --- a/x/upgrade/keeper/querier.go +++ b/x/upgrade/keeper/querier.go @@ -14,7 +14,7 @@ import ( ) // NewQuerier creates a querier for upgrade cli and REST endpoints -func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { switch path[0] { @@ -30,7 +30,7 @@ func NewQuerier(k Keeper, legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { } } -func queryCurrent(ctx sdk.Context, _ abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryCurrent(ctx sdk.Context, _ abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { plan, has := k.GetUpgradePlan(ctx) if !has { return nil, nil @@ -44,7 +44,7 @@ func queryCurrent(ctx sdk.Context, _ abci.RequestQuery, k Keeper, legacyQuerierC return res, nil } -func queryApplied(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func queryApplied(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryAppliedPlanRequest err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) diff --git a/x/upgrade/module.go b/x/upgrade/module.go index 650715ae4..0c4075f98 100644 --- a/x/upgrade/module.go +++ b/x/upgrade/module.go @@ -93,7 +93,7 @@ func (AppModule) Route() sdk.Route { return sdk.Route{} } func (AppModule) QuerierRoute() string { return types.QuerierKey } // LegacyQuerierHandler registers a query handler to respond to the module-specific queries -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc codec.JSONMarshaler) sdk.Querier { +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return keeper.NewQuerier(am.keeper, legacyQuerierCdc) }