From 97c59def135b91830f3f829be51c8d78f5d2df5b Mon Sep 17 00:00:00 2001 From: blushi Date: Thu, 13 Aug 2020 12:49:00 +0200 Subject: [PATCH 01/20] Make JSONMarshaler require proto.Message --- client/context.go | 9 +++++++-- codec/amino.go | 10 ++++------ codec/amino_codec.go | 2 +- codec/amino_codec_test.go | 6 +++--- codec/codec.go | 10 +++++----- codec/hybrid_codec.go | 15 +++++++++------ codec/proto_codec.go | 9 +++++---- codec/proto_codec_test.go | 20 -------------------- server/util.go | 6 +++--- types/coin_test.go | 24 ++++++++++++++---------- types/rest/rest.go | 12 ++++++------ types/result.go | 10 +++++++--- x/auth/client/rest/broadcast.go | 2 +- x/auth/keeper/querier.go | 6 +++--- x/auth/types/account_retriever.go | 4 ++-- x/crisis/types/msgs.go | 2 +- x/evidence/types/msgs.go | 2 +- x/ibc/03-connection/types/msgs.go | 8 ++++---- x/params/types/subspace.go | 29 +++++++++++++++++++++++++---- 19 files changed, 101 insertions(+), 85 deletions(-) diff --git a/client/context.go b/client/context.go index ade34161e7b..ead20afa982 100644 --- a/client/context.go +++ b/client/context.go @@ -2,6 +2,7 @@ package client import ( "encoding/json" + "fmt" "io" "os" @@ -218,12 +219,16 @@ func (ctx Context) PrintOutput(toPrint proto.Message) error { // 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) + return ctx.WithLegacyAmino(ctx.LegacyAmino).printOutput(toPrint) } func (ctx Context) printOutput(toPrint interface{}) error { + msg, ok := toPrint.(proto.Message) + if !ok { + return fmt.Errorf("can't proto marshal %T", toPrint) + } // always serialize JSON initially because proto json can't be directly YAML encoded - out, err := ctx.JSONMarshaler.MarshalJSON(toPrint) + out, err := ctx.JSONMarshaler.MarshalJSON(msg) if err != nil { return err } diff --git a/codec/amino.go b/codec/amino.go index 058f2fa2386..59177efc8b7 100644 --- a/codec/amino.go +++ b/codec/amino.go @@ -19,8 +19,6 @@ type LegacyAmino struct { Amino *amino.Codec } -var _ JSONMarshaler = &LegacyAmino{} - func (cdc *LegacyAmino) Seal() { cdc.Amino.Seal() } @@ -38,8 +36,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 } @@ -53,8 +51,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 79b58fa8163..2f579868810 100644 --- a/codec/amino_codec.go +++ b/codec/amino_codec.go @@ -6,7 +6,7 @@ type AminoCodec struct { *LegacyAmino } -var _ Marshaler = &AminoCodec{} +var _ BinaryMarshaler = &AminoCodec{} func NewAminoCodec(codec *LegacyAmino) *AminoCodec { return &AminoCodec{LegacyAmino: codec} diff --git a/codec/amino_codec_test.go b/codec/amino_codec_test.go index cc8e0fac144..7c683d6f001 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 a65231261ae..a0bf5a598b9 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/hybrid_codec.go b/codec/hybrid_codec.go index 5e9667c7081..57d84c812c1 100644 --- a/codec/hybrid_codec.go +++ b/codec/hybrid_codec.go @@ -1,12 +1,15 @@ package codec -import "github.com/cosmos/cosmos-sdk/codec/types" +import ( + "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/gogo/protobuf/proto" +) // HybridCodec defines a codec that utilizes Protobuf for binary encoding // and Amino for JSON encoding. type HybridCodec struct { proto Marshaler - amino Marshaler + amino *AminoCodec } func NewHybridCodec(amino *LegacyAmino, unpacker types.AnyUnpacker) Marshaler { @@ -48,19 +51,19 @@ func (hc *HybridCodec) MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMar hc.proto.MustUnmarshalBinaryLengthPrefixed(bz, ptr) } -func (hc *HybridCodec) MarshalJSON(o interface{}) ([]byte, error) { +func (hc *HybridCodec) MarshalJSON(o proto.Message) ([]byte, error) { return hc.amino.MarshalJSON(o) } -func (hc *HybridCodec) MustMarshalJSON(o interface{}) []byte { +func (hc *HybridCodec) MustMarshalJSON(o proto.Message) []byte { return hc.amino.MustMarshalJSON(o) } -func (hc *HybridCodec) UnmarshalJSON(bz []byte, ptr interface{}) error { +func (hc *HybridCodec) UnmarshalJSON(bz []byte, ptr proto.Message) error { return hc.amino.UnmarshalJSON(bz, ptr) } -func (hc *HybridCodec) MustUnmarshalJSON(bz []byte, ptr interface{}) { +func (hc *HybridCodec) MustUnmarshalJSON(bz []byte, ptr proto.Message) { hc.amino.MustUnmarshalJSON(bz, ptr) } diff --git a/codec/proto_codec.go b/codec/proto_codec.go index c38a5c7febf..b9dfdf69a9b 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 @@ -95,7 +96,7 @@ func (pc *ProtoCodec) MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMars } } -func (pc *ProtoCodec) MarshalJSON(o interface{}) ([]byte, error) { +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 +105,7 @@ func (pc *ProtoCodec) MarshalJSON(o interface{}) ([]byte, error) { return ProtoMarshalJSON(m) } -func (pc *ProtoCodec) MustMarshalJSON(o interface{}) []byte { +func (pc *ProtoCodec) MustMarshalJSON(o proto.Message) []byte { bz, err := pc.MarshalJSON(o) if err != nil { panic(err) @@ -113,7 +114,7 @@ func (pc *ProtoCodec) MustMarshalJSON(o interface{}) []byte { return bz } -func (pc *ProtoCodec) UnmarshalJSON(bz []byte, ptr interface{}) error { +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,7 +128,7 @@ func (pc *ProtoCodec) UnmarshalJSON(bz []byte, ptr interface{}) error { return types.UnpackInterfaces(ptr, pc.anyUnpacker) } -func (pc *ProtoCodec) MustUnmarshalJSON(bz []byte, ptr interface{}) { +func (pc *ProtoCodec) MustUnmarshalJSON(bz []byte, ptr proto.Message) { if err := pc.UnmarshalJSON(bz, ptr); err != nil { panic(err) } diff --git a/codec/proto_codec_test.go b/codec/proto_codec_test.go index 522c80c4e8e..734bf1320ba 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/server/util.go b/server/util.go index 7db8742d38b..2eef6e57679 100644 --- a/server/util.go +++ b/server/util.go @@ -197,15 +197,15 @@ func AddCommands(rootCmd *cobra.Command, defaultNodeHome string, appCreator type // // 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) { +func InsertKeyJSON(legacyAminoCdc *codec.LegacyAmino, baseJSON []byte, key string, value json.RawMessage) ([]byte, error) { var jsonMap map[string]json.RawMessage - if err := cdc.UnmarshalJSON(baseJSON, &jsonMap); err != nil { + if err := legacyAminoCdc.UnmarshalJSON(baseJSON, &jsonMap); err != nil { return nil, err } jsonMap[key] = value - bz, err := codec.MarshalJSONIndent(cdc, jsonMap) + bz, err := codec.MarshalJSONIndent(legacyAminoCdc, jsonMap) return json.RawMessage(bz), err } diff --git a/types/coin_test.go b/types/coin_test.go index 9d896861ab8..ac3042b25b5 100644 --- a/types/coin_test.go +++ b/types/coin_test.go @@ -768,18 +768,22 @@ func TestMarshalJSONCoins(t *testing.T) { for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { - bz, err := cdc.MarshalJSON(tc.input) - require.NoError(t, err) - require.Equal(t, tc.strOutput, string(bz)) + var strs []string + for _, coin := range tc.input { + bz, err := cdc.MarshalJSON(&coin) + require.NoError(t, err) + strs = append(strs, string(bz)) + } + require.Equal(t, tc.strOutput, strings.Join(strings.Split(fmt.Sprintf("%v", strs), " "), ",")) - var newCoins Coins - require.NoError(t, cdc.UnmarshalJSON(bz, &newCoins)) + // var newCoins Coins + // require.NoError(t, cdc.UnmarshalJSON(bz, &newCoins)) - if tc.input.Empty() { - require.Nil(t, newCoins) - } else { - require.Equal(t, tc.input, newCoins) - } + // if tc.input.Empty() { + // require.Nil(t, newCoins) + // } else { + // require.Equal(t, tc.input, newCoins) + // } }) } } diff --git a/types/rest/rest.go b/types/rest/rest.go index 7eb29e36b95..7dd0111777a 100644 --- a/types/rest/rest.go +++ b/types/rest/rest.go @@ -45,7 +45,7 @@ func NewResponseWithHeight(height int64, result json.RawMessage) ResponseWithHei // ParseResponseWithHeight returns the raw result from a JSON-encoded // ResponseWithHeight object. -func ParseResponseWithHeight(cdc codec.JSONMarshaler, bz []byte) ([]byte, error) { +func ParseResponseWithHeight(cdc *codec.LegacyAmino, bz []byte) ([]byte, error) { r := ResponseWithHeight{} if err := cdc.UnmarshalJSON(bz, &r); err != nil { return nil, err @@ -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 } @@ -279,7 +279,7 @@ func PostProcessResponseBare(w http.ResponseWriter, ctx client.Context, body int resp = b default: - resp, err = ctx.JSONMarshaler.MarshalJSON(body) + resp, err = ctx.LegacyAmino.MarshalJSON(body) if CheckInternalServerError(w, err) { return } diff --git a/types/result.go b/types/result.go index a71cfc82fb3..dd58e14332f 100644 --- a/types/result.go +++ b/types/result.go @@ -50,10 +50,14 @@ func NewABCIMessageLog(i uint32, log string, events Events) ABCIMessageLog { // String implements the fmt.Stringer interface for the ABCIMessageLogs type. func (logs ABCIMessageLogs) String() (str string) { if logs != nil { - raw, err := cdc.MarshalJSON(logs) - if err == nil { - str = string(raw) + var strs []string + for _, log := range logs { + raw, err := cdc.MarshalJSON(&log) + if err == nil { + strs = append(strs, string(raw)) + } } + str = strings.Join(strs, " ") } return str diff --git a/x/auth/client/rest/broadcast.go b/x/auth/client/rest/broadcast.go index 632c10c3a4a..d778284cf5a 100644 --- a/x/auth/client/rest/broadcast.go +++ b/x/auth/client/rest/broadcast.go @@ -47,7 +47,7 @@ func BroadcastTxRequest(clientCtx client.Context) http.HandlerFunc { } // NOTE: amino is set intentionally here, don't migrate it! - clientCtx = clientCtx.WithJSONMarshaler(clientCtx.LegacyAmino) + clientCtx = clientCtx.WithLegacyAmino(clientCtx.LegacyAmino) rest.PostProcessResponseBare(w, clientCtx, res) } } diff --git a/x/auth/keeper/querier.go b/x/auth/keeper/querier.go index ac2ab398484..0a654867d43 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/types/account_retriever.go b/x/auth/types/account_retriever.go index 78a8df6dc9d..96b76296201 100644 --- a/x/auth/types/account_retriever.go +++ b/x/auth/types/account_retriever.go @@ -11,11 +11,11 @@ import ( // AccountRetriever defines the properties of a type that can be used to // retrieve accounts. type AccountRetriever struct { - codec codec.JSONMarshaler + codec *codec.LegacyAmino } // NewAccountRetriever initialises a new AccountRetriever instance. -func NewAccountRetriever(codec codec.JSONMarshaler) AccountRetriever { +func NewAccountRetriever(codec *codec.LegacyAmino) AccountRetriever { return AccountRetriever{codec: codec} } diff --git a/x/crisis/types/msgs.go b/x/crisis/types/msgs.go index 97446f07d1b..3487d229d2f 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/evidence/types/msgs.go b/x/evidence/types/msgs.go index aca411ef9d3..c7ec4a8be12 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/ibc/03-connection/types/msgs.go b/x/ibc/03-connection/types/msgs.go index f40c4165a30..f158c763d54 100644 --- a/x/ibc/03-connection/types/msgs.go +++ b/x/ibc/03-connection/types/msgs.go @@ -50,7 +50,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 @@ -127,7 +127,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 @@ -192,7 +192,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 @@ -244,7 +244,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/params/types/subspace.go b/x/params/types/subspace.go index 4f086b36843..1bcf621b16b 100644 --- a/x/params/types/subspace.go +++ b/x/params/types/subspace.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/gogo/protobuf/proto" ) const ( @@ -103,7 +104,12 @@ func (s Subspace) Get(ctx sdk.Context, key []byte, ptr interface{}) { store := s.kvStore(ctx) bz := store.Get(key) - if err := s.cdc.UnmarshalJSON(bz, ptr); err != nil { + msg, ok := ptr.(proto.Message) + if !ok { + panic(fmt.Errorf("can't proto marshal %T", ptr)) + } + + if err := s.cdc.UnmarshalJSON(bz, msg); err != nil { panic(err) } } @@ -120,7 +126,12 @@ func (s Subspace) GetIfExists(ctx sdk.Context, key []byte, ptr interface{}) { s.checkType(key, ptr) - if err := s.cdc.UnmarshalJSON(bz, ptr); err != nil { + msg, ok := ptr.(proto.Message) + if !ok { + panic(fmt.Errorf("can't proto marshal %T", ptr)) + } + + if err := s.cdc.UnmarshalJSON(bz, msg); err != nil { panic(err) } } @@ -170,7 +181,12 @@ func (s Subspace) Set(ctx sdk.Context, key []byte, value interface{}) { s.checkType(key, value) store := s.kvStore(ctx) - bz, err := s.cdc.MarshalJSON(value) + msg, ok := value.(proto.Message) + if !ok { + panic(fmt.Errorf("can't proto marshal %T", value)) + } + + bz, err := s.cdc.MarshalJSON(msg) if err != nil { panic(err) } @@ -197,7 +213,12 @@ func (s Subspace) Update(ctx sdk.Context, key, value []byte) error { dest := reflect.New(ty).Interface() s.GetIfExists(ctx, key, dest) - if err := s.cdc.UnmarshalJSON(value, dest); err != nil { + msg, ok := dest.(proto.Message) + if !ok { + panic(fmt.Errorf("can't proto marshal %T", dest)) + } + + if err := s.cdc.UnmarshalJSON(value, msg); err != nil { return err } From 8f43ba667daba5277ced7213177e6357520e94b6 Mon Sep 17 00:00:00 2001 From: blushi Date: Thu, 13 Aug 2020 12:55:03 +0200 Subject: [PATCH 02/20] Use &msg with MarshalJSON --- x/bank/types/msgs.go | 4 ++-- x/gov/types/msgs.go | 6 +++--- x/staking/types/msg.go | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/x/bank/types/msgs.go b/x/bank/types/msgs.go index 9d79f37c901..514142bc094 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/gov/types/msgs.go b/x/gov/types/msgs.go index c6d57b87df9..1770f1d745d 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/staking/types/msg.go b/x/staking/types/msg.go index 10a9373eb5e..f66a9ad6c4f 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) } @@ -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) } From b6dd69b3edf1174047262c2b1bc23a793d0585b5 Mon Sep 17 00:00:00 2001 From: blushi Date: Thu, 13 Aug 2020 13:49:47 +0200 Subject: [PATCH 03/20] Use *LegacyAmino in queriers instead of JSONMarshaler --- x/bank/keeper/querier.go | 10 ++++----- x/distribution/keeper/querier.go | 20 +++++++++--------- x/distribution/types/msg.go | 8 +++---- x/evidence/keeper/querier.go | 6 +++--- x/gov/keeper/querier.go | 18 ++++++++-------- x/ibc/02-client/client/utils/utils.go | 4 ++-- x/ibc/07-tendermint/types/msgs.go | 4 ++-- x/mint/keeper/querier.go | 8 +++---- x/params/keeper/querier.go | 4 ++-- x/slashing/keeper/querier.go | 8 +++---- x/slashing/types/msg.go | 2 +- x/staking/keeper/querier.go | 30 +++++++++++++-------------- x/staking/types/msg.go | 2 +- 13 files changed, 62 insertions(+), 62 deletions(-) diff --git a/x/bank/keeper/querier.go b/x/bank/keeper/querier.go index 8acc5a3c5a3..88bfac373be 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/distribution/keeper/querier.go b/x/distribution/keeper/querier.go index 78662796cd4..e2621eec2a4 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/types/msg.go b/x/distribution/types/msg.go index 8fa3aa4cef9..1ba548a7b05 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/keeper/querier.go b/x/evidence/keeper/querier.go index a07576b324c..c1ae20d4d9c 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/gov/keeper/querier.go b/x/gov/keeper/querier.go index af1a2027062..6eb343d070a 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/ibc/02-client/client/utils/utils.go b/x/ibc/02-client/client/utils/utils.go index 873215a0201..6c0f5a25ecf 100644 --- a/x/ibc/02-client/client/utils/utils.go +++ b/x/ibc/02-client/client/utils/utils.go @@ -18,7 +18,7 @@ import ( // any merkle proof. func QueryAllClientStates(clientCtx client.Context, page, limit int) ([]exported.ClientState, int64, error) { params := types.NewQueryAllClientsParams(page, limit) - bz, err := clientCtx.JSONMarshaler.MarshalJSON(params) + bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if err != nil { return nil, 0, fmt.Errorf("failed to marshal query params: %w", err) } @@ -30,7 +30,7 @@ func QueryAllClientStates(clientCtx client.Context, page, limit int) ([]exported } var clients []exported.ClientState - err = clientCtx.JSONMarshaler.UnmarshalJSON(res, &clients) + err = clientCtx.LegacyAmino.UnmarshalJSON(res, &clients) if err != nil { return nil, 0, fmt.Errorf("failed to unmarshal light clients: %w", err) } diff --git a/x/ibc/07-tendermint/types/msgs.go b/x/ibc/07-tendermint/types/msgs.go index d617f330ab8..993ab6d47bf 100644 --- a/x/ibc/07-tendermint/types/msgs.go +++ b/x/ibc/07-tendermint/types/msgs.go @@ -118,7 +118,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 @@ -189,7 +189,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 diff --git a/x/mint/keeper/querier.go b/x/mint/keeper/querier.go index 4b88ab6ff24..294445614a5 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/params/keeper/querier.go b/x/params/keeper/querier.go index 29a8ab637dc..9d6f3c3da69 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/slashing/keeper/querier.go b/x/slashing/keeper/querier.go index d2eea2fabbb..b168c4e62f6 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/types/msg.go b/x/slashing/types/msg.go index e67a849a2fb..da691dffcfc 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/keeper/querier.go b/x/staking/keeper/querier.go index 2b637e0c507..ebe6ab79b63 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/types/msg.go b/x/staking/types/msg.go index f66a9ad6c4f..75d8c24763e 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -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) } From 3af50559076b6c702043e4aaf54d675427892ed2 Mon Sep 17 00:00:00 2001 From: blushi Date: Thu, 13 Aug 2020 14:07:28 +0200 Subject: [PATCH 04/20] Revert ABCIMessageLogs String() and coins tests --- client/context.go | 1 + types/coin_test.go | 24 ++++++++++-------------- types/result.go | 10 +++------- x/distribution/client/common/common.go | 8 ++++---- x/ibc/09-localhost/types/msgs.go | 2 +- 5 files changed, 19 insertions(+), 26 deletions(-) diff --git a/client/context.go b/client/context.go index ead20afa982..f145cd18340 100644 --- a/client/context.go +++ b/client/context.go @@ -227,6 +227,7 @@ func (ctx Context) printOutput(toPrint interface{}) error { if !ok { return fmt.Errorf("can't proto marshal %T", toPrint) } + // always serialize JSON initially because proto json can't be directly YAML encoded out, err := ctx.JSONMarshaler.MarshalJSON(msg) if err != nil { diff --git a/types/coin_test.go b/types/coin_test.go index ac3042b25b5..9d896861ab8 100644 --- a/types/coin_test.go +++ b/types/coin_test.go @@ -768,22 +768,18 @@ func TestMarshalJSONCoins(t *testing.T) { for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { - var strs []string - for _, coin := range tc.input { - bz, err := cdc.MarshalJSON(&coin) - require.NoError(t, err) - strs = append(strs, string(bz)) - } - require.Equal(t, tc.strOutput, strings.Join(strings.Split(fmt.Sprintf("%v", strs), " "), ",")) + bz, err := cdc.MarshalJSON(tc.input) + require.NoError(t, err) + require.Equal(t, tc.strOutput, string(bz)) - // var newCoins Coins - // require.NoError(t, cdc.UnmarshalJSON(bz, &newCoins)) + var newCoins Coins + require.NoError(t, cdc.UnmarshalJSON(bz, &newCoins)) - // if tc.input.Empty() { - // require.Nil(t, newCoins) - // } else { - // require.Equal(t, tc.input, newCoins) - // } + if tc.input.Empty() { + require.Nil(t, newCoins) + } else { + require.Equal(t, tc.input, newCoins) + } }) } } diff --git a/types/result.go b/types/result.go index dd58e14332f..a71cfc82fb3 100644 --- a/types/result.go +++ b/types/result.go @@ -50,14 +50,10 @@ func NewABCIMessageLog(i uint32, log string, events Events) ABCIMessageLog { // String implements the fmt.Stringer interface for the ABCIMessageLogs type. func (logs ABCIMessageLogs) String() (str string) { if logs != nil { - var strs []string - for _, log := range logs { - raw, err := cdc.MarshalJSON(&log) - if err == nil { - strs = append(strs, string(raw)) - } + raw, err := cdc.MarshalJSON(logs) + if err == nil { + str = string(raw) } - str = strings.Join(strs, " ") } return str diff --git a/x/distribution/client/common/common.go b/x/distribution/client/common/common.go index f18f0d7756f..a2d5fceda0b 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) } @@ -36,7 +36,7 @@ func QueryDelegationRewards(clientCtx client.Context, delAddr, valAddr string) ( func QueryDelegatorValidators(clientCtx client.Context, delegatorAddr sdk.AccAddress) ([]byte, error) { res, _, err := clientCtx.QueryWithData( fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegatorValidators), - clientCtx.JSONMarshaler.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), + clientCtx.LegacyAmino.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), ) return res, 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 } @@ -61,7 +61,7 @@ func WithdrawAllDelegatorRewards(clientCtx client.Context, delegatorAddr sdk.Acc } var validators []sdk.ValAddress - if err := clientCtx.JSONMarshaler.UnmarshalJSON(bz, &validators); err != nil { + if err := clientCtx.LegacyAmino.UnmarshalJSON(bz, &validators); err != nil { return nil, err } diff --git a/x/ibc/09-localhost/types/msgs.go b/x/ibc/09-localhost/types/msgs.go index c0b8897b856..3d18613ff63 100644 --- a/x/ibc/09-localhost/types/msgs.go +++ b/x/ibc/09-localhost/types/msgs.go @@ -43,7 +43,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 From 282cc2842260d2e792be41b334a29bba4bb9a787 Mon Sep 17 00:00:00 2001 From: blushi Date: Thu, 13 Aug 2020 14:29:35 +0200 Subject: [PATCH 05/20] Use LegacyAmino in client/debug and fix subspace tests --- client/debug/main.go | 2 +- x/params/types/subspace_test.go | 17 +++++++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/client/debug/main.go b/client/debug/main.go index eb2a3ecb2f5..524bcbb3f8b 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/x/params/types/subspace_test.go b/x/params/types/subspace_test.go index d7c30ba18f6..65bd5102a61 100644 --- a/x/params/types/subspace_test.go +++ b/x/params/types/subspace_test.go @@ -11,6 +11,7 @@ import ( dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/params/types" @@ -20,9 +21,10 @@ import ( type SubspaceTestSuite struct { suite.Suite - cdc codec.Marshaler - ctx sdk.Context - ss types.Subspace + cdc codec.BinaryMarshaler + amino *codec.LegacyAmino + ctx sdk.Context + ss types.Subspace } func (suite *SubspaceTestSuite) SetupTest() { @@ -35,8 +37,11 @@ func (suite *SubspaceTestSuite) SetupTest() { suite.NoError(ms.LoadLatestVersion()) ss := types.NewSubspace(cdc, key, tkey, "testsubspace") + encCfg := simapp.MakeEncodingConfig() + ss := types.NewSubspace(encCfg.Marshaler, encCfg.Amino, key, tkey, "testsubspace") - suite.cdc = cdc + suite.cdc = encCfg.Marshaler + suite.amino = encCfg.Amino suite.ctx = sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) suite.ss = ss.WithKeyTable(paramKeyTable()) } @@ -122,12 +127,12 @@ func (suite *SubspaceTestSuite) TestUpdate() { bad := time.Minute * 5 - bz, err := suite.cdc.MarshalJSON(bad) + bz, err := suite.amino.MarshalJSON(bad) suite.Require().NoError(err) suite.Require().Error(suite.ss.Update(suite.ctx, keyUnbondingTime, bz)) good := time.Hour * 360 - bz, err = suite.cdc.MarshalJSON(good) + bz, err = suite.amino.MarshalJSON(good) suite.Require().NoError(err) suite.Require().NoError(suite.ss.Update(suite.ctx, keyUnbondingTime, bz)) From 3f68d9ac0313ffa5661256269d8d88e1a9d0474d Mon Sep 17 00:00:00 2001 From: blushi Date: Fri, 14 Aug 2020 15:02:56 +0200 Subject: [PATCH 06/20] Use LegacyAmino in all legacy queriers and adapt simulation --- client/context.go | 29 ++++++------ client/context_test.go | 6 +-- client/tx/tx.go | 10 ++++- server/start.go | 1 - simapp/app.go | 4 +- simapp/sim_bench_test.go | 4 +- simapp/sim_test.go | 10 ++--- simapp/simd/cmd/genaccounts.go | 7 +-- simapp/simd/cmd/testnet.go | 6 +-- simapp/state.go | 18 ++++---- tests/mocks/types_module_module.go | 2 +- types/module/module.go | 6 +-- types/module/module_test.go | 22 +++++---- types/module/simulation.go | 2 + types/rest/rest_test.go | 3 +- types/simulation/types.go | 9 +++- 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_test.go | 2 +- x/auth/module.go | 2 +- x/auth/simulation/genesis.go | 2 +- x/auth/simulation/genesis_test.go | 10 +++-- x/bank/client/cli/cli_test.go | 4 +- x/bank/client/rest/query.go | 6 +-- x/bank/client/rest/tx.go | 2 +- x/bank/keeper/querier_test.go | 43 +++++++++--------- x/bank/module.go | 2 +- x/bank/simulation/genesis.go | 2 +- x/bank/simulation/genesis_test.go | 17 ++++--- x/bank/types/codec.go | 2 +- x/capability/module.go | 2 +- x/capability/simulation/genesis.go | 2 +- x/capability/simulation/genesis_test.go | 17 ++++--- x/crisis/client/cli/cli_test.go | 2 +- x/crisis/module.go | 2 +- x/distribution/client/cli/cli_test.go | 10 ++--- x/distribution/client/common/common_test.go | 2 +- x/distribution/client/rest/query.go | 14 +++--- x/distribution/keeper/querier_test.go | 3 +- x/distribution/module.go | 2 +- x/distribution/simulation/genesis.go | 2 +- x/distribution/simulation/genesis_test.go | 17 ++++--- x/evidence/client/rest/query.go | 2 +- x/evidence/keeper/keeper_test.go | 5 +-- x/evidence/module.go | 2 +- x/evidence/simulation/genesis.go | 2 +- x/evidence/simulation/genesis_test.go | 6 ++- x/genutil/client/cli/collect.go | 3 +- x/genutil/client/cli/init.go | 9 ++-- x/genutil/client/cli/init_test.go | 22 +++++++-- x/genutil/client/cli/migrate.go | 8 ++-- x/genutil/client/cli/migrate_test.go | 2 +- x/genutil/client/cli/validate_genesis.go | 3 +- 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 | 2 +- x/gov/client/cli/query.go | 8 +++- x/gov/client/rest/query.go | 26 +++++------ x/gov/client/utils/query.go | 14 +++--- x/gov/client/utils/query_test.go | 3 +- x/gov/keeper/querier_test.go | 49 ++++++++++----------- x/gov/module.go | 2 +- x/gov/simulation/genesis.go | 2 +- x/gov/simulation/genesis_test.go | 24 ++++++---- x/ibc-transfer/module.go | 2 +- x/ibc-transfer/simulation/genesis.go | 2 +- x/ibc-transfer/simulation/genesis_test.go | 18 +++++--- x/ibc/02-client/client/rest/query.go | 2 +- x/ibc/02-client/keeper/querier.go | 2 +- x/ibc/keeper/keeper_test.go | 3 +- x/ibc/keeper/querier.go | 2 +- x/ibc/module.go | 2 +- x/ibc/simulation/genesis.go | 2 +- x/ibc/simulation/genesis_test.go | 24 +++++----- x/mint/keeper/querier_test.go | 8 ++-- x/mint/module.go | 2 +- x/mint/simulation/genesis.go | 2 +- x/mint/simulation/genesis_test.go | 18 +++++--- x/params/client/cli/tx.go | 2 +- x/params/client/utils/utils.go | 2 +- x/params/module.go | 2 +- x/simulation/params.go | 8 ++-- x/slashing/client/cli/cli_test.go | 2 +- x/slashing/client/rest/query.go | 4 +- x/slashing/client/rest/tx.go | 2 +- x/slashing/keeper/querier_test.go | 4 +- x/slashing/module.go | 2 +- x/slashing/simulation/genesis.go | 2 +- x/slashing/simulation/genesis_test.go | 18 +++++--- x/staking/client/cli/cli_test.go | 2 +- x/staking/client/rest/query.go | 8 ++-- x/staking/client/rest/utils.go | 6 +-- x/staking/keeper/querier_test.go | 16 +++---- x/staking/module.go | 2 +- x/staking/simulation/genesis.go | 2 +- x/staking/simulation/genesis_test.go | 19 +++++--- x/upgrade/abci_test.go | 3 +- x/upgrade/client/rest/query.go | 2 +- x/upgrade/keeper/querier.go | 6 +-- x/upgrade/module.go | 2 +- 102 files changed, 407 insertions(+), 314 deletions(-) diff --git a/client/context.go b/client/context.go index f145cd18340..56133fbcbf6 100644 --- a/client/context.go +++ b/client/context.go @@ -2,7 +2,6 @@ package client import ( "encoding/json" - "fmt" "io" "os" @@ -67,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 @@ -213,32 +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) + // 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 { - return ctx.WithLegacyAmino(ctx.LegacyAmino).printOutput(toPrint) -} - -func (ctx Context) printOutput(toPrint interface{}) error { - msg, ok := toPrint.(proto.Message) - if !ok { - return fmt.Errorf("can't proto marshal %T", toPrint) - } - - // always serialize JSON initially because proto json can't be directly YAML encoded - out, err := ctx.JSONMarshaler.MarshalJSON(msg) + 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 } @@ -254,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 7d879e1b4e9..79f6de5d0df 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/tx/tx.go b/client/tx/tx.go index bcffbc321ec..61fc8a13046 100644 --- a/client/tx/tx.go +++ b/client/tx/tx.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/gogo/protobuf/jsonpb" + "github.com/gogo/protobuf/proto" "github.com/spf13/pflag" "github.com/tendermint/tendermint/crypto" @@ -100,7 +101,12 @@ func BroadcastTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error { } if !clientCtx.SkipConfirm { - out, err := clientCtx.JSONMarshaler.MarshalJSON(tx) + msg, ok := tx.(proto.Message) + if !ok { + return fmt.Errorf("can't proto marshal %T", tx) + } + + out, err := clientCtx.JSONMarshaler.MarshalJSON(msg) if err != nil { return err } @@ -108,7 +114,7 @@ func BroadcastTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error { _, _ = fmt.Fprintf(os.Stderr, "%s\n\n", out) buf := bufio.NewReader(os.Stdin) - ok, err := input.GetConfirmation("confirm transaction before signing and broadcasting", buf, os.Stderr) + ok, err = input.GetConfirmation("confirm transaction before signing and broadcasting", buf, os.Stderr) if err != nil || !ok { _, _ = fmt.Fprintf(os.Stderr, "%s\n", "cancelled transaction") diff --git a/server/start.go b/server/start.go index 925f6793003..23cec1ebd37 100644 --- a/server/start.go +++ b/server/start.go @@ -232,7 +232,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/simapp/app.go b/simapp/app.go index 5187e040e33..51a11d37af9 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -328,7 +328,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(), codec.NewAminoCodec(encodingConfig.Amino).LegacyAmino) app.mm.RegisterQueryServices(app.GRPCQueryRouter()) // add test gRPC service for testing gRPC queries in isolation @@ -504,8 +504,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/sim_bench_test.go b/simapp/sim_bench_test.go index 20a89e94b46..8a0263c880f 100644 --- a/simapp/sim_bench_test.go +++ b/simapp/sim_bench_test.go @@ -30,7 +30,7 @@ func BenchmarkFullAppSimulation(b *testing.B) { // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - b, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), + b, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, ) @@ -69,7 +69,7 @@ func BenchmarkInvariants(b *testing.B) { // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - b, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), + b, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, ) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 2fac8adb5ee..c098843f264 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -72,7 +72,7 @@ func TestFullAppSimulation(t *testing.T) { // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), + t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, ) @@ -104,7 +104,7 @@ func TestAppImportExport(t *testing.T) { // Run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), + t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, ) @@ -195,7 +195,7 @@ func TestAppSimulationAfterImport(t *testing.T) { // Run randomized simulation stopEarly, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), + t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, ) @@ -237,7 +237,7 @@ func TestAppSimulationAfterImport(t *testing.T) { }) _, _, err = simulation.SimulateFromSeed( - t, os.Stdout, newApp.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), + t, os.Stdout, newApp.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), SimulationOperations(newApp, newApp.AppCodec(), config), newApp.ModuleAccountAddrs(), config, ) @@ -282,7 +282,7 @@ func TestAppStateDeterminism(t *testing.T) { ) _, _, err := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), + t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, ) diff --git a/simapp/simd/cmd/genaccounts.go b/simapp/simd/cmd/genaccounts.go index 00dbe6621d4..0c98534f7fb 100644 --- a/simapp/simd/cmd/genaccounts.go +++ b/simapp/simd/cmd/genaccounts.go @@ -40,6 +40,7 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa RunE: func(cmd *cobra.Command, args []string) error { clientCtx := client.GetClientContextFromCmd(cmd) depCdc := clientCtx.JSONMarshaler + legacyAmino := clientCtx.LegacyAmino cdc := depCdc.(codec.Marshaler) serverCtx := server.GetServerContextFromCmd(cmd) @@ -113,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) } @@ -140,7 +141,7 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa } authGenState.Accounts = genAccs - authGenStateBz, err := cdc.MarshalJSON(authGenState) + authGenStateBz, err := cdc.MarshalJSON(&authGenState) if err != nil { return fmt.Errorf("failed to marshal auth genesis state: %w", err) } @@ -158,7 +159,7 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa appState[banktypes.ModuleName] = bankGenStateBz - appStateJSON, err := cdc.MarshalJSON(appState) + appStateJSON, err := legacyAmino.MarshalJSON(appState) if err != nil { return fmt.Errorf("failed to marshal application genesis state: %w", err) } diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index 8e94969b3c2..f7541455759 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -288,16 +288,16 @@ func initGenFiles( } authGenState.Accounts = accounts - appGenState[authtypes.ModuleName] = clientCtx.JSONMarshaler.MustMarshalJSON(authGenState) + appGenState[authtypes.ModuleName] = clientCtx.JSONMarshaler.MustMarshalJSON(&authGenState) // set the balances in the genesis state var bankGenState banktypes.GenesisState clientCtx.JSONMarshaler.MustUnmarshalJSON(appGenState[banktypes.ModuleName], &bankGenState) bankGenState.Balances = genBalances - appGenState[banktypes.ModuleName] = clientCtx.JSONMarshaler.MustMarshalJSON(bankGenState) + appGenState[banktypes.ModuleName] = clientCtx.JSONMarshaler.MustMarshalJSON(&bankGenState) - appGenStateJSON, err := codec.MarshalJSONIndent(clientCtx.JSONMarshaler, appGenState) + appGenStateJSON, err := codec.MarshalJSONIndent(clientCtx.LegacyAmino, appGenState) if err != nil { return err } diff --git a/simapp/state.go b/simapp/state.go index 9d646461c43..da8beaa7520 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -21,7 +21,7 @@ import ( // AppStateFn returns the initial application state using a genesis or the simulation parameters. // It panics if the user provides files for both of them. // If a file is not given for the genesis or the sim params, it creates a randomized one. -func AppStateFn(cdc codec.JSONMarshaler, simManager *module.SimulationManager) simtypes.AppStateFn { +func AppStateFn(cdc codec.JSONMarshaler, legacyAmino *codec.LegacyAmino, simManager *module.SimulationManager) simtypes.AppStateFn { return func(r *rand.Rand, accs []simtypes.Account, config simtypes.Config, ) (appState json.RawMessage, simAccs []simtypes.Account, chainID string, genesisTimestamp time.Time) { @@ -38,7 +38,7 @@ func AppStateFn(cdc codec.JSONMarshaler, simManager *module.SimulationManager) s case config.GenesisFile != "": // override the default chain-id from simapp to set it later to the config - genesisDoc, accounts := AppStateFromGenesisFileFn(r, cdc, config.GenesisFile) + genesisDoc, accounts := AppStateFromGenesisFileFn(r, cdc, legacyAmino, config.GenesisFile) if FlagGenesisTimeValue == 0 { // use genesis timestamp if no custom timestamp is provided (i.e no random timestamp) @@ -56,12 +56,12 @@ func AppStateFn(cdc codec.JSONMarshaler, simManager *module.SimulationManager) s panic(err) } - cdc.MustUnmarshalJSON(bz, &appParams) - appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) + legacyAmino.MustUnmarshalJSON(bz, &appParams) + appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, legacyAmino, accs, genesisTimestamp, appParams) default: appParams := make(simtypes.AppParams) - appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) + appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, legacyAmino, accs, genesisTimestamp, appParams) } return appState, simAccs, chainID, genesisTimestamp @@ -71,7 +71,7 @@ func AppStateFn(cdc codec.JSONMarshaler, simManager *module.SimulationManager) s // AppStateRandomizedFn creates calls each module's GenesisState generator function // and creates the simulation params func AppStateRandomizedFn( - simManager *module.SimulationManager, r *rand.Rand, cdc codec.JSONMarshaler, + simManager *module.SimulationManager, r *rand.Rand, cdc codec.JSONMarshaler, legacyAmino *codec.LegacyAmino, accs []simtypes.Account, genesisTimestamp time.Time, appParams simtypes.AppParams, ) (json.RawMessage, []simtypes.Account) { numAccs := int64(len(accs)) @@ -125,17 +125,17 @@ func AppStateRandomizedFn( // AppStateFromGenesisFileFn util function to generate the genesis AppState // from a genesis.json file. -func AppStateFromGenesisFileFn(r io.Reader, cdc codec.JSONMarshaler, genesisFile string) (tmtypes.GenesisDoc, []simtypes.Account) { +func AppStateFromGenesisFileFn(r io.Reader, cdc codec.JSONMarshaler, legacyAmino *codec.LegacyAmino, genesisFile string) (tmtypes.GenesisDoc, []simtypes.Account) { bytes, err := ioutil.ReadFile(genesisFile) if err != nil { panic(err) } var genesis tmtypes.GenesisDoc - cdc.MustUnmarshalJSON(bytes, &genesis) + legacyAmino.MustUnmarshalJSON(bytes, &genesis) var appState GenesisState - cdc.MustUnmarshalJSON(genesis.AppState, &appState) + legacyAmino.MustUnmarshalJSON(genesis.AppState, &appState) 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 cf32937f809..decc58ed2c4 100644 --- a/tests/mocks/types_module_module.go +++ b/tests/mocks/types_module_module.go @@ -503,7 +503,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 797c29cdb6a..7786ec6edf1 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -160,7 +160,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) @@ -193,7 +193,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 } func (gam GenesisOnlyAppModule) RegisterQueryService(grpc.Server) {} @@ -264,7 +264,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 0826a76bb23..80c14cdca6e 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,10 @@ func TestManager_InitGenesis(t *testing.T) { require.NotNil(t, mm) require.Equal(t, 2, len(mm.Modules)) - cdc, ctx := codec.New(), sdk.Context{} + // 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 +230,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/module/simulation.go b/types/module/simulation.go index e01277f457a..002342c6422 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -99,6 +99,7 @@ func (sm *SimulationManager) WeightedOperations(simState SimulationState) []simu // GenesisState generator function type SimulationState struct { AppParams simulation.AppParams + LegacyAmino *codec.LegacyAmino Cdc codec.JSONMarshaler // application codec Rand *rand.Rand // random number GenState map[string]json.RawMessage // genesis state @@ -109,4 +110,5 @@ type SimulationState struct { UnbondTime time.Duration // staking unbond time stored to use it as the slashing maximum evidence duration ParamChanges []simulation.ParamChange // simulated parameter changes from modules Contents []simulation.WeightedProposalContent // proposal content generator functions with their default weight and app sim key + } diff --git a/types/rest/rest_test.go b/types/rest/rest_test.go index e05deb18771..5116593ca94 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 0474d616308..f7f75a3c326 100644 --- a/types/simulation/types.go +++ b/types/simulation/types.go @@ -2,12 +2,14 @@ package simulation import ( "encoding/json" + "fmt" "math/rand" "time" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/gogo/protobuf/proto" ) type WeightedProposalContent interface { @@ -137,7 +139,12 @@ type AppParams map[string]json.RawMessage // 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) { if v, ok := sp[key]; ok && v != nil { - cdc.MustUnmarshalJSON(v, ptr) + msg, ok := ptr.(proto.Message) + if !ok { + panic(fmt.Errorf("can't proto marshal %T", ptr)) + } + + cdc.MustUnmarshalJSON(v, msg) return } diff --git a/x/auth/client/cli/query.go b/x/auth/client/cli/query.go index d58a303ca59..3706a3a4720 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 d778284cf5a..37daf508403 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.WithLegacyAmino(clientCtx.LegacyAmino) rest.PostProcessResponseBare(w, clientCtx, res) } } diff --git a/x/auth/client/rest/decode.go b/x/auth/client/rest/decode.go index 5081412b6ab..ed327a78e73 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_test.go b/x/auth/keeper/querier_test.go index 470ebb82619..4d468956dd4 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) diff --git a/x/auth/module.go b/x/auth/module.go index 96b096ae593..b40c2dfb1e0 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -113,7 +113,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 e1b3b293a5e..390a1e1a4fc 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -89,7 +89,7 @@ func RandomizedGenState(simState *module.SimulationState) { authGenesis := types.NewGenesisState(params, genesisAccs) - fmt.Printf("Selected randomly generated auth parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.Cdc, &authGenesis.Params)) + fmt.Printf("Selected randomly generated auth parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.LegacyAmino, &authGenesis.Params)) 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 e0ae05f87cb..6fcc6c540bb 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,10 @@ 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) + legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -28,6 +29,7 @@ func TestRandomizedGenState(t *testing.T) { simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, + LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), diff --git a/x/bank/client/cli/cli_test.go b/x/bank/client/cli/cli_test.go index e51ee19b711..819916449d3 100644 --- a/x/bank/client/cli/cli_test.go +++ b/x/bank/client/cli/cli_test.go @@ -116,7 +116,7 @@ func (s *IntegrationTestSuite) TestGetBalancesCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType)) + s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType)) s.Require().Equal(tc.expected.String(), tc.respType.String()) } }) @@ -303,7 +303,7 @@ 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.LegacyAmino.UnmarshalJSON(bz.Bytes(), tc.respType), bz.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) diff --git a/x/bank/client/rest/query.go b/x/bank/client/rest/query.go index b8e25822595..7c88c790f83 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 a59450c3f0a..e630710dff2 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_test.go b/x/bank/keeper/querier_test.go index 0e1ba93d09c..84ec3d09579 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 21726cf86aa..00c1e69b75b 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -118,7 +118,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 61a28932815..1b8a207e6e5 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -77,6 +77,6 @@ func RandomizedGenState(simState *module.SimulationState) { Supply: supply, } - fmt.Printf("Selected randomly generated bank parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.Cdc, &bankGenesis.Params)) + fmt.Printf("Selected randomly generated bank parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.LegacyAmino, &bankGenesis.Params)) 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 8bc2d8d4425..2e4e28260a6 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,13 +18,16 @@ 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) + legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, + LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -46,7 +50,9 @@ 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) + legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -60,9 +66,10 @@ 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, + LegacyAmino: legacyAmino, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/bank/types/codec.go b/x/bank/types/codec.go index 5b869df7461..b0acd6b7c19 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/capability/module.go b/x/capability/module.go index b4aa43f0218..099434393ef 100644 --- a/x/capability/module.go +++ b/x/capability/module.go @@ -107,7 +107,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 465a9aa4724..911e313436a 100644 --- a/x/capability/simulation/genesis.go +++ b/x/capability/simulation/genesis.go @@ -31,6 +31,6 @@ 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)) + fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, codec.MustMarshalJSONIndent(simState.LegacyAmino, &capabilityGenesis)) 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 5c255e2f764..40664da2f7c 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,13 +18,16 @@ 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) + legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, + LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -42,7 +46,9 @@ 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) + legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -56,9 +62,10 @@ 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, + LegacyAmino: legacyAmino, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/crisis/client/cli/cli_test.go b/x/crisis/client/cli/cli_test.go index 4d93a0a3a0c..ac50861f34b 100644 --- a/x/crisis/client/cli/cli_test.go +++ b/x/crisis/client/cli/cli_test.go @@ -105,7 +105,7 @@ func (s *IntegrationTestSuite) TestNewMsgVerifyInvariantTxCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) diff --git a/x/crisis/module.go b/x/crisis/module.go index 97f6a10d676..8a3d9a1e7ef 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -107,7 +107,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/distribution/client/cli/cli_test.go b/x/distribution/client/cli/cli_test.go index 8d76c3ee433..935c305df0c 100644 --- a/x/distribution/client/cli/cli_test.go +++ b/x/distribution/client/cli/cli_test.go @@ -555,7 +555,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawRewardsCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(bz, tc.respType), string(bz)) + s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(bz, tc.respType), string(bz)) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) @@ -616,7 +616,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawAllRewardsCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) @@ -679,7 +679,7 @@ func (s *IntegrationTestSuite) TestNewSetWithdrawAddrCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) @@ -742,7 +742,7 @@ func (s *IntegrationTestSuite) TestNewFundCommunityPoolCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) @@ -835,7 +835,7 @@ func (s *IntegrationTestSuite) TestGetCmdSubmitProposal() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) diff --git a/x/distribution/client/common/common_test.go b/x/distribution/client/common/common_test.go index 9adef2662e8..6b3ecdd5cdf 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 9f90e31f540..0fb923afc94 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_test.go b/x/distribution/keeper/querier_test.go index 154c61b5613..df78462e0d0 100644 --- a/x/distribution/keeper/querier_test.go +++ b/x/distribution/keeper/querier_test.go @@ -113,7 +113,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, abci.Header{}) @@ -122,7 +121,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 ca20c9e0ba9..71501a43b69 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -129,7 +129,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 e4b79bdbb63..39f49e229e2 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -77,6 +77,6 @@ func RandomizedGenState(simState *module.SimulationState) { }, } - fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.Cdc, &distrGenesis)) + fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.LegacyAmino, &distrGenesis)) 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 2ee2464b645..4a4af80f0d0 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,13 +19,16 @@ 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) + legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, + LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -52,7 +56,9 @@ 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) + legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -66,9 +72,10 @@ 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, + LegacyAmino: legacyAmino, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/evidence/client/rest/query.go b/x/evidence/client/rest/query.go index bc74cd30078..21ae8b7bb30 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 b52334b45e1..0650d37c4f4 100644 --- a/x/evidence/keeper/keeper_test.go +++ b/x/evidence/keeper/keeper_test.go @@ -6,8 +6,6 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" @@ -83,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( @@ -96,7 +93,7 @@ func (suite *KeeperTestSuite) SetupTest() { app.EvidenceKeeper = *evidenceKeeper suite.ctx = app.BaseApp.NewContext(checkTx, abci.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/module.go b/x/evidence/module.go index 9867b692bc4..1c8241bf236 100644 --- a/x/evidence/module.go +++ b/x/evidence/module.go @@ -138,7 +138,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 9d1aa4c6c96..4829a73c0e1 100644 --- a/x/evidence/simulation/genesis.go +++ b/x/evidence/simulation/genesis.go @@ -33,6 +33,6 @@ 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)) + fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, codec.MustMarshalJSONIndent(simState.LegacyAmino, evidenceGenesis)) 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 633f7a8e0ff..c4e5cca1749 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,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) + legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -25,6 +28,7 @@ func TestRandomizedGenState(t *testing.T) { simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, + LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), diff --git a/x/genutil/client/cli/collect.go b/x/genutil/client/cli/collect.go index 1fefbe382a8..9ef6bff8b2f 100644 --- a/x/genutil/client/cli/collect.go +++ b/x/genutil/client/cli/collect.go @@ -28,6 +28,7 @@ func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, defaultNodeH clientCtx := client.GetClientContextFromCmd(cmd) cdc := clientCtx.JSONMarshaler + legacyAmino := clientCtx.LegacyAmino config.SetRoot(clientCtx.HomeDir) @@ -59,7 +60,7 @@ func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, defaultNodeH toPrint.AppMessage = appMessage - return displayInfo(cdc, toPrint) + return displayInfo(legacyAmino, toPrint) }, } diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 2269a3eb637..6a5c9e408e1 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -45,8 +45,8 @@ func newPrintInfo(moniker, chainID, nodeID, genTxsDir string, appMessage json.Ra } } -func displayInfo(cdc codec.JSONMarshaler, info printInfo) error { - out, err := codec.MarshalJSONIndent(cdc, info) +func displayInfo(legacyAmino *codec.LegacyAmino, info printInfo) error { + out, err := codec.MarshalJSONIndent(legacyAmino, info) if err != nil { return err } @@ -67,6 +67,7 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { clientCtx := client.GetClientContextFromCmd(cmd) cdc := clientCtx.JSONMarshaler + legacyAmino := clientCtx.LegacyAmino serverCtx := server.GetServerContextFromCmd(cmd) config := serverCtx.Config @@ -91,7 +92,7 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { if !overwrite && tmos.FileExists(genFile) { return fmt.Errorf("genesis.json file already exists: %v", genFile) } - appState, err := codec.MarshalJSONIndent(cdc, mbm.DefaultGenesis(cdc)) + appState, err := codec.MarshalJSONIndent(legacyAmino, mbm.DefaultGenesis(cdc)) if err != nil { return errors.Wrap(err, "Failed to marshall default genesis state") } @@ -118,7 +119,7 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { toPrint := newPrintInfo(config.Moniker, chainID, nodeID, "", appState) cfg.WriteConfigFile(filepath.Join(config.RootDir, "config", "config.toml"), config) - return displayInfo(cdc, toPrint) + return displayInfo(legacyAmino, toPrint) }, } diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index a0e2bc5f136..769ab55ed19 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -18,6 +18,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" @@ -72,7 +73,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) @@ -110,7 +116,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) @@ -157,7 +168,12 @@ func TestStartStandAlone(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) diff --git a/x/genutil/client/cli/migrate.go b/x/genutil/client/cli/migrate.go index c0453e8344c..d43881129dc 100644 --- a/x/genutil/client/cli/migrate.go +++ b/x/genutil/client/cli/migrate.go @@ -69,7 +69,7 @@ $ %s migrate v0.36 /path/to/genesis.json --chain-id=cosmoshub-3 --genesis-time=2 Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { clientCtx := client.GetClientContextFromCmd(cmd) - cdc := clientCtx.JSONMarshaler + legacyAmino := clientCtx.LegacyAmino var err error @@ -82,7 +82,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 := legacyAmino.UnmarshalJSON(genDoc.AppState, &initialState); err != nil { return errors.Wrap(err, "failed to JSON unmarshal initial genesis state") } @@ -94,7 +94,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 = legacyAmino.MarshalJSON(newGenState) if err != nil { return errors.Wrap(err, "failed to JSON marshal migrated genesis state") } @@ -116,7 +116,7 @@ $ %s migrate v0.36 /path/to/genesis.json --chain-id=cosmoshub-3 --genesis-time=2 genDoc.ChainID = chainID } - bz, err := codec.MarshalJSONIndent(cdc, genDoc) + bz, err := codec.MarshalJSONIndent(legacyAmino, genDoc) if err != nil { return errors.Wrap(err, "failed to marshal genesis doc") } diff --git a/x/genutil/client/cli/migrate_test.go b/x/genutil/client/cli/migrate_test.go index d5d35754ee9..8dc495ed141 100644 --- a/x/genutil/client/cli/migrate_test.go +++ b/x/genutil/client/cli/migrate_test.go @@ -30,7 +30,7 @@ func TestMigrateGenesis(t *testing.T) { cmd := 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 756b06a26ea..7cde3ac8183 100644 --- a/x/genutil/client/cli/validate_genesis.go +++ b/x/genutil/client/cli/validate_genesis.go @@ -24,6 +24,7 @@ func ValidateGenesisCmd(mbm module.BasicManager, txEncCfg client.TxEncodingConfi clientCtx := client.GetClientContextFromCmd(cmd) cdc := clientCtx.JSONMarshaler + legacyAmino := clientCtx.LegacyAmino // Load default if passed no args, otherwise load passed file var genesis string @@ -41,7 +42,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 = legacyAmino.UnmarshalJSON(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 e66071a871e..7361c4672a0 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 a7915b717ff..b3e28bb6de8 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 adb77154897..5d2b2d8627b 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 9c387992b34..d69c50d0a79 100644 --- a/x/gov/client/cli/cli_test.go +++ b/x/gov/client/cli/cli_test.go @@ -152,7 +152,7 @@ func (s *IntegrationTestSuite) TestNewCmdSubmitProposal() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index 48af66a62d2..26a2efd6a7b 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 7c7228a3b22..d526629be9d 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 f03d4393b23..400148bd7d1 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -65,7 +65,9 @@ func QueryDepositsByTxQuery(clientCtx client.Context, params types.QueryProposal } } - bz, err := clientCtx.JSONMarshaler.MarshalJSON(deposits) + // TODO migrate to use JSONMarshaler (implement MarshalJSONArray + // or wrap lists of proto.Message in some other message) + bz, err := clientCtx.LegacyAmino.MarshalJSON(deposits) if err != nil { return nil, err } @@ -117,7 +119,9 @@ func QueryVotesByTxQuery(clientCtx client.Context, params types.QueryProposalVot votes = votes[start:end] } - bz, err := clientCtx.JSONMarshaler.MarshalJSON(votes) + // TODO migrate to use JSONMarshaler (implement MarshalJSONArray + // or wrap lists of proto.Message in some other message) + bz, err := clientCtx.LegacyAmino.MarshalJSON(votes) if err != nil { return nil, err } @@ -151,7 +155,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 +196,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 +240,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 8985b4d91d2..8a319fc74be 100644 --- a/x/gov/client/utils/query_test.go +++ b/x/gov/client/utils/query_test.go @@ -146,7 +146,6 @@ func TestGetPaginatedVotes(t *testing.T) { cli := TxSearchMock{txs: marshalled} clientCtx := client.Context{}. - WithJSONMarshaler(cdc). WithLegacyAmino(cdc). WithClient(cli) @@ -154,7 +153,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_test.go b/x/gov/keeper/querier_test.go index 0c04995fc4e..58dc8e0912a 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -18,7 +18,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{}, @@ -59,7 +59,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 { @@ -78,7 +78,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)), @@ -94,7 +94,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)), @@ -110,7 +110,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)), @@ -126,7 +126,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}, "/"), @@ -146,8 +146,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, abci.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)) @@ -157,7 +156,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) @@ -205,35 +204,35 @@ 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]) @@ -249,45 +248,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 25bbf604825..c434e62f84e 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -145,7 +145,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 694c54e651b..e34ba8af932 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -102,6 +102,6 @@ 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)) + fmt.Printf("Selected randomly generated governance parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.LegacyAmino, govGenesis)) 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 0a6e32d62c4..2495d745c7a 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,13 +19,17 @@ 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) + legacyAmino := codec.New() + s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, + LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -48,14 +53,16 @@ func TestRandomizedGenState(t *testing.T) { require.Equal(t, dec2, govGenesis.TallyParams.Threshold) require.Equal(t, dec3, govGenesis.TallyParams.Veto) 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) + legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -68,9 +75,10 @@ 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, + LegacyAmino: legacyAmino, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/ibc-transfer/module.go b/x/ibc-transfer/module.go index 2119c2dbc58..cd5bff067ad 100644 --- a/x/ibc-transfer/module.go +++ b/x/ibc-transfer/module.go @@ -112,7 +112,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 b191e3c6da8..a6cb86fb5d7 100644 --- a/x/ibc-transfer/simulation/genesis.go +++ b/x/ibc-transfer/simulation/genesis.go @@ -26,6 +26,6 @@ func RandomizedGenState(simState *module.SimulationState) { PortID: portID, } - fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, codec.MustMarshalJSONIndent(simState.Cdc, &transferGenesis)) + fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, codec.MustMarshalJSONIndent(simState.LegacyAmino, &transferGenesis)) 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 46ac79d2a42..c0959a75c40 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,13 +18,17 @@ 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) + legacyAmino := codec.New() + s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, + LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -42,7 +47,9 @@ 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) + legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -55,9 +62,10 @@ 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, + LegacyAmino: legacyAmino, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/ibc/02-client/client/rest/query.go b/x/ibc/02-client/client/rest/query.go index 41c28f68f39..93dc1573aeb 100644 --- a/x/ibc/02-client/client/rest/query.go +++ b/x/ibc/02-client/client/rest/query.go @@ -145,7 +145,7 @@ func queryHeaderHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - res := clientCtx.JSONMarshaler.MustMarshalJSON(header) + res := clientCtx.LegacyAmino.MustMarshalJSON(header) clientCtx = clientCtx.WithHeight(height) rest.PostProcessResponse(w, clientCtx, res) } diff --git a/x/ibc/02-client/keeper/querier.go b/x/ibc/02-client/keeper/querier.go index 416c7e3aeaa..6e73d1bb5e6 100644 --- a/x/ibc/02-client/keeper/querier.go +++ b/x/ibc/02-client/keeper/querier.go @@ -12,7 +12,7 @@ import ( ) // QuerierClients defines the sdk.Querier to query all the light client states. -func QuerierClients(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc codec.JSONMarshaler) ([]byte, error) { +func QuerierClients(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryAllClientsParams if err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { diff --git a/x/ibc/keeper/keeper_test.go b/x/ibc/keeper/keeper_test.go index b6b97af7452..84d26253fde 100644 --- a/x/ibc/keeper/keeper_test.go +++ b/x/ibc/keeper/keeper_test.go @@ -25,12 +25,11 @@ type KeeperTestSuite struct { func (suite *KeeperTestSuite) SetupTest() { isCheckTx := false app := simapp.Setup(isCheckTx) - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) suite.cdc = app.LegacyAmino() suite.ctx = app.BaseApp.NewContext(isCheckTx, abci.Header{}) suite.keeper = app.IBCKeeper - suite.querier = keeper.NewQuerier(*app.IBCKeeper, legacyQuerierCdc) + suite.querier = keeper.NewQuerier(*app.IBCKeeper, app.LegacyAmino()) } func TestKeeperTestSuite(t *testing.T) { diff --git a/x/ibc/keeper/querier.go b/x/ibc/keeper/querier.go index 0c0965cbc95..e6f4bcf4f78 100644 --- a/x/ibc/keeper/querier.go +++ b/x/ibc/keeper/querier.go @@ -14,7 +14,7 @@ import ( ) // NewQuerier creates a querier for the IBC 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) { var ( res []byte diff --git a/x/ibc/module.go b/x/ibc/module.go index 3a5e2893c49..847d0edd104 100644 --- a/x/ibc/module.go +++ b/x/ibc/module.go @@ -120,7 +120,7 @@ func (AppModule) QuerierRoute() string { } // LegacyQuerierHandler returns the ibc 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/ibc/simulation/genesis.go b/x/ibc/simulation/genesis.go index 3aff7ff6275..46546cb9266 100644 --- a/x/ibc/simulation/genesis.go +++ b/x/ibc/simulation/genesis.go @@ -55,6 +55,6 @@ func RandomizedGenState(simState *module.SimulationState) { ChannelGenesis: channelGenesisState, } - fmt.Printf("Selected randomly generated %s parameters:\n%s\n", host.ModuleName, codec.MustMarshalJSONIndent(simState.Cdc, &ibcGenesis)) + fmt.Printf("Selected randomly generated %s parameters:\n%s\n", host.ModuleName, codec.MustMarshalJSONIndent(simState.LegacyAmino, &ibcGenesis)) 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 ccd2e5fc626..b69aeab60ee 100644 --- a/x/ibc/simulation/genesis_test.go +++ b/x/ibc/simulation/genesis_test.go @@ -8,27 +8,28 @@ 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) + legacyAmino := codec.New() + s := rand.NewSource(1) r := rand.New(s) - // Make sure to register cdc. - // Otherwise RandomizedGenState will panic! - types.RegisterCodec(cdc) - simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, + LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -44,12 +45,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_test.go b/x/mint/keeper/querier_test.go index d2f1b223a75..2e987aa042c 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 5cdb995e0a8..cedba4f7898 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -112,7 +112,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 b4b3e1534cb..907c23dcdcb 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -87,6 +87,6 @@ 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)) + fmt.Printf("Selected randomly generated minting parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.LegacyAmino, mintGenesis)) 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 e6dbf422124..7099614a25d 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,13 +19,17 @@ 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) + legacyAmino := codec.New() + s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, + LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -55,7 +60,9 @@ 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) + legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -68,9 +75,10 @@ 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, + LegacyAmino: legacyAmino, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/params/client/cli/tx.go b/x/params/client/cli/tx.go index 739fadd3936..fcc80804383 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 cb3199bef4f..b4c680fdde2 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/module.go b/x/params/module.go index bc12ca60a90..c9dace0a3f6 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -99,7 +99,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 f206659b208..b4338a70640 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -157,11 +157,13 @@ func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulato // RandomParams returns random simulation consensus parameters, it extracts the Evidence from the Staking genesis state. func RandomConsensusParams(r *rand.Rand, appState json.RawMessage) *abci.ConsensusParams { - cdc := params.MakeEncodingConfig().Marshaler + encodingConfig := params.MakeEncodingConfig() + cdc := encodingConfig.Marshaler + amino := encodingConfig.Amino var genesisState map[string]json.RawMessage - cdc.UnmarshalJSON(appState, &genesisState) + amino.UnmarshalJSON(appState, &genesisState) stakingGenesisState := stakingtypes.GetGenesisStateFromAppState(cdc, genesisState) @@ -178,7 +180,7 @@ 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)) + fmt.Printf("Selected randomly generated consensus parameters:\n%s\n", codec.MustMarshalJSONIndent(amino, consensusParams)) return consensusParams } diff --git a/x/slashing/client/cli/cli_test.go b/x/slashing/client/cli/cli_test.go index f4569c11dfd..bd0aa6d2462 100644 --- a/x/slashing/client/cli/cli_test.go +++ b/x/slashing/client/cli/cli_test.go @@ -199,7 +199,7 @@ func (s *IntegrationTestSuite) TestNewUnjailTxCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) diff --git a/x/slashing/client/rest/query.go b/x/slashing/client/rest/query.go index 3fb4278f2e5..3cb65d81e03 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 ffe7023b0bc..eaac614fa1c 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_test.go b/x/slashing/keeper/querier_test.go index b26260007ea..7bbf1ce518b 100644 --- a/x/slashing/keeper/querier_test.go +++ b/x/slashing/keeper/querier_test.go @@ -18,7 +18,7 @@ func TestNewQuerier(t *testing.T) { ctx := app.BaseApp.NewContext(false, abci.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: "", @@ -36,7 +36,7 @@ func TestQueryParams(t *testing.T) { ctx := app.BaseApp.NewContext(false, abci.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 01efbd78e6b..1575ae46896 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -127,7 +127,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 5d60c5a5d83..b187b842057 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -88,6 +88,6 @@ 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)) + fmt.Printf("Selected randomly generated slashing parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.LegacyAmino, &slashingGenesis.Params)) 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 e9604dad780..7f0fbb56c7a 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,13 +20,17 @@ 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) + legacyAmino := codec.New() + s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, + LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -54,7 +59,9 @@ 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) + legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -68,9 +75,10 @@ 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, + LegacyAmino: legacyAmino, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/staking/client/cli/cli_test.go b/x/staking/client/cli/cli_test.go index b6e44511d29..67e888e06b4 100644 --- a/x/staking/client/cli/cli_test.go +++ b/x/staking/client/cli/cli_test.go @@ -173,7 +173,7 @@ func (s *IntegrationTestSuite) TestNewCreateValidatorCmd() { s.Require().Error(err) } else { s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) diff --git a/x/staking/client/rest/query.go b/x/staking/client/rest/query.go index 27e458d9b30..8a326c93bc7 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 6cc30499bff..cacba533dc6 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_test.go b/x/staking/keeper/querier_test.go index ae9d2e80789..5d3e5819aec 100644 --- a/x/staking/keeper/querier_test.go +++ b/x/staking/keeper/querier_test.go @@ -46,7 +46,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) @@ -111,7 +111,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 @@ -138,7 +138,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)) @@ -206,7 +206,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] @@ -455,7 +455,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) @@ -540,7 +540,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] @@ -612,7 +612,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] @@ -708,7 +708,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 03a5f0bbcaf..90b0d0f2f05 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -123,7 +123,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 ffe07f68094..bd5f08084ab 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -98,6 +98,6 @@ 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)) + fmt.Printf("Selected randomly generated staking parameters:\n%s\n", codec.MustMarshalJSONIndent(types.ModuleCdc.LegacyAmino, stakingGenesis.Params)) 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 7d8d8feaa69..2022f3efe84 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,13 +18,17 @@ 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) + legacyAmino := codec.New() + s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, + LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -63,7 +68,9 @@ 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) + legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -76,15 +83,17 @@ 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, + LegacyAmino: legacyAmino, + Rand: r, }, "invalid memory address or nil pointer dereference"}, { // panic => reason: numBonded != len(Accnounts) module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, + LegacyAmino: legacyAmino, Rand: r, NumBonded: 4, Accounts: simtypes.RandomAccounts(r, 3), diff --git a/x/upgrade/abci_test.go b/x/upgrade/abci_test.go index 6a915b310a5..d371917ead7 100644 --- a/x/upgrade/abci_test.go +++ b/x/upgrade/abci_test.go @@ -15,7 +15,6 @@ import ( "github.com/tendermint/tendermint/libs/log" dbm "github.com/tendermint/tm-db" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -55,7 +54,7 @@ func setupTest(height int64, skip map[int64]bool) TestSuite { s.ctx = app.BaseApp.NewContext(false, abci.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 2df7b86b9c8..946430634ef 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 9d0fffa650c..227d770f206 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 e13cdadbd6f..f5cd1137355 100644 --- a/x/upgrade/module.go +++ b/x/upgrade/module.go @@ -89,7 +89,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) } From 2d452d48cc38281315b7c9f03942f434017cc179 Mon Sep 17 00:00:00 2001 From: blushi Date: Fri, 14 Aug 2020 16:58:42 +0200 Subject: [PATCH 07/20] Make AminoCodec implement Marshaler and some godoc fixes --- codec/amino.go | 2 +- codec/amino_codec.go | 20 +++++++++++++++++++- simapp/app.go | 2 +- simapp/state.go | 1 + x/auth/keeper/querier_test.go | 6 +++--- x/bank/simulation/params.go | 2 +- 6 files changed, 26 insertions(+), 7 deletions(-) diff --git a/codec/amino.go b/codec/amino.go index 59177efc8b7..e264906b20e 100644 --- a/codec/amino.go +++ b/codec/amino.go @@ -13,7 +13,7 @@ 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 diff --git a/codec/amino_codec.go b/codec/amino_codec.go index 2f579868810..4782d4cf07a 100644 --- a/codec/amino_codec.go +++ b/codec/amino_codec.go @@ -1,12 +1,14 @@ package codec +import "github.com/gogo/protobuf/proto" + // AminoCodec defines a codec that utilizes Codec for both binary and JSON // encoding. type AminoCodec struct { *LegacyAmino } -var _ BinaryMarshaler = &AminoCodec{} +var _ Marshaler = &AminoCodec{} func NewAminoCodec(codec *LegacyAmino) *AminoCodec { return &AminoCodec{LegacyAmino: codec} @@ -43,3 +45,19 @@ func (ac *AminoCodec) UnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshale func (ac *AminoCodec) MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) { ac.LegacyAmino.MustUnmarshalBinaryLengthPrefixed(bz, ptr) } + +func (ac *AminoCodec) MarshalJSON(o proto.Message) ([]byte, error) { + return ac.LegacyAmino.MarshalJSON(o) +} + +func (ac *AminoCodec) MustMarshalJSON(o proto.Message) []byte { + return ac.LegacyAmino.MustMarshalJSON(o) +} + +func (ac *AminoCodec) UnmarshalJSON(bz []byte, ptr proto.Message) error { + return ac.LegacyAmino.UnmarshalJSON(bz, ptr) +} + +func (ac *AminoCodec) MustUnmarshalJSON(bz []byte, ptr proto.Message) { + ac.LegacyAmino.MustUnmarshalJSON(bz, ptr) +} diff --git a/simapp/app.go b/simapp/app.go index 51a11d37af9..e150b7c4a07 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -445,7 +445,7 @@ func (app *SimApp) BlockedAddrs() map[string]bool { return blockedAddrs } -// Codec returns SimApp's codec. +// LegacyAmino returns SimApp's legacy amino codec. // // NOTE: This is solely to be used for testing purposes as it may be desirable // for modules to register their own custom testing types. diff --git a/simapp/state.go b/simapp/state.go index da8beaa7520..d2ef849a774 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -105,6 +105,7 @@ func AppStateRandomizedFn( simState := &module.SimulationState{ AppParams: appParams, Cdc: cdc, + LegacyAmino: legacyAmino, Rand: r, GenState: genesisState, Accounts: accs, diff --git a/x/auth/keeper/querier_test.go b/x/auth/keeper/querier_test.go index 4d468956dd4..55bb20ca7b5 100644 --- a/x/auth/keeper/querier_test.go +++ b/x/auth/keeper/querier_test.go @@ -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/bank/simulation/params.go b/x/bank/simulation/params.go index a2699659f6d..e4d14983f0d 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -18,7 +18,7 @@ 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))) + return fmt.Sprintf("%s", types.ModuleCdc.LegacyAmino.MustMarshalJSON(RandomGenesisSendParams(r))) }, ), simulation.NewSimParamChange(types.ModuleName, string(types.KeyDefaultSendEnabled), From 28db5eac02d0858b67c8a6a057750cd4a6252af9 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Mon, 17 Aug 2020 12:18:11 -0400 Subject: [PATCH 08/20] Test fixes --- go.sum | 10 ---------- x/genutil/client/cli/collect.go | 1 - x/genutil/client/cli/init.go | 1 - 3 files changed, 12 deletions(-) diff --git a/go.sum b/go.sum index 95c4fc39b08..8b0b98c6b6d 100644 --- a/go.sum +++ b/go.sum @@ -179,8 +179,6 @@ github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4er github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= -github.com/golang/mock v1.4.3 h1:GV+pQPG/EUUbkh47niozDcADz6go/dUwhVzdUQHIVRw= -github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -237,8 +235,6 @@ github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= -github.com/grpc-ecosystem/grpc-gateway v1.14.6 h1:8ERzHx8aj1Sc47mu9n/AksaKCSWrMchFtkdrS4BIj5o= -github.com/grpc-ecosystem/grpc-gateway v1.14.6/go.mod h1:zdiPV4Yse/1gnckTHtghG4GkDEdKCRJduHpTxT3/jcw= github.com/grpc-ecosystem/grpc-gateway v1.14.7 h1:Nk5kuHrnWUTf/0GL1a/vchH/om9Ap2/HnVna+jYZgTY= github.com/grpc-ecosystem/grpc-gateway v1.14.7/go.mod h1:oYZKL012gGh6LMyg/xA7Q2yq6j8bu0wa+9w14EEthWU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= @@ -432,8 +428,6 @@ github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt2 github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= github.com/prometheus/common v0.10.0 h1:RyRA7RzGXQZiW+tGMr7sxa85G1z0yOpM1qq5c8lNawc= github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= -github.com/prometheus/common v0.11.1 h1:0ZISXCMRuCZcxF77aT1BXY5m74mX2vrGYl1dSwBI0Jo= -github.com/prometheus/common v0.11.1/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s= github.com/prometheus/common v0.12.0 h1:mj4ewtVukAfkS37JU7IXPJPr7zwLEjwgWO6nZo8ROvk= github.com/prometheus/common v0.12.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= @@ -661,7 +655,6 @@ golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1 h1:ogLJMz+qpzav7lGMh10LMvAkM golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae h1:Ih9Yo4hSPImZOpfGuA4bR/ORKTAbhZo2AbWNRCnevdo= golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= @@ -736,7 +729,6 @@ google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQ google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.31.0 h1:T7P4R73V3SSDPhH7WW7ATbfViLtmamH0DKrP3f9AuDI= google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= @@ -785,7 +777,5 @@ honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= -rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= -rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= diff --git a/x/genutil/client/cli/collect.go b/x/genutil/client/cli/collect.go index a374b511214..cc862583680 100644 --- a/x/genutil/client/cli/collect.go +++ b/x/genutil/client/cli/collect.go @@ -28,7 +28,6 @@ func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, defaultNodeH clientCtx := client.GetClientContextFromCmd(cmd) cdc := clientCtx.JSONMarshaler - legacyAmino := clientCtx.LegacyAmino config.SetRoot(clientCtx.HomeDir) diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 3b0ed752535..60eb18deed2 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -67,7 +67,6 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { clientCtx := client.GetClientContextFromCmd(cmd) cdc := clientCtx.JSONMarshaler - legacyAmino := clientCtx.LegacyAmino serverCtx := server.GetServerContextFromCmd(cmd) config := serverCtx.Config From 2b65f5ab1438aa4f3d772a19eb15c66c790a314d Mon Sep 17 00:00:00 2001 From: blushi Date: Wed, 19 Aug 2020 09:46:04 +0200 Subject: [PATCH 09/20] Remove unrelevant comment --- x/gov/client/utils/query.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/x/gov/client/utils/query.go b/x/gov/client/utils/query.go index 6e32ea9bd5e..9c62ac86582 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -65,8 +65,6 @@ func QueryDepositsByTxQuery(clientCtx client.Context, params types.QueryProposal } } - // TODO migrate to use JSONMarshaler (implement MarshalJSONArray - // or wrap lists of proto.Message in some other message) bz, err := clientCtx.LegacyAmino.MarshalJSON(deposits) if err != nil { return nil, err @@ -119,8 +117,6 @@ func QueryVotesByTxQuery(clientCtx client.Context, params types.QueryProposalVot votes = votes[start:end] } - // TODO migrate to use JSONMarshaler (implement MarshalJSONArray - // or wrap lists of proto.Message in some other message) bz, err := clientCtx.LegacyAmino.MarshalJSON(votes) if err != nil { return nil, err From b4da972bcc8ddca5c360c92cdaa091f0a536a5ea Mon Sep 17 00:00:00 2001 From: blushi Date: Wed, 19 Aug 2020 10:43:57 +0200 Subject: [PATCH 10/20] Use TxConfig.TxJSONEncoder --- client/tx/tx.go | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/client/tx/tx.go b/client/tx/tx.go index 61fc8a13046..790bf89ce1d 100644 --- a/client/tx/tx.go +++ b/client/tx/tx.go @@ -9,7 +9,6 @@ import ( "strings" "github.com/gogo/protobuf/jsonpb" - "github.com/gogo/protobuf/proto" "github.com/spf13/pflag" "github.com/tendermint/tendermint/crypto" @@ -101,12 +100,7 @@ func BroadcastTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error { } if !clientCtx.SkipConfirm { - msg, ok := tx.(proto.Message) - if !ok { - return fmt.Errorf("can't proto marshal %T", tx) - } - - out, err := clientCtx.JSONMarshaler.MarshalJSON(msg) + out, err := clientCtx.TxConfig.TxJSONEncoder()(tx.GetTx()) if err != nil { return err } @@ -114,7 +108,7 @@ func BroadcastTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error { _, _ = fmt.Fprintf(os.Stderr, "%s\n\n", out) buf := bufio.NewReader(os.Stdin) - ok, err = input.GetConfirmation("confirm transaction before signing and broadcasting", buf, os.Stderr) + ok, err := input.GetConfirmation("confirm transaction before signing and broadcasting", buf, os.Stderr) if err != nil || !ok { _, _ = fmt.Fprintf(os.Stderr, "%s\n", "cancelled transaction") From ecc133aa06dcb5d36085c4ae5887fc527964a4c2 Mon Sep 17 00:00:00 2001 From: blushi Date: Wed, 19 Aug 2020 15:25:15 +0200 Subject: [PATCH 11/20] Use encoding/json in genutil cli migrate/validate genesis cmds --- x/genutil/client/cli/migrate.go | 8 ++------ x/genutil/client/cli/validate_genesis.go | 3 +-- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/x/genutil/client/cli/migrate.go b/x/genutil/client/cli/migrate.go index 756ac0a6266..151beef124d 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) - legacyAmino := clientCtx.LegacyAmino - 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 := legacyAmino.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 = legacyAmino.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/validate_genesis.go b/x/genutil/client/cli/validate_genesis.go index 7cde3ac8183..a2e148b24be 100644 --- a/x/genutil/client/cli/validate_genesis.go +++ b/x/genutil/client/cli/validate_genesis.go @@ -24,7 +24,6 @@ func ValidateGenesisCmd(mbm module.BasicManager, txEncCfg client.TxEncodingConfi clientCtx := client.GetClientContextFromCmd(cmd) cdc := clientCtx.JSONMarshaler - legacyAmino := clientCtx.LegacyAmino // Load default if passed no args, otherwise load passed file var genesis string @@ -42,7 +41,7 @@ func ValidateGenesisCmd(mbm module.BasicManager, txEncCfg client.TxEncodingConfi } var genState map[string]json.RawMessage - if err = legacyAmino.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()) } From 7e6d09d7e49f42d38368b4a5246b2b22eb64500e Mon Sep 17 00:00:00 2001 From: blushi Date: Wed, 19 Aug 2020 17:26:42 +0200 Subject: [PATCH 12/20] Address simulation related comments --- simapp/app.go | 2 +- simapp/sim_bench_test.go | 4 ++-- simapp/sim_test.go | 10 ++++---- simapp/state.go | 28 +++++++++++++++-------- types/module/simulation.go | 1 - x/auth/simulation/genesis.go | 8 +++++-- x/auth/simulation/genesis_test.go | 2 -- x/bank/simulation/genesis.go | 8 +++++-- x/bank/simulation/genesis_test.go | 10 +++----- x/bank/simulation/params.go | 7 +++++- x/capability/simulation/genesis.go | 9 +++++--- x/capability/simulation/genesis_test.go | 10 +++----- x/distribution/simulation/genesis.go | 9 +++++--- x/distribution/simulation/genesis_test.go | 10 +++----- x/evidence/simulation/genesis.go | 9 +++++--- x/evidence/simulation/genesis_test.go | 2 -- x/gov/simulation/genesis.go | 9 +++++--- x/gov/simulation/genesis_test.go | 4 ---- x/ibc-transfer/simulation/genesis.go | 8 +++++-- x/ibc-transfer/simulation/genesis_test.go | 10 +++----- x/ibc/simulation/genesis.go | 9 +++++--- x/ibc/simulation/genesis_test.go | 2 -- x/mint/simulation/genesis.go | 9 +++++--- x/mint/simulation/genesis_test.go | 10 +++----- x/simulation/params.go | 17 +++++++++----- x/slashing/simulation/genesis.go | 9 +++++--- x/slashing/simulation/genesis_test.go | 10 +++----- x/staking/simulation/genesis.go | 9 +++++--- x/staking/simulation/genesis_test.go | 11 +++------ 29 files changed, 130 insertions(+), 116 deletions(-) diff --git a/simapp/app.go b/simapp/app.go index c413413c6a0..2e45f0ed9a0 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -329,7 +329,7 @@ func NewSimApp( ) app.mm.RegisterInvariants(&app.CrisisKeeper) - app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), codec.NewAminoCodec(encodingConfig.Amino).LegacyAmino) + app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino) app.mm.RegisterQueryServices(app.GRPCQueryRouter()) // add test gRPC service for testing gRPC queries in isolation diff --git a/simapp/sim_bench_test.go b/simapp/sim_bench_test.go index 51976c761e7..ed97770034b 100644 --- a/simapp/sim_bench_test.go +++ b/simapp/sim_bench_test.go @@ -30,7 +30,7 @@ func BenchmarkFullAppSimulation(b *testing.B) { // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - b, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), + b, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, ) @@ -69,7 +69,7 @@ func BenchmarkInvariants(b *testing.B) { // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - b, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), + b, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, ) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index bee6de488f0..6428e1a656a 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -72,7 +72,7 @@ func TestFullAppSimulation(t *testing.T) { // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), + t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, ) @@ -104,7 +104,7 @@ func TestAppImportExport(t *testing.T) { // Run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), + t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, ) @@ -195,7 +195,7 @@ func TestAppSimulationAfterImport(t *testing.T) { // Run randomized simulation stopEarly, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), + t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, ) @@ -237,7 +237,7 @@ func TestAppSimulationAfterImport(t *testing.T) { }) _, _, err = simulation.SimulateFromSeed( - t, os.Stdout, newApp.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), + t, os.Stdout, newApp.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), SimulationOperations(newApp, newApp.AppCodec(), config), newApp.ModuleAccountAddrs(), config, ) @@ -282,7 +282,7 @@ func TestAppStateDeterminism(t *testing.T) { ) _, _, err := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.LegacyAmino(), app.SimulationManager()), + t, os.Stdout, app.BaseApp, AppStateFn(app.AppCodec(), app.SimulationManager()), SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, ) diff --git a/simapp/state.go b/simapp/state.go index 8dcc25875a8..487152b1a26 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -21,7 +21,7 @@ import ( // AppStateFn returns the initial application state using a genesis or the simulation parameters. // It panics if the user provides files for both of them. // If a file is not given for the genesis or the sim params, it creates a randomized one. -func AppStateFn(cdc codec.JSONMarshaler, legacyAmino *codec.LegacyAmino, simManager *module.SimulationManager) simtypes.AppStateFn { +func AppStateFn(cdc codec.JSONMarshaler, simManager *module.SimulationManager) simtypes.AppStateFn { return func(r *rand.Rand, accs []simtypes.Account, config simtypes.Config, ) (appState json.RawMessage, simAccs []simtypes.Account, chainID string, genesisTimestamp time.Time) { @@ -38,7 +38,7 @@ func AppStateFn(cdc codec.JSONMarshaler, legacyAmino *codec.LegacyAmino, simMana case config.GenesisFile != "": // override the default chain-id from simapp to set it later to the config - genesisDoc, accounts := AppStateFromGenesisFileFn(r, cdc, legacyAmino, config.GenesisFile) + genesisDoc, accounts := AppStateFromGenesisFileFn(r, cdc, config.GenesisFile) if FlagGenesisTimeValue == 0 { // use genesis timestamp if no custom timestamp is provided (i.e no random timestamp) @@ -56,12 +56,15 @@ func AppStateFn(cdc codec.JSONMarshaler, legacyAmino *codec.LegacyAmino, simMana panic(err) } - legacyAmino.MustUnmarshalJSON(bz, &appParams) - appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, legacyAmino, accs, genesisTimestamp, appParams) + err = json.Unmarshal(bz, &appParams) + if err != nil { + panic(err) + } + appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) default: appParams := make(simtypes.AppParams) - appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, legacyAmino, accs, genesisTimestamp, appParams) + appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) } return appState, simAccs, chainID, genesisTimestamp @@ -71,7 +74,7 @@ func AppStateFn(cdc codec.JSONMarshaler, legacyAmino *codec.LegacyAmino, simMana // AppStateRandomizedFn creates calls each module's GenesisState generator function // and creates the simulation params func AppStateRandomizedFn( - simManager *module.SimulationManager, r *rand.Rand, cdc codec.JSONMarshaler, legacyAmino *codec.LegacyAmino, + simManager *module.SimulationManager, r *rand.Rand, cdc codec.JSONMarshaler, accs []simtypes.Account, genesisTimestamp time.Time, appParams simtypes.AppParams, ) (json.RawMessage, []simtypes.Account) { numAccs := int64(len(accs)) @@ -105,7 +108,6 @@ func AppStateRandomizedFn( simState := &module.SimulationState{ AppParams: appParams, Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, GenState: genesisState, Accounts: accs, @@ -126,17 +128,23 @@ func AppStateRandomizedFn( // AppStateFromGenesisFileFn util function to generate the genesis AppState // from a genesis.json file. -func AppStateFromGenesisFileFn(r io.Reader, cdc codec.JSONMarshaler, legacyAmino *codec.LegacyAmino, genesisFile string) (tmtypes.GenesisDoc, []simtypes.Account) { +func AppStateFromGenesisFileFn(r io.Reader, cdc codec.JSONMarshaler, genesisFile string) (tmtypes.GenesisDoc, []simtypes.Account) { bytes, err := ioutil.ReadFile(genesisFile) if err != nil { panic(err) } var genesis tmtypes.GenesisDoc - legacyAmino.MustUnmarshalJSON(bytes, &genesis) + err = json.Unmarshal(bytes, &genesis) + if err != nil { + panic(err) + } var appState GenesisState - legacyAmino.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/types/module/simulation.go b/types/module/simulation.go index 002342c6422..eb146fbe67f 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -99,7 +99,6 @@ func (sm *SimulationManager) WeightedOperations(simState SimulationState) []simu // GenesisState generator function type SimulationState struct { AppParams simulation.AppParams - LegacyAmino *codec.LegacyAmino Cdc codec.JSONMarshaler // application codec Rand *rand.Rand // random number GenState map[string]json.RawMessage // genesis state diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 390a1e1a4fc..d673944fdfe 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/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/types/simulation" @@ -89,7 +89,11 @@ func RandomizedGenState(simState *module.SimulationState) { authGenesis := types.NewGenesisState(params, genesisAccs) - fmt.Printf("Selected randomly generated auth parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.LegacyAmino, &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 6fcc6c540bb..64afba4995f 100644 --- a/x/auth/simulation/genesis_test.go +++ b/x/auth/simulation/genesis_test.go @@ -21,7 +21,6 @@ func TestRandomizedGenState(t *testing.T) { registry := codectypes.NewInterfaceRegistry() types.RegisterInterfaces(registry) cdc := codec.NewProtoCodec(registry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -29,7 +28,6 @@ func TestRandomizedGenState(t *testing.T) { simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index 1b8a207e6e5..c23cace908c 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.LegacyAmino, &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 2e4e28260a6..fc31ca38e9e 100644 --- a/x/bank/simulation/genesis_test.go +++ b/x/bank/simulation/genesis_test.go @@ -20,14 +20,12 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -52,7 +50,6 @@ func TestRandomizedGenState(t *testing.T) { func TestRandomizedGenState1(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -66,10 +63,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, - LegacyAmino: legacyAmino, - Rand: r, + AppParams: make(simtypes.AppParams), + Cdc: cdc, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go index e4d14983f0d..c3da182205b 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.LegacyAmino.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/capability/simulation/genesis.go b/x/capability/simulation/genesis.go index 911e313436a..ab1d11fb3d4 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.LegacyAmino, &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 40664da2f7c..16d54c177a5 100644 --- a/x/capability/simulation/genesis_test.go +++ b/x/capability/simulation/genesis_test.go @@ -20,14 +20,12 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -48,7 +46,6 @@ func TestRandomizedGenState(t *testing.T) { func TestRandomizedGenState1(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -62,10 +59,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, - LegacyAmino: legacyAmino, - Rand: r, + AppParams: make(simtypes.AppParams), + Cdc: cdc, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index 39f49e229e2..3f64d5c01e5 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.LegacyAmino, &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 4a4af80f0d0..e923fbd4c83 100644 --- a/x/distribution/simulation/genesis_test.go +++ b/x/distribution/simulation/genesis_test.go @@ -21,14 +21,12 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -58,7 +56,6 @@ func TestRandomizedGenState(t *testing.T) { func TestRandomizedGenState1(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -72,10 +69,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, - LegacyAmino: legacyAmino, - Rand: r, + AppParams: make(simtypes.AppParams), + Cdc: cdc, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/evidence/simulation/genesis.go b/x/evidence/simulation/genesis.go index 4829a73c0e1..640670ebe9a 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.LegacyAmino, 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 c4e5cca1749..8cfa086adc9 100644 --- a/x/evidence/simulation/genesis_test.go +++ b/x/evidence/simulation/genesis_test.go @@ -20,7 +20,6 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -28,7 +27,6 @@ func TestRandomizedGenState(t *testing.T) { simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index e34ba8af932..3f9ed2d086a 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.LegacyAmino, 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 29aed7176a9..46c86febb19 100644 --- a/x/gov/simulation/genesis_test.go +++ b/x/gov/simulation/genesis_test.go @@ -21,7 +21,6 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -29,7 +28,6 @@ func TestRandomizedGenState(t *testing.T) { simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -62,7 +60,6 @@ func TestRandomizedGenState(t *testing.T) { func TestRandomizedGenState1(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -77,7 +74,6 @@ func TestRandomizedGenState1(t *testing.T) { module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/ibc-transfer/simulation/genesis.go b/x/ibc-transfer/simulation/genesis.go index 5434663cd79..9ed6925a02d 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" @@ -26,6 +26,10 @@ func RandomizedGenState(simState *module.SimulationState) { PortId: portID, } - fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, codec.MustMarshalJSONIndent(simState.LegacyAmino, &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 6cb3ae423be..cfb71191323 100644 --- a/x/ibc-transfer/simulation/genesis_test.go +++ b/x/ibc-transfer/simulation/genesis_test.go @@ -20,7 +20,6 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -28,7 +27,6 @@ func TestRandomizedGenState(t *testing.T) { simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -49,7 +47,6 @@ func TestRandomizedGenState(t *testing.T) { func TestRandomizedGenState1(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -62,10 +59,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, - LegacyAmino: legacyAmino, - Rand: r, + AppParams: make(simtypes.AppParams), + Cdc: cdc, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/ibc/simulation/genesis.go b/x/ibc/simulation/genesis.go index 46546cb9266..1cc142e53c5 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.LegacyAmino, &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 b69aeab60ee..9ef3f4824da 100644 --- a/x/ibc/simulation/genesis_test.go +++ b/x/ibc/simulation/genesis_test.go @@ -21,7 +21,6 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -29,7 +28,6 @@ func TestRandomizedGenState(t *testing.T) { simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index 907c23dcdcb..77d5064416e 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.LegacyAmino, 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 7099614a25d..ac57da7acc0 100644 --- a/x/mint/simulation/genesis_test.go +++ b/x/mint/simulation/genesis_test.go @@ -21,7 +21,6 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -29,7 +28,6 @@ func TestRandomizedGenState(t *testing.T) { simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -62,7 +60,6 @@ func TestRandomizedGenState(t *testing.T) { func TestRandomizedGenState1(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -75,10 +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, - LegacyAmino: legacyAmino, - Rand: r, + AppParams: make(simtypes.AppParams), + Cdc: cdc, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/simulation/params.go b/x/simulation/params.go index fd9b9dcfd52..f7fc798e658 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" @@ -156,13 +155,14 @@ func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulato // RandomParams returns random simulation consensus parameters, it extracts the Evidence from the Staking genesis state. func RandomConsensusParams(r *rand.Rand, appState json.RawMessage) *abci.ConsensusParams { - encodingConfig := params.MakeEncodingConfig() - cdc := encodingConfig.Marshaler - amino := encodingConfig.Amino + cdc := params.MakeEncodingConfig().Marshaler var genesisState map[string]json.RawMessage - amino.UnmarshalJSON(appState, &genesisState) + err := json.Unmarshal(appState, &genesisState) + if err != nil { + panic(err) + } stakingGenesisState := stakingtypes.GetGenesisStateFromAppState(cdc, genesisState) @@ -179,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(amino, 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/simulation/genesis.go b/x/slashing/simulation/genesis.go index b187b842057..2c1eba7db73 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.LegacyAmino, &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 7f0fbb56c7a..a386588d836 100644 --- a/x/slashing/simulation/genesis_test.go +++ b/x/slashing/simulation/genesis_test.go @@ -22,7 +22,6 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -30,7 +29,6 @@ func TestRandomizedGenState(t *testing.T) { simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -61,7 +59,6 @@ func TestRandomizedGenState(t *testing.T) { func TestRandomizedGenState1(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -75,10 +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, - LegacyAmino: legacyAmino, - Rand: r, + AppParams: make(simtypes.AppParams), + Cdc: cdc, + Rand: r, }, "assignment to entry in nil map"}, } diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index e21a0312aa4..e4ed7d34830 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.LegacyAmino, 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 25f95f0f8f4..b32a9c411e3 100644 --- a/x/staking/simulation/genesis_test.go +++ b/x/staking/simulation/genesis_test.go @@ -20,7 +20,6 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -28,7 +27,6 @@ func TestRandomizedGenState(t *testing.T) { simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), @@ -70,7 +68,6 @@ func TestRandomizedGenState(t *testing.T) { func TestRandomizedGenState1(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - legacyAmino := codec.New() s := rand.NewSource(1) r := rand.New(s) @@ -83,17 +80,15 @@ 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, - LegacyAmino: legacyAmino, - Rand: r, + AppParams: make(simtypes.AppParams), + Cdc: cdc, + Rand: r, }, "invalid memory address or nil pointer dereference"}, { // panic => reason: numBonded != len(Accnounts) module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, - LegacyAmino: legacyAmino, Rand: r, NumBonded: 4, Accounts: simtypes.RandomAccounts(r, 3), From abfdd223e01b554292f82082e1d9af2da7547723 Mon Sep 17 00:00:00 2001 From: blushi Date: Wed, 19 Aug 2020 19:18:53 +0200 Subject: [PATCH 13/20] Use JSONMarshaler in cli tests --- x/bank/client/cli/cli_test.go | 10 +++++++--- x/crisis/client/cli/cli_test.go | 3 ++- x/distribution/client/cli/cli_test.go | 11 ++++++----- x/gov/client/cli/cli_test.go | 3 ++- x/slashing/client/cli/cli_test.go | 3 ++- x/staking/client/cli/cli_test.go | 4 +++- 6 files changed, 22 insertions(+), 12 deletions(-) diff --git a/x/bank/client/cli/cli_test.go b/x/bank/client/cli/cli_test.go index c6d8bd643e7..73c1e44270d 100644 --- a/x/bank/client/cli/cli_test.go +++ b/x/bank/client/cli/cli_test.go @@ -90,7 +90,11 @@ func (s *IntegrationTestSuite) TestGetBalancesCmd() { }, { "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()), @@ -108,7 +112,7 @@ func (s *IntegrationTestSuite) TestGetBalancesCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(val.ClientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType)) + s.Require().NoError(val.ClientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message))) s.Require().Equal(tc.expected.String(), tc.respType.String()) } }) @@ -284,8 +288,8 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(bz.Bytes(), tc.respType), bz.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(bz.Bytes(), tc.respType.(proto.Message)), bz.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) } diff --git a/x/crisis/client/cli/cli_test.go b/x/crisis/client/cli/cli_test.go index 69e3584eac8..4be145c6dc4 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" @@ -95,7 +96,7 @@ func (s *IntegrationTestSuite) TestNewMsgVerifyInvariantTxCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) diff --git a/x/distribution/client/cli/cli_test.go b/x/distribution/client/cli/cli_test.go index 6dc73e5d310..690c7217a35 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" @@ -509,7 +510,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawRewardsCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(bz, tc.respType), string(bz)) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(bz, tc.respType.(proto.Message)), string(bz)) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) @@ -562,7 +563,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawAllRewardsCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) @@ -617,7 +618,7 @@ func (s *IntegrationTestSuite) TestNewSetWithdrawAddrCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) @@ -672,7 +673,7 @@ func (s *IntegrationTestSuite) TestNewFundCommunityPoolCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) @@ -758,7 +759,7 @@ func (s *IntegrationTestSuite) TestGetCmdSubmitProposal() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) diff --git a/x/gov/client/cli/cli_test.go b/x/gov/client/cli/cli_test.go index 9b57e8aa42d..14eb3156a9c 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" @@ -140,7 +141,7 @@ func (s *IntegrationTestSuite) TestNewCmdSubmitProposal() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) } diff --git a/x/slashing/client/cli/cli_test.go b/x/slashing/client/cli/cli_test.go index dcef0b56d00..8d0d6605b75 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" @@ -174,7 +175,7 @@ func (s *IntegrationTestSuite) TestNewUnjailTxCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) diff --git a/x/staking/client/cli/cli_test.go b/x/staking/client/cli/cli_test.go index 2727c75e327..ed58187e809 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" @@ -163,7 +165,7 @@ func (s *IntegrationTestSuite) TestNewCreateValidatorCmd() { s.Require().Error(err) } else { s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) From a3e394e3789bb34c4006c3d306bf4656d0310ed0 Mon Sep 17 00:00:00 2001 From: blushi Date: Thu, 20 Aug 2020 09:39:04 +0200 Subject: [PATCH 14/20] Use proto.Message as respType in cli tests --- types/simulation/types.go | 12 ++++-------- x/bank/client/cli/cli_test.go | 19 ++++++++++++------- x/crisis/client/cli/cli_test.go | 4 ++-- x/distribution/client/cli/cli_test.go | 20 ++++++++++---------- x/gov/client/cli/cli_test.go | 4 ++-- x/slashing/client/cli/cli_test.go | 4 ++-- x/staking/client/cli/cli_test.go | 4 ++-- 7 files changed, 34 insertions(+), 33 deletions(-) diff --git a/types/simulation/types.go b/types/simulation/types.go index f7f75a3c326..618caa0a0b5 100644 --- a/types/simulation/types.go +++ b/types/simulation/types.go @@ -2,14 +2,12 @@ package simulation import ( "encoding/json" - "fmt" "math/rand" "time" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/gogo/protobuf/proto" ) type WeightedProposalContent interface { @@ -137,14 +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 { - msg, ok := ptr.(proto.Message) - if !ok { - panic(fmt.Errorf("can't proto marshal %T", ptr)) + err := json.Unmarshal(v, ptr) + if err != nil { + panic(err) } - - cdc.MustUnmarshalJSON(v, msg) return } diff --git a/x/bank/client/cli/cli_test.go b/x/bank/client/cli/cli_test.go index 73c1e44270d..a1f129653af 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,7 +86,7 @@ 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", @@ -97,7 +97,7 @@ func (s *IntegrationTestSuite) TestGetBalancesCmd() { }, false, &sdk.Coin{}, - sdk.NewCoin("foobar", sdk.ZeroInt()), + NewCoin("foobar", sdk.ZeroInt()), }, } @@ -112,7 +112,7 @@ func (s *IntegrationTestSuite) TestGetBalancesCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(val.ClientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message))) + s.Require().NoError(val.ClientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType)) s.Require().Equal(tc.expected.String(), tc.respType.String()) } }) @@ -220,7 +220,7 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { amount sdk.Coins args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -289,7 +289,7 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(bz.Bytes(), tc.respType.(proto.Message)), 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) } @@ -300,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/crisis/client/cli/cli_test.go b/x/crisis/client/cli/cli_test.go index 4be145c6dc4..ef135b2de4a 100644 --- a/x/crisis/client/cli/cli_test.go +++ b/x/crisis/client/cli/cli_test.go @@ -46,7 +46,7 @@ func (s *IntegrationTestSuite) TestNewMsgVerifyInvariantTxCmd() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -96,7 +96,7 @@ func (s *IntegrationTestSuite) TestNewMsgVerifyInvariantTxCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) diff --git a/x/distribution/client/cli/cli_test.go b/x/distribution/client/cli/cli_test.go index 690c7217a35..0b6fea8c674 100644 --- a/x/distribution/client/cli/cli_test.go +++ b/x/distribution/client/cli/cli_test.go @@ -457,7 +457,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawRewardsCmd() { valAddr fmt.Stringer args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -510,7 +510,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawRewardsCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(bz, tc.respType.(proto.Message)), string(bz)) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(bz, tc.respType), string(bz)) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) @@ -526,7 +526,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawAllRewardsCmd() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -563,7 +563,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawAllRewardsCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) @@ -579,7 +579,7 @@ func (s *IntegrationTestSuite) TestNewSetWithdrawAddrCmd() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -618,7 +618,7 @@ func (s *IntegrationTestSuite) TestNewSetWithdrawAddrCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) @@ -634,7 +634,7 @@ func (s *IntegrationTestSuite) TestNewFundCommunityPoolCmd() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -673,7 +673,7 @@ func (s *IntegrationTestSuite) TestNewFundCommunityPoolCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) @@ -719,7 +719,7 @@ func (s *IntegrationTestSuite) TestGetCmdSubmitProposal() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -759,7 +759,7 @@ func (s *IntegrationTestSuite) TestGetCmdSubmitProposal() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) diff --git a/x/gov/client/cli/cli_test.go b/x/gov/client/cli/cli_test.go index 14eb3156a9c..ae60494ff03 100644 --- a/x/gov/client/cli/cli_test.go +++ b/x/gov/client/cli/cli_test.go @@ -77,7 +77,7 @@ func (s *IntegrationTestSuite) TestNewCmdSubmitProposal() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -141,7 +141,7 @@ func (s *IntegrationTestSuite) TestNewCmdSubmitProposal() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) } diff --git a/x/slashing/client/cli/cli_test.go b/x/slashing/client/cli/cli_test.go index 8d0d6605b75..e925e64336b 100644 --- a/x/slashing/client/cli/cli_test.go +++ b/x/slashing/client/cli/cli_test.go @@ -148,7 +148,7 @@ func (s *IntegrationTestSuite) TestNewUnjailTxCmd() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -175,7 +175,7 @@ func (s *IntegrationTestSuite) TestNewUnjailTxCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) diff --git a/x/staking/client/cli/cli_test.go b/x/staking/client/cli/cli_test.go index ed58187e809..ea809ee036e 100644 --- a/x/staking/client/cli/cli_test.go +++ b/x/staking/client/cli/cli_test.go @@ -70,7 +70,7 @@ func (s *IntegrationTestSuite) TestNewCreateValidatorCmd() { name string args []string expectErr bool - respType fmt.Stringer + respType proto.Message expectedCode uint32 }{ { @@ -165,7 +165,7 @@ func (s *IntegrationTestSuite) TestNewCreateValidatorCmd() { s.Require().Error(err) } else { s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType.(proto.Message)), out.String()) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) From 7665df4b4ce3ceda2b7781ba2fb313c7956ea90a Mon Sep 17 00:00:00 2001 From: blushi Date: Mon, 24 Aug 2020 13:05:31 +0200 Subject: [PATCH 15/20] Use tmjson for tm GenesisDoc --- server/util.go | 2 +- simapp/state.go | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/server/util.go b/server/util.go index 3c41bf76d33..a5151b468ab 100644 --- a/server/util.go +++ b/server/util.go @@ -199,7 +199,7 @@ func AddCommands(rootCmd *cobra.Command, defaultNodeHome string, appCreator type func InsertKeyJSON(legacyAminoCdc *codec.LegacyAmino, baseJSON []byte, key string, value json.RawMessage) ([]byte, error) { var jsonMap map[string]json.RawMessage - if err := legacyAminoCdc.UnmarshalJSON(baseJSON, &jsonMap); err != nil { + if err := json.Unmarshal(baseJSON, &jsonMap); err != nil { return nil, err } diff --git a/simapp/state.go b/simapp/state.go index 487152b1a26..921aac5906c 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" @@ -135,7 +136,8 @@ func AppStateFromGenesisFileFn(r io.Reader, cdc codec.JSONMarshaler, genesisFile } var genesis tmtypes.GenesisDoc - err = json.Unmarshal(bytes, &genesis) + // NOTE: Tendermint uses a custom JSON decoder for GenesisDoc + err = tmjson.Unmarshal(bytes, &genesis) if err != nil { panic(err) } From 12754cd15fbfdc98d2b520c11d49b5c2e71a718b Mon Sep 17 00:00:00 2001 From: Marie Date: Tue, 25 Aug 2020 16:58:25 +0200 Subject: [PATCH 16/20] Update types/module/simulation.go Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com> --- types/module/simulation.go | 1 - 1 file changed, 1 deletion(-) diff --git a/types/module/simulation.go b/types/module/simulation.go index eb146fbe67f..e01277f457a 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -109,5 +109,4 @@ type SimulationState struct { UnbondTime time.Duration // staking unbond time stored to use it as the slashing maximum evidence duration ParamChanges []simulation.ParamChange // simulated parameter changes from modules Contents []simulation.WeightedProposalContent // proposal content generator functions with their default weight and app sim key - } From 17ea31735536790dd55f5a30c81982c26f8e7849 Mon Sep 17 00:00:00 2001 From: Marie Date: Tue, 25 Aug 2020 16:58:40 +0200 Subject: [PATCH 17/20] Update types/module/module_test.go Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com> --- types/module/module_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/types/module/module_test.go b/types/module/module_test.go index 80c14cdca6e..6472370b4c6 100644 --- a/types/module/module_test.go +++ b/types/module/module_test.go @@ -200,7 +200,6 @@ 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) From 41218100f46023dd9acdd2d2dcad33ae8e562c06 Mon Sep 17 00:00:00 2001 From: blushi Date: Wed, 26 Aug 2020 09:50:49 +0200 Subject: [PATCH 18/20] Add godoc comments --- codec/amino_codec.go | 17 +++++++++++++++++ codec/proto_codec.go | 20 ++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/codec/amino_codec.go b/codec/amino_codec.go index 4782d4cf07a..21b751e8d13 100644 --- a/codec/amino_codec.go +++ b/codec/amino_codec.go @@ -10,54 +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/proto_codec.go b/codec/proto_codec.go index b9dfdf69a9b..02677af3627 100644 --- a/codec/proto_codec.go +++ b/codec/proto_codec.go @@ -19,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 { @@ -36,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 { @@ -47,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 { @@ -56,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 { @@ -68,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 { @@ -90,12 +98,15 @@ 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) } } +// 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 { @@ -105,6 +116,8 @@ func (pc *ProtoCodec) MarshalJSON(o proto.Message) ([]byte, error) { return ProtoMarshalJSON(m) } +// 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 { @@ -114,6 +127,8 @@ func (pc *ProtoCodec) MustMarshalJSON(o proto.Message) []byte { return bz } +// 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 { @@ -128,12 +143,17 @@ func (pc *ProtoCodec) UnmarshalJSON(bz []byte, ptr proto.Message) error { return types.UnpackInterfaces(ptr, pc.anyUnpacker) } +// 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) } From 4aa1d08a624be54e9b8027a42f97918e0ffd8cff Mon Sep 17 00:00:00 2001 From: blushi Date: Wed, 26 Aug 2020 10:05:24 +0200 Subject: [PATCH 19/20] Remove unused InsertKeyJSON --- server/util.go | 20 -------------------- server/util_test.go | 40 +--------------------------------------- 2 files changed, 1 insertion(+), 59 deletions(-) diff --git a/server/util.go b/server/util.go index a5151b468ab..6e34dcfe5b5 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(legacyAminoCdc *codec.LegacyAmino, baseJSON []byte, key string, value json.RawMessage) ([]byte, error) { - var jsonMap map[string]json.RawMessage - - if err := json.Unmarshal(baseJSON, &jsonMap); err != nil { - return nil, err - } - - jsonMap[key] = value - bz, err := codec.MarshalJSONIndent(legacyAminoCdc, 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 index fb4e7325974..6385dbfe164 100644 --- a/server/util_test.go +++ b/server/util_test.go @@ -1,41 +1,3 @@ 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) -} +// TODO: add server util tests From 0cff5ca8a753b722c28a8606c210701fa0ef1039 Mon Sep 17 00:00:00 2001 From: blushi Date: Wed, 26 Aug 2020 11:17:05 +0200 Subject: [PATCH 20/20] Fix tests --- server/util_test.go | 3 --- x/bank/client/rest/grpc_query_test.go | 6 ++++-- x/ibc/07-tendermint/client/cli/tx.go | 21 ++++++++++++------- .../solomachine/client/cli/tx.go | 8 +++---- 4 files changed, 21 insertions(+), 17 deletions(-) delete mode 100644 server/util_test.go diff --git a/server/util_test.go b/server/util_test.go deleted file mode 100644 index 6385dbfe164..00000000000 --- a/server/util_test.go +++ /dev/null @@ -1,3 +0,0 @@ -package server - -// TODO: add server util tests diff --git a/x/bank/client/rest/grpc_query_test.go b/x/bank/client/rest/grpc_query_test.go index 1ca5946b1d8..e1b4384ef9c 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/ibc/07-tendermint/client/cli/tx.go b/x/ibc/07-tendermint/client/cli/tx.go index a8fbe0c98f1..6e6c4b39997 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/light-clients/solomachine/client/cli/tx.go b/x/ibc/light-clients/solomachine/client/cli/tx.go index cea28440b61..678e33499a2 100644 --- a/x/ibc/light-clients/solomachine/client/cli/tx.go +++ b/x/ibc/light-clients/solomachine/client/cli/tx.go @@ -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") } }