diff --git a/CHANGELOG.md b/CHANGELOG.md index 35013902ab2f..1ae9bac0a4ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -85,6 +85,12 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (auth/tx) [\#8926](https://github.com/cosmos/cosmos-sdk/pull/8926) The `ProtoTxProvider` interface used as a workaround for transaction simulation has been removed. * (x/bank) [\#8798](https://github.com/cosmos/cosmos-sdk/pull/8798) `GetTotalSupply` is removed in favour of `GetPaginatedTotalSupply` * (x/bank/types) [\#9061](https://github.com/cosmos/cosmos-sdk/pull/9061) `AddressFromBalancesStore` now returns an error for invalid key instead of panic. +* (codec) [\#9061](https://github.com/cosmos/cosmos-sdk/pull/9226) Rename codec interfaces and methods, to follow a general Go interfaces: + * `codec.Marshaler` → `codec.Codec` (this defines objects which serialize other objects) + * `codec.BinaryMarshaler` → `codec.BinaryCodec` + * `codec.JSONMarshaler` → `codec.JSONCodec` + * Removed `BinaryBare` suffix from `BinaryCodec` methods (`MarshalBinaryBare`, `UnmarshalBinaryBare`, ...) + * Removed `Binary` infix from `BinaryCodec` methods (`MarshalBinaryLengthPrefixed`, `UnmarshalBinaryLengthPrefixed`, ...) diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index add6b982a3cd..80d0f179efb3 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -164,7 +164,7 @@ func setupBaseAppWithSnapshots(t *testing.T, blocks uint, blockTxs int, options tx.Msgs = append(tx.Msgs, msgKeyValue{Key: key, Value: value}) keyCounter++ } - txBytes, err := codec.MarshalBinaryBare(tx) + txBytes, err := codec.Marshal(tx) require.NoError(t, err) resp := app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes}) require.True(t, resp.IsOK(), "%v", resp.String()) @@ -476,7 +476,7 @@ func TestTxDecoder(t *testing.T) { app := newBaseApp(t.Name()) tx := newTxCounter(1, 0) - txBytes := codec.MustMarshalBinaryBare(tx) + txBytes := codec.MustMarshal(tx) dTx, err := app.txDecoder(txBytes) require.NoError(t, err) @@ -804,7 +804,7 @@ func testTxDecoder(cdc *codec.LegacyAmino) sdk.TxDecoder { return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "tx bytes are empty") } - err := cdc.UnmarshalBinaryBare(txBytes, &tx) + err := cdc.Unmarshal(txBytes, &tx) if err != nil { return nil, sdkerrors.ErrTxDecode } @@ -935,7 +935,7 @@ func TestCheckTx(t *testing.T) { for i := int64(0); i < nTxs; i++ { tx := newTxCounter(i, 0) // no messages - txBytes, err := codec.MarshalBinaryBare(tx) + txBytes, err := codec.Marshal(tx) require.NoError(t, err) r := app.CheckTx(abci.RequestCheckTx{Tx: txBytes}) require.Empty(t, r.GetEvents()) @@ -991,7 +991,7 @@ func TestDeliverTx(t *testing.T) { counter := int64(blockN*txPerHeight + i) tx := newTxCounter(counter, counter) - txBytes, err := codec.MarshalBinaryBare(tx) + txBytes, err := codec.Marshal(tx) require.NoError(t, err) res := app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes}) @@ -1041,7 +1041,7 @@ func TestMultiMsgDeliverTx(t *testing.T) { header := tmproto.Header{Height: 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) tx := newTxCounter(0, 0, 1, 2) - txBytes, err := codec.MarshalBinaryBare(tx) + txBytes, err := codec.Marshal(tx) require.NoError(t, err) res := app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes}) require.True(t, res.IsOK(), fmt.Sprintf("%v", res)) @@ -1061,7 +1061,7 @@ func TestMultiMsgDeliverTx(t *testing.T) { tx = newTxCounter(1, 3) tx.Msgs = append(tx.Msgs, msgCounter2{0}) tx.Msgs = append(tx.Msgs, msgCounter2{1}) - txBytes, err = codec.MarshalBinaryBare(tx) + txBytes, err = codec.Marshal(tx) require.NoError(t, err) res = app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes}) require.True(t, res.IsOK(), fmt.Sprintf("%v", res)) @@ -1123,7 +1123,7 @@ func TestSimulateTx(t *testing.T) { app.BeginBlock(abci.RequestBeginBlock{Header: header}) tx := newTxCounter(count, count) - txBytes, err := cdc.MarshalBinaryBare(tx) + txBytes, err := cdc.Marshal(tx) require.Nil(t, err) // simulate a message, check gas reported @@ -1252,7 +1252,7 @@ func TestRunInvalidTransaction(t *testing.T) { registerTestCodec(newCdc) newCdc.RegisterConcrete(&msgNoDecode{}, "cosmos-sdk/baseapp/msgNoDecode", nil) - txBytes, err := newCdc.MarshalBinaryBare(tx) + txBytes, err := newCdc.Marshal(tx) require.NoError(t, err) res := app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes}) @@ -1520,7 +1520,7 @@ func TestBaseAppAnteHandler(t *testing.T) { // the next txs ante handler execution (anteHandlerTxTest). tx := newTxCounter(0, 0) tx.setFailOnAnte(true) - txBytes, err := cdc.MarshalBinaryBare(tx) + txBytes, err := cdc.Marshal(tx) require.NoError(t, err) res := app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes}) require.Empty(t, res.Events) @@ -1535,7 +1535,7 @@ func TestBaseAppAnteHandler(t *testing.T) { tx = newTxCounter(0, 0) tx.setFailOnHandler(true) - txBytes, err = cdc.MarshalBinaryBare(tx) + txBytes, err = cdc.Marshal(tx) require.NoError(t, err) res = app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes}) @@ -1551,7 +1551,7 @@ func TestBaseAppAnteHandler(t *testing.T) { // implicitly checked by previous tx executions tx = newTxCounter(1, 0) - txBytes, err = cdc.MarshalBinaryBare(tx) + txBytes, err = cdc.Marshal(tx) require.NoError(t, err) res = app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes}) @@ -1624,7 +1624,7 @@ func TestGasConsumptionBadTx(t *testing.T) { tx := newTxCounter(5, 0) tx.setFailOnAnte(true) - txBytes, err := cdc.MarshalBinaryBare(tx) + txBytes, err := cdc.Marshal(tx) require.NoError(t, err) res := app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes}) @@ -1632,7 +1632,7 @@ func TestGasConsumptionBadTx(t *testing.T) { // require next tx to fail due to black gas limit tx = newTxCounter(5, 0) - txBytes, err = cdc.MarshalBinaryBare(tx) + txBytes, err = cdc.Marshal(tx) require.NoError(t, err) res = app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes}) @@ -1992,7 +1992,7 @@ func TestWithRouter(t *testing.T) { counter := int64(blockN*txPerHeight + i) tx := newTxCounter(counter, counter) - txBytes, err := codec.MarshalBinaryBare(tx) + txBytes, err := codec.Marshal(tx) require.NoError(t, err) res := app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes}) diff --git a/client/context.go b/client/context.go index 844b434bd5fe..a9a3dba86393 100644 --- a/client/context.go +++ b/client/context.go @@ -25,7 +25,7 @@ type Context struct { FromAddress sdk.AccAddress Client rpcclient.Client ChainID string - JSONMarshaler codec.JSONMarshaler + JSONMarshaler codec.JSONCodec InterfaceRegistry codectypes.InterfaceRegistry Input io.Reader Keyring keyring.Keyring @@ -73,7 +73,7 @@ func (ctx Context) WithInput(r io.Reader) Context { } // WithJSONMarshaler returns a copy of the Context with an updated JSONMarshaler. -func (ctx Context) WithJSONMarshaler(m codec.JSONMarshaler) Context { +func (ctx Context) WithJSONMarshaler(m codec.JSONCodec) Context { ctx.JSONMarshaler = m return ctx } diff --git a/codec/amino.go b/codec/amino.go index ea4c8d4fd842..fe22fd14fbd4 100644 --- a/codec/amino.go +++ b/codec/amino.go @@ -77,7 +77,7 @@ func (cdc *LegacyAmino) jsonUnmarshalAnys(o interface{}) error { return types.UnpackInterfaces(o, types.AminoJSONUnpacker{Cdc: cdc.Amino}) } -func (cdc *LegacyAmino) MarshalBinaryBare(o interface{}) ([]byte, error) { +func (cdc *LegacyAmino) Marshal(o interface{}) ([]byte, error) { err := cdc.marshalAnys(o) if err != nil { return nil, err @@ -85,15 +85,15 @@ func (cdc *LegacyAmino) MarshalBinaryBare(o interface{}) ([]byte, error) { return cdc.Amino.MarshalBinaryBare(o) } -func (cdc *LegacyAmino) MustMarshalBinaryBare(o interface{}) []byte { - bz, err := cdc.MarshalBinaryBare(o) +func (cdc *LegacyAmino) MustMarshal(o interface{}) []byte { + bz, err := cdc.Marshal(o) if err != nil { panic(err) } return bz } -func (cdc *LegacyAmino) MarshalBinaryLengthPrefixed(o interface{}) ([]byte, error) { +func (cdc *LegacyAmino) MarshalLengthPrefixed(o interface{}) ([]byte, error) { err := cdc.marshalAnys(o) if err != nil { return nil, err @@ -101,15 +101,15 @@ func (cdc *LegacyAmino) MarshalBinaryLengthPrefixed(o interface{}) ([]byte, erro return cdc.Amino.MarshalBinaryLengthPrefixed(o) } -func (cdc *LegacyAmino) MustMarshalBinaryLengthPrefixed(o interface{}) []byte { - bz, err := cdc.MarshalBinaryLengthPrefixed(o) +func (cdc *LegacyAmino) MustMarshalLengthPrefixed(o interface{}) []byte { + bz, err := cdc.MarshalLengthPrefixed(o) if err != nil { panic(err) } return bz } -func (cdc *LegacyAmino) UnmarshalBinaryBare(bz []byte, ptr interface{}) error { +func (cdc *LegacyAmino) Unmarshal(bz []byte, ptr interface{}) error { err := cdc.Amino.UnmarshalBinaryBare(bz, ptr) if err != nil { return err @@ -117,14 +117,14 @@ func (cdc *LegacyAmino) UnmarshalBinaryBare(bz []byte, ptr interface{}) error { return cdc.unmarshalAnys(ptr) } -func (cdc *LegacyAmino) MustUnmarshalBinaryBare(bz []byte, ptr interface{}) { - err := cdc.UnmarshalBinaryBare(bz, ptr) +func (cdc *LegacyAmino) MustUnmarshal(bz []byte, ptr interface{}) { + err := cdc.Unmarshal(bz, ptr) if err != nil { panic(err) } } -func (cdc *LegacyAmino) UnmarshalBinaryLengthPrefixed(bz []byte, ptr interface{}) error { +func (cdc *LegacyAmino) UnmarshalLengthPrefixed(bz []byte, ptr interface{}) error { err := cdc.Amino.UnmarshalBinaryLengthPrefixed(bz, ptr) if err != nil { return err @@ -132,14 +132,14 @@ func (cdc *LegacyAmino) UnmarshalBinaryLengthPrefixed(bz []byte, ptr interface{} return cdc.unmarshalAnys(ptr) } -func (cdc *LegacyAmino) MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr interface{}) { - err := cdc.UnmarshalBinaryLengthPrefixed(bz, ptr) +func (cdc *LegacyAmino) MustUnmarshalLengthPrefixed(bz []byte, ptr interface{}) { + err := cdc.UnmarshalLengthPrefixed(bz, ptr) if err != nil { panic(err) } } -// MarshalJSON implements codec.Marshaler interface +// MarshalJSON implements codec.Codec interface func (cdc *LegacyAmino) MarshalJSON(o interface{}) ([]byte, error) { err := cdc.jsonMarshalAnys(o) if err != nil { @@ -156,7 +156,7 @@ func (cdc *LegacyAmino) MustMarshalJSON(o interface{}) []byte { return bz } -// UnmarshalJSON implements codec.Marshaler interface +// UnmarshalJSON implements codec.Codec interface func (cdc *LegacyAmino) UnmarshalJSON(bz []byte, ptr interface{}) error { err := cdc.Amino.UnmarshalJSON(bz, ptr) if err != nil { diff --git a/codec/amino_codec.go b/codec/amino_codec.go index 3ba7a2feb9b7..668efb70b1b8 100644 --- a/codec/amino_codec.go +++ b/codec/amino_codec.go @@ -10,51 +10,51 @@ type AminoCodec struct { *LegacyAmino } -var _ Marshaler = &AminoCodec{} +var _ Codec = &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) +// Marshal implements BinaryMarshaler.Marshal method. +func (ac *AminoCodec) Marshal(o ProtoMarshaler) ([]byte, error) { + return ac.LegacyAmino.Marshal(o) } -// MustMarshalBinaryBare implements BinaryMarshaler.MustMarshalBinaryBare method. -func (ac *AminoCodec) MustMarshalBinaryBare(o ProtoMarshaler) []byte { - return ac.LegacyAmino.MustMarshalBinaryBare(o) +// MustMarshal implements BinaryMarshaler.MustMarshal method. +func (ac *AminoCodec) MustMarshal(o ProtoMarshaler) []byte { + return ac.LegacyAmino.MustMarshal(o) } -// MarshalBinaryLengthPrefixed implements BinaryMarshaler.MarshalBinaryLengthPrefixed method. -func (ac *AminoCodec) MarshalBinaryLengthPrefixed(o ProtoMarshaler) ([]byte, error) { - return ac.LegacyAmino.MarshalBinaryLengthPrefixed(o) +// MarshalLengthPrefixed implements BinaryMarshaler.MarshalLengthPrefixed method. +func (ac *AminoCodec) MarshalLengthPrefixed(o ProtoMarshaler) ([]byte, error) { + return ac.LegacyAmino.MarshalLengthPrefixed(o) } -// MustMarshalBinaryLengthPrefixed implements BinaryMarshaler.MustMarshalBinaryLengthPrefixed method. -func (ac *AminoCodec) MustMarshalBinaryLengthPrefixed(o ProtoMarshaler) []byte { - return ac.LegacyAmino.MustMarshalBinaryLengthPrefixed(o) +// MustMarshalLengthPrefixed implements BinaryMarshaler.MustMarshalLengthPrefixed method. +func (ac *AminoCodec) MustMarshalLengthPrefixed(o ProtoMarshaler) []byte { + return ac.LegacyAmino.MustMarshalLengthPrefixed(o) } -// UnmarshalBinaryBare implements BinaryMarshaler.UnmarshalBinaryBare method. -func (ac *AminoCodec) UnmarshalBinaryBare(bz []byte, ptr ProtoMarshaler) error { - return ac.LegacyAmino.UnmarshalBinaryBare(bz, ptr) +// Unmarshal implements BinaryMarshaler.Unmarshal method. +func (ac *AminoCodec) Unmarshal(bz []byte, ptr ProtoMarshaler) error { + return ac.LegacyAmino.Unmarshal(bz, ptr) } -// MustUnmarshalBinaryBare implements BinaryMarshaler.MustUnmarshalBinaryBare method. -func (ac *AminoCodec) MustUnmarshalBinaryBare(bz []byte, ptr ProtoMarshaler) { - ac.LegacyAmino.MustUnmarshalBinaryBare(bz, ptr) +// MustUnmarshal implements BinaryMarshaler.MustUnmarshal method. +func (ac *AminoCodec) MustUnmarshal(bz []byte, ptr ProtoMarshaler) { + ac.LegacyAmino.MustUnmarshal(bz, ptr) } -// UnmarshalBinaryLengthPrefixed implements BinaryMarshaler.UnmarshalBinaryLengthPrefixed method. -func (ac *AminoCodec) UnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) error { - return ac.LegacyAmino.UnmarshalBinaryLengthPrefixed(bz, ptr) +// UnmarshalLengthPrefixed implements BinaryMarshaler.UnmarshalLengthPrefixed method. +func (ac *AminoCodec) UnmarshalLengthPrefixed(bz []byte, ptr ProtoMarshaler) error { + return ac.LegacyAmino.UnmarshalLengthPrefixed(bz, ptr) } -// MustUnmarshalBinaryLengthPrefixed implements BinaryMarshaler.MustUnmarshalBinaryLengthPrefixed method. -func (ac *AminoCodec) MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) { - ac.LegacyAmino.MustUnmarshalBinaryLengthPrefixed(bz, ptr) +// MustUnmarshalLengthPrefixed implements BinaryMarshaler.MustUnmarshalLengthPrefixed method. +func (ac *AminoCodec) MustUnmarshalLengthPrefixed(bz []byte, ptr ProtoMarshaler) { + ac.LegacyAmino.MustUnmarshalLengthPrefixed(bz, ptr) } // MarshalJSON implements JSONMarshaler.MarshalJSON method, @@ -83,23 +83,23 @@ func (ac *AminoCodec) MustUnmarshalJSON(bz []byte, ptr proto.Message) { // MarshalInterface is a convenience function for amino marshaling interfaces. // The `i` must be an interface. -// NOTE: to marshal a concrete type, you should use MarshalBinaryBare instead +// NOTE: to marshal a concrete type, you should use Marshal instead func (ac *AminoCodec) MarshalInterface(i proto.Message) ([]byte, error) { if err := assertNotNil(i); err != nil { return nil, err } - return ac.LegacyAmino.MarshalBinaryBare(i) + return ac.LegacyAmino.Marshal(i) } // UnmarshalInterface is a convenience function for amino unmarshaling interfaces. // `ptr` must be a pointer to an interface. -// NOTE: to unmarshal a concrete type, you should use UnmarshalBinaryBare instead +// NOTE: to unmarshal a concrete type, you should use Unmarshal instead // // Example: // var x MyInterface // err := cdc.UnmarshalInterface(bz, &x) func (ac *AminoCodec) UnmarshalInterface(bz []byte, ptr interface{}) error { - return ac.LegacyAmino.UnmarshalBinaryBare(bz, ptr) + return ac.LegacyAmino.Unmarshal(bz, ptr) } // MarshalInterfaceJSON is a convenience function for amino marshaling interfaces. diff --git a/codec/any_test.go b/codec/any_test.go index ff80d8ee427c..a9c30c0def4a 100644 --- a/codec/any_test.go +++ b/codec/any_test.go @@ -84,11 +84,11 @@ func TestMarshalProtoPubKey(t *testing.T) { // **** test binary serialization **** - bz, err = ccfg.Marshaler.MarshalBinaryBare(pkAny) + bz, err = ccfg.Marshaler.Marshal(pkAny) require.NoError(err) var pkAny3 codectypes.Any - err = ccfg.Marshaler.UnmarshalBinaryBare(bz, &pkAny3) + err = ccfg.Marshaler.Unmarshal(bz, &pkAny3) require.NoError(err) err = ccfg.InterfaceRegistry.UnpackAny(&pkAny3, &pkI) require.NoError(err) diff --git a/codec/codec.go b/codec/codec.go index 4746c58b6fae..6da2f453f0c3 100644 --- a/codec/codec.go +++ b/codec/codec.go @@ -7,49 +7,76 @@ import ( ) 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 two typical implementations that fulfill this contract: + // Codec defines a functionality for serializing other objects. + // Users can defin a custom Protobuf-based serialization. + // Note, Amino can still be used without any dependency on Protobuf. + // SDK provides to Codec implementations: // // 1. AminoCodec: Provides full Amino serialization compatibility. // 2. ProtoCodec: Provides full Protobuf serialization compatibility. - Marshaler interface { - BinaryMarshaler - JSONMarshaler + Codec interface { + BinaryCodec + JSONCodec } - BinaryMarshaler interface { - MarshalBinaryBare(o ProtoMarshaler) ([]byte, error) - MustMarshalBinaryBare(o ProtoMarshaler) []byte + BinaryCodec interface { + // Marshal returns binary encoding of v. + Marshal(o ProtoMarshaler) ([]byte, error) + // MustMarshal calls Marshal and panics if error is returned. + MustMarshal(o ProtoMarshaler) []byte - MarshalBinaryLengthPrefixed(o ProtoMarshaler) ([]byte, error) - MustMarshalBinaryLengthPrefixed(o ProtoMarshaler) []byte + // MarshalLengthPrefixed returns binary encoding of v with bytes length prefix. + MarshalLengthPrefixed(o ProtoMarshaler) ([]byte, error) + // MustMarshalLengthPrefixed calls MarshalLengthPrefixed and panics if + // error is returned. + MustMarshalLengthPrefixed(o ProtoMarshaler) []byte - UnmarshalBinaryBare(bz []byte, ptr ProtoMarshaler) error - MustUnmarshalBinaryBare(bz []byte, ptr ProtoMarshaler) + // Unmarshal parses the data encoded with Marshal method and stores the result + // in the value pointed to by v. + Unmarshal(bz []byte, ptr ProtoMarshaler) error + // MustUnmarshal calls Unmarshal and panics if error is returned. + MustUnmarshal(bz []byte, ptr ProtoMarshaler) - UnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) error - MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) + // Unmarshal parses the data encoded with UnmarshalLengthPrefixed method and stores + // the result in the value pointed to by v. + UnmarshalLengthPrefixed(bz []byte, ptr ProtoMarshaler) error + // MustUnmarshalLengthPrefixed calls UnmarshalLengthPrefixed and panics if error + // is returned. + MustUnmarshalLengthPrefixed(bz []byte, ptr ProtoMarshaler) + // MarshalInterface is a helper method which will wrap `i` into `Any` for correct + // binary interface (de)serialization. MarshalInterface(i proto.Message) ([]byte, error) + // UnmarshalInterface is a helper method which will parse binary enoded data + // into `Any` and unpack any into the `ptr`. It fails if the target interface type + // is not registered in codec, or is not compatible with the serialized data UnmarshalInterface(bz []byte, ptr interface{}) error types.AnyUnpacker } - JSONMarshaler interface { + JSONCodec interface { + // MarshalJSON returns JSON encoding of v. MarshalJSON(o proto.Message) ([]byte, error) + // MustMarshalJSON calls MarshalJSON and panics if error is returned. MustMarshalJSON(o proto.Message) []byte + // MarshalInterfaceJSON is a helper method which will wrap `i` into `Any` for correct + // JSON interface (de)serialization. MarshalInterfaceJSON(i proto.Message) ([]byte, error) + // UnmarshalInterfaceJSON is a helper method which will parse JSON enoded data + // into `Any` and unpack any into the `ptr`. It fails if the target interface type + // is not registered in codec, or is not compatible with the serialized data UnmarshalInterfaceJSON(bz []byte, ptr interface{}) error + // UnmarshalJSON parses the data encoded with MarshalJSON method and stores the result + // in the value pointed to by v. UnmarshalJSON(bz []byte, ptr proto.Message) error + // MustUnmarshalJSON calls Unmarshal and panics if error is returned. MustUnmarshalJSON(bz []byte, ptr proto.Message) } - // ProtoMarshaler defines an interface a type must implement as protocol buffer - // defined message. + // ProtoMarshaler defines an interface a type must implement to serialize itself + // as a protocol buffer defined message. ProtoMarshaler interface { proto.Message // for JSON serialization @@ -60,8 +87,8 @@ type ( Unmarshal(data []byte) error } - // AminoMarshaler defines an interface where Amino marshalling can be - // overridden by custom marshalling. + // AminoMarshaler defines an interface a type must implement to serialize itself + // for Amino codec. AminoMarshaler interface { MarshalAmino() ([]byte, error) UnmarshalAmino([]byte) error diff --git a/codec/codec_common_test.go b/codec/codec_common_test.go index 12e9bd2224e1..59af923d7920 100644 --- a/codec/codec_common_test.go +++ b/codec/codec_common_test.go @@ -87,7 +87,7 @@ func testMarshalingTestCase(require *require.Assertions, tc testCase, m mustMars } } -func testMarshaling(t *testing.T, cdc codec.Marshaler) { +func testMarshaling(t *testing.T, cdc codec.Codec) { any, err := types.NewAnyWithValue(&testdata.Dog{Name: "rufus"}) require.NoError(t, err) @@ -117,8 +117,8 @@ func testMarshaling(t *testing.T, cdc codec.Marshaler) { for _, tc := range testCases { tc := tc - m1 := mustMarshaler{cdc.MarshalBinaryBare, cdc.MustMarshalBinaryBare, cdc.UnmarshalBinaryBare, cdc.MustUnmarshalBinaryBare} - m2 := mustMarshaler{cdc.MarshalBinaryLengthPrefixed, cdc.MustMarshalBinaryLengthPrefixed, cdc.UnmarshalBinaryLengthPrefixed, cdc.MustUnmarshalBinaryLengthPrefixed} + m1 := mustMarshaler{cdc.Marshal, cdc.MustMarshal, cdc.Unmarshal, cdc.MustUnmarshal} + m2 := mustMarshaler{cdc.MarshalLengthPrefixed, cdc.MustMarshalLengthPrefixed, cdc.UnmarshalLengthPrefixed, cdc.MustUnmarshalLengthPrefixed} m3 := mustMarshaler{ func(i codec.ProtoMarshaler) ([]byte, error) { return cdc.MarshalJSON(i) }, func(i codec.ProtoMarshaler) []byte { return cdc.MustMarshalJSON(i) }, diff --git a/codec/legacy/codec.go b/codec/legacy/codec.go index 5ec6b2976cab..a4a963b6d211 100644 --- a/codec/legacy/codec.go +++ b/codec/legacy/codec.go @@ -20,12 +20,12 @@ func init() { // PrivKeyFromBytes unmarshals private key bytes and returns a PrivKey func PrivKeyFromBytes(privKeyBytes []byte) (privKey cryptotypes.PrivKey, err error) { - err = Cdc.UnmarshalBinaryBare(privKeyBytes, &privKey) + err = Cdc.Unmarshal(privKeyBytes, &privKey) return } // PubKeyFromBytes unmarshals public key bytes and returns a PubKey func PubKeyFromBytes(pubKeyBytes []byte) (pubKey cryptotypes.PubKey, err error) { - err = Cdc.UnmarshalBinaryBare(pubKeyBytes, &pubKey) + err = Cdc.Unmarshal(pubKeyBytes, &pubKey) return } diff --git a/codec/proto_codec.go b/codec/proto_codec.go index 7afc99c69075..19c867f55830 100644 --- a/codec/proto_codec.go +++ b/codec/proto_codec.go @@ -15,7 +15,7 @@ import ( // ProtoCodecMarshaler defines an interface for codecs that utilize Protobuf for both // binary and JSON encoding. type ProtoCodecMarshaler interface { - Marshaler + Codec InterfaceRegistry() types.InterfaceRegistry } @@ -25,7 +25,7 @@ type ProtoCodec struct { interfaceRegistry types.InterfaceRegistry } -var _ Marshaler = &ProtoCodec{} +var _ Codec = &ProtoCodec{} var _ ProtoCodecMarshaler = &ProtoCodec{} // NewProtoCodec returns a reference to a new ProtoCodec @@ -33,18 +33,18 @@ func NewProtoCodec(interfaceRegistry types.InterfaceRegistry) *ProtoCodec { return &ProtoCodec{interfaceRegistry: interfaceRegistry} } -// MarshalBinaryBare implements BinaryMarshaler.MarshalBinaryBare method. +// Marshal implements BinaryMarshaler.Marshal method. // NOTE: this function must be used with a concrete type which // implements proto.Message. For interface please use the codec.MarshalInterface -func (pc *ProtoCodec) MarshalBinaryBare(o ProtoMarshaler) ([]byte, error) { +func (pc *ProtoCodec) Marshal(o ProtoMarshaler) ([]byte, error) { return o.Marshal() } -// MustMarshalBinaryBare implements BinaryMarshaler.MustMarshalBinaryBare method. +// MustMarshal implements BinaryMarshaler.MustMarshal method. // NOTE: this function must be used with a concrete type which // implements proto.Message. For interface please use the codec.MarshalInterface -func (pc *ProtoCodec) MustMarshalBinaryBare(o ProtoMarshaler) []byte { - bz, err := pc.MarshalBinaryBare(o) +func (pc *ProtoCodec) MustMarshal(o ProtoMarshaler) []byte { + bz, err := pc.Marshal(o) if err != nil { panic(err) } @@ -52,9 +52,9 @@ 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) +// MarshalLengthPrefixed implements BinaryMarshaler.MarshalLengthPrefixed method. +func (pc *ProtoCodec) MarshalLengthPrefixed(o ProtoMarshaler) ([]byte, error) { + bz, err := pc.Marshal(o) if err != nil { return nil, err } @@ -64,9 +64,9 @@ 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) +// MustMarshalLengthPrefixed implements BinaryMarshaler.MustMarshalLengthPrefixed method. +func (pc *ProtoCodec) MustMarshalLengthPrefixed(o ProtoMarshaler) []byte { + bz, err := pc.MarshalLengthPrefixed(o) if err != nil { panic(err) } @@ -74,10 +74,10 @@ func (pc *ProtoCodec) MustMarshalBinaryLengthPrefixed(o ProtoMarshaler) []byte { return bz } -// UnmarshalBinaryBare implements BinaryMarshaler.UnmarshalBinaryBare method. +// Unmarshal implements BinaryMarshaler.Unmarshal method. // NOTE: this function must be used with a concrete type which // implements proto.Message. For interface please use the codec.UnmarshalInterface -func (pc *ProtoCodec) UnmarshalBinaryBare(bz []byte, ptr ProtoMarshaler) error { +func (pc *ProtoCodec) Unmarshal(bz []byte, ptr ProtoMarshaler) error { err := ptr.Unmarshal(bz) if err != nil { return err @@ -89,17 +89,17 @@ func (pc *ProtoCodec) UnmarshalBinaryBare(bz []byte, ptr ProtoMarshaler) error { return nil } -// MustUnmarshalBinaryBare implements BinaryMarshaler.MustUnmarshalBinaryBare method. +// MustUnmarshal implements BinaryMarshaler.MustUnmarshal method. // NOTE: this function must be used with a concrete type which // implements proto.Message. For interface please use the codec.UnmarshalInterface -func (pc *ProtoCodec) MustUnmarshalBinaryBare(bz []byte, ptr ProtoMarshaler) { - if err := pc.UnmarshalBinaryBare(bz, ptr); err != nil { +func (pc *ProtoCodec) MustUnmarshal(bz []byte, ptr ProtoMarshaler) { + if err := pc.Unmarshal(bz, ptr); err != nil { panic(err) } } -// UnmarshalBinaryLengthPrefixed implements BinaryMarshaler.UnmarshalBinaryLengthPrefixed method. -func (pc *ProtoCodec) UnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) error { +// UnmarshalLengthPrefixed implements BinaryMarshaler.UnmarshalLengthPrefixed method. +func (pc *ProtoCodec) UnmarshalLengthPrefixed(bz []byte, ptr ProtoMarshaler) error { size, n := binary.Uvarint(bz) if n < 0 { return fmt.Errorf("invalid number of bytes read from length-prefixed encoding: %d", n) @@ -112,12 +112,12 @@ func (pc *ProtoCodec) UnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshale } bz = bz[n:] - return pc.UnmarshalBinaryBare(bz, ptr) + return pc.Unmarshal(bz, ptr) } -// MustUnmarshalBinaryLengthPrefixed implements BinaryMarshaler.MustUnmarshalBinaryLengthPrefixed method. -func (pc *ProtoCodec) MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) { - if err := pc.UnmarshalBinaryLengthPrefixed(bz, ptr); err != nil { +// MustUnmarshalLengthPrefixed implements BinaryMarshaler.MustUnmarshalLengthPrefixed method. +func (pc *ProtoCodec) MustUnmarshalLengthPrefixed(bz []byte, ptr ProtoMarshaler) { + if err := pc.UnmarshalLengthPrefixed(bz, ptr); err != nil { panic(err) } } @@ -179,7 +179,7 @@ func (pc *ProtoCodec) MustUnmarshalJSON(bz []byte, ptr proto.Message) { // MarshalInterface is a convenience function for proto marshalling interfaces. It packs // the provided value, which must be an interface, in an Any and then marshals it to bytes. -// NOTE: to marshal a concrete type, you should use MarshalBinaryBare instead +// NOTE: to marshal a concrete type, you should use Marshal instead func (pc *ProtoCodec) MarshalInterface(i proto.Message) ([]byte, error) { if err := assertNotNil(i); err != nil { return nil, err @@ -189,20 +189,20 @@ func (pc *ProtoCodec) MarshalInterface(i proto.Message) ([]byte, error) { return nil, err } - return pc.MarshalBinaryBare(any) + return pc.Marshal(any) } // UnmarshalInterface is a convenience function for proto unmarshaling interfaces. It // unmarshals an Any from bz bytes and then unpacks it to the `ptr`, which must // be a pointer to a non empty interface with registered implementations. -// NOTE: to unmarshal a concrete type, you should use UnmarshalBinaryBare instead +// NOTE: to unmarshal a concrete type, you should use Unmarshal instead // // Example: // var x MyInterface // err := cdc.UnmarshalInterface(bz, &x) func (pc *ProtoCodec) UnmarshalInterface(bz []byte, ptr interface{}) error { any := &types.Any{} - err := pc.UnmarshalBinaryBare(bz, any) + err := pc.Unmarshal(bz, any) if err != nil { return err } diff --git a/codec/proto_codec_test.go b/codec/proto_codec_test.go index 706d025d5994..40d810deefc1 100644 --- a/codec/proto_codec_test.go +++ b/codec/proto_codec_test.go @@ -46,11 +46,11 @@ func (lpm *lyingProtoMarshaler) Size() int { return lpm.falseSize } -func TestProtoCodecUnmarshalBinaryLengthPrefixedChecks(t *testing.T) { +func TestProtoCodecUnmarshalLengthPrefixedChecks(t *testing.T) { cdc := codec.NewProtoCodec(createTestInterfaceRegistry()) truth := &testdata.Cat{Lives: 9, Moniker: "glowing"} - realSize := len(cdc.MustMarshalBinaryBare(truth)) + realSize := len(cdc.MustMarshal(truth)) falseSizes := []int{ 100, @@ -66,10 +66,10 @@ func TestProtoCodecUnmarshalBinaryLengthPrefixedChecks(t *testing.T) { falseSize: falseSize, } var serialized []byte - require.NotPanics(t, func() { serialized = cdc.MustMarshalBinaryLengthPrefixed(lpm) }) + require.NotPanics(t, func() { serialized = cdc.MustMarshalLengthPrefixed(lpm) }) recv := new(testdata.Cat) - gotErr := cdc.UnmarshalBinaryLengthPrefixed(serialized, recv) + gotErr := cdc.UnmarshalLengthPrefixed(serialized, recv) var wantErr error if falseSize > realSize { wantErr = fmt.Errorf("not enough bytes to read; want: %d, got: %d", falseSize, realSize) @@ -83,10 +83,10 @@ func TestProtoCodecUnmarshalBinaryLengthPrefixedChecks(t *testing.T) { t.Run("Crafted bad uvarint size", func(t *testing.T) { crafted := []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f} recv := new(testdata.Cat) - gotErr := cdc.UnmarshalBinaryLengthPrefixed(crafted, recv) + gotErr := cdc.UnmarshalLengthPrefixed(crafted, recv) require.Equal(t, gotErr, errors.New("invalid number of bytes read from length-prefixed encoding: -10")) - require.Panics(t, func() { cdc.MustUnmarshalBinaryLengthPrefixed(crafted, recv) }) + require.Panics(t, func() { cdc.MustUnmarshalLengthPrefixed(crafted, recv) }) }) } @@ -98,7 +98,7 @@ func mustAny(msg proto.Message) *types.Any { return any } -func BenchmarkProtoCodecMarshalBinaryLengthPrefixed(b *testing.B) { +func BenchmarkProtoCodecMarshalLengthPrefixed(b *testing.B) { var pCdc = codec.NewProtoCodec(types.NewInterfaceRegistry()) var msg = &testdata.HasAnimal{ X: 1000, @@ -124,7 +124,7 @@ func BenchmarkProtoCodecMarshalBinaryLengthPrefixed(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { - blob, err := pCdc.MarshalBinaryLengthPrefixed(msg) + blob, err := pCdc.MarshalLengthPrefixed(msg) if err != nil { b.Fatal(err) } diff --git a/codec/yaml.go b/codec/yaml.go index bba5e90ed821..d641e52f2018 100644 --- a/codec/yaml.go +++ b/codec/yaml.go @@ -10,7 +10,7 @@ import ( // MarshalYAML marshals toPrint using jsonMarshaler to leverage specialized MarshalJSON methods // (usually related to serialize data with protobuf or amin depending on a configuration). // This involves additional roundtrip through JSON. -func MarshalYAML(jsonMarshaler JSONMarshaler, toPrint proto.Message) ([]byte, error) { +func MarshalYAML(jsonMarshaler JSONCodec, toPrint proto.Message) ([]byte, error) { // We are OK with the performance hit of the additional JSON roundtip. MarshalYAML is not // used in any critical parts of the system. bz, err := jsonMarshaler.MarshalJSON(toPrint) diff --git a/cosmovisor/README.md b/cosmovisor/README.md deleted file mode 120000 index a37c5c784512..000000000000 --- a/cosmovisor/README.md +++ /dev/null @@ -1 +0,0 @@ -../docs/run-node/cosmovisor.md \ No newline at end of file diff --git a/cosmovisor/README.md b/cosmovisor/README.md new file mode 100644 index 000000000000..99cb81e0cc45 --- /dev/null +++ b/cosmovisor/README.md @@ -0,0 +1,170 @@ +# Cosmosvisor Quick Start + +`cosmovisor` is a small process manager around Cosmos SDK binaries that monitors the governance module via stdout to see if there's a chain upgrade proposal coming in. If it see a proposal that gets approved it can be run manually or automatically to download the new code, stop the node, run the migration script, replace the node binary, and start with the new genesis file. + +## Installation + +Run: + +`go get github.com/cosmos/cosmos-sdk/cosmovisor/cmd/cosmovisor` + +## Command Line Arguments And Environment Variables + +All arguments passed to the `cosmovisor` program will be passed to the current daemon binary (as a subprocess). +It will return `/dev/stdout` and `/dev/stderr` of the subprocess as its own. Because of that, it cannot accept +any command line arguments, nor print anything to output (unless it terminates unexpectedly before executing a +binary). + +`cosmovisor` reads its configuration from environment variables: + +* `DAEMON_HOME` is the location where upgrade binaries should be kept (e.g. `$HOME/.gaiad` or `$HOME/.xrnd`). +* `DAEMON_NAME` is the name of the binary itself (eg. `xrnd`, `gaiad`, `simd`, etc). +* `DAEMON_ALLOW_DOWNLOAD_BINARIES` (*optional*) if set to `true` will enable auto-downloading of new binaries +(for security reasons, this is intended for full nodes rather than validators). +* `DAEMON_RESTART_AFTER_UPGRADE` (*optional*) if set to `true` it will restart the sub-process with the same +command line arguments and flags (but new binary) after a successful upgrade. By default, `cosmovisor` dies +afterwards and allows the supervisor to restart it if needed. Note that this will not auto-restart the child +if there was an error. + +## Data Folder Layout + +`$DAEMON_HOME/cosmovisor` is expected to belong completely to `cosmovisor` and +subprocesses that are controlled by it. The folder content is organised as follows: + +``` +. +├── current -> genesis or upgrades/ +├── genesis +│   └── bin +│   └── $DAEMON_NAME +└── upgrades + └── + └── bin + └── $DAEMON_NAME +``` + +Each version of the Cosmos SDK application is stored under either `genesis` or `upgrades/`, which holds `bin/$DAEMON_NAME` +along with any other needed files such as auxiliary client programs or libraries. `current` is a symbolic link to the currently +active folder (so `current/bin/$DAEMON_NAME` is the currently active binary). + +*Note: the `name` variable in `upgrades/` holds the URI-encoded name of the upgrade as specified in the upgrade module plan.* + +Please note that `$DAEMON_HOME/cosmovisor` just stores the *binaries* and associated *program code*. +The `cosmovisor` binary can be stored in any typical location (eg `/usr/local/bin`). The actual blockchain +program will store it's data under their default data directory (e.g. `$HOME/.gaiad`) which is independent of +the `$DAEMON_HOME`. You can choose to set `$DAEMON_HOME` to the actual binary's home directory and then end up +with a configuation like the following, but this is left as a choice to the system admininstrator for best +directory layout: + +``` +.gaiad +├── config +├── data +└── cosmovisor +``` + +## Usage + +The system administrator admin is responsible for: +* installing the `cosmovisor` binary and configure the host's init system (e.g. `systemd`, `launchd`, etc) along with the environmental variables appropriately; +* installing the `genesis` folder manually; +* installing the `upgrades/` folders manually. + +`cosmovisor` will set the `current` link to point to `genesis` at first start (when no `current` link exists) and handles +binaries switch overs at the correct points in time, so that the system administrator can prepare days in advance and relax at upgrade time. + +Note that blockchain applications that wish to support upgrades may package up a genesis `cosmovisor` tarball with this information, +just as they prepare the genesis binary tarball. In fact, they may offer a tarball will all upgrades up to current point for easy download +for those who wish to sync a fullnode from start. + +The `DAEMON` specific code and operations (e.g. tendermint config, the application db, syncing blocks, etc) are performed as normal. +Application binaries' directives such as command-line flags and environment variables work normally. + +## Example: simd + +The following instructions provide a demonstration of `cosmovisor`'s integration with the `simd` application +shipped along the Cosmos SDK's source code. + +First compile `simd`: + +``` +cd cosmos-sdk/ +make build +``` + +Create a new key and setup the `simd` node: + +``` +rm -rf $HOME/.simapp +./build/simd keys --keyring-backend=test add validator +./build/simd init testing --chain-id test +./build/simd add-genesis-account --keyring-backend=test $(./build/simd keys --keyring-backend=test show validator -a) 1000000000stake,1000000000validatortoken +./build/simd gentx --keyring-backend test --chain-id test validator 100000stake +./build/simd collect-gentxs +``` + +Set the required environment variables: + +``` +export DAEMON_NAME=simd # binary name +export DAEMON_HOME=$HOME/.simapp # daemon's home directory +``` + +Create the `cosmovisor`’s genesis folders and deploy the binary: + +``` +mkdir -p $DAEMON_HOME/cosmovisor/genesis/bin +cp ./build/simd $DAEMON_HOME/cosmovisor/genesis/bin +``` + +For the sake of this demonstration, we would amend `voting_params.voting_period` in `.simapp/config/genesis.json` to a reduced time ~5 minutes (300s) and eventually launch `cosmosvisor`: + +``` +cosmovisor start +``` + +Submit a software upgrade proposal: + +``` +./build/simd tx gov submit-proposal software-upgrade test1 --title "upgrade-demo" --description "upgrade" --from validator --upgrade-height 100 --deposit 10000000stake --chain-id test --keyring-backend test -y +``` + +Query the proposal to ensure it was correctly broadcast and added to a block: + +``` +./build/simd query gov proposal 1 +``` + +Submit a `Yes` vote for the upgrade proposal: + +``` +./build/simd tx gov vote 1 yes --from validator --keyring-backend test --chain-id test -y +``` + +For the sake of this demonstration, we will hardcode a modification in `simapp` to simulate a code change. +In `simapp/app.go`, find the line containing the upgrade Keeper initialisation, it should look like +`app.UpgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, keys[upgradetypes.StoreKey], appCodec, homePath)`. +After that line, add the following snippet: + + ``` + app.UpgradeKeeper.SetUpgradeHandler("test1", func(ctx sdk.Context, plan upgradetypes.Plan) { + // Add some coins to a random account + addr, err := sdk.AccAddressFromBech32("cosmos18cgkqduwuh253twzmhedesw3l7v3fm37sppt58") + if err != nil { + panic(err) + } + err = app.BankKeeper.AddCoins(ctx, addr, sdk.Coins{sdk.Coin{Denom: "stake", Amount: sdk.NewInt(345600000)}}) + if err != nil { + panic(err) + } + }) +``` + +Now recompile a new binary and place it in `$DAEMON_HOME/cosmosvisor/upgrades/test1/bin`: + +``` +make build +cp ./build/simd $DAEMON_HOME/cosmovisor/upgrades/test1/bin +``` + +The upgrade will occur automatically at height 100. diff --git a/crypto/armor.go b/crypto/armor.go index 35deb107798f..201f1438c05e 100644 --- a/crypto/armor.go +++ b/crypto/armor.go @@ -152,7 +152,7 @@ func encryptPrivKey(privKey cryptotypes.PrivKey, passphrase string) (saltBytes [ } key = crypto.Sha256(key) // get 32 bytes - privKeyBytes := legacy.Cdc.MustMarshalBinaryBare(privKey) + privKeyBytes := legacy.Cdc.MustMarshal(privKey) return saltBytes, xsalsa20symmetric.EncryptSymmetric(privKeyBytes, key) } diff --git a/crypto/keyring/info.go b/crypto/keyring/info.go index aa205eec019a..2b183317c971 100644 --- a/crypto/keyring/info.go +++ b/crypto/keyring/info.go @@ -179,7 +179,7 @@ func (i offlineInfo) GetPath() (*hd.BIP44Params, error) { // Deprecated: this structure is not used anymore and it's here only to allow // decoding old multiInfo records from keyring. -// The problem with legacy.Cdc.UnmarshalBinaryLengthPrefixed - the legacy codec doesn't +// The problem with legacy.Cdc.UnmarshalLengthPrefixed - the legacy codec doesn't // tolerate extensibility. type multisigPubKeyInfo struct { PubKey cryptotypes.PubKey `json:"pubkey"` @@ -244,12 +244,12 @@ func (i multiInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { // encoding info func marshalInfo(i Info) []byte { - return legacy.Cdc.MustMarshalBinaryLengthPrefixed(i) + return legacy.Cdc.MustMarshalLengthPrefixed(i) } // decoding info func unmarshalInfo(bz []byte) (info Info, err error) { - err = legacy.Cdc.UnmarshalBinaryLengthPrefixed(bz, &info) + err = legacy.Cdc.UnmarshalLengthPrefixed(bz, &info) if err != nil { return nil, err } @@ -264,7 +264,7 @@ func unmarshalInfo(bz []byte) (info Info, err error) { _, ok := info.(multiInfo) if ok { var multi multiInfo - err = legacy.Cdc.UnmarshalBinaryLengthPrefixed(bz, &multi) + err = legacy.Cdc.UnmarshalLengthPrefixed(bz, &multi) return multi, err } diff --git a/crypto/keyring/keyring.go b/crypto/keyring/keyring.go index b68fc8d65039..7ec770ae8637 100644 --- a/crypto/keyring/keyring.go +++ b/crypto/keyring/keyring.go @@ -224,7 +224,7 @@ func (ks keystore) ExportPubKeyArmor(uid string) (string, error) { return "", fmt.Errorf("no key to export with name: %s", uid) } - return crypto.ArmorPubKeyBytes(legacy.Cdc.MustMarshalBinaryBare(bz.GetPubKey()), string(bz.GetAlgo())), nil + return crypto.ArmorPubKeyBytes(legacy.Cdc.MustMarshal(bz.GetPubKey()), string(bz.GetAlgo())), nil } func (ks keystore) ExportPubKeyArmorByAddress(address sdk.Address) (string, error) { @@ -743,7 +743,7 @@ func newRealPrompt(dir string, buf io.Reader) func(string) (string, error) { func (ks keystore) writeLocalKey(name string, priv types.PrivKey, algo hd.PubKeyType) (Info, error) { // encrypt private key using keyring pub := priv.PubKey() - info := newLocalInfo(name, pub, string(legacy.Cdc.MustMarshalBinaryBare(priv)), algo) + info := newLocalInfo(name, pub, string(legacy.Cdc.MustMarshal(priv)), algo) if err := ks.writeInfo(info); err != nil { return nil, err } diff --git a/crypto/keys/ed25519/ed25519_test.go b/crypto/keys/ed25519/ed25519_test.go index 44b003fbefe4..83622ee43030 100644 --- a/crypto/keys/ed25519/ed25519_test.go +++ b/crypto/keys/ed25519/ed25519_test.go @@ -162,11 +162,11 @@ func TestMarshalAmino(t *testing.T) { for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { // Do a round trip of encoding/decoding binary. - bz, err := aminoCdc.MarshalBinaryBare(tc.msg) + bz, err := aminoCdc.Marshal(tc.msg) require.NoError(t, err) require.Equal(t, tc.expBinary, bz) - err = aminoCdc.UnmarshalBinaryBare(bz, tc.typ) + err = aminoCdc.Unmarshal(bz, tc.typ) require.NoError(t, err) require.Equal(t, tc.msg, tc.typ) @@ -203,7 +203,7 @@ func TestMarshalAmino_BackwardsCompatibility(t *testing.T) { "ed25519 private key, binary", tmPrivKey, privKey, - aminoCdc.MarshalBinaryBare, + aminoCdc.Marshal, }, { "ed25519 private key, JSON", @@ -215,7 +215,7 @@ func TestMarshalAmino_BackwardsCompatibility(t *testing.T) { "ed25519 public key, binary", tmPubKey, pubKey, - aminoCdc.MarshalBinaryBare, + aminoCdc.Marshal, }, { "ed25519 public key, JSON", diff --git a/crypto/keys/multisig/multisig.go b/crypto/keys/multisig/multisig.go index c0dfbb779177..e39c508be6f8 100644 --- a/crypto/keys/multisig/multisig.go +++ b/crypto/keys/multisig/multisig.go @@ -39,7 +39,7 @@ func (m *LegacyAminoPubKey) Address() cryptotypes.Address { // Bytes returns the proto encoded version of the LegacyAminoPubKey func (m *LegacyAminoPubKey) Bytes() []byte { - return AminoCdc.MustMarshalBinaryBare(m) + return AminoCdc.MustMarshal(m) } // VerifyMultisignature implements the multisigtypes.PubKey VerifyMultisignature method. diff --git a/crypto/keys/multisig/multisig_test.go b/crypto/keys/multisig/multisig_test.go index 03b4f7eb6703..8fb93d3524c4 100644 --- a/crypto/keys/multisig/multisig_test.go +++ b/crypto/keys/multisig/multisig_test.go @@ -276,12 +276,12 @@ func TestPubKeyMultisigThresholdAminoToIface(t *testing.T) { pubkeys := generatePubKeys(5) multisigKey := kmultisig.NewLegacyAminoPubKey(2, pubkeys) - ab, err := legacy.Cdc.MarshalBinaryLengthPrefixed(multisigKey) + ab, err := legacy.Cdc.MarshalLengthPrefixed(multisigKey) require.NoError(t, err) // like other cryptotypes.Pubkey implementations (e.g. ed25519.PubKey), // LegacyAminoPubKey should be deserializable into a cryptotypes.LegacyAminoPubKey: var pubKey kmultisig.LegacyAminoPubKey - err = legacy.Cdc.UnmarshalBinaryLengthPrefixed(ab, &pubKey) + err = legacy.Cdc.UnmarshalLengthPrefixed(ab, &pubKey) require.NoError(t, err) require.Equal(t, multisigKey.Equals(&pubKey), true) @@ -365,10 +365,10 @@ func TestAminoBinary(t *testing.T) { msig := kmultisig.NewLegacyAminoPubKey(2, pubkeys) // Do a round-trip key->bytes->key. - bz, err := legacy.Cdc.MarshalBinaryBare(msig) + bz, err := legacy.Cdc.Marshal(msig) require.NoError(t, err) var newMsig cryptotypes.PubKey - err = legacy.Cdc.UnmarshalBinaryBare(bz, &newMsig) + err = legacy.Cdc.Unmarshal(bz, &newMsig) require.NoError(t, err) require.Equal(t, msig.Threshold, newMsig.(*kmultisig.LegacyAminoPubKey).Threshold) } diff --git a/crypto/keys/secp256k1/secp256k1_test.go b/crypto/keys/secp256k1/secp256k1_test.go index 56c67f594b0b..8f9d0810ce46 100644 --- a/crypto/keys/secp256k1/secp256k1_test.go +++ b/crypto/keys/secp256k1/secp256k1_test.go @@ -247,11 +247,11 @@ func TestMarshalAmino(t *testing.T) { for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { // Do a round trip of encoding/decoding binary. - bz, err := aminoCdc.MarshalBinaryBare(tc.msg) + bz, err := aminoCdc.Marshal(tc.msg) require.NoError(t, err) require.Equal(t, tc.expBinary, bz) - err = aminoCdc.UnmarshalBinaryBare(bz, tc.typ) + err = aminoCdc.Unmarshal(bz, tc.typ) require.NoError(t, err) require.Equal(t, tc.msg, tc.typ) @@ -288,7 +288,7 @@ func TestMarshalAmino_BackwardsCompatibility(t *testing.T) { "secp256k1 private key, binary", tmPrivKey, privKey, - aminoCdc.MarshalBinaryBare, + aminoCdc.Marshal, }, { "secp256k1 private key, JSON", @@ -300,7 +300,7 @@ func TestMarshalAmino_BackwardsCompatibility(t *testing.T) { "secp256k1 public key, binary", tmPubKey, pubKey, - aminoCdc.MarshalBinaryBare, + aminoCdc.Marshal, }, { "secp256k1 public key, JSON", diff --git a/crypto/keys/secp256r1/privkey_internal_test.go b/crypto/keys/secp256r1/privkey_internal_test.go index d00040f7aa56..d690cbf472e1 100644 --- a/crypto/keys/secp256r1/privkey_internal_test.go +++ b/crypto/keys/secp256r1/privkey_internal_test.go @@ -64,9 +64,9 @@ func (suite *SKSuite) TestMarshalProto() { sk = PrivKey{} registry := types.NewInterfaceRegistry() cdc := codec.NewProtoCodec(registry) - bz, err = cdc.MarshalBinaryBare(suite.sk.(*PrivKey)) + bz, err = cdc.Marshal(suite.sk.(*PrivKey)) require.NoError(err) - require.NoError(cdc.UnmarshalBinaryBare(bz, &sk)) + require.NoError(cdc.Unmarshal(bz, &sk)) require.True(sk.Equals(suite.sk)) const bufSize = 100 diff --git a/crypto/keys/secp256r1/pubkey_internal_test.go b/crypto/keys/secp256r1/pubkey_internal_test.go index 84b587d0c63b..e661fccad808 100644 --- a/crypto/keys/secp256r1/pubkey_internal_test.go +++ b/crypto/keys/secp256r1/pubkey_internal_test.go @@ -74,9 +74,9 @@ func (suite *PKSuite) TestMarshalProto() { pk = PubKey{} registry := types.NewInterfaceRegistry() cdc := codec.NewProtoCodec(registry) - bz, err = cdc.MarshalBinaryBare(suite.pk) + bz, err = cdc.Marshal(suite.pk) require.NoError(err) - require.NoError(cdc.UnmarshalBinaryBare(bz, &pk)) + require.NoError(cdc.Unmarshal(bz, &pk)) require.True(pk.Equals(suite.pk)) const bufSize = 100 diff --git a/crypto/ledger/ledger_secp256k1.go b/crypto/ledger/ledger_secp256k1.go index 659181d30648..b57cba9dbf4c 100644 --- a/crypto/ledger/ledger_secp256k1.go +++ b/crypto/ledger/ledger_secp256k1.go @@ -149,7 +149,7 @@ func (pkl *PrivKeyLedgerSecp256k1) AssertIsPrivKeyInner() {} // Bytes implements the PrivKey interface. It stores the cached public key so // we can verify the same key when we reconnect to a ledger. func (pkl PrivKeyLedgerSecp256k1) Bytes() []byte { - return cdc.MustMarshalBinaryBare(pkl) + return cdc.MustMarshal(pkl) } // Equals implements the PrivKey interface. It makes sure two private keys diff --git a/crypto/ledger/ledger_test.go b/crypto/ledger/ledger_test.go index ecef0d3e69c1..61d50c7de801 100644 --- a/crypto/ledger/ledger_test.go +++ b/crypto/ledger/ledger_test.go @@ -235,7 +235,7 @@ func TestRealDeviceSecp256k1(t *testing.T) { require.True(t, valid) // make sure pubkeys serialize properly as well - bs = legacy.Cdc.MustMarshalBinaryBare(pub) + bs = legacy.Cdc.MustMarshal(pub) bpub, err := legacy.PubKeyFromBytes(bs) require.NoError(t, err) require.Equal(t, pub, bpub) diff --git a/docs/architecture/adr-019-protobuf-state-encoding.md b/docs/architecture/adr-019-protobuf-state-encoding.md index e69621e66836..a7d4df746d27 100644 --- a/docs/architecture/adr-019-protobuf-state-encoding.md +++ b/docs/architecture/adr-019-protobuf-state-encoding.md @@ -6,7 +6,7 @@ - 2020 Feb 24: Updates to handle messages with interface fields - 2020 Apr 27: Convert usages of `oneof` for interfaces to `Any` - 2020 May 15: Describe `cosmos_proto` extensions and amino compatibility -- 2020 Dec 4: Move and rename `MarshalAny` and `UnmarshalAny` into the `codec.Marshaler` interface. +- 2020 Dec 4: Move and rename `MarshalAny` and `UnmarshalAny` into the `codec.Codec` interface. - 2021 Feb 24: Remove mentions of `HybridCodec`, which has been abandoned in [#6843](https://github.com/cosmos/cosmos-sdk/pull/6843). ## Status @@ -92,7 +92,7 @@ Example: // ... } - bz := cdc.MustMarshalBinaryBare(ts) + bz := cdc.MustMarshal(ts) ``` However, modules can vary greatly in purpose and design and so we must support the ability for modules @@ -106,7 +106,7 @@ Example: // x/auth/types/codec.go type Codec interface { - codec.Marshaler + codec.Codec MarshalAccount(acc exported.Account) ([]byte, error) UnmarshalAccount(bz []byte) (exported.Account, error) @@ -231,11 +231,11 @@ The SDK will provide support methods `MarshalInterface` and `UnmarshalInterface` import "github.com/cosmos/cosmos-sdk/codec" // note: eviexported.Evidence is an interface type -func MarshalEvidence(cdc codec.BinaryMarshaler, e eviexported.Evidence) ([]byte, error) { +func MarshalEvidence(cdc codec.BinaryCodec, e eviexported.Evidence) ([]byte, error) { return cdc.MarshalInterface(e) } -func UnmarshalEvidence(cdc codec.BinaryMarshaler, bz []byte) (eviexported.Evidence, error) { +func UnmarshalEvidence(cdc codec.BinaryCodec, bz []byte) (eviexported.Evidence, error) { var evi eviexported.Evidence err := cdc.UnmarshalInterface(&evi, bz) return err, nil diff --git a/docs/architecture/adr-038-state-listening.md b/docs/architecture/adr-038-state-listening.md index bee6a837c909..7170f126bcdd 100644 --- a/docs/architecture/adr-038-state-listening.md +++ b/docs/architecture/adr-038-state-listening.md @@ -60,11 +60,11 @@ message StoreKVPair { // protobuf encoded StoreKVPairs to an underlying io.Writer type StoreKVPairWriteListener struct { writer io.Writer - marshaller codec.BinaryMarshaler + marshaller codec.BinaryCodec } -// NewStoreKVPairWriteListener wraps creates a StoreKVPairWriteListener with a provdied io.Writer and codec.BinaryMarshaler -func NewStoreKVPairWriteListener(w io.Writer, m codec.BinaryMarshaler) *StoreKVPairWriteListener { +// NewStoreKVPairWriteListener wraps creates a StoreKVPairWriteListener with a provdied io.Writer and codec.BinaryCodec +func NewStoreKVPairWriteListener(w io.Writer, m codec.BinaryCodec) *StoreKVPairWriteListener { return &StoreKVPairWriteListener{ writer: w, marshaller: m, @@ -248,7 +248,7 @@ type FileStreamingService struct { filePrefix string // optional prefix for each of the generated files writeDir string // directory to write files into dstFile *os.File // the current write output file - marshaller codec.BinaryMarshaler // marshaller used for re-marshalling the ABCI messages to write them out to the destination files + marshaller codec.BinaryCodec // marshaller used for re-marshalling the ABCI messages to write them out to the destination files stateCache [][]byte // cache the protobuf binary encoded StoreKVPairs in the order they are received } ``` @@ -279,7 +279,7 @@ func (iw *intermediateWriter) Write(b []byte) (int, error) { } // NewFileStreamingService creates a new FileStreamingService for the provided writeDir, (optional) filePrefix, and storeKeys -func NewFileStreamingService(writeDir, filePrefix string, storeKeys []sdk.StoreKey, m codec.BinaryMarshaler) (*FileStreamingService, error) { +func NewFileStreamingService(writeDir, filePrefix string, storeKeys []sdk.StoreKey, m codec.BinaryCodec) (*FileStreamingService, error) { listenChan := make(chan []byte, 0) iw := NewIntermediateWriter(listenChan) listener := listen.NewStoreKVPairWriteListener(iw, m) diff --git a/docs/building-modules/keeper.md b/docs/building-modules/keeper.md index e84abfb01fd7..d35c6da8e616 100644 --- a/docs/building-modules/keeper.md +++ b/docs/building-modules/keeper.md @@ -40,7 +40,7 @@ Let us go through the different parameters: - An expected `keeper` is a `keeper` external to a module that is required by the internal `keeper` of said module. External `keeper`s are listed in the internal `keeper`'s type definition as interfaces. These interfaces are themselves defined in a `types/expected_keepers.go` file within the module's folder. In this context, interfaces are used to reduce the number of dependencies, as well as to facilitate the maintenance of the module itself. - `storeKey`s grant access to the store(s) of the [multistore](../core/store.md) managed by the module. They should always remain unexposed to external modules. -- A [codec `cdc`](../core/encoding.md), used to marshall and unmarshall struct to/from `[]byte`, that can be any of `codec.BinaryMarshaler`,`codec.JSONMarshaler` or `codec.Marshaler` based on your requirements. It can be either a proto or amino codec as long as they implement these interfaces. +- A [codec `cdc`](../core/encoding.md), used to marshall and unmarshall struct to/from `[]byte`, that can be any of `codec.BinaryCodec`,`codec.JSONCodec` or `codec.Codec` based on your requirements. It can be either a proto or amino codec as long as they implement these interfaces. Of course, it is possible to define different types of internal `keeper`s for the same module (e.g. a read-only `keeper`). Each type of `keeper` comes with its own constructor function, which is called from the [application's constructor function](../basics/app-anatomy.md). This is where `keeper`s are instantiated, and where developers make sure to pass correct instances of modules' `keeper`s to other modules that require it. diff --git a/docs/building-modules/module-manager.md b/docs/building-modules/module-manager.md index 919ec1425c84..5533721650d0 100644 --- a/docs/building-modules/module-manager.md +++ b/docs/building-modules/module-manager.md @@ -36,8 +36,8 @@ Let us go through the methods: - `Name()`: Returns the name of the module as a `string`. - `RegisterLegacyAminoCodec(*codec.LegacyAmino)`: Registers the `amino` codec for the module, which is used to marshal and unmarshal structs to/from `[]byte` in order to persist them in the module's `KVStore`. - `RegisterInterfaces(codectypes.InterfaceRegistry)`: Registers a module's interface types and their concrete implementations as `proto.Message`. -- `DefaultGenesis(codec.JSONMarshaler)`: Returns a default [`GenesisState`](./genesis.md#genesisstate) for the module, marshalled to `json.RawMessage`. The default `GenesisState` need to be defined by the module developer and is primarily used for testing. -- `ValidateGenesis(codec.JSONMarshaler, client.TxEncodingConfig, json.RawMessage)`: Used to validate the `GenesisState` defined by a module, given in its `json.RawMessage` form. It will usually unmarshall the `json` before running a custom [`ValidateGenesis`](./genesis.md#validategenesis) function defined by the module developer. +- `DefaultGenesis(codec.JSONCodec)`: Returns a default [`GenesisState`](./genesis.md#genesisstate) for the module, marshalled to `json.RawMessage`. The default `GenesisState` need to be defined by the module developer and is primarily used for testing. +- `ValidateGenesis(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage)`: Used to validate the `GenesisState` defined by a module, given in its `json.RawMessage` form. It will usually unmarshall the `json` before running a custom [`ValidateGenesis`](./genesis.md#validategenesis) function defined by the module developer. - `RegisterRESTRoutes(client.Context, *mux.Router)`: Registers the REST routes for the module. These routes will be used to map REST request to the module in order to process them. See [../interfaces/rest.md] for more. - `RegisterGRPCGatewayRoutes(client.Context, *runtime.ServeMux)`: Registers gRPC routes for the module. - `GetTxCmd()`: Returns the root [`Tx` command](./module-interfaces.md#tx) for the module. The subcommands of this root command are used by end-users to generate new transactions containing [`message`s](./messages-and-queries.md#queries) defined in the module. @@ -53,10 +53,10 @@ The `AppModuleGenesis` interface is a simple embedding of the `AppModuleBasic` i Let us go through the two added methods: -- `InitGenesis(sdk.Context, codec.JSONMarshaler, json.RawMessage)`: Initializes the subset of the state managed by the module. It is called at genesis (i.e. when the chain is first started). -- `ExportGenesis(sdk.Context, codec.JSONMarshaler)`: Exports the latest subset of the state managed by the module to be used in a new genesis file. `ExportGenesis` is called for each module when a new chain is started from the state of an existing chain. +- `InitGenesis(sdk.Context, codec.JSONCodec, json.RawMessage)`: Initializes the subset of the state managed by the module. It is called at genesis (i.e. when the chain is first started). +- `ExportGenesis(sdk.Context, codec.JSONCodec)`: Exports the latest subset of the state managed by the module to be used in a new genesis file. `ExportGenesis` is called for each module when a new chain is started from the state of an existing chain. -It does not have its own manager, and exists separately from [`AppModule`](#appmodule) only for modules that exist only to implement genesis functionalities, so that they can be managed without having to implement all of `AppModule`'s methods. If the module is not only used during genesis, `InitGenesis(sdk.Context, codec.JSONMarshaler, json.RawMessage)` and `ExportGenesis(sdk.Context, codec.JSONMarshaler)` will generally be defined as methods of the concrete type implementing hte `AppModule` interface. +It does not have its own manager, and exists separately from [`AppModule`](#appmodule) only for modules that exist only to implement genesis functionalities, so that they can be managed without having to implement all of `AppModule`'s methods. If the module is not only used during genesis, `InitGenesis(sdk.Context, codec.JSONCodec, json.RawMessage)` and `ExportGenesis(sdk.Context, codec.JSONCodec)` will generally be defined as methods of the concrete type implementing hte `AppModule` interface. ### `AppModule` @@ -114,8 +114,8 @@ It implements the following methods: - `NewBasicManager(modules ...AppModuleBasic)`: Constructor function. It takes a list of the application's `AppModuleBasic` and builds a new `BasicManager`. This function is generally called in the `init()` function of [`app.go`](../basics/app-anatomy.md#core-application-file) to quickly initialize the independent elements of the application's modules (click [here](https://github.com/cosmos/gaia/blob/master/app/app.go#L59-L74) to see an example). - `RegisterLegacyAminoCodec(cdc *codec.LegacyAmino)`: Registers the [`codec.LegacyAmino`s](../core/encoding.md#amino) of each of the application's `AppModuleBasic`. This function is usually called early on in the [application's construction](../basics/app-anatomy.md#constructor). - `RegisterInterfaces(registry codectypes.InterfaceRegistry)`: Registers interface types and implementations of each of the application's `AppModuleBasic`. -- `DefaultGenesis(cdc codec.JSONMarshaler)`: Provides default genesis information for modules in the application by calling the [`DefaultGenesis(cdc codec.JSONMarshaler)`](./genesis.md#defaultgenesis) function of each module. It is used to construct a default genesis file for the application. -- `ValidateGenesis(cdc codec.JSONMarshaler, txEncCfg client.TxEncodingConfig, genesis map[string]json.RawMessage)`: Validates the genesis information modules by calling the [`ValidateGenesis(codec.JSONMarshaler, client.TxEncodingConfig, json.RawMessage)`](./genesis.md#validategenesis) function of each module. +- `DefaultGenesis(cdc codec.JSONCodec)`: Provides default genesis information for modules in the application by calling the [`DefaultGenesis(cdc codec.JSONCodec)`](./genesis.md#defaultgenesis) function of each module. It is used to construct a default genesis file for the application. +- `ValidateGenesis(cdc codec.JSONCodec, txEncCfg client.TxEncodingConfig, genesis map[string]json.RawMessage)`: Validates the genesis information modules by calling the [`ValidateGenesis(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage)`](./genesis.md#validategenesis) function of each module. - `RegisterRESTRoutes(ctx client.Context, rtr *mux.Router)`: Registers REST routes for modules by calling the [`RegisterRESTRoutes`](./module-interfaces.md#register-routes) function of each module. This function is usually called function from the `main.go` function of the [application's command-line interface](../interfaces/cli.md). - `RegisterGRPCGatewayRoutes(clientCtx client.Context, rtr *runtime.ServeMux)`: Registers gRPC routes for modules. - `AddTxCommands(rootTxCmd *cobra.Command)`: Adds modules' transaction commands to the application's [`rootTxCommand`](../interfaces/cli.md#transaction-commands). This function is usually called function from the `main.go` function of the [application's command-line interface](../interfaces/cli.md). @@ -137,8 +137,8 @@ The module manager is used throughout the application whenever an action on a co - `RegisterInvariants(ir sdk.InvariantRegistry)`: Registers the [invariants](./invariants.md) of each module. - `RegisterRoutes(router sdk.Router, queryRouter sdk.QueryRouter, legacyQuerierCdc *codec.LegacyAmino)`: Registers legacy [`Msg`](./messages-and-queries.md#messages) and [`querier`](./query-services.md#legacy-queriers) routes. - `RegisterServices(cfg Configurator)`: Registers all module services. -- `InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, genesisData map[string]json.RawMessage)`: Calls the [`InitGenesis`](./genesis.md#initgenesis) function of each module when the application is first started, in the order defined in `OrderInitGenesis`. Returns an `abci.ResponseInitChain` to the underlying consensus engine, which can contain validator updates. -- `ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler)`: Calls the [`ExportGenesis`](./genesis.md#exportgenesis) function of each module, in the order defined in `OrderExportGenesis`. The export constructs a genesis file from a previously existing state, and is mainly used when a hard-fork upgrade of the chain is required. +- `InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, genesisData map[string]json.RawMessage)`: Calls the [`InitGenesis`](./genesis.md#initgenesis) function of each module when the application is first started, in the order defined in `OrderInitGenesis`. Returns an `abci.ResponseInitChain` to the underlying consensus engine, which can contain validator updates. +- `ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec)`: Calls the [`ExportGenesis`](./genesis.md#exportgenesis) function of each module, in the order defined in `OrderExportGenesis`. The export constructs a genesis file from a previously existing state, and is mainly used when a hard-fork upgrade of the chain is required. - `BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock)`: At the beginning of each block, this function is called from [`BaseApp`](../core/baseapp.md#beginblock) and, in turn, calls the [`BeginBlock`](./beginblock-endblock.md) function of each module, in the order defined in `OrderBeginBlockers`. It creates a child [context](../core/context.md) with an event manager to aggregate [events](../core/events.md) emitted from all modules. The function returns an `abci.ResponseBeginBlock` which contains the aforementioned events. - `EndBlock(ctx sdk.Context, req abci.RequestEndBlock)`: At the end of each block, this function is called from [`BaseApp`](../core/baseapp.md#endblock) and, in turn, calls the [`EndBlock`](./beginblock-endblock.md) function of each module, in the order defined in `OrderEndBlockers`. It creates a child [context](../core/context.md) with an event manager to aggregate [events](../core/events.md) emitted from all modules. The function returns an `abci.ResponseEndBlock` which contains the aforementioned events, as well as validator set updates (if any). diff --git a/docs/core/encoding.md b/docs/core/encoding.md index fc390f79dd5c..7b6b1274ca2a 100644 --- a/docs/core/encoding.md +++ b/docs/core/encoding.md @@ -59,8 +59,8 @@ Where there is no protobuf-based type definition for a module (see below), Amino is used to encode and decode raw wire bytes to the concrete type or interface: ```go -bz := keeper.cdc.MustMarshalBinaryBare(typeOrInterface) -keeper.cdc.MustUnmarshalBinaryBare(bz, &typeOrInterface) +bz := keeper.cdc.MustMarshal(typeOrInterface) +keeper.cdc.MustUnmarshal(bz, &typeOrInterface) ``` Note, there are length-prefixed variants of the above functionality and this is @@ -150,7 +150,7 @@ profile := Profile { } // We can then marshal the profile as usual. -bz, err := cdc.MarshalBinaryBare(profile) +bz, err := cdc.Marshal(profile) jsonBz, err := cdc.MarshalJSON(profile) ``` @@ -162,7 +162,7 @@ The reverse operation of retrieving the concrete Go type from inside an `Any`, c profileBz := ... // The proto-encoded bytes of a Profile, e.g. retrieved through gRPC. var myProfile Profile // Unmarshal the bytes into the myProfile struct. -err := cdc.UnmarshalBinaryBare(profilebz, &myProfile) +err := cdc.Unmarshal(profilebz, &myProfile) // Let's see the types of the Account field. fmt.Printf("%T\n", myProfile.Account) // Prints "Any" @@ -241,7 +241,7 @@ message MsgSubmitEvidence { } ``` -The SDK `codec.Marshaler` interface provides support methods `MarshalInterface` and `UnmarshalInterface` to easy encoding of state to `Any`. +The SDK `codec.Codec` interface provides support methods `MarshalInterface` and `UnmarshalInterface` to easy encoding of state to `Any`. Module should register interfaces using `InterfaceRegistry` which provides a mechanism for registering interfaces: `RegisterInterface(protoName string, iface interface{})` and implementations: `RegisterImplementations(iface interface{}, impls ...proto.Message)` that can be safely unpacked from Any, similarly to type registration with Amino: diff --git a/docs/ibc/upgrades/developer-guide.md b/docs/ibc/upgrades/developer-guide.md index 998cb276e70c..d41b3346d4f7 100644 --- a/docs/ibc/upgrades/developer-guide.md +++ b/docs/ibc/upgrades/developer-guide.md @@ -19,7 +19,7 @@ The IBC protocol allows client implementations to provide a path to upgrading cl // may be cancelled or modified before the last planned height. VerifyUpgradeAndUpdateState( ctx sdk.Context, - cdc codec.BinaryMarshaler, + cdc codec.BinaryCodec, store sdk.KVStore, newClient ClientState, newConsState ConsensusState, diff --git a/docs/migrations/app_and_modules.md b/docs/migrations/app_and_modules.md index 454ecdab2a0d..5249a0131359 100644 --- a/docs/migrations/app_and_modules.md +++ b/docs/migrations/app_and_modules.md @@ -123,11 +123,11 @@ Moreover, a new `RegisterInterfaces` method has been added to the `AppModule` in ### Keeper -The `Keeper` constructor now takes a `codec.Marshaler` instead of a concrete Amino codec. This `codec.Marshaler` is used to encode types as binary and save the bytes into the state. With an interface, you can define `codec.Marshaler` to be Amino or Protobuf on an app level, and keepers will use that encoding library to encode state. Please note that Amino is deprecated in v0.40, and we strongly recommend to use Protobuf. Internally, the SDK still uses Amino in a couple of places (legacy REST API, x/params, keyring...), but Amino is planned to be removed in a future release. +The `Keeper` constructor now takes a `codec.Codec` instead of a concrete Amino codec. This `codec.Codec` is used to encode types as binary and save the bytes into the state. With an interface, you can define `codec.Codec` to be Amino or Protobuf on an app level, and keepers will use that encoding library to encode state. Please note that Amino is deprecated in v0.40, and we strongly recommend to use Protobuf. Internally, the SDK still uses Amino in a couple of places (legacy REST API, x/params, keyring...), but Amino is planned to be removed in a future release. Keeping Amino for now can be useful if you wish to update to SDK v0.40 without doing a chain upgrade with a genesis migration. This will not require updating the stores, so you can migrate to Cosmos SDK v0.40 with less effort. However, as Amino will be removed in a future release, the chain migration with genesis export/import will need to be performed then. -Related to the keepers, each module's `AppModuleBasic` now also includes this `codec.Marshaler`: +Related to the keepers, each module's `AppModuleBasic` now also includes this `codec.Codec`: +++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/x/bank/module.go#L35-L38 @@ -173,12 +173,12 @@ A number of other smaller breaking changes are also noteworthy. | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `alias.go` file | Removed | `alias` usage is removed, please see [#6311](https://github.com/cosmos/cosmos-sdk/issues/6311) for details. | | `codec.New()` | `codec.NewLegacyAmino()` | Simple rename. | -| `DefaultGenesis()` | `DefaultGenesis(cdc codec.JSONMarshaler)` | `DefaultGenesis` takes a codec argument now | -| `ValidateGenesis()` | `ValidateGenesis(cdc codec.JSONMarshaler, config client.TxEncodingConfig, bz json.RawMessage)` | `ValidateGenesis` now requires `Marshaler`, `TxEncodingConfig`, `json.RawMessage` as input. | +| `DefaultGenesis()` | `DefaultGenesis(cdc codec.JSONCodec)` | `DefaultGenesis` takes a codec argument now | +| `ValidateGenesis()` | `ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage)` | `ValidateGenesis` now requires `Marshaler`, `TxEncodingConfig`, `json.RawMessage` as input. | | `Route() string` | `Route() sdk.Route` | For legacy handlers, return type of `Route()` method is changed from `string` to `"github.com/cosmos/cosmos-sdk/types".Route`. It should return a `NewRoute()` which includes `RouterKey` and `NewHandler` as params. | | `QuerierHandler` | `LegacyQuerierHandler` | Simple rename. | -| `InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate` | InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate | `InitGenesis` now takes a codec input. | -| `ExportGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate` | ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate | `ExportGenesis` now takes a codec input. | +| `InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate` | InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate | `InitGenesis` now takes a codec input. | +| `ExportGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate` | ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate | `ExportGenesis` now takes a codec input. | ## Updating Your App @@ -215,7 +215,7 @@ These codecs are used to populate the following fields on your app (again, we ar +++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/simapp/app.go#L146-L153 -As explained in the [modules migration section](#updating-modules), some functions and structs in modules require an additional `codec.Marshaler` argument. You should pass `app.appCodec` in these cases, and this will be the default codec used throughout the app. +As explained in the [modules migration section](#updating-modules), some functions and structs in modules require an additional `codec.Codec` argument. You should pass `app.appCodec` in these cases, and this will be the default codec used throughout the app. ### Registering Non-Module Protobuf Services diff --git a/server/export_test.go b/server/export_test.go index d4e41ef8e886..7280bbc718f4 100644 --- a/server/export_test.go +++ b/server/export_test.go @@ -177,7 +177,7 @@ func createConfigFolder(dir string) error { return os.Mkdir(path.Join(dir, "config"), 0700) } -func newDefaultGenesisDoc(cdc codec.Marshaler) *tmtypes.GenesisDoc { +func newDefaultGenesisDoc(cdc codec.Codec) *tmtypes.GenesisDoc { genesisState := simapp.NewDefaultGenesisState(cdc) stateBytes, err := json.MarshalIndent(genesisState, "", " ") diff --git a/server/grpc/grpc_web_test.go b/server/grpc/grpc_web_test.go index 8f563becc666..fa657ae941ad 100644 --- a/server/grpc/grpc_web_test.go +++ b/server/grpc/grpc_web_test.go @@ -72,7 +72,7 @@ func (s *GRPCWebTestSuite) Test_Latest_Validators() { s.assertTrailerGrpcCode(trailers, codes.OK, "") s.assertContentTypeSet(headers, contentType) var valsSet tmservice.GetLatestValidatorSetResponse - err = s.protoCdc.UnmarshalBinaryBare(responses[0], &valsSet) + err = s.protoCdc.Unmarshal(responses[0], &valsSet) s.Require().NoError(err) pubKey, ok := valsSet.Validators[0].PubKey.GetCachedValue().(cryptotypes.PubKey) s.Require().Equal(true, ok) @@ -92,7 +92,7 @@ func (s *GRPCWebTestSuite) Test_Total_Supply() { s.assertTrailerGrpcCode(trailers, codes.OK, "") s.assertContentTypeSet(headers, contentType) var totalSupply banktypes.QueryTotalSupplyResponse - _ = s.protoCdc.UnmarshalBinaryBare(responses[0], &totalSupply) + _ = s.protoCdc.Unmarshal(responses[0], &totalSupply) } } diff --git a/server/rosetta.go b/server/rosetta.go index c6a928d062d0..088de4a70f69 100644 --- a/server/rosetta.go +++ b/server/rosetta.go @@ -13,7 +13,7 @@ import ( // RosettaCommand builds the rosetta root command given // a protocol buffers serializer/deserializer -func RosettaCommand(ir codectypes.InterfaceRegistry, cdc codec.Marshaler) *cobra.Command { +func RosettaCommand(ir codectypes.InterfaceRegistry, cdc codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "rosetta", Short: "spin up a rosetta server", diff --git a/simapp/app.go b/simapp/app.go index 0e5281a2f6d8..17ebfbe16b3f 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -142,7 +142,7 @@ var ( type SimApp struct { *baseapp.BaseApp legacyAmino *codec.LegacyAmino - appCodec codec.Marshaler + appCodec codec.Codec interfaceRegistry types.InterfaceRegistry invCheckPeriod uint @@ -467,7 +467,7 @@ func (app *SimApp) LegacyAmino() *codec.LegacyAmino { // // NOTE: This is solely to be used for testing purposes as it may be desirable // for modules to register their own custom testing types. -func (app *SimApp) AppCodec() codec.Marshaler { +func (app *SimApp) AppCodec() codec.Codec { return app.appCodec } @@ -563,7 +563,7 @@ func GetMaccPerms() map[string][]string { } // initParamsKeeper init params keeper and its subspaces -func initParamsKeeper(appCodec codec.BinaryMarshaler, legacyAmino *codec.LegacyAmino, key, tkey sdk.StoreKey) paramskeeper.Keeper { +func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey sdk.StoreKey) paramskeeper.Keeper { paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey) paramsKeeper.Subspace(authtypes.ModuleName) diff --git a/simapp/genesis.go b/simapp/genesis.go index dbb4e01c7690..772e452d4434 100644 --- a/simapp/genesis.go +++ b/simapp/genesis.go @@ -16,6 +16,6 @@ import ( type GenesisState map[string]json.RawMessage // NewDefaultGenesisState generates the default state for the application. -func NewDefaultGenesisState(cdc codec.JSONMarshaler) GenesisState { +func NewDefaultGenesisState(cdc codec.JSONCodec) GenesisState { return ModuleBasics.DefaultGenesis(cdc) } diff --git a/simapp/params/encoding.go b/simapp/params/encoding.go index 698408dafdcb..3d634abf16b2 100644 --- a/simapp/params/encoding.go +++ b/simapp/params/encoding.go @@ -10,7 +10,7 @@ import ( // This is provided for compatibility between protobuf and amino implementations. type EncodingConfig struct { InterfaceRegistry types.InterfaceRegistry - Marshaler codec.Marshaler + Marshaler codec.Codec TxConfig client.TxConfig Amino *codec.LegacyAmino } diff --git a/simapp/simd/cmd/genaccounts.go b/simapp/simd/cmd/genaccounts.go index 57de144c36b4..9c34f3388dca 100644 --- a/simapp/simd/cmd/genaccounts.go +++ b/simapp/simd/cmd/genaccounts.go @@ -41,7 +41,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 - cdc := depCdc.(codec.Marshaler) + cdc := depCdc.(codec.Codec) serverCtx := server.GetServerContextFromCmd(cmd) config := serverCtx.Config diff --git a/simapp/state.go b/simapp/state.go index e90bb0257ca0..45df84384289 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -25,7 +25,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.JSONCodec, 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) { @@ -129,7 +129,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.JSONCodec, accs []simtypes.Account, genesisTimestamp time.Time, appParams simtypes.AppParams, ) (json.RawMessage, []simtypes.Account) { numAccs := int64(len(accs)) @@ -183,7 +183,7 @@ 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.JSONCodec, genesisFile string) (tmtypes.GenesisDoc, []simtypes.Account) { bytes, err := ioutil.ReadFile(genesisFile) if err != nil { panic(err) diff --git a/simapp/utils.go b/simapp/utils.go index 2067ed54b108..a1614198b3dd 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -49,7 +49,7 @@ func SetupSimulation(dirPrefix, dbName string) (simtypes.Config, dbm.DB, string, // SimulationOperations retrieves the simulation params from the provided file path // and returns all the modules weighted operations -func SimulationOperations(app App, cdc codec.JSONMarshaler, config simtypes.Config) []simtypes.WeightedOperation { +func SimulationOperations(app App, cdc codec.JSONCodec, config simtypes.Config) []simtypes.WeightedOperation { simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, diff --git a/simapp/utils_test.go b/simapp/utils_test.go index 6d8bb21f3f08..0240c482a558 100644 --- a/simapp/utils_test.go +++ b/simapp/utils_test.go @@ -41,7 +41,7 @@ func TestGetSimulationLog(t *testing.T) { }, { authtypes.StoreKey, - []kv.Pair{{Key: authtypes.GlobalAccountNumberKey, Value: cdc.MustMarshalBinaryBare(uint64(10))}}, + []kv.Pair{{Key: authtypes.GlobalAccountNumberKey, Value: cdc.MustMarshal(uint64(10))}}, "10", }, { diff --git a/store/listenkv/store_test.go b/store/listenkv/store_test.go index 6391458e8be0..5d4fd0cca9c4 100644 --- a/store/listenkv/store_test.go +++ b/store/listenkv/store_test.go @@ -121,7 +121,7 @@ func TestListenKVStoreSet(t *testing.T) { buf.Reset() store.Set(tc.key, tc.value) storeKVPair := new(types.StoreKVPair) - testMarshaller.UnmarshalBinaryLengthPrefixed(buf.Bytes(), storeKVPair) + testMarshaller.UnmarshalLengthPrefixed(buf.Bytes(), storeKVPair) require.Equal(t, tc.expectedOut, storeKVPair) } @@ -156,7 +156,7 @@ func TestListenKVStoreDelete(t *testing.T) { buf.Reset() store.Delete(tc.key) storeKVPair := new(types.StoreKVPair) - testMarshaller.UnmarshalBinaryLengthPrefixed(buf.Bytes(), storeKVPair) + testMarshaller.UnmarshalLengthPrefixed(buf.Bytes(), storeKVPair) require.Equal(t, tc.expectedOut, storeKVPair) } diff --git a/store/rootmulti/store_test.go b/store/rootmulti/store_test.go index 6a501ae1f776..cf7653b076cb 100644 --- a/store/rootmulti/store_test.go +++ b/store/rootmulti/store_test.go @@ -728,7 +728,7 @@ func TestGetListenWrappedKVStore(t *testing.T) { require.IsType(t, &listenkv.Store{}, listenWrappedStore1) listenWrappedStore1.Set(testKey1, testValue1) - expectedOutputKVPairSet1, err := testMarshaller.MarshalBinaryLengthPrefixed(&types.StoreKVPair{ + expectedOutputKVPairSet1, err := testMarshaller.MarshalLengthPrefixed(&types.StoreKVPair{ Key: testKey1, Value: testValue1, StoreKey: testStoreKey1.Name(), @@ -740,7 +740,7 @@ func TestGetListenWrappedKVStore(t *testing.T) { require.Equal(t, expectedOutputKVPairSet1, kvPairSet1Bytes) listenWrappedStore1.Delete(testKey1) - expectedOutputKVPairDelete1, err := testMarshaller.MarshalBinaryLengthPrefixed(&types.StoreKVPair{ + expectedOutputKVPairDelete1, err := testMarshaller.MarshalLengthPrefixed(&types.StoreKVPair{ Key: testKey1, Value: nil, StoreKey: testStoreKey1.Name(), @@ -755,7 +755,7 @@ func TestGetListenWrappedKVStore(t *testing.T) { require.IsType(t, &listenkv.Store{}, listenWrappedStore2) listenWrappedStore2.Set(testKey2, testValue2) - expectedOutputKVPairSet2, err := testMarshaller.MarshalBinaryLengthPrefixed(&types.StoreKVPair{ + expectedOutputKVPairSet2, err := testMarshaller.MarshalLengthPrefixed(&types.StoreKVPair{ Key: testKey2, Value: testValue2, StoreKey: testStoreKey2.Name(), @@ -766,7 +766,7 @@ func TestGetListenWrappedKVStore(t *testing.T) { require.Equal(t, expectedOutputKVPairSet2, kvPairSet2Bytes) listenWrappedStore2.Delete(testKey2) - expectedOutputKVPairDelete2, err := testMarshaller.MarshalBinaryLengthPrefixed(&types.StoreKVPair{ + expectedOutputKVPairDelete2, err := testMarshaller.MarshalLengthPrefixed(&types.StoreKVPair{ Key: testKey2, Value: nil, StoreKey: testStoreKey2.Name(), diff --git a/store/types/listening.go b/store/types/listening.go index 96f29cce9e52..2294a5ada531 100644 --- a/store/types/listening.go +++ b/store/types/listening.go @@ -18,11 +18,11 @@ type WriteListener interface { // protobuf encoded StoreKVPairs to an underlying io.Writer type StoreKVPairWriteListener struct { writer io.Writer - marshaller codec.BinaryMarshaler + marshaller codec.BinaryCodec } -// NewStoreKVPairWriteListener wraps creates a StoreKVPairWriteListener with a provdied io.Writer and codec.BinaryMarshaler -func NewStoreKVPairWriteListener(w io.Writer, m codec.BinaryMarshaler) *StoreKVPairWriteListener { +// NewStoreKVPairWriteListener wraps creates a StoreKVPairWriteListener with a provdied io.Writer and codec.BinaryCodec +func NewStoreKVPairWriteListener(w io.Writer, m codec.BinaryCodec) *StoreKVPairWriteListener { return &StoreKVPairWriteListener{ writer: w, marshaller: m, @@ -36,7 +36,7 @@ func (wl *StoreKVPairWriteListener) OnWrite(storeKey StoreKey, key []byte, value kvPair.Delete = delete kvPair.Key = key kvPair.Value = value - by, err := wl.marshaller.MarshalBinaryLengthPrefixed(kvPair) + by, err := wl.marshaller.MarshalLengthPrefixed(kvPair) if err != nil { return err } diff --git a/store/types/listening_test.go b/store/types/listening_test.go index acf17b5001b8..af1362e4f938 100644 --- a/store/types/listening_test.go +++ b/store/types/listening_test.go @@ -45,7 +45,7 @@ func TestOnWrite(t *testing.T) { StoreKey: testStoreKey.Name(), Delete: false, } - testMarshaller.UnmarshalBinaryLengthPrefixed(outputBytes, outputKVPair) + testMarshaller.UnmarshalLengthPrefixed(outputBytes, outputKVPair) require.EqualValues(t, expectedOutputKVPair, outputKVPair) testWriter.Reset() @@ -61,6 +61,6 @@ func TestOnWrite(t *testing.T) { StoreKey: testStoreKey.Name(), Delete: true, } - testMarshaller.UnmarshalBinaryLengthPrefixed(outputBytes, outputKVPair) + testMarshaller.UnmarshalLengthPrefixed(outputBytes, outputKVPair) require.EqualValues(t, expectedOutputKVPair, outputKVPair) } diff --git a/tests/mocks/types_module_module.go b/tests/mocks/types_module_module.go index 0d00584ab9a8..974ec1f17abd 100644 --- a/tests/mocks/types_module_module.go +++ b/tests/mocks/types_module_module.go @@ -6,6 +6,8 @@ package mocks import ( json "encoding/json" + reflect "reflect" + client "github.com/cosmos/cosmos-sdk/client" codec "github.com/cosmos/cosmos-sdk/codec" types "github.com/cosmos/cosmos-sdk/codec/types" @@ -16,7 +18,6 @@ import ( runtime "github.com/grpc-ecosystem/grpc-gateway/runtime" cobra "github.com/spf13/cobra" types1 "github.com/tendermint/tendermint/abci/types" - reflect "reflect" ) // MockAppModuleBasic is a mock of AppModuleBasic interface @@ -81,7 +82,7 @@ func (mr *MockAppModuleBasicMockRecorder) RegisterInterfaces(arg0 interface{}) * } // DefaultGenesis mocks base method -func (m *MockAppModuleBasic) DefaultGenesis(arg0 codec.JSONMarshaler) json.RawMessage { +func (m *MockAppModuleBasic) DefaultGenesis(arg0 codec.JSONCodec) json.RawMessage { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DefaultGenesis", arg0) ret0, _ := ret[0].(json.RawMessage) @@ -95,7 +96,7 @@ func (mr *MockAppModuleBasicMockRecorder) DefaultGenesis(arg0 interface{}) *gomo } // ValidateGenesis mocks base method -func (m *MockAppModuleBasic) ValidateGenesis(arg0 codec.JSONMarshaler, arg1 client.TxEncodingConfig, arg2 json.RawMessage) error { +func (m *MockAppModuleBasic) ValidateGenesis(arg0 codec.JSONCodec, arg1 client.TxEncodingConfig, arg2 json.RawMessage) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ValidateGenesis", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -222,7 +223,7 @@ func (mr *MockAppModuleGenesisMockRecorder) RegisterInterfaces(arg0 interface{}) } // DefaultGenesis mocks base method -func (m *MockAppModuleGenesis) DefaultGenesis(arg0 codec.JSONMarshaler) json.RawMessage { +func (m *MockAppModuleGenesis) DefaultGenesis(arg0 codec.JSONCodec) json.RawMessage { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DefaultGenesis", arg0) ret0, _ := ret[0].(json.RawMessage) @@ -236,7 +237,7 @@ func (mr *MockAppModuleGenesisMockRecorder) DefaultGenesis(arg0 interface{}) *go } // ValidateGenesis mocks base method -func (m *MockAppModuleGenesis) ValidateGenesis(arg0 codec.JSONMarshaler, arg1 client.TxEncodingConfig, arg2 json.RawMessage) error { +func (m *MockAppModuleGenesis) ValidateGenesis(arg0 codec.JSONCodec, arg1 client.TxEncodingConfig, arg2 json.RawMessage) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ValidateGenesis", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -302,7 +303,7 @@ func (mr *MockAppModuleGenesisMockRecorder) GetQueryCmd() *gomock.Call { } // InitGenesis mocks base method -func (m *MockAppModuleGenesis) InitGenesis(arg0 types0.Context, arg1 codec.JSONMarshaler, arg2 json.RawMessage) []types1.ValidatorUpdate { +func (m *MockAppModuleGenesis) InitGenesis(arg0 types0.Context, arg1 codec.JSONCodec, arg2 json.RawMessage) []types1.ValidatorUpdate { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InitGenesis", arg0, arg1, arg2) ret0, _ := ret[0].([]types1.ValidatorUpdate) @@ -316,7 +317,7 @@ func (mr *MockAppModuleGenesisMockRecorder) InitGenesis(arg0, arg1, arg2 interfa } // ExportGenesis mocks base method -func (m *MockAppModuleGenesis) ExportGenesis(arg0 types0.Context, arg1 codec.JSONMarshaler) json.RawMessage { +func (m *MockAppModuleGenesis) ExportGenesis(arg0 types0.Context, arg1 codec.JSONCodec) json.RawMessage { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ExportGenesis", arg0, arg1) ret0, _ := ret[0].(json.RawMessage) @@ -391,7 +392,7 @@ func (mr *MockAppModuleMockRecorder) RegisterInterfaces(arg0 interface{}) *gomoc } // DefaultGenesis mocks base method -func (m *MockAppModule) DefaultGenesis(arg0 codec.JSONMarshaler) json.RawMessage { +func (m *MockAppModule) DefaultGenesis(arg0 codec.JSONCodec) json.RawMessage { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DefaultGenesis", arg0) ret0, _ := ret[0].(json.RawMessage) @@ -405,7 +406,7 @@ func (mr *MockAppModuleMockRecorder) DefaultGenesis(arg0 interface{}) *gomock.Ca } // ValidateGenesis mocks base method -func (m *MockAppModule) ValidateGenesis(arg0 codec.JSONMarshaler, arg1 client.TxEncodingConfig, arg2 json.RawMessage) error { +func (m *MockAppModule) ValidateGenesis(arg0 codec.JSONCodec, arg1 client.TxEncodingConfig, arg2 json.RawMessage) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ValidateGenesis", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -471,7 +472,7 @@ func (mr *MockAppModuleMockRecorder) GetQueryCmd() *gomock.Call { } // InitGenesis mocks base method -func (m *MockAppModule) InitGenesis(arg0 types0.Context, arg1 codec.JSONMarshaler, arg2 json.RawMessage) []types1.ValidatorUpdate { +func (m *MockAppModule) InitGenesis(arg0 types0.Context, arg1 codec.JSONCodec, arg2 json.RawMessage) []types1.ValidatorUpdate { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InitGenesis", arg0, arg1, arg2) ret0, _ := ret[0].([]types1.ValidatorUpdate) @@ -485,7 +486,7 @@ func (mr *MockAppModuleMockRecorder) InitGenesis(arg0, arg1, arg2 interface{}) * } // ExportGenesis mocks base method -func (m *MockAppModule) ExportGenesis(arg0 types0.Context, arg1 codec.JSONMarshaler) json.RawMessage { +func (m *MockAppModule) ExportGenesis(arg0 types0.Context, arg1 codec.JSONCodec) json.RawMessage { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ExportGenesis", arg0, arg1) ret0, _ := ret[0].(json.RawMessage) diff --git a/testutil/network/network.go b/testutil/network/network.go index b17ce9cb4e72..edb3d0879dc7 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -70,7 +70,7 @@ func NewAppConstructor(encodingCfg params.EncodingConfig) AppConstructor { // Config defines the necessary configuration used to bootstrap and start an // in-process local testing network. type Config struct { - Codec codec.Marshaler + Codec codec.Codec LegacyAmino *codec.LegacyAmino // TODO: Remove! InterfaceRegistry codectypes.InterfaceRegistry diff --git a/types/bech32/legacybech32/pk.go b/types/bech32/legacybech32/pk.go index d87053190f40..114e05944f87 100644 --- a/types/bech32/legacybech32/pk.go +++ b/types/bech32/legacybech32/pk.go @@ -27,7 +27,7 @@ const ( // prefix based on the key type provided for a given PublicKey. func MarshalPubKey(pkt Bech32PubKeyType, pubkey cryptotypes.PubKey) (string, error) { bech32Prefix := getPrefix(pkt) - return bech32.ConvertAndEncode(bech32Prefix, legacy.Cdc.MustMarshalBinaryBare(pubkey)) + return bech32.ConvertAndEncode(bech32Prefix, legacy.Cdc.MustMarshal(pubkey)) } // Deprecated: MustMarshalPubKey calls MarshalPubKey and panics on error. diff --git a/types/coin_test.go b/types/coin_test.go index fad7f2f527cf..1f7af5473446 100644 --- a/types/coin_test.go +++ b/types/coin_test.go @@ -975,10 +975,10 @@ func (s *coinTestSuite) TestCoinAminoEncoding() { cdc := codec.NewLegacyAmino() c := sdk.NewInt64Coin(testDenom1, 5) - bz1, err := cdc.MarshalBinaryBare(c) + bz1, err := cdc.Marshal(c) s.Require().NoError(err) - bz2, err := cdc.MarshalBinaryLengthPrefixed(c) + bz2, err := cdc.MarshalLengthPrefixed(c) s.Require().NoError(err) bz3, err := c.Marshal() diff --git a/types/module/configurator.go b/types/module/configurator.go index f1e16f7e798a..3f19e9d27330 100644 --- a/types/module/configurator.go +++ b/types/module/configurator.go @@ -35,7 +35,7 @@ type Configurator interface { } type configurator struct { - cdc codec.Marshaler + cdc codec.Codec msgServer grpc.Server queryServer grpc.Server @@ -44,7 +44,7 @@ type configurator struct { } // NewConfigurator returns a new Configurator instance -func NewConfigurator(cdc codec.Marshaler, msgServer grpc.Server, queryServer grpc.Server) Configurator { +func NewConfigurator(cdc codec.Codec, msgServer grpc.Server, queryServer grpc.Server) Configurator { return configurator{ cdc: cdc, msgServer: msgServer, diff --git a/types/module/module.go b/types/module/module.go index 418795efb983..d773ceb71f57 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -49,8 +49,8 @@ type AppModuleBasic interface { RegisterLegacyAminoCodec(*codec.LegacyAmino) RegisterInterfaces(codectypes.InterfaceRegistry) - DefaultGenesis(codec.JSONMarshaler) json.RawMessage - ValidateGenesis(codec.JSONMarshaler, client.TxEncodingConfig, json.RawMessage) error + DefaultGenesis(codec.JSONCodec) json.RawMessage + ValidateGenesis(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage) error // client functionality RegisterRESTRoutes(client.Context, *mux.Router) @@ -86,7 +86,7 @@ func (bm BasicManager) RegisterInterfaces(registry codectypes.InterfaceRegistry) } // DefaultGenesis provides default genesis information for all modules -func (bm BasicManager) DefaultGenesis(cdc codec.JSONMarshaler) map[string]json.RawMessage { +func (bm BasicManager) DefaultGenesis(cdc codec.JSONCodec) map[string]json.RawMessage { genesis := make(map[string]json.RawMessage) for _, b := range bm { genesis[b.Name()] = b.DefaultGenesis(cdc) @@ -96,7 +96,7 @@ func (bm BasicManager) DefaultGenesis(cdc codec.JSONMarshaler) map[string]json.R } // ValidateGenesis performs genesis state validation for all modules -func (bm BasicManager) ValidateGenesis(cdc codec.JSONMarshaler, txEncCfg client.TxEncodingConfig, genesis map[string]json.RawMessage) error { +func (bm BasicManager) ValidateGenesis(cdc codec.JSONCodec, txEncCfg client.TxEncodingConfig, genesis map[string]json.RawMessage) error { for _, b := range bm { if err := b.ValidateGenesis(cdc, txEncCfg, genesis[b.Name()]); err != nil { return err @@ -148,8 +148,8 @@ func (bm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command) { type AppModuleGenesis interface { AppModuleBasic - InitGenesis(sdk.Context, codec.JSONMarshaler, json.RawMessage) []abci.ValidatorUpdate - ExportGenesis(sdk.Context, codec.JSONMarshaler) json.RawMessage + InitGenesis(sdk.Context, codec.JSONCodec, json.RawMessage) []abci.ValidatorUpdate + ExportGenesis(sdk.Context, codec.JSONCodec) json.RawMessage } // AppModule is the standard form for an application module @@ -296,7 +296,7 @@ func (m *Manager) RegisterServices(cfg Configurator) { } // InitGenesis performs init genesis functionality for modules -func (m *Manager) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, genesisData map[string]json.RawMessage) abci.ResponseInitChain { +func (m *Manager) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, genesisData map[string]json.RawMessage) abci.ResponseInitChain { var validatorUpdates []abci.ValidatorUpdate for _, moduleName := range m.OrderInitGenesis { if genesisData[moduleName] == nil { @@ -321,7 +321,7 @@ func (m *Manager) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, genesisD } // ExportGenesis performs export genesis functionality for modules -func (m *Manager) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) map[string]json.RawMessage { +func (m *Manager) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) map[string]json.RawMessage { genesisData := make(map[string]json.RawMessage) for _, moduleName := range m.OrderExportGenesis { genesisData[moduleName] = m.Modules[moduleName].ExportGenesis(ctx, cdc) diff --git a/types/module/simulation.go b/types/module/simulation.go index e01277f457a4..252cf268f837 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -99,7 +99,7 @@ func (sm *SimulationManager) WeightedOperations(simState SimulationState) []simu // GenesisState generator function type SimulationState struct { AppParams simulation.AppParams - Cdc codec.JSONMarshaler // application codec + Cdc codec.JSONCodec // application codec Rand *rand.Rand // random number GenState map[string]json.RawMessage // genesis state Accounts []simulation.Account // simulation accounts diff --git a/types/query/filtered_pagination_test.go b/types/query/filtered_pagination_test.go index 9830b6afffbe..96adf0cb6c8d 100644 --- a/types/query/filtered_pagination_test.go +++ b/types/query/filtered_pagination_test.go @@ -201,7 +201,7 @@ func ExampleFilteredPaginate() { var balResult sdk.Coins pageRes, err := query.FilteredPaginate(accountStore, pageReq, func(key []byte, value []byte, accumulate bool) (bool, error) { var bal sdk.Coin - err := appCodec.UnmarshalBinaryBare(value, &bal) + err := appCodec.Unmarshal(value, &bal) if err != nil { return false, err } @@ -226,14 +226,14 @@ func ExampleFilteredPaginate() { // balances: pagination: } -func execFilterPaginate(store sdk.KVStore, pageReq *query.PageRequest, appCodec codec.Marshaler) (balances sdk.Coins, res *query.PageResponse, err error) { +func execFilterPaginate(store sdk.KVStore, pageReq *query.PageRequest, appCodec codec.Codec) (balances sdk.Coins, res *query.PageResponse, err error) { balancesStore := prefix.NewStore(store, types.BalancesPrefix) accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1)) var balResult sdk.Coins res, err = query.FilteredPaginate(accountStore, pageReq, func(key []byte, value []byte, accumulate bool) (bool, error) { var bal sdk.Coin - err := appCodec.UnmarshalBinaryBare(value, &bal) + err := appCodec.Unmarshal(value, &bal) if err != nil { return false, err } diff --git a/types/query/pagination_test.go b/types/query/pagination_test.go index b78b63bf4a19..0ecc948a6274 100644 --- a/types/query/pagination_test.go +++ b/types/query/pagination_test.go @@ -320,7 +320,7 @@ func ExamplePaginate() { accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1)) pageRes, err := query.Paginate(accountStore, request.Pagination, func(key []byte, value []byte) error { var tempRes sdk.Coin - err := app.AppCodec().UnmarshalBinaryBare(value, &tempRes) + err := app.AppCodec().Unmarshal(value, &tempRes) if err != nil { return err } @@ -335,7 +335,7 @@ func ExamplePaginate() { // balances: pagination: } -func setupTest() (*simapp.SimApp, sdk.Context, codec.Marshaler) { +func setupTest() (*simapp.SimApp, sdk.Context, codec.Codec) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{Height: 1}) appCodec := app.AppCodec() diff --git a/types/simulation/types.go b/types/simulation/types.go index fabbcd47552b..e2a77c11baf3 100644 --- a/types/simulation/types.go +++ b/types/simulation/types.go @@ -144,7 +144,7 @@ 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(_ codec.JSONMarshaler, key string, ptr interface{}, r *rand.Rand, ps ParamSimulator) { +func (sp AppParams) GetOrGenerate(_ codec.JSONCodec, key string, ptr interface{}, r *rand.Rand, ps ParamSimulator) { if v, ok := sp[key]; ok && v != nil { err := json.Unmarshal(v, ptr) if err != nil { diff --git a/x/auth/ante/basic.go b/x/auth/ante/basic.go index 8ba07d85844a..8ec0d68ec495 100644 --- a/x/auth/ante/basic.go +++ b/x/auth/ante/basic.go @@ -126,7 +126,7 @@ func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, sim PubKey: pubkey, } - sigBz := legacy.Cdc.MustMarshalBinaryBare(simSig) + sigBz := legacy.Cdc.MustMarshal(simSig) cost := sdk.Gas(len(sigBz) + 6) // If the pubkey is a multi-signature pubkey, then we estimate for the maximum diff --git a/x/auth/keeper/keeper.go b/x/auth/keeper/keeper.go index 62a10e26ba52..3f68a008d513 100644 --- a/x/auth/keeper/keeper.go +++ b/x/auth/keeper/keeper.go @@ -48,7 +48,7 @@ type AccountKeeperI interface { // encoding/decoding library. type AccountKeeper struct { key sdk.StoreKey - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec paramSubspace paramtypes.Subspace permAddrs map[string]types.PermissionsForAddress @@ -65,7 +65,7 @@ var _ AccountKeeperI = &AccountKeeper{} // and don't have to fit into any predefined structure. This auth module does not use account permissions internally, though other modules // may use auth.Keeper to access the accounts permissions map. func NewAccountKeeper( - cdc codec.BinaryMarshaler, key sdk.StoreKey, paramstore paramtypes.Subspace, proto func() types.AccountI, + cdc codec.BinaryCodec, key sdk.StoreKey, paramstore paramtypes.Subspace, proto func() types.AccountI, maccPerms map[string][]string, ) AccountKeeper { @@ -126,7 +126,7 @@ func (ak AccountKeeper) GetNextAccountNumber(ctx sdk.Context) uint64 { } else { val := gogotypes.UInt64Value{} - err := ak.cdc.UnmarshalBinaryBare(bz, &val) + err := ak.cdc.Unmarshal(bz, &val) if err != nil { panic(err) } @@ -134,7 +134,7 @@ func (ak AccountKeeper) GetNextAccountNumber(ctx sdk.Context) uint64 { accNumber = val.GetValue() } - bz = ak.cdc.MustMarshalBinaryBare(&gogotypes.UInt64Value{Value: accNumber + 1}) + bz = ak.cdc.MustMarshal(&gogotypes.UInt64Value{Value: accNumber + 1}) store.Set(types.GlobalAccountNumberKey, bz) return accNumber @@ -231,5 +231,5 @@ func (ak AccountKeeper) UnmarshalAccount(bz []byte) (types.AccountI, error) { return acc, ak.cdc.UnmarshalInterface(bz, &acc) } -// GetCodec return codec.Marshaler object used by the keeper -func (ak AccountKeeper) GetCodec() codec.BinaryMarshaler { return ak.cdc } +// GetCodec return codec.Codec object used by the keeper +func (ak AccountKeeper) GetCodec() codec.BinaryCodec { return ak.cdc } diff --git a/x/auth/legacy/legacytx/amino_signing.go b/x/auth/legacy/legacytx/amino_signing.go index d09b1b30ac47..2f5b1d4a4218 100644 --- a/x/auth/legacy/legacytx/amino_signing.go +++ b/x/auth/legacy/legacytx/amino_signing.go @@ -64,7 +64,7 @@ func SignatureDataToAminoSignature(cdc *codec.LegacyAmino, data signingtypes.Sig return nil, err } - return cdc.MarshalBinaryBare(aminoMSig) + return cdc.Marshal(aminoMSig) default: return nil, fmt.Errorf("unexpected signature data %T", data) } diff --git a/x/auth/legacy/legacytx/stdsign.go b/x/auth/legacy/legacytx/stdsign.go index dbb71f1a9819..0f352db26e16 100644 --- a/x/auth/legacy/legacytx/stdsign.go +++ b/x/auth/legacy/legacytx/stdsign.go @@ -127,7 +127,7 @@ func pubKeySigToSigData(cdc *codec.LegacyAmino, key cryptotypes.PubKey, sig []by }, nil } var multiSig multisig.AminoMultisignature - err := cdc.UnmarshalBinaryBare(sig, &multiSig) + err := cdc.Unmarshal(sig, &multiSig) if err != nil { return nil, err } diff --git a/x/auth/legacy/legacytx/stdtx_builder.go b/x/auth/legacy/legacytx/stdtx_builder.go index ae0e97a3f34c..02ae449618ee 100644 --- a/x/auth/legacy/legacytx/stdtx_builder.go +++ b/x/auth/legacy/legacytx/stdtx_builder.go @@ -117,7 +117,7 @@ func (s StdTxConfig) TxEncoder() sdk.TxEncoder { } func (s StdTxConfig) TxDecoder() sdk.TxDecoder { - return mkDecoder(s.Cdc.UnmarshalBinaryBare) + return mkDecoder(s.Cdc.Unmarshal) } func (s StdTxConfig) TxJSONEncoder() sdk.TxEncoder { @@ -209,6 +209,6 @@ func mkDecoder(unmarshaler Unmarshaler) sdk.TxDecoder { // DefaultTxEncoder logic for standard transaction encoding func DefaultTxEncoder(cdc *codec.LegacyAmino) sdk.TxEncoder { return func(tx sdk.Tx) ([]byte, error) { - return cdc.MarshalBinaryBare(tx) + return cdc.Marshal(tx) } } diff --git a/x/auth/legacy/legacytx/stdtx_test.go b/x/auth/legacy/legacytx/stdtx_test.go index f1e496ad49d6..ec70281f6828 100644 --- a/x/auth/legacy/legacytx/stdtx_test.go +++ b/x/auth/legacy/legacytx/stdtx_test.go @@ -172,7 +172,7 @@ func TestDefaultTxEncoder(t *testing.T) { tx := NewStdTx(msgs, fee, sigs, "") - cdcBytes, err := cdc.MarshalBinaryBare(tx) + cdcBytes, err := cdc.Marshal(tx) require.NoError(t, err) encoderBytes, err := encoder(tx) @@ -251,7 +251,7 @@ func TestGetSignaturesV2(t *testing.T) { require.Nil(t, err) require.Equal(t, len(sigs), 1) - require.Equal(t, cdc.MustMarshalBinaryBare(sigs[0].PubKey), cdc.MustMarshalBinaryBare(sig.GetPubKey())) + require.Equal(t, cdc.MustMarshal(sigs[0].PubKey), cdc.MustMarshal(sig.GetPubKey())) require.Equal(t, sigs[0].Data, &signing.SingleSignatureData{ SignMode: signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, Signature: sig.GetSignature(), diff --git a/x/auth/module.go b/x/auth/module.go index f0c26cd97e59..ca2be016761e 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -46,12 +46,12 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { // DefaultGenesis returns default genesis state as raw bytes for the auth // module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the auth module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, config client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { var data types.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -96,7 +96,7 @@ type AppModule struct { } // NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Marshaler, accountKeeper keeper.AccountKeeper, randGenAccountsFn types.RandomGenesisAccountsFn) AppModule { +func NewAppModule(cdc codec.Codec, accountKeeper keeper.AccountKeeper, randGenAccountsFn types.RandomGenesisAccountsFn) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{}, accountKeeper: accountKeeper, @@ -138,7 +138,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { // InitGenesis performs genesis initialization for the auth module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.accountKeeper, genesisState) @@ -147,7 +147,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data j // ExportGenesis returns the exported genesis state as raw bytes for the auth // module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { gs := ExportGenesis(ctx, am.accountKeeper) return cdc.MustMarshalJSON(gs) } diff --git a/x/auth/simulation/decoder.go b/x/auth/simulation/decoder.go index 2fdf752037b3..61a551ba5208 100644 --- a/x/auth/simulation/decoder.go +++ b/x/auth/simulation/decoder.go @@ -13,7 +13,7 @@ import ( type AuthUnmarshaler interface { UnmarshalAccount([]byte) (types.AccountI, error) - GetCodec() codec.BinaryMarshaler + GetCodec() codec.BinaryCodec } // NewDecodeStore returns a decoder function closure that unmarshals the KVPair's @@ -36,8 +36,8 @@ func NewDecodeStore(ak AuthUnmarshaler) func(kvA, kvB kv.Pair) string { case bytes.Equal(kvA.Key, types.GlobalAccountNumberKey): var globalAccNumberA, globalAccNumberB gogotypes.UInt64Value - ak.GetCodec().MustUnmarshalBinaryBare(kvA.Value, &globalAccNumberA) - ak.GetCodec().MustUnmarshalBinaryBare(kvB.Value, &globalAccNumberB) + ak.GetCodec().MustUnmarshal(kvA.Value, &globalAccNumberA) + ak.GetCodec().MustUnmarshal(kvB.Value, &globalAccNumberB) return fmt.Sprintf("GlobalAccNumberA: %d\nGlobalAccNumberB: %d", globalAccNumberA, globalAccNumberB) diff --git a/x/auth/simulation/decoder_test.go b/x/auth/simulation/decoder_test.go index 0caeccee0784..9e21df6e5791 100644 --- a/x/auth/simulation/decoder_test.go +++ b/x/auth/simulation/decoder_test.go @@ -39,7 +39,7 @@ func TestDecodeStore(t *testing.T) { }, { Key: types.GlobalAccountNumberKey, - Value: cdc.MustMarshalBinaryBare(&globalAccNumber), + Value: cdc.MustMarshal(&globalAccNumber), }, { Key: []byte{0x99}, diff --git a/x/auth/tx/builder_test.go b/x/auth/tx/builder_test.go index 50e81a676d16..e45a67116378 100644 --- a/x/auth/tx/builder_test.go +++ b/x/auth/tx/builder_test.go @@ -44,7 +44,7 @@ func TestTxBuilder(t *testing.T) { PubKey: pubkey, Data: &signing.SingleSignatureData{ SignMode: signing.SignMode_SIGN_MODE_DIRECT, - Signature: legacy.Cdc.MustMarshalBinaryBare(pubkey), + Signature: legacy.Cdc.MustMarshal(pubkey), }, Sequence: accSeq, } @@ -57,7 +57,7 @@ func TestTxBuilder(t *testing.T) { SignerInfos: signerInfo, } - authInfoBytes := marshaler.MustMarshalBinaryBare(authInfo) + authInfoBytes := marshaler.MustMarshal(authInfo) require.NotEmpty(t, authInfoBytes) @@ -76,7 +76,7 @@ func TestTxBuilder(t *testing.T) { Memo: memo, Messages: anys, } - bodyBytes := marshaler.MustMarshalBinaryBare(txBody) + bodyBytes := marshaler.MustMarshal(txBody) require.NotEmpty(t, bodyBytes) require.Empty(t, txBuilder.getBodyBytes()) @@ -143,7 +143,7 @@ func TestBuilderValidateBasic(t *testing.T) { PubKey: pubKey1, Data: &signing.SingleSignatureData{ SignMode: signing.SignMode_SIGN_MODE_DIRECT, - Signature: legacy.Cdc.MustMarshalBinaryBare(pubKey1), + Signature: legacy.Cdc.MustMarshal(pubKey1), }, Sequence: 0, // Arbitrary account sequence } @@ -152,7 +152,7 @@ func TestBuilderValidateBasic(t *testing.T) { PubKey: pubKey2, Data: &signing.SingleSignatureData{ SignMode: signing.SignMode_SIGN_MODE_DIRECT, - Signature: legacy.Cdc.MustMarshalBinaryBare(pubKey2), + Signature: legacy.Cdc.MustMarshal(pubKey2), }, Sequence: 0, // Arbitrary account sequence } diff --git a/x/auth/tx/decoder.go b/x/auth/tx/decoder.go index 5f48ddd3aae6..a32a118604f9 100644 --- a/x/auth/tx/decoder.go +++ b/x/auth/tx/decoder.go @@ -19,7 +19,7 @@ func DefaultTxDecoder(cdc codec.ProtoCodecMarshaler) sdk.TxDecoder { return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error()) } - err = cdc.UnmarshalBinaryBare(txBytes, &raw) + err = cdc.Unmarshal(txBytes, &raw) if err != nil { return nil, err } @@ -32,7 +32,7 @@ func DefaultTxDecoder(cdc codec.ProtoCodecMarshaler) sdk.TxDecoder { return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error()) } - err = cdc.UnmarshalBinaryBare(raw.BodyBytes, &body) + err = cdc.Unmarshal(raw.BodyBytes, &body) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error()) } @@ -45,7 +45,7 @@ func DefaultTxDecoder(cdc codec.ProtoCodecMarshaler) sdk.TxDecoder { return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error()) } - err = cdc.UnmarshalBinaryBare(raw.AuthInfoBytes, &authInfo) + err = cdc.Unmarshal(raw.AuthInfoBytes, &authInfo) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error()) } diff --git a/x/auth/tx/direct_test.go b/x/auth/tx/direct_test.go index 731a5968da65..bef1e81ed974 100644 --- a/x/auth/tx/direct_test.go +++ b/x/auth/tx/direct_test.go @@ -83,7 +83,7 @@ func TestDirectModeHandler(t *testing.T) { SignerInfos: signerInfo, } - authInfoBytes := marshaler.MustMarshalBinaryBare(authInfo) + authInfoBytes := marshaler.MustMarshal(authInfo) anys := make([]*codectypes.Any, len(msgs)) @@ -99,7 +99,7 @@ func TestDirectModeHandler(t *testing.T) { Memo: memo, Messages: anys, } - bodyBytes := marshaler.MustMarshalBinaryBare(txBody) + bodyBytes := marshaler.MustMarshal(txBody) t.Log("verify GetSignBytes with generating sign bytes by marshaling SignDoc") signDoc := txtypes.SignDoc{ diff --git a/x/auth/types/genesis.go b/x/auth/types/genesis.go index 2b33aa3a5a82..380d85fc6b81 100644 --- a/x/auth/types/genesis.go +++ b/x/auth/types/genesis.go @@ -48,7 +48,7 @@ func DefaultGenesisState() *GenesisState { // GetGenesisStateFromAppState returns x/auth GenesisState given raw application // genesis state. -func GetGenesisStateFromAppState(cdc codec.Marshaler, appState map[string]json.RawMessage) GenesisState { +func GetGenesisStateFromAppState(cdc codec.Codec, appState map[string]json.RawMessage) GenesisState { var genesisState GenesisState if appState[ModuleName] != nil { @@ -110,7 +110,7 @@ type GenesisAccountIterator struct{} // appGenesis and invokes a callback on each genesis account. If any call // returns true, iteration stops. func (GenesisAccountIterator) IterateGenesisAccounts( - cdc codec.Marshaler, appGenesis map[string]json.RawMessage, cb func(AccountI) (stop bool), + cdc codec.Codec, appGenesis map[string]json.RawMessage, cb func(AccountI) (stop bool), ) { for _, genAcc := range GetGenesisStateFromAppState(cdc, appGenesis).Accounts { acc, ok := genAcc.GetCachedValue().(AccountI) diff --git a/x/auth/vesting/module.go b/x/auth/vesting/module.go index 259143469388..25820b11bf66 100644 --- a/x/auth/vesting/module.go +++ b/x/auth/vesting/module.go @@ -45,12 +45,12 @@ func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) } // DefaultGenesis returns the module's default genesis state as raw bytes. -func (AppModuleBasic) DefaultGenesis(_ codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { return []byte("{}") } // ValidateGenesis performs genesis state validation. Currently, this is a no-op. -func (AppModuleBasic) ValidateGenesis(_ codec.JSONMarshaler, _ client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { return nil } @@ -111,7 +111,7 @@ func (am AppModule) LegacyQuerierHandler(_ *codec.LegacyAmino) sdk.Querier { } // InitGenesis performs a no-op. -func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONMarshaler, _ json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } @@ -124,7 +124,7 @@ func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Valid } // ExportGenesis is always empty, as InitGenesis does nothing either. -func (am AppModule) ExportGenesis(_ sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(_ sdk.Context, cdc codec.JSONCodec) json.RawMessage { return am.DefaultGenesis(cdc) } diff --git a/x/authz/keeper/grpc_query.go b/x/authz/keeper/grpc_query.go index 7b1fcb1995dd..7554ecc489a2 100644 --- a/x/authz/keeper/grpc_query.go +++ b/x/authz/keeper/grpc_query.go @@ -74,8 +74,8 @@ func (k Keeper) Authorizations(c context.Context, req *types.QueryAuthorizations } // unmarshal an authorization from a store value -func unmarshalAuthorization(cdc codec.BinaryMarshaler, value []byte) (v types.AuthorizationGrant, err error) { - err = cdc.UnmarshalBinaryBare(value, &v) +func unmarshalAuthorization(cdc codec.BinaryCodec, value []byte) (v types.AuthorizationGrant, err error) { + err = cdc.Unmarshal(value, &v) return v, err } diff --git a/x/authz/keeper/keeper.go b/x/authz/keeper/keeper.go index dcbee170cb1e..42acd0d77405 100644 --- a/x/authz/keeper/keeper.go +++ b/x/authz/keeper/keeper.go @@ -19,12 +19,12 @@ import ( type Keeper struct { storeKey sdk.StoreKey - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec router *baseapp.MsgServiceRouter } // NewKeeper constructs a message authorization Keeper -func NewKeeper(storeKey sdk.StoreKey, cdc codec.BinaryMarshaler, router *baseapp.MsgServiceRouter) Keeper { +func NewKeeper(storeKey sdk.StoreKey, cdc codec.BinaryCodec, router *baseapp.MsgServiceRouter) Keeper { return Keeper{ storeKey: storeKey, cdc: cdc, @@ -44,7 +44,7 @@ func (k Keeper) getAuthorizationGrant(ctx sdk.Context, grantStoreKey []byte) (gr if bz == nil { return grant, false } - k.cdc.MustUnmarshalBinaryBare(bz, &grant) + k.cdc.MustUnmarshal(bz, &grant) return grant, true } @@ -67,7 +67,7 @@ func (k Keeper) update(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccA grant.Authorization = any store := ctx.KVStore(k.storeKey) - store.Set(grantStoreKey, k.cdc.MustMarshalBinaryBare(&grant)) + store.Set(grantStoreKey, k.cdc.MustMarshal(&grant)) return nil } @@ -126,7 +126,7 @@ func (k Keeper) Grant(ctx sdk.Context, grantee, granter sdk.AccAddress, authoriz return err } - bz := k.cdc.MustMarshalBinaryBare(&grant) + bz := k.cdc.MustMarshal(&grant) grantStoreKey := types.GetAuthorizationStoreKey(grantee, granter, authorization.MethodName()) store.Set(grantStoreKey, bz) @@ -172,7 +172,7 @@ func (k Keeper) GetAuthorizations(ctx sdk.Context, grantee sdk.AccAddress, grant defer iter.Close() var authorization types.AuthorizationGrant for ; iter.Valid(); iter.Next() { - k.cdc.MustUnmarshalBinaryBare(iter.Value(), &authorization) + k.cdc.MustUnmarshal(iter.Value(), &authorization) authorizations = append(authorizations, authorization.GetAuthorizationGrant()) } return authorizations @@ -203,7 +203,7 @@ func (k Keeper) IterateGrants(ctx sdk.Context, for ; iter.Valid(); iter.Next() { var grant types.AuthorizationGrant granterAddr, granteeAddr := types.ExtractAddressesFromGrantKey(iter.Key()) - k.cdc.MustUnmarshalBinaryBare(iter.Value(), &grant) + k.cdc.MustUnmarshal(iter.Value(), &grant) if handler(granterAddr, granteeAddr, grant) { break } diff --git a/x/authz/module.go b/x/authz/module.go index b39c02487fe0..b793a85946ed 100644 --- a/x/authz/module.go +++ b/x/authz/module.go @@ -33,7 +33,7 @@ var ( // AppModuleBasic defines the basic application module used by the authz module. type AppModuleBasic struct { - cdc codec.Marshaler + cdc codec.Codec } // Name returns the authz module's name. @@ -58,12 +58,12 @@ func (AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { // DefaultGenesis returns default genesis state as raw bytes for the authz // module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the authz module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { var data types.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { return sdkerrors.Wrapf(err, "failed to unmarshal %s genesis state", types.ModuleName) @@ -101,7 +101,7 @@ type AppModule struct { } // NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Marshaler, keeper keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper, registry cdctypes.InterfaceRegistry) AppModule { +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper, registry cdctypes.InterfaceRegistry) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc}, keeper: keeper, @@ -138,7 +138,7 @@ func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sd // InitGenesis performs genesis initialization for the authz module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.keeper, &genesisState) @@ -147,7 +147,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data j // ExportGenesis returns the exported genesis state as raw bytes for the authz // module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return cdc.MustMarshalJSON(gs) } diff --git a/x/authz/simulation/decoder.go b/x/authz/simulation/decoder.go index c87f7a70c13a..88b9631ab28d 100644 --- a/x/authz/simulation/decoder.go +++ b/x/authz/simulation/decoder.go @@ -11,13 +11,13 @@ import ( // NewDecodeStore returns a decoder function closure that umarshals the KVPair's // Value to the corresponding authz type. -func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string { +func NewDecodeStore(cdc codec.Codec) func(kvA, kvB kv.Pair) string { return func(kvA, kvB kv.Pair) string { switch { case bytes.Equal(kvA.Key[:1], types.GrantKey): var grantA, grantB types.AuthorizationGrant - cdc.MustUnmarshalBinaryBare(kvA.Value, &grantA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &grantB) + cdc.MustUnmarshal(kvA.Value, &grantA) + cdc.MustUnmarshal(kvB.Value, &grantB) return fmt.Sprintf("%v\n%v", grantA, grantB) default: panic(fmt.Sprintf("invalid authz key %X", kvA.Key)) diff --git a/x/authz/simulation/decoder_test.go b/x/authz/simulation/decoder_test.go index 8b5e71cfbdd7..caa6a0369aa8 100644 --- a/x/authz/simulation/decoder_test.go +++ b/x/authz/simulation/decoder_test.go @@ -20,7 +20,7 @@ func TestDecodeStore(t *testing.T) { dec := simulation.NewDecodeStore(cdc) grant, _ := types.NewAuthorizationGrant(banktypes.NewSendAuthorization(sdk.NewCoins(sdk.NewInt64Coin("foo", 123))), time.Now().UTC()) - grantBz, err := cdc.MarshalBinaryBare(&grant) + grantBz, err := cdc.Marshal(&grant) require.NoError(t, err) kvPairs := kv.Pairs{ Pairs: []kv.Pair{ diff --git a/x/authz/simulation/operations.go b/x/authz/simulation/operations.go index 8fef468b06db..b01296d8bc11 100644 --- a/x/authz/simulation/operations.go +++ b/x/authz/simulation/operations.go @@ -35,7 +35,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONMarshaler, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, appCdc cdctypes.AnyUnpacker, protoCdc *codec.ProtoCodec) simulation.WeightedOperations { + appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, appCdc cdctypes.AnyUnpacker, protoCdc *codec.ProtoCodec) simulation.WeightedOperations { var ( weightMsgGrantAuthorization int diff --git a/x/bank/keeper/grpc_query.go b/x/bank/keeper/grpc_query.go index 356cc4596b04..02655aa2f595 100644 --- a/x/bank/keeper/grpc_query.go +++ b/x/bank/keeper/grpc_query.go @@ -61,7 +61,7 @@ func (k BaseKeeper) AllBalances(ctx context.Context, req *types.QueryAllBalances pageRes, err := query.Paginate(accountStore, req.Pagination, func(_, value []byte) error { var result sdk.Coin - err := k.cdc.UnmarshalBinaryBare(value, &result) + err := k.cdc.Unmarshal(value, &result) if err != nil { return err } @@ -127,7 +127,7 @@ func (k BaseKeeper) DenomsMetadata(c context.Context, req *types.QueryDenomsMeta metadatas := []types.Metadata{} pageRes, err := query.Paginate(store, req.Pagination, func(_, value []byte) error { var metadata types.Metadata - k.cdc.MustUnmarshalBinaryBare(value, &metadata) + k.cdc.MustUnmarshal(value, &metadata) metadatas = append(metadatas, metadata) return nil diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index a5b05b044ab8..c32aafb28793 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -50,7 +50,7 @@ type BaseKeeper struct { BaseSendKeeper ak types.AccountKeeper - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec storeKey sdk.StoreKey paramSpace paramtypes.Subspace } @@ -85,7 +85,7 @@ func (k BaseKeeper) GetPaginatedTotalSupply(ctx sdk.Context, pagination *query.P // to receive funds through direct and explicit actions, for example, by using a MsgSend or // by using a SendCoinsFromModuleToAccount execution. func NewBaseKeeper( - cdc codec.BinaryMarshaler, + cdc codec.BinaryCodec, storeKey sdk.StoreKey, ak types.AccountKeeper, paramSpace paramtypes.Subspace, @@ -222,7 +222,7 @@ func (k BaseKeeper) GetDenomMetaData(ctx sdk.Context, denom string) (types.Metad } var metadata types.Metadata - k.cdc.MustUnmarshalBinaryBare(bz, &metadata) + k.cdc.MustUnmarshal(bz, &metadata) return metadata, true } @@ -250,7 +250,7 @@ func (k BaseKeeper) IterateAllDenomMetaData(ctx sdk.Context, cb func(types.Metad for ; iterator.Valid(); iterator.Next() { var metadata types.Metadata - k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &metadata) + k.cdc.MustUnmarshal(iterator.Value(), &metadata) if cb(metadata) { break @@ -263,7 +263,7 @@ func (k BaseKeeper) SetDenomMetaData(ctx sdk.Context, denomMetaData types.Metada store := ctx.KVStore(k.storeKey) denomMetaDataStore := prefix.NewStore(store, types.DenomMetadataKey(denomMetaData.Base)) - m := k.cdc.MustMarshalBinaryBare(&denomMetaData) + m := k.cdc.MustMarshal(&denomMetaData) denomMetaDataStore.Set([]byte(denomMetaData.Base), m) } diff --git a/x/bank/keeper/send.go b/x/bank/keeper/send.go index 0093a3b805a5..e701ff4dcab6 100644 --- a/x/bank/keeper/send.go +++ b/x/bank/keeper/send.go @@ -33,7 +33,7 @@ var _ SendKeeper = (*BaseSendKeeper)(nil) type BaseSendKeeper struct { BaseViewKeeper - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec ak types.AccountKeeper storeKey sdk.StoreKey paramSpace paramtypes.Subspace @@ -43,7 +43,7 @@ type BaseSendKeeper struct { } func NewBaseSendKeeper( - cdc codec.BinaryMarshaler, storeKey sdk.StoreKey, ak types.AccountKeeper, paramSpace paramtypes.Subspace, blockedAddrs map[string]bool, + cdc codec.BinaryCodec, storeKey sdk.StoreKey, ak types.AccountKeeper, paramSpace paramtypes.Subspace, blockedAddrs map[string]bool, ) BaseSendKeeper { return BaseSendKeeper{ @@ -266,7 +266,7 @@ func (k BaseSendKeeper) setBalance(ctx sdk.Context, addr sdk.AccAddress, balance accountStore := k.getAccountStore(ctx, addr) - bz := k.cdc.MustMarshalBinaryBare(&balance) + bz := k.cdc.MustMarshal(&balance) accountStore.Set([]byte(balance.Denom), bz) return nil diff --git a/x/bank/keeper/view.go b/x/bank/keeper/view.go index d2a560cb7834..fe46ec9b6ec1 100644 --- a/x/bank/keeper/view.go +++ b/x/bank/keeper/view.go @@ -33,13 +33,13 @@ type ViewKeeper interface { // BaseViewKeeper implements a read only keeper implementation of ViewKeeper. type BaseViewKeeper struct { - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec storeKey sdk.StoreKey ak types.AccountKeeper } // NewBaseViewKeeper returns a new BaseViewKeeper. -func NewBaseViewKeeper(cdc codec.BinaryMarshaler, storeKey sdk.StoreKey, ak types.AccountKeeper) BaseViewKeeper { +func NewBaseViewKeeper(cdc codec.BinaryCodec, storeKey sdk.StoreKey, ak types.AccountKeeper) BaseViewKeeper { return BaseViewKeeper{ cdc: cdc, storeKey: storeKey, @@ -105,7 +105,7 @@ func (k BaseViewKeeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom s } var balance sdk.Coin - k.cdc.MustUnmarshalBinaryBare(bz, &balance) + k.cdc.MustUnmarshal(bz, &balance) return balance } @@ -121,7 +121,7 @@ func (k BaseViewKeeper) IterateAccountBalances(ctx sdk.Context, addr sdk.AccAddr for ; iterator.Valid(); iterator.Next() { var balance sdk.Coin - k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &balance) + k.cdc.MustUnmarshal(iterator.Value(), &balance) if cb(balance) { break @@ -149,7 +149,7 @@ func (k BaseViewKeeper) IterateAllBalances(ctx sdk.Context, cb func(sdk.AccAddre } var balance sdk.Coin - k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &balance) + k.cdc.MustUnmarshal(iterator.Value(), &balance) if cb(address, balance) { break diff --git a/x/bank/legacy/v043/store.go b/x/bank/legacy/v043/store.go index dfd021abd9ea..f22901b9cc8f 100644 --- a/x/bank/legacy/v043/store.go +++ b/x/bank/legacy/v043/store.go @@ -12,7 +12,7 @@ import ( // migrateSupply migrates the supply to be stored by denom key instead in a // single blob. // ref: https://github.com/cosmos/cosmos-sdk/issues/7092 -func migrateSupply(store sdk.KVStore, cdc codec.BinaryMarshaler) error { +func migrateSupply(store sdk.KVStore, cdc codec.BinaryCodec) error { // Old supply was stored as a single blob under the SupplyKey. var oldSupplyI v040bank.SupplyI err := cdc.UnmarshalInterface(store.Get(v040bank.SupplyKey), &oldSupplyI) @@ -75,7 +75,7 @@ func migrateBalanceKeys(store sdk.KVStore) { // - Change addresses to be length-prefixed. // - Change balances prefix to 1 byte // - Change supply to be indexed by denom -func MigrateStore(ctx sdk.Context, storeKey sdk.StoreKey, cdc codec.BinaryMarshaler) error { +func MigrateStore(ctx sdk.Context, storeKey sdk.StoreKey, cdc codec.BinaryCodec) error { store := ctx.KVStore(storeKey) migrateBalanceKeys(store) diff --git a/x/bank/module.go b/x/bank/module.go index 26effe98a026..ea97a9efa3e7 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -35,7 +35,7 @@ var ( // AppModuleBasic defines the basic application module used by the bank module. type AppModuleBasic struct { - cdc codec.Marshaler + cdc codec.Codec } // Name returns the bank module's name. @@ -48,12 +48,12 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { // DefaultGenesis returns default genesis state as raw bytes for the bank // module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the bank module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, _ client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { var data types.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -108,7 +108,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { } // NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Marshaler, keeper keeper.Keeper, accountKeeper types.AccountKeeper) AppModule { +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc}, keeper: keeper, @@ -139,7 +139,7 @@ func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sd // InitGenesis performs genesis initialization for the bank module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { start := time.Now() var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) @@ -151,7 +151,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data j // ExportGenesis returns the exported genesis state as raw bytes for the bank // module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { gs := am.keeper.ExportGenesis(ctx) return cdc.MustMarshalJSON(gs) } diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 78feff814ccd..16e1b775006b 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -23,7 +23,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONMarshaler, ak types.AccountKeeper, bk keeper.Keeper, + appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk keeper.Keeper, ) simulation.WeightedOperations { var weightMsgSend, weightMsgMultiSend int diff --git a/x/bank/types/balance.go b/x/bank/types/balance.go index 7c017ee90051..dc67f7e5bd09 100644 --- a/x/bank/types/balance.go +++ b/x/bank/types/balance.go @@ -113,7 +113,7 @@ type GenesisBalancesIterator struct{} // appGenesis and invokes a callback on each genesis account. If any call // returns true, iteration stops. func (GenesisBalancesIterator) IterateGenesisBalances( - cdc codec.JSONMarshaler, appState map[string]json.RawMessage, cb func(exported.GenesisBalance) (stop bool), + cdc codec.JSONCodec, appState map[string]json.RawMessage, cb func(exported.GenesisBalance) (stop bool), ) { for _, balance := range GetGenesisStateFromAppState(cdc, appState).Balances { if cb(balance) { diff --git a/x/bank/types/genesis.go b/x/bank/types/genesis.go index d40093126f2b..ffeb23e2014a 100644 --- a/x/bank/types/genesis.go +++ b/x/bank/types/genesis.go @@ -78,7 +78,7 @@ func DefaultGenesisState() *GenesisState { // GetGenesisStateFromAppState returns x/bank GenesisState given raw application // genesis state. -func GetGenesisStateFromAppState(cdc codec.JSONMarshaler, appState map[string]json.RawMessage) *GenesisState { +func GetGenesisStateFromAppState(cdc codec.JSONCodec, appState map[string]json.RawMessage) *GenesisState { var genesisState GenesisState if appState[ModuleName] != nil { diff --git a/x/capability/keeper/keeper.go b/x/capability/keeper/keeper.go index 61de0338991c..2398ec2aa215 100644 --- a/x/capability/keeper/keeper.go +++ b/x/capability/keeper/keeper.go @@ -27,7 +27,7 @@ type ( // The keeper allows the ability to create scoped sub-keepers which are tied to // a single specific module. Keeper struct { - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec storeKey sdk.StoreKey memKey sdk.StoreKey capMap map[uint64]*types.Capability @@ -42,7 +42,7 @@ type ( // by name, in addition to creating new capabilities & authenticating capabilities // passed by other modules. ScopedKeeper struct { - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec storeKey sdk.StoreKey memKey sdk.StoreKey capMap map[uint64]*types.Capability @@ -52,7 +52,7 @@ type ( // NewKeeper constructs a new CapabilityKeeper instance and initializes maps // for capability map and scopedModules map. -func NewKeeper(cdc codec.BinaryMarshaler, storeKey, memKey sdk.StoreKey) *Keeper { +func NewKeeper(cdc codec.BinaryCodec, storeKey, memKey sdk.StoreKey) *Keeper { return &Keeper{ cdc: cdc, storeKey: storeKey, @@ -116,7 +116,7 @@ func (k *Keeper) InitializeAndSeal(ctx sdk.Context) { var capOwners types.CapabilityOwners - k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &capOwners) + k.cdc.MustUnmarshal(iterator.Value(), &capOwners) k.InitializeCapability(ctx, index, capOwners) } @@ -153,7 +153,7 @@ func (k Keeper) SetOwners(ctx sdk.Context, index uint64, owners types.Capability indexKey := types.IndexToKey(index) // set owners in persistent store - prefixStore.Set(indexKey, k.cdc.MustMarshalBinaryBare(&owners)) + prefixStore.Set(indexKey, k.cdc.MustMarshal(&owners)) } // GetOwners returns the capability owners with a given index. @@ -167,7 +167,7 @@ func (k Keeper) GetOwners(ctx sdk.Context, index uint64) (types.CapabilityOwners return types.CapabilityOwners{}, false } var owners types.CapabilityOwners - k.cdc.MustUnmarshalBinaryBare(ownerBytes, &owners) + k.cdc.MustUnmarshal(ownerBytes, &owners) return owners, true } @@ -332,7 +332,7 @@ func (sk ScopedKeeper) ReleaseCapability(ctx sdk.Context, cap *types.Capability) delete(sk.capMap, cap.GetIndex()) } else { // update capability owner set - prefixStore.Set(indexKey, sk.cdc.MustMarshalBinaryBare(capOwners)) + prefixStore.Set(indexKey, sk.cdc.MustMarshal(capOwners)) } return nil @@ -401,7 +401,7 @@ func (sk ScopedKeeper) GetOwners(ctx sdk.Context, name string) (*types.Capabilit return nil, false } - sk.cdc.MustUnmarshalBinaryBare(bz, &capOwners) + sk.cdc.MustUnmarshal(bz, &capOwners) return &capOwners, true } @@ -443,7 +443,7 @@ func (sk ScopedKeeper) addOwner(ctx sdk.Context, cap *types.Capability, name str } // update capability owner set - prefixStore.Set(indexKey, sk.cdc.MustMarshalBinaryBare(capOwners)) + prefixStore.Set(indexKey, sk.cdc.MustMarshal(capOwners)) return nil } @@ -459,7 +459,7 @@ func (sk ScopedKeeper) getOwners(ctx sdk.Context, cap *types.Capability) *types. } var capOwners types.CapabilityOwners - sk.cdc.MustUnmarshalBinaryBare(bz, &capOwners) + sk.cdc.MustUnmarshal(bz, &capOwners) return &capOwners } diff --git a/x/capability/module.go b/x/capability/module.go index 06bee1e2d029..d43d37761aa0 100644 --- a/x/capability/module.go +++ b/x/capability/module.go @@ -34,10 +34,10 @@ var ( // AppModuleBasic implements the AppModuleBasic interface for the capability module. type AppModuleBasic struct { - cdc codec.Marshaler + cdc codec.Codec } -func NewAppModuleBasic(cdc codec.Marshaler) AppModuleBasic { +func NewAppModuleBasic(cdc codec.Codec) AppModuleBasic { return AppModuleBasic{cdc: cdc} } @@ -53,12 +53,12 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} func (a AppModuleBasic) RegisterInterfaces(_ cdctypes.InterfaceRegistry) {} // DefaultGenesis returns the capability module's default genesis state. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesis()) } // ValidateGenesis performs genesis state validation for the capability module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, config client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { var genState types.GenesisState if err := cdc.UnmarshalJSON(bz, &genState); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -90,7 +90,7 @@ type AppModule struct { keeper keeper.Keeper } -func NewAppModule(cdc codec.Marshaler, keeper keeper.Keeper) AppModule { +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper) AppModule { return AppModule{ AppModuleBasic: NewAppModuleBasic(cdc), keeper: keeper, @@ -120,7 +120,7 @@ func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // InitGenesis performs the capability module's genesis initialization It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, gs json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { var genState types.GenesisState // Initialize global index to index in genesis state cdc.MustUnmarshalJSON(gs, &genState) @@ -131,7 +131,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, gs jso } // ExportGenesis returns the capability module's exported genesis state as raw JSON bytes. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { genState := ExportGenesis(ctx, am.keeper) return cdc.MustMarshalJSON(genState) } diff --git a/x/capability/simulation/decoder.go b/x/capability/simulation/decoder.go index 9cd0dcc6da4e..96e2c41c0a2e 100644 --- a/x/capability/simulation/decoder.go +++ b/x/capability/simulation/decoder.go @@ -12,7 +12,7 @@ import ( // NewDecodeStore returns a decoder function closure that unmarshals the KVPair's // Value to the corresponding capability type. -func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string { +func NewDecodeStore(cdc codec.Codec) func(kvA, kvB kv.Pair) string { return func(kvA, kvB kv.Pair) string { switch { case bytes.Equal(kvA.Key, types.KeyIndex): @@ -22,8 +22,8 @@ func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string { case bytes.HasPrefix(kvA.Key, types.KeyPrefixIndexCapability): var capOwnersA, capOwnersB types.CapabilityOwners - cdc.MustUnmarshalBinaryBare(kvA.Value, &capOwnersA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &capOwnersB) + cdc.MustUnmarshal(kvA.Value, &capOwnersA) + cdc.MustUnmarshal(kvB.Value, &capOwnersB) return fmt.Sprintf("CapabilityOwners A: %v\nCapabilityOwners B: %v\n", capOwnersA, capOwnersB) default: diff --git a/x/capability/simulation/decoder_test.go b/x/capability/simulation/decoder_test.go index 51232b810ab7..a18bcd56115d 100644 --- a/x/capability/simulation/decoder_test.go +++ b/x/capability/simulation/decoder_test.go @@ -29,7 +29,7 @@ func TestDecodeStore(t *testing.T) { }, { Key: types.KeyPrefixIndexCapability, - Value: cdc.MustMarshalBinaryBare(&capOwners), + Value: cdc.MustMarshal(&capOwners), }, { Key: []byte{0x99}, diff --git a/x/crisis/module.go b/x/crisis/module.go index ecea78f111c3..0f75edfcf886 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -46,12 +46,12 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { // DefaultGenesis returns default genesis state as raw bytes for the crisis // module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the crisis module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, config client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { var data types.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -136,7 +136,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { // InitGenesis performs genesis initialization for the crisis module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { start := time.Now() var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) @@ -151,7 +151,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data j // ExportGenesis returns the exported genesis state as raw bytes for the crisis // module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { gs := am.keeper.ExportGenesis(ctx) return cdc.MustMarshalJSON(gs) } diff --git a/x/distribution/client/cli/utils.go b/x/distribution/client/cli/utils.go index fe531e49b9cb..45f941f08979 100644 --- a/x/distribution/client/cli/utils.go +++ b/x/distribution/client/cli/utils.go @@ -8,7 +8,7 @@ import ( ) // ParseCommunityPoolSpendProposalWithDeposit reads and parses a CommunityPoolSpendProposalWithDeposit from a file. -func ParseCommunityPoolSpendProposalWithDeposit(cdc codec.JSONMarshaler, proposalFile string) (types.CommunityPoolSpendProposalWithDeposit, error) { +func ParseCommunityPoolSpendProposalWithDeposit(cdc codec.JSONCodec, proposalFile string) (types.CommunityPoolSpendProposalWithDeposit, error) { proposal := types.CommunityPoolSpendProposalWithDeposit{} contents, err := ioutil.ReadFile(proposalFile) diff --git a/x/distribution/keeper/grpc_query.go b/x/distribution/keeper/grpc_query.go index 7991634fc401..5cf71bbb102d 100644 --- a/x/distribution/keeper/grpc_query.go +++ b/x/distribution/keeper/grpc_query.go @@ -92,7 +92,7 @@ func (k Keeper) ValidatorSlashes(c context.Context, req *types.QueryValidatorSla pageRes, err := query.FilteredPaginate(slashesStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { var result types.ValidatorSlashEvent - err := k.cdc.UnmarshalBinaryBare(value, &result) + err := k.cdc.Unmarshal(value, &result) if err != nil { return false, err diff --git a/x/distribution/keeper/keeper.go b/x/distribution/keeper/keeper.go index 0d5c32f78eb0..b139c35f4a50 100644 --- a/x/distribution/keeper/keeper.go +++ b/x/distribution/keeper/keeper.go @@ -15,7 +15,7 @@ import ( // Keeper of the distribution store type Keeper struct { storeKey sdk.StoreKey - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec paramSpace paramtypes.Subspace authKeeper types.AccountKeeper bankKeeper types.BankKeeper @@ -28,7 +28,7 @@ type Keeper struct { // NewKeeper creates a new distribution Keeper instance func NewKeeper( - cdc codec.BinaryMarshaler, key sdk.StoreKey, paramSpace paramtypes.Subspace, + cdc codec.BinaryCodec, key sdk.StoreKey, paramSpace paramtypes.Subspace, ak types.AccountKeeper, bk types.BankKeeper, sk types.StakingKeeper, feeCollectorName string, blockedAddrs map[string]bool, ) Keeper { diff --git a/x/distribution/keeper/store.go b/x/distribution/keeper/store.go index 302e2ee81e92..0203ee13f672 100644 --- a/x/distribution/keeper/store.go +++ b/x/distribution/keeper/store.go @@ -50,14 +50,14 @@ func (k Keeper) GetFeePool(ctx sdk.Context) (feePool types.FeePool) { if b == nil { panic("Stored fee pool should not have been nil") } - k.cdc.MustUnmarshalBinaryBare(b, &feePool) + k.cdc.MustUnmarshal(b, &feePool) return } // set the global fee pool distribution info func (k Keeper) SetFeePool(ctx sdk.Context, feePool types.FeePool) { store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshalBinaryBare(&feePool) + b := k.cdc.MustMarshal(&feePool) store.Set(types.FeePoolKey, b) } @@ -71,14 +71,14 @@ func (k Keeper) GetPreviousProposerConsAddr(ctx sdk.Context) sdk.ConsAddress { } addrValue := gogotypes.BytesValue{} - k.cdc.MustUnmarshalBinaryBare(bz, &addrValue) + k.cdc.MustUnmarshal(bz, &addrValue) return addrValue.GetValue() } // set the proposer public key for this block func (k Keeper) SetPreviousProposerConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshalBinaryBare(&gogotypes.BytesValue{Value: consAddr}) + bz := k.cdc.MustMarshal(&gogotypes.BytesValue{Value: consAddr}) store.Set(types.ProposerKey, bz) } @@ -86,14 +86,14 @@ func (k Keeper) SetPreviousProposerConsAddr(ctx sdk.Context, consAddr sdk.ConsAd func (k Keeper) GetDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress) (period types.DelegatorStartingInfo) { store := ctx.KVStore(k.storeKey) b := store.Get(types.GetDelegatorStartingInfoKey(val, del)) - k.cdc.MustUnmarshalBinaryBare(b, &period) + k.cdc.MustUnmarshal(b, &period) return } // set the starting info associated with a delegator func (k Keeper) SetDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress, period types.DelegatorStartingInfo) { store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshalBinaryBare(&period) + b := k.cdc.MustMarshal(&period) store.Set(types.GetDelegatorStartingInfoKey(val, del), b) } @@ -116,7 +116,7 @@ func (k Keeper) IterateDelegatorStartingInfos(ctx sdk.Context, handler func(val defer iter.Close() for ; iter.Valid(); iter.Next() { var info types.DelegatorStartingInfo - k.cdc.MustUnmarshalBinaryBare(iter.Value(), &info) + k.cdc.MustUnmarshal(iter.Value(), &info) val, del := types.GetDelegatorStartingInfoAddresses(iter.Key()) if handler(val, del, info) { break @@ -128,14 +128,14 @@ func (k Keeper) IterateDelegatorStartingInfos(ctx sdk.Context, handler func(val func (k Keeper) GetValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAddress, period uint64) (rewards types.ValidatorHistoricalRewards) { store := ctx.KVStore(k.storeKey) b := store.Get(types.GetValidatorHistoricalRewardsKey(val, period)) - k.cdc.MustUnmarshalBinaryBare(b, &rewards) + k.cdc.MustUnmarshal(b, &rewards) return } // set historical rewards for a particular period func (k Keeper) SetValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAddress, period uint64, rewards types.ValidatorHistoricalRewards) { store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshalBinaryBare(&rewards) + b := k.cdc.MustMarshal(&rewards) store.Set(types.GetValidatorHistoricalRewardsKey(val, period), b) } @@ -146,7 +146,7 @@ func (k Keeper) IterateValidatorHistoricalRewards(ctx sdk.Context, handler func( defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorHistoricalRewards - k.cdc.MustUnmarshalBinaryBare(iter.Value(), &rewards) + k.cdc.MustUnmarshal(iter.Value(), &rewards) addr, period := types.GetValidatorHistoricalRewardsAddressPeriod(iter.Key()) if handler(addr, period, rewards) { break @@ -187,7 +187,7 @@ func (k Keeper) GetValidatorHistoricalReferenceCount(ctx sdk.Context) (count uin defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorHistoricalRewards - k.cdc.MustUnmarshalBinaryBare(iter.Value(), &rewards) + k.cdc.MustUnmarshal(iter.Value(), &rewards) count += uint64(rewards.ReferenceCount) } return @@ -197,14 +197,14 @@ func (k Keeper) GetValidatorHistoricalReferenceCount(ctx sdk.Context) (count uin func (k Keeper) GetValidatorCurrentRewards(ctx sdk.Context, val sdk.ValAddress) (rewards types.ValidatorCurrentRewards) { store := ctx.KVStore(k.storeKey) b := store.Get(types.GetValidatorCurrentRewardsKey(val)) - k.cdc.MustUnmarshalBinaryBare(b, &rewards) + k.cdc.MustUnmarshal(b, &rewards) return } // set current rewards for a validator func (k Keeper) SetValidatorCurrentRewards(ctx sdk.Context, val sdk.ValAddress, rewards types.ValidatorCurrentRewards) { store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshalBinaryBare(&rewards) + b := k.cdc.MustMarshal(&rewards) store.Set(types.GetValidatorCurrentRewardsKey(val), b) } @@ -221,7 +221,7 @@ func (k Keeper) IterateValidatorCurrentRewards(ctx sdk.Context, handler func(val defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorCurrentRewards - k.cdc.MustUnmarshalBinaryBare(iter.Value(), &rewards) + k.cdc.MustUnmarshal(iter.Value(), &rewards) addr := types.GetValidatorCurrentRewardsAddress(iter.Key()) if handler(addr, rewards) { break @@ -236,7 +236,7 @@ func (k Keeper) GetValidatorAccumulatedCommission(ctx sdk.Context, val sdk.ValAd if b == nil { return types.ValidatorAccumulatedCommission{} } - k.cdc.MustUnmarshalBinaryBare(b, &commission) + k.cdc.MustUnmarshal(b, &commission) return } @@ -246,9 +246,9 @@ func (k Keeper) SetValidatorAccumulatedCommission(ctx sdk.Context, val sdk.ValAd store := ctx.KVStore(k.storeKey) if commission.Commission.IsZero() { - bz = k.cdc.MustMarshalBinaryBare(&types.ValidatorAccumulatedCommission{}) + bz = k.cdc.MustMarshal(&types.ValidatorAccumulatedCommission{}) } else { - bz = k.cdc.MustMarshalBinaryBare(&commission) + bz = k.cdc.MustMarshal(&commission) } store.Set(types.GetValidatorAccumulatedCommissionKey(val), bz) @@ -267,7 +267,7 @@ func (k Keeper) IterateValidatorAccumulatedCommissions(ctx sdk.Context, handler defer iter.Close() for ; iter.Valid(); iter.Next() { var commission types.ValidatorAccumulatedCommission - k.cdc.MustUnmarshalBinaryBare(iter.Value(), &commission) + k.cdc.MustUnmarshal(iter.Value(), &commission) addr := types.GetValidatorAccumulatedCommissionAddress(iter.Key()) if handler(addr, commission) { break @@ -279,14 +279,14 @@ func (k Keeper) IterateValidatorAccumulatedCommissions(ctx sdk.Context, handler func (k Keeper) GetValidatorOutstandingRewards(ctx sdk.Context, val sdk.ValAddress) (rewards types.ValidatorOutstandingRewards) { store := ctx.KVStore(k.storeKey) bz := store.Get(types.GetValidatorOutstandingRewardsKey(val)) - k.cdc.MustUnmarshalBinaryBare(bz, &rewards) + k.cdc.MustUnmarshal(bz, &rewards) return } // set validator outstanding rewards func (k Keeper) SetValidatorOutstandingRewards(ctx sdk.Context, val sdk.ValAddress, rewards types.ValidatorOutstandingRewards) { store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshalBinaryBare(&rewards) + b := k.cdc.MustMarshal(&rewards) store.Set(types.GetValidatorOutstandingRewardsKey(val), b) } @@ -303,7 +303,7 @@ func (k Keeper) IterateValidatorOutstandingRewards(ctx sdk.Context, handler func defer iter.Close() for ; iter.Valid(); iter.Next() { rewards := types.ValidatorOutstandingRewards{} - k.cdc.MustUnmarshalBinaryBare(iter.Value(), &rewards) + k.cdc.MustUnmarshal(iter.Value(), &rewards) addr := types.GetValidatorOutstandingRewardsAddress(iter.Key()) if handler(addr, rewards) { break @@ -318,14 +318,14 @@ func (k Keeper) GetValidatorSlashEvent(ctx sdk.Context, val sdk.ValAddress, heig if b == nil { return types.ValidatorSlashEvent{}, false } - k.cdc.MustUnmarshalBinaryBare(b, &event) + k.cdc.MustUnmarshal(b, &event) return event, true } // set slash event for height func (k Keeper) SetValidatorSlashEvent(ctx sdk.Context, val sdk.ValAddress, height, period uint64, event types.ValidatorSlashEvent) { store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshalBinaryBare(&event) + b := k.cdc.MustMarshal(&event) store.Set(types.GetValidatorSlashEventKey(val, height, period), b) } @@ -340,7 +340,7 @@ func (k Keeper) IterateValidatorSlashEventsBetween(ctx sdk.Context, val sdk.ValA defer iter.Close() for ; iter.Valid(); iter.Next() { var event types.ValidatorSlashEvent - k.cdc.MustUnmarshalBinaryBare(iter.Value(), &event) + k.cdc.MustUnmarshal(iter.Value(), &event) _, height := types.GetValidatorSlashEventAddressHeight(iter.Key()) if handler(height, event) { break @@ -355,7 +355,7 @@ func (k Keeper) IterateValidatorSlashEvents(ctx sdk.Context, handler func(val sd defer iter.Close() for ; iter.Valid(); iter.Next() { var event types.ValidatorSlashEvent - k.cdc.MustUnmarshalBinaryBare(iter.Value(), &event) + k.cdc.MustUnmarshal(iter.Value(), &event) val, height := types.GetValidatorSlashEventAddressHeight(iter.Key()) if handler(val, height, event) { break diff --git a/x/distribution/module.go b/x/distribution/module.go index d6261d3cd573..b2dec5b30167 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -34,7 +34,7 @@ var ( // AppModuleBasic defines the basic application module used by the distribution module. type AppModuleBasic struct { - cdc codec.Marshaler + cdc codec.Codec } // Name returns the distribution module's name. @@ -49,12 +49,12 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { // DefaultGenesis returns default genesis state as raw bytes for the distribution // module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the distribution module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { var data types.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -100,7 +100,7 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule( - cdc codec.Marshaler, keeper keeper.Keeper, accountKeeper types.AccountKeeper, + cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper, stakingKeeper stakingkeeper.Keeper, ) AppModule { return AppModule{ @@ -148,7 +148,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { // InitGenesis performs genesis initialization for the distribution module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) am.keeper.InitGenesis(ctx, genesisState) @@ -157,7 +157,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data j // ExportGenesis returns the exported genesis state as raw bytes for the distribution // module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { gs := am.keeper.ExportGenesis(ctx) return cdc.MustMarshalJSON(gs) } diff --git a/x/distribution/simulation/decoder.go b/x/distribution/simulation/decoder.go index a2be7dc188bf..a1d64d20dc05 100644 --- a/x/distribution/simulation/decoder.go +++ b/x/distribution/simulation/decoder.go @@ -12,13 +12,13 @@ import ( // NewDecodeStore returns a decoder function closure that unmarshals the KVPair's // Value to the corresponding distribution type. -func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string { +func NewDecodeStore(cdc codec.Codec) func(kvA, kvB kv.Pair) string { return func(kvA, kvB kv.Pair) string { switch { case bytes.Equal(kvA.Key[:1], types.FeePoolKey): var feePoolA, feePoolB types.FeePool - cdc.MustUnmarshalBinaryBare(kvA.Value, &feePoolA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &feePoolB) + cdc.MustUnmarshal(kvA.Value, &feePoolA) + cdc.MustUnmarshal(kvB.Value, &feePoolB) return fmt.Sprintf("%v\n%v", feePoolA, feePoolB) case bytes.Equal(kvA.Key[:1], types.ProposerKey): @@ -26,8 +26,8 @@ func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string { case bytes.Equal(kvA.Key[:1], types.ValidatorOutstandingRewardsPrefix): var rewardsA, rewardsB types.ValidatorOutstandingRewards - cdc.MustUnmarshalBinaryBare(kvA.Value, &rewardsA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &rewardsB) + cdc.MustUnmarshal(kvA.Value, &rewardsA) + cdc.MustUnmarshal(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) case bytes.Equal(kvA.Key[:1], types.DelegatorWithdrawAddrPrefix): @@ -35,32 +35,32 @@ func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string { case bytes.Equal(kvA.Key[:1], types.DelegatorStartingInfoPrefix): var infoA, infoB types.DelegatorStartingInfo - cdc.MustUnmarshalBinaryBare(kvA.Value, &infoA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &infoB) + cdc.MustUnmarshal(kvA.Value, &infoA) + cdc.MustUnmarshal(kvB.Value, &infoB) return fmt.Sprintf("%v\n%v", infoA, infoB) case bytes.Equal(kvA.Key[:1], types.ValidatorHistoricalRewardsPrefix): var rewardsA, rewardsB types.ValidatorHistoricalRewards - cdc.MustUnmarshalBinaryBare(kvA.Value, &rewardsA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &rewardsB) + cdc.MustUnmarshal(kvA.Value, &rewardsA) + cdc.MustUnmarshal(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) case bytes.Equal(kvA.Key[:1], types.ValidatorCurrentRewardsPrefix): var rewardsA, rewardsB types.ValidatorCurrentRewards - cdc.MustUnmarshalBinaryBare(kvA.Value, &rewardsA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &rewardsB) + cdc.MustUnmarshal(kvA.Value, &rewardsA) + cdc.MustUnmarshal(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) case bytes.Equal(kvA.Key[:1], types.ValidatorAccumulatedCommissionPrefix): var commissionA, commissionB types.ValidatorAccumulatedCommission - cdc.MustUnmarshalBinaryBare(kvA.Value, &commissionA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &commissionB) + cdc.MustUnmarshal(kvA.Value, &commissionA) + cdc.MustUnmarshal(kvB.Value, &commissionB) return fmt.Sprintf("%v\n%v", commissionA, commissionB) case bytes.Equal(kvA.Key[:1], types.ValidatorSlashEventPrefix): var eventA, eventB types.ValidatorSlashEvent - cdc.MustUnmarshalBinaryBare(kvA.Value, &eventA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &eventB) + cdc.MustUnmarshal(kvA.Value, &eventA) + cdc.MustUnmarshal(kvB.Value, &eventB) return fmt.Sprintf("%v\n%v", eventA, eventB) default: diff --git a/x/distribution/simulation/decoder_test.go b/x/distribution/simulation/decoder_test.go index 1032550acb10..69bb6b3b77a0 100644 --- a/x/distribution/simulation/decoder_test.go +++ b/x/distribution/simulation/decoder_test.go @@ -37,15 +37,15 @@ func TestDecodeDistributionStore(t *testing.T) { kvPairs := kv.Pairs{ Pairs: []kv.Pair{ - {Key: types.FeePoolKey, Value: cdc.MustMarshalBinaryBare(&feePool)}, + {Key: types.FeePoolKey, Value: cdc.MustMarshal(&feePool)}, {Key: types.ProposerKey, Value: consAddr1.Bytes()}, - {Key: types.GetValidatorOutstandingRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryBare(&outstanding)}, + {Key: types.GetValidatorOutstandingRewardsKey(valAddr1), Value: cdc.MustMarshal(&outstanding)}, {Key: types.GetDelegatorWithdrawAddrKey(delAddr1), Value: delAddr1.Bytes()}, - {Key: types.GetDelegatorStartingInfoKey(valAddr1, delAddr1), Value: cdc.MustMarshalBinaryBare(&info)}, - {Key: types.GetValidatorHistoricalRewardsKey(valAddr1, 100), Value: cdc.MustMarshalBinaryBare(&historicalRewards)}, - {Key: types.GetValidatorCurrentRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryBare(¤tRewards)}, - {Key: types.GetValidatorAccumulatedCommissionKey(valAddr1), Value: cdc.MustMarshalBinaryBare(&commission)}, - {Key: types.GetValidatorSlashEventKeyPrefix(valAddr1, 13), Value: cdc.MustMarshalBinaryBare(&slashEvent)}, + {Key: types.GetDelegatorStartingInfoKey(valAddr1, delAddr1), Value: cdc.MustMarshal(&info)}, + {Key: types.GetValidatorHistoricalRewardsKey(valAddr1, 100), Value: cdc.MustMarshal(&historicalRewards)}, + {Key: types.GetValidatorCurrentRewardsKey(valAddr1), Value: cdc.MustMarshal(¤tRewards)}, + {Key: types.GetValidatorAccumulatedCommissionKey(valAddr1), Value: cdc.MustMarshal(&commission)}, + {Key: types.GetValidatorSlashEventKeyPrefix(valAddr1, 13), Value: cdc.MustMarshal(&slashEvent)}, {Key: []byte{0x99}, Value: []byte{0x99}}, }, } diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index b83e6f8a4e4b..677e9cc843fc 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -26,7 +26,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONMarshaler, ak types.AccountKeeper, + appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper, ) simulation.WeightedOperations { diff --git a/x/evidence/handler_test.go b/x/evidence/handler_test.go index b3f95c300a4f..f6294f3e5526 100644 --- a/x/evidence/handler_test.go +++ b/x/evidence/handler_test.go @@ -116,7 +116,7 @@ func (suite *HandlerTestSuite) TestMsgSubmitEvidence() { msg := tc.msg.(exported.MsgSubmitEvidenceI) var resultData types.MsgSubmitEvidenceResponse - suite.app.AppCodec().UnmarshalBinaryBare(res.Data, &resultData) + suite.app.AppCodec().Unmarshal(res.Data, &resultData) suite.Require().Equal(msg.GetEvidence().Hash().Bytes(), resultData.Hash, "invalid hash; tc #%d", i) } } diff --git a/x/evidence/keeper/keeper.go b/x/evidence/keeper/keeper.go index aa660bcff13b..e913e7ab55ee 100644 --- a/x/evidence/keeper/keeper.go +++ b/x/evidence/keeper/keeper.go @@ -18,7 +18,7 @@ import ( // managing persistence, state transitions and query handling for the evidence // module. type Keeper struct { - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec storeKey sdk.StoreKey router types.Router stakingKeeper types.StakingKeeper @@ -26,7 +26,7 @@ type Keeper struct { } func NewKeeper( - cdc codec.BinaryMarshaler, storeKey sdk.StoreKey, stakingKeeper types.StakingKeeper, + cdc codec.BinaryCodec, storeKey sdk.StoreKey, stakingKeeper types.StakingKeeper, slashingKeeper types.SlashingKeeper, ) *Keeper { diff --git a/x/evidence/legacy/v038/types.go b/x/evidence/legacy/v038/types.go index 994f718ca5fd..8d3cb4f6095f 100644 --- a/x/evidence/legacy/v038/types.go +++ b/x/evidence/legacy/v038/types.go @@ -86,7 +86,7 @@ func (e Equivocation) String() string { // Hash returns the hash of an Equivocation object. func (e Equivocation) Hash() tmbytes.HexBytes { - return tmhash.Sum(ModuleCdc.LegacyAmino.MustMarshalBinaryBare(e)) + return tmhash.Sum(ModuleCdc.LegacyAmino.MustMarshal(e)) } // ValidateBasic performs basic stateless validation checks on an Equivocation object. diff --git a/x/evidence/module.go b/x/evidence/module.go index 204cb263516a..cfcf5a35d353 100644 --- a/x/evidence/module.go +++ b/x/evidence/module.go @@ -60,12 +60,12 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { } // DefaultGenesis returns the evidence module's default genesis state. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the evidence module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, config client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { var gs types.GenesisState if err := cdc.UnmarshalJSON(bz, &gs); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -159,7 +159,7 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) {} // InitGenesis performs the evidence module's genesis initialization It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, bz json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, bz json.RawMessage) []abci.ValidatorUpdate { var gs types.GenesisState err := cdc.UnmarshalJSON(bz, &gs) if err != nil { @@ -171,7 +171,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, bz jso } // ExportGenesis returns the evidence module's exported genesis state as raw JSON bytes. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(ExportGenesis(ctx, am.keeper)) } diff --git a/x/feegrant/keeper/grpc_query.go b/x/feegrant/keeper/grpc_query.go index d8e6c49138f1..b298ebdbae1b 100644 --- a/x/feegrant/keeper/grpc_query.go +++ b/x/feegrant/keeper/grpc_query.go @@ -78,7 +78,7 @@ func (q Keeper) FeeAllowances(c context.Context, req *types.QueryFeeAllowancesRe pageRes, err := query.Paginate(grantsStore, req.Pagination, func(key []byte, value []byte) error { var grant types.FeeAllowanceGrant - if err := q.cdc.UnmarshalBinaryBare(value, &grant); err != nil { + if err := q.cdc.Unmarshal(value, &grant); err != nil { return err } diff --git a/x/feegrant/keeper/keeper.go b/x/feegrant/keeper/keeper.go index d79a58417c08..a67369142d6c 100644 --- a/x/feegrant/keeper/keeper.go +++ b/x/feegrant/keeper/keeper.go @@ -15,7 +15,7 @@ import ( // Keeper manages state of all fee grants, as well as calculating approval. // It must have a codec with all available allowances registered. type Keeper struct { - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec storeKey sdk.StoreKey authKeeper types.AccountKeeper } @@ -23,7 +23,7 @@ type Keeper struct { var _ ante.FeegrantKeeper = &Keeper{} // NewKeeper creates a fee grant Keeper -func NewKeeper(cdc codec.BinaryMarshaler, storeKey sdk.StoreKey, ak types.AccountKeeper) Keeper { +func NewKeeper(cdc codec.BinaryCodec, storeKey sdk.StoreKey, ak types.AccountKeeper) Keeper { return Keeper{ cdc: cdc, storeKey: storeKey, @@ -53,7 +53,7 @@ func (k Keeper) GrantFeeAllowance(ctx sdk.Context, granter, grantee sdk.AccAddre return err } - bz, err := k.cdc.MarshalBinaryBare(&grant) + bz, err := k.cdc.Marshal(&grant) if err != nil { return err } @@ -114,7 +114,7 @@ func (k Keeper) getFeeGrant(ctx sdk.Context, granter sdk.AccAddress, grantee sdk } var feegrant types.FeeAllowanceGrant - if err := k.cdc.UnmarshalBinaryBare(bz, &feegrant); err != nil { + if err := k.cdc.Unmarshal(bz, &feegrant); err != nil { return nil, err } @@ -133,7 +133,7 @@ func (k Keeper) IterateAllFeeAllowances(ctx sdk.Context, cb func(types.FeeAllowa for ; iter.Valid() && !stop; iter.Next() { bz := iter.Value() var feeGrant types.FeeAllowanceGrant - if err := k.cdc.UnmarshalBinaryBare(bz, &feeGrant); err != nil { + if err := k.cdc.Unmarshal(bz, &feeGrant); err != nil { return err } diff --git a/x/feegrant/module.go b/x/feegrant/module.go index 77b113b1b0b7..c50547433581 100644 --- a/x/feegrant/module.go +++ b/x/feegrant/module.go @@ -36,7 +36,7 @@ var ( // AppModuleBasic defines the basic application module used by the feegrant module. type AppModuleBasic struct { - cdc codec.Marshaler + cdc codec.Codec } // Name returns the feegrant module's name. @@ -67,12 +67,12 @@ func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sd // DefaultGenesis returns default genesis state as raw bytes for the feegrant // module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the feegrant module. -func (a AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { +func (a AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { var data types.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { sdkerrors.Wrapf(err, "failed to unmarshal %s genesis state", types.ModuleName) @@ -113,7 +113,7 @@ type AppModule struct { } // NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Marshaler, ak types.AccountKeeper, bk types.BankKeeper, keeper keeper.Keeper, registry cdctypes.InterfaceRegistry) AppModule { +func NewAppModule(cdc codec.Codec, ak types.AccountKeeper, bk types.BankKeeper, keeper keeper.Keeper, registry cdctypes.InterfaceRegistry) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc}, keeper: keeper, @@ -148,7 +148,7 @@ func (AppModule) QuerierRoute() string { // InitGenesis performs genesis initialization for the feegrant module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, bz json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, bz json.RawMessage) []abci.ValidatorUpdate { var gs types.GenesisState cdc.MustUnmarshalJSON(bz, &gs) @@ -161,7 +161,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, bz jso // ExportGenesis returns the exported genesis state as raw bytes for the feegrant // module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { gs, err := ExportGenesis(ctx, am.keeper) if err != nil { panic(err) diff --git a/x/feegrant/simulation/decoder.go b/x/feegrant/simulation/decoder.go index 46e35594fdf8..1d8b58cb4f64 100644 --- a/x/feegrant/simulation/decoder.go +++ b/x/feegrant/simulation/decoder.go @@ -11,13 +11,13 @@ import ( // NewDecodeStore returns a decoder function closure that unmarshals the KVPair's // Value to the corresponding feegrant type. -func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string { +func NewDecodeStore(cdc codec.Codec) func(kvA, kvB kv.Pair) string { return func(kvA, kvB kv.Pair) string { switch { case bytes.Equal(kvA.Key[:1], types.FeeAllowanceKeyPrefix): var grantA, grantB types.FeeAllowanceGrant - cdc.MustUnmarshalBinaryBare(kvA.Value, &grantA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &grantB) + cdc.MustUnmarshal(kvA.Value, &grantA) + cdc.MustUnmarshal(kvB.Value, &grantB) return fmt.Sprintf("%v\n%v", grantA, grantB) default: panic(fmt.Sprintf("invalid feegrant key %X", kvA.Key)) diff --git a/x/feegrant/simulation/decoder_test.go b/x/feegrant/simulation/decoder_test.go index 887111845636..7a5c0ba3dcb6 100644 --- a/x/feegrant/simulation/decoder_test.go +++ b/x/feegrant/simulation/decoder_test.go @@ -31,7 +31,7 @@ func TestDecodeStore(t *testing.T) { require.NoError(t, err) - grantBz, err := cdc.MarshalBinaryBare(&grant) + grantBz, err := cdc.Marshal(&grant) require.NoError(t, err) kvPairs := kv.Pairs{ diff --git a/x/feegrant/simulation/operations.go b/x/feegrant/simulation/operations.go index a9a7978b428f..f8c53a7092c9 100644 --- a/x/feegrant/simulation/operations.go +++ b/x/feegrant/simulation/operations.go @@ -26,7 +26,7 @@ const ( ) func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONMarshaler, + appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, protoCdc *codec.ProtoCodec, ) simulation.WeightedOperations { diff --git a/x/feegrant/types/grant_test.go b/x/feegrant/types/grant_test.go index bd6907faa9de..769f7628969c 100644 --- a/x/feegrant/types/grant_test.go +++ b/x/feegrant/types/grant_test.go @@ -89,10 +89,10 @@ func TestGrant(t *testing.T) { require.NoError(t, err) // if it is valid, let's try to serialize, deserialize, and make sure it matches - bz, err := cdc.MarshalBinaryBare(&grant) + bz, err := cdc.Marshal(&grant) require.NoError(t, err) var loaded types.FeeAllowanceGrant - err = cdc.UnmarshalBinaryBare(bz, &loaded) + err = cdc.Unmarshal(bz, &loaded) require.NoError(t, err) err = loaded.ValidateBasic() diff --git a/x/genutil/client/testutil/helpers.go b/x/genutil/client/testutil/helpers.go index 1fc4affb7d42..ec9331e9b1a6 100644 --- a/x/genutil/client/testutil/helpers.go +++ b/x/genutil/client/testutil/helpers.go @@ -17,7 +17,7 @@ import ( genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" ) -func ExecInitCmd(testMbm module.BasicManager, home string, cdc codec.JSONMarshaler) error { +func ExecInitCmd(testMbm module.BasicManager, home string, cdc codec.JSONCodec) error { logger := log.NewNopLogger() cfg, err := CreateDefaultTendermintConfig(home) if err != nil { diff --git a/x/genutil/collect.go b/x/genutil/collect.go index fe507cca8720..b93942e0ba00 100644 --- a/x/genutil/collect.go +++ b/x/genutil/collect.go @@ -25,7 +25,7 @@ import ( ) // GenAppStateFromConfig gets the genesis app state from the config -func GenAppStateFromConfig(cdc codec.JSONMarshaler, txEncodingConfig client.TxEncodingConfig, +func GenAppStateFromConfig(cdc codec.JSONCodec, txEncodingConfig client.TxEncodingConfig, config *cfg.Config, initCfg types.InitConfig, genDoc tmtypes.GenesisDoc, genBalIterator types.GenesisBalancesIterator, ) (appState json.RawMessage, err error) { @@ -69,7 +69,7 @@ func GenAppStateFromConfig(cdc codec.JSONMarshaler, txEncodingConfig client.TxEn // CollectTxs processes and validates application's genesis Txs and returns // the list of appGenTxs, and persistent peers required to generate genesis.json. -func CollectTxs(cdc codec.JSONMarshaler, txJSONDecoder sdk.TxDecoder, moniker, genTxsDir string, +func CollectTxs(cdc codec.JSONCodec, txJSONDecoder sdk.TxDecoder, moniker, genTxsDir string, genDoc tmtypes.GenesisDoc, genBalIterator types.GenesisBalancesIterator, ) (appGenTxs []sdk.Tx, persistentPeers string, err error) { // prepare a map of all balances in genesis state to then validate diff --git a/x/genutil/collect_test.go b/x/genutil/collect_test.go index 66244cf74448..46e20f88f1b3 100644 --- a/x/genutil/collect_test.go +++ b/x/genutil/collect_test.go @@ -21,7 +21,7 @@ import ( ) type doNothingUnmarshalJSON struct { - codec.JSONMarshaler + codec.JSONCodec } func (dnj *doNothingUnmarshalJSON) UnmarshalJSON(_ []byte, _ proto.Message) error { @@ -32,7 +32,7 @@ type doNothingIterator struct { gtypes.GenesisBalancesIterator } -func (dni *doNothingIterator) IterateGenesisBalances(_ codec.JSONMarshaler, _ map[string]json.RawMessage, _ func(bankexported.GenesisBalance) bool) { +func (dni *doNothingIterator) IterateGenesisBalances(_ codec.JSONCodec, _ map[string]json.RawMessage, _ func(bankexported.GenesisBalance) bool) { } // Ensures that CollectTx correctly traverses directories and won't error out on encountering diff --git a/x/genutil/gentx.go b/x/genutil/gentx.go index b5415ffb31f2..61b237151f2d 100644 --- a/x/genutil/gentx.go +++ b/x/genutil/gentx.go @@ -16,7 +16,7 @@ import ( // SetGenTxsInAppGenesisState - sets the genesis transactions in the app genesis state func SetGenTxsInAppGenesisState( - cdc codec.JSONMarshaler, txJSONEncoder sdk.TxEncoder, appGenesisState map[string]json.RawMessage, genTxs []sdk.Tx, + cdc codec.JSONCodec, txJSONEncoder sdk.TxEncoder, appGenesisState map[string]json.RawMessage, genTxs []sdk.Tx, ) (map[string]json.RawMessage, error) { genesisState := types.GetGenesisStateFromAppState(cdc, appGenesisState) @@ -39,7 +39,7 @@ func SetGenTxsInAppGenesisState( // balance in the set of genesis accounts. func ValidateAccountInGenesis( appGenesisState map[string]json.RawMessage, genBalIterator types.GenesisBalancesIterator, - addr sdk.Address, coins sdk.Coins, cdc codec.JSONMarshaler, + addr sdk.Address, coins sdk.Coins, cdc codec.JSONCodec, ) error { var stakingData stakingtypes.GenesisState diff --git a/x/genutil/module.go b/x/genutil/module.go index ebfb70c4ab43..4b8bcc72e77d 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -39,12 +39,12 @@ func (b AppModuleBasic) RegisterInterfaces(_ cdctypes.InterfaceRegistry) {} // DefaultGenesis returns default genesis state as raw bytes for the genutil // module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the genutil module. -func (b AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, txEncodingConfig client.TxEncodingConfig, bz json.RawMessage) error { +func (b AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, txEncodingConfig client.TxEncodingConfig, bz json.RawMessage) error { var data types.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -93,7 +93,7 @@ func NewAppModule(accountKeeper types.AccountKeeper, // InitGenesis performs genesis initialization for the genutil module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) validators, err := InitGenesis(ctx, am.stakingKeeper, am.deliverTx, genesisState, am.txEncodingConfig) @@ -105,7 +105,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data j // ExportGenesis returns the exported genesis state as raw bytes for the genutil // module. -func (am AppModule) ExportGenesis(_ sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(_ sdk.Context, cdc codec.JSONCodec) json.RawMessage { return am.DefaultGenesis(cdc) } diff --git a/x/genutil/types/expected_keepers.go b/x/genutil/types/expected_keepers.go index 341d2eb2c8ec..854422a3c990 100644 --- a/x/genutil/types/expected_keepers.go +++ b/x/genutil/types/expected_keepers.go @@ -35,7 +35,7 @@ type GenesisAccountsIterator interface { // GenesisAccountsIterator defines the expected iterating genesis accounts object (noalias) type GenesisBalancesIterator interface { IterateGenesisBalances( - cdc codec.JSONMarshaler, + cdc codec.JSONCodec, appGenesis map[string]json.RawMessage, cb func(bankexported.GenesisBalance) (stop bool), ) diff --git a/x/genutil/types/genesis_state.go b/x/genutil/types/genesis_state.go index b3e28bb6de80..a7c4cdd8c6c4 100644 --- a/x/genutil/types/genesis_state.go +++ b/x/genutil/types/genesis_state.go @@ -46,7 +46,7 @@ func NewGenesisStateFromTx(txJSONEncoder sdk.TxEncoder, genTxs []sdk.Tx) *Genesi } // GetGenesisStateFromAppState gets the genutil genesis state from the expected app state -func GetGenesisStateFromAppState(cdc codec.JSONMarshaler, appState map[string]json.RawMessage) *GenesisState { +func GetGenesisStateFromAppState(cdc codec.JSONCodec, appState map[string]json.RawMessage) *GenesisState { var genesisState GenesisState if appState[ModuleName] != nil { cdc.MustUnmarshalJSON(appState[ModuleName], &genesisState) @@ -56,7 +56,7 @@ func GetGenesisStateFromAppState(cdc codec.JSONMarshaler, appState map[string]js // SetGenesisStateInAppState sets the genutil genesis state within the expected app state func SetGenesisStateInAppState( - cdc codec.JSONMarshaler, appState map[string]json.RawMessage, genesisState *GenesisState, + cdc codec.JSONCodec, appState map[string]json.RawMessage, genesisState *GenesisState, ) map[string]json.RawMessage { genesisStateBz := cdc.MustMarshalJSON(genesisState) diff --git a/x/gov/keeper/deposit.go b/x/gov/keeper/deposit.go index cac3418859c0..9275fbff40dc 100644 --- a/x/gov/keeper/deposit.go +++ b/x/gov/keeper/deposit.go @@ -16,7 +16,7 @@ func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID uint64, depositorAdd return deposit, false } - keeper.cdc.MustUnmarshalBinaryBare(bz, &deposit) + keeper.cdc.MustUnmarshal(bz, &deposit) return deposit, true } @@ -24,7 +24,7 @@ func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID uint64, depositorAdd // SetDeposit sets a Deposit to the gov store func (keeper Keeper) SetDeposit(ctx sdk.Context, deposit types.Deposit) { store := ctx.KVStore(keeper.storeKey) - bz := keeper.cdc.MustMarshalBinaryBare(&deposit) + bz := keeper.cdc.MustMarshal(&deposit) depositor, err := sdk.AccAddressFromBech32(deposit.Depositor) if err != nil { panic(err) @@ -82,7 +82,7 @@ func (keeper Keeper) IterateAllDeposits(ctx sdk.Context, cb func(deposit types.D for ; iterator.Valid(); iterator.Next() { var deposit types.Deposit - keeper.cdc.MustUnmarshalBinaryBare(iterator.Value(), &deposit) + keeper.cdc.MustUnmarshal(iterator.Value(), &deposit) if cb(deposit) { break @@ -100,7 +100,7 @@ func (keeper Keeper) IterateDeposits(ctx sdk.Context, proposalID uint64, cb func for ; iterator.Valid(); iterator.Next() { var deposit types.Deposit - keeper.cdc.MustUnmarshalBinaryBare(iterator.Value(), &deposit) + keeper.cdc.MustUnmarshal(iterator.Value(), &deposit) if cb(deposit) { break diff --git a/x/gov/keeper/grpc_query.go b/x/gov/keeper/grpc_query.go index 93a0e05937ed..ceb563b0cb3b 100644 --- a/x/gov/keeper/grpc_query.go +++ b/x/gov/keeper/grpc_query.go @@ -44,7 +44,7 @@ func (q Keeper) Proposals(c context.Context, req *types.QueryProposalsRequest) ( pageRes, err := query.FilteredPaginate(proposalStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { var p types.Proposal - if err := q.cdc.UnmarshalBinaryBare(value, &p); err != nil { + if err := q.cdc.Unmarshal(value, &p); err != nil { return false, status.Error(codes.Internal, err.Error()) } @@ -139,7 +139,7 @@ func (q Keeper) Votes(c context.Context, req *types.QueryVotesRequest) (*types.Q pageRes, err := query.Paginate(votesStore, req.Pagination, func(key []byte, value []byte) error { var vote types.Vote - if err := q.cdc.UnmarshalBinaryBare(value, &vote); err != nil { + if err := q.cdc.Unmarshal(value, &vote); err != nil { return err } @@ -228,7 +228,7 @@ func (q Keeper) Deposits(c context.Context, req *types.QueryDepositsRequest) (*t pageRes, err := query.Paginate(depositStore, req.Pagination, func(key []byte, value []byte) error { var deposit types.Deposit - if err := q.cdc.UnmarshalBinaryBare(value, &deposit); err != nil { + if err := q.cdc.Unmarshal(value, &deposit); err != nil { return err } diff --git a/x/gov/keeper/keeper.go b/x/gov/keeper/keeper.go index 8645a92da20f..9e639fe5d0fc 100644 --- a/x/gov/keeper/keeper.go +++ b/x/gov/keeper/keeper.go @@ -30,7 +30,7 @@ type Keeper struct { storeKey sdk.StoreKey // The codec codec for binary encoding/decoding. - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec // Proposal router router types.Router @@ -44,7 +44,7 @@ type Keeper struct { // // CONTRACT: the parameter Subspace must have the param key table already initialized func NewKeeper( - cdc codec.BinaryMarshaler, key sdk.StoreKey, paramSpace types.ParamSubspace, + cdc codec.BinaryCodec, key sdk.StoreKey, paramSpace types.ParamSubspace, authKeeper types.AccountKeeper, bankKeeper types.BankKeeper, sk types.StakingKeeper, rtr types.Router, ) Keeper { diff --git a/x/gov/keeper/proposal.go b/x/gov/keeper/proposal.go index 853f9af35716..216596932fad 100644 --- a/x/gov/keeper/proposal.go +++ b/x/gov/keeper/proposal.go @@ -195,7 +195,7 @@ func (keeper Keeper) ActivateVotingPeriod(ctx sdk.Context, proposal types.Propos } func (keeper Keeper) MarshalProposal(proposal types.Proposal) ([]byte, error) { - bz, err := keeper.cdc.MarshalBinaryBare(&proposal) + bz, err := keeper.cdc.Marshal(&proposal) if err != nil { return nil, err } @@ -203,7 +203,7 @@ func (keeper Keeper) MarshalProposal(proposal types.Proposal) ([]byte, error) { } func (keeper Keeper) UnmarshalProposal(bz []byte, proposal *types.Proposal) error { - err := keeper.cdc.UnmarshalBinaryBare(bz, proposal) + err := keeper.cdc.Unmarshal(bz, proposal) if err != nil { return err } diff --git a/x/gov/keeper/vote.go b/x/gov/keeper/vote.go index e4000a1a9117..c54ce875c81f 100644 --- a/x/gov/keeper/vote.go +++ b/x/gov/keeper/vote.go @@ -67,14 +67,14 @@ func (keeper Keeper) GetVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.A return vote, false } - keeper.cdc.MustUnmarshalBinaryBare(bz, &vote) + keeper.cdc.MustUnmarshal(bz, &vote) return vote, true } // SetVote sets a Vote to the gov store func (keeper Keeper) SetVote(ctx sdk.Context, vote types.Vote) { store := ctx.KVStore(keeper.storeKey) - bz := keeper.cdc.MustMarshalBinaryBare(&vote) + bz := keeper.cdc.MustMarshal(&vote) addr, err := sdk.AccAddressFromBech32(vote.Voter) if err != nil { panic(err) @@ -90,7 +90,7 @@ func (keeper Keeper) IterateAllVotes(ctx sdk.Context, cb func(vote types.Vote) ( defer iterator.Close() for ; iterator.Valid(); iterator.Next() { var vote types.Vote - keeper.cdc.MustUnmarshalBinaryBare(iterator.Value(), &vote) + keeper.cdc.MustUnmarshal(iterator.Value(), &vote) if cb(vote) { break @@ -106,7 +106,7 @@ func (keeper Keeper) IterateVotes(ctx sdk.Context, proposalID uint64, cb func(vo defer iterator.Close() for ; iterator.Valid(); iterator.Next() { var vote types.Vote - keeper.cdc.MustUnmarshalBinaryBare(iterator.Value(), &vote) + keeper.cdc.MustUnmarshal(iterator.Value(), &vote) if cb(vote) { break diff --git a/x/gov/legacy/v043/store.go b/x/gov/legacy/v043/store.go index 0cacf51c3bac..1658af56c8fa 100644 --- a/x/gov/legacy/v043/store.go +++ b/x/gov/legacy/v043/store.go @@ -42,19 +42,19 @@ func migrateVote(oldVote v040gov.Vote) types.Vote { } // migrateStoreWeightedVotes migrates in-place all legacy votes to ADR-037 weighted votes. -func migrateStoreWeightedVotes(store sdk.KVStore, cdc codec.BinaryMarshaler) error { +func migrateStoreWeightedVotes(store sdk.KVStore, cdc codec.BinaryCodec) error { iterator := sdk.KVStorePrefixIterator(store, v040gov.VotesKeyPrefix) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { var oldVote v040gov.Vote - err := cdc.UnmarshalBinaryBare(iterator.Value(), &oldVote) + err := cdc.Unmarshal(iterator.Value(), &oldVote) if err != nil { return err } newVote := migrateVote(oldVote) - bz, err := cdc.MarshalBinaryBare(&newVote) + bz, err := cdc.Marshal(&newVote) if err != nil { return err } @@ -69,7 +69,7 @@ func migrateStoreWeightedVotes(store sdk.KVStore, cdc codec.BinaryMarshaler) err // migration includes: // // - Change addresses to be length-prefixed. -func MigrateStore(ctx sdk.Context, storeKey sdk.StoreKey, cdc codec.BinaryMarshaler) error { +func MigrateStore(ctx sdk.Context, storeKey sdk.StoreKey, cdc codec.BinaryCodec) error { store := ctx.KVStore(storeKey) migratePrefixProposalAddress(store, v040gov.DepositsKeyPrefix) migratePrefixProposalAddress(store, v040gov.VotesKeyPrefix) diff --git a/x/gov/legacy/v043/store_test.go b/x/gov/legacy/v043/store_test.go index d84e8859109e..db2ffa873773 100644 --- a/x/gov/legacy/v043/store_test.go +++ b/x/gov/legacy/v043/store_test.go @@ -29,9 +29,9 @@ func TestMigrateStore(t *testing.T) { dummyValue := []byte("foo") // Use real values for votes, as we're testing weighted votes. oldVote := v040gov.Vote{ProposalId: 1, Voter: "foobar", Option: types.OptionNoWithVeto} - oldVoteValue := cdc.MustMarshalBinaryBare(&oldVote) + oldVoteValue := cdc.MustMarshal(&oldVote) newVote := types.Vote{ProposalId: 1, Voter: "foobar", Options: types.WeightedVoteOptions{{Option: types.OptionNoWithVeto, Weight: sdk.NewDec(1)}}} - newVoteValue := cdc.MustMarshalBinaryBare(&newVote) + newVoteValue := cdc.MustMarshal(&newVote) testCases := []struct { name string diff --git a/x/gov/module.go b/x/gov/module.go index 5e24cda3ab13..3c54e3cbc634 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -37,7 +37,7 @@ var ( // AppModuleBasic defines the basic application module used by the gov module. type AppModuleBasic struct { - cdc codec.Marshaler + cdc codec.Codec proposalHandlers []govclient.ProposalHandler // proposal handlers which live in governance cli and rest } @@ -60,12 +60,12 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { // DefaultGenesis returns default genesis state as raw bytes for the gov // module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the gov module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, config client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { var data types.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -119,7 +119,7 @@ type AppModule struct { } // NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Marshaler, keeper keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper) AppModule { +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc}, keeper: keeper, @@ -164,7 +164,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { // InitGenesis performs genesis initialization for the gov module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.accountKeeper, am.bankKeeper, am.keeper, &genesisState) @@ -173,7 +173,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data j // ExportGenesis returns the exported genesis state as raw bytes for the gov // module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return cdc.MustMarshalJSON(gs) } diff --git a/x/gov/simulation/decoder.go b/x/gov/simulation/decoder.go index 180754ddee08..762b8ffb13eb 100644 --- a/x/gov/simulation/decoder.go +++ b/x/gov/simulation/decoder.go @@ -12,17 +12,17 @@ import ( // NewDecodeStore returns a decoder function closure that unmarshals the KVPair's // Value to the corresponding gov type. -func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string { +func NewDecodeStore(cdc codec.Codec) func(kvA, kvB kv.Pair) string { return func(kvA, kvB kv.Pair) string { switch { case bytes.Equal(kvA.Key[:1], types.ProposalsKeyPrefix): var proposalA types.Proposal - err := cdc.UnmarshalBinaryBare(kvA.Value, &proposalA) + err := cdc.Unmarshal(kvA.Value, &proposalA) if err != nil { panic(err) } var proposalB types.Proposal - err = cdc.UnmarshalBinaryBare(kvB.Value, &proposalB) + err = cdc.Unmarshal(kvB.Value, &proposalB) if err != nil { panic(err) } @@ -37,14 +37,14 @@ func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string { case bytes.Equal(kvA.Key[:1], types.DepositsKeyPrefix): var depositA, depositB types.Deposit - cdc.MustUnmarshalBinaryBare(kvA.Value, &depositA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &depositB) + cdc.MustUnmarshal(kvA.Value, &depositA) + cdc.MustUnmarshal(kvB.Value, &depositB) return fmt.Sprintf("%v\n%v", depositA, depositB) case bytes.Equal(kvA.Key[:1], types.VotesKeyPrefix): var voteA, voteB types.Vote - cdc.MustUnmarshalBinaryBare(kvA.Value, &voteA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &voteB) + cdc.MustUnmarshal(kvA.Value, &voteA) + cdc.MustUnmarshal(kvB.Value, &voteB) return fmt.Sprintf("%v\n%v", voteA, voteB) default: diff --git a/x/gov/simulation/decoder_test.go b/x/gov/simulation/decoder_test.go index 4f6273a171e4..188fe9e540f0 100644 --- a/x/gov/simulation/decoder_test.go +++ b/x/gov/simulation/decoder_test.go @@ -37,9 +37,9 @@ func TestDecodeStore(t *testing.T) { deposit := types.NewDeposit(1, delAddr1, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()))) vote := types.NewVote(1, delAddr1, types.NewNonSplitVoteOption(types.OptionYes)) - proposalBzA, err := cdc.MarshalBinaryBare(&proposalA) + proposalBzA, err := cdc.Marshal(&proposalA) require.NoError(t, err) - proposalBzB, err := cdc.MarshalBinaryBare(&proposalB) + proposalBzB, err := cdc.Marshal(&proposalB) require.NoError(t, err) tests := []struct { @@ -62,14 +62,14 @@ func TestDecodeStore(t *testing.T) { }, { "deposits", - kv.Pair{Key: types.DepositKey(1, delAddr1), Value: cdc.MustMarshalBinaryBare(&deposit)}, - kv.Pair{Key: types.DepositKey(1, delAddr1), Value: cdc.MustMarshalBinaryBare(&deposit)}, + kv.Pair{Key: types.DepositKey(1, delAddr1), Value: cdc.MustMarshal(&deposit)}, + kv.Pair{Key: types.DepositKey(1, delAddr1), Value: cdc.MustMarshal(&deposit)}, fmt.Sprintf("%v\n%v", deposit, deposit), false, }, { "votes", - kv.Pair{Key: types.VoteKey(1, delAddr1), Value: cdc.MustMarshalBinaryBare(&vote)}, - kv.Pair{Key: types.VoteKey(1, delAddr1), Value: cdc.MustMarshalBinaryBare(&vote)}, + kv.Pair{Key: types.VoteKey(1, delAddr1), Value: cdc.MustMarshal(&vote)}, + kv.Pair{Key: types.VoteKey(1, delAddr1), Value: cdc.MustMarshal(&vote)}, fmt.Sprintf("%v\n%v", vote, vote), false, }, { diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 8ce709da834f..21ec3f7b298c 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -27,7 +27,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONMarshaler, ak types.AccountKeeper, + appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, wContents []simtypes.WeightedProposalContent, ) simulation.WeightedOperations { diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index 46eb6ba535f5..b010204e8a18 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -11,7 +11,7 @@ import ( // Keeper of the mint store type Keeper struct { - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec storeKey sdk.StoreKey paramSpace paramtypes.Subspace stakingKeeper types.StakingKeeper @@ -21,7 +21,7 @@ type Keeper struct { // NewKeeper creates a new mint Keeper instance func NewKeeper( - cdc codec.BinaryMarshaler, key sdk.StoreKey, paramSpace paramtypes.Subspace, + cdc codec.BinaryCodec, key sdk.StoreKey, paramSpace paramtypes.Subspace, sk types.StakingKeeper, ak types.AccountKeeper, bk types.BankKeeper, feeCollectorName string, ) Keeper { @@ -58,14 +58,14 @@ func (k Keeper) GetMinter(ctx sdk.Context) (minter types.Minter) { panic("stored minter should not have been nil") } - k.cdc.MustUnmarshalBinaryBare(b, &minter) + k.cdc.MustUnmarshal(b, &minter) return } // set the minter func (k Keeper) SetMinter(ctx sdk.Context, minter types.Minter) { store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshalBinaryBare(&minter) + b := k.cdc.MustMarshal(&minter) store.Set(types.MinterKey, b) } diff --git a/x/mint/module.go b/x/mint/module.go index a4d1f113f08f..f8d51f9cf5f3 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -32,7 +32,7 @@ var ( // AppModuleBasic defines the basic application module used by the mint module. type AppModuleBasic struct { - cdc codec.Marshaler + cdc codec.Codec } var _ module.AppModuleBasic = AppModuleBasic{} @@ -50,12 +50,12 @@ func (b AppModuleBasic) RegisterInterfaces(_ cdctypes.InterfaceRegistry) {} // DefaultGenesis returns default genesis state as raw bytes for the mint // module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the mint module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, config client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { var data types.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -92,7 +92,7 @@ type AppModule struct { } // NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Marshaler, keeper keeper.Keeper, ak types.AccountKeeper) AppModule { +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak types.AccountKeeper) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc}, keeper: keeper, @@ -129,7 +129,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { // InitGenesis performs genesis initialization for the mint module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) @@ -139,7 +139,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data j // ExportGenesis returns the exported genesis state as raw bytes for the mint // module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return cdc.MustMarshalJSON(gs) } diff --git a/x/mint/simulation/decoder.go b/x/mint/simulation/decoder.go index f0a89be43965..b9337fed0074 100644 --- a/x/mint/simulation/decoder.go +++ b/x/mint/simulation/decoder.go @@ -11,13 +11,13 @@ import ( // NewDecodeStore returns a decoder function closure that unmarshals the KVPair's // Value to the corresponding mint type. -func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string { +func NewDecodeStore(cdc codec.Codec) func(kvA, kvB kv.Pair) string { return func(kvA, kvB kv.Pair) string { switch { case bytes.Equal(kvA.Key, types.MinterKey): var minterA, minterB types.Minter - cdc.MustUnmarshalBinaryBare(kvA.Value, &minterA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &minterB) + cdc.MustUnmarshal(kvA.Value, &minterA) + cdc.MustUnmarshal(kvB.Value, &minterB) return fmt.Sprintf("%v\n%v", minterA, minterB) default: panic(fmt.Sprintf("invalid mint key %X", kvA.Key)) diff --git a/x/mint/simulation/decoder_test.go b/x/mint/simulation/decoder_test.go index 0116108b4ed3..43a8cfbd42c4 100644 --- a/x/mint/simulation/decoder_test.go +++ b/x/mint/simulation/decoder_test.go @@ -21,7 +21,7 @@ func TestDecodeStore(t *testing.T) { kvPairs := kv.Pairs{ Pairs: []kv.Pair{ - {Key: types.MinterKey, Value: cdc.MustMarshalBinaryBare(&minter)}, + {Key: types.MinterKey, Value: cdc.MustMarshal(&minter)}, {Key: []byte{0x99}, Value: []byte{0x99}}, }, } diff --git a/x/params/keeper/keeper.go b/x/params/keeper/keeper.go index b3d649a2ec49..388d99c51c99 100644 --- a/x/params/keeper/keeper.go +++ b/x/params/keeper/keeper.go @@ -11,7 +11,7 @@ import ( // Keeper of the global paramstore type Keeper struct { - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec legacyAmino *codec.LegacyAmino key sdk.StoreKey tkey sdk.StoreKey @@ -19,7 +19,7 @@ type Keeper struct { } // NewKeeper constructs a params keeper -func NewKeeper(cdc codec.BinaryMarshaler, legacyAmino *codec.LegacyAmino, key, tkey sdk.StoreKey) Keeper { +func NewKeeper(cdc codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey sdk.StoreKey) Keeper { return Keeper{ cdc: cdc, legacyAmino: legacyAmino, diff --git a/x/params/module.go b/x/params/module.go index 624ff2d25e96..616c7e28a1c6 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -45,10 +45,10 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { // DefaultGenesis returns default genesis state as raw bytes for the params // module. -func (AppModuleBasic) DefaultGenesis(_ codec.JSONMarshaler) json.RawMessage { return nil } +func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { return nil } // ValidateGenesis performs genesis state validation for the params module. -func (AppModuleBasic) ValidateGenesis(_ codec.JSONMarshaler, config client.TxEncodingConfig, _ json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, config client.TxEncodingConfig, _ json.RawMessage) error { return nil } @@ -90,7 +90,7 @@ func NewAppModule(k keeper.Keeper) AppModule { func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // InitGenesis performs a no-op. -func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONMarshaler, _ json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } @@ -133,7 +133,7 @@ func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.Weig } // ExportGenesis performs a no-op. -func (am AppModule) ExportGenesis(_ sdk.Context, _ codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(_ sdk.Context, _ codec.JSONCodec) json.RawMessage { return nil } diff --git a/x/params/types/subspace.go b/x/params/types/subspace.go index da0a755d417b..42afe6cc9b21 100644 --- a/x/params/types/subspace.go +++ b/x/params/types/subspace.go @@ -21,7 +21,7 @@ const ( // Transient store persists for a block, so we use it for // recording whether the parameter has been changed or not type Subspace struct { - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec legacyAmino *codec.LegacyAmino key sdk.StoreKey // []byte -> []byte, stores parameter tkey sdk.StoreKey // []byte -> bool, stores parameter change @@ -30,7 +30,7 @@ type Subspace struct { } // NewSubspace constructs a store with namestore -func NewSubspace(cdc codec.BinaryMarshaler, legacyAmino *codec.LegacyAmino, key sdk.StoreKey, tkey sdk.StoreKey, name string) Subspace { +func NewSubspace(cdc codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key sdk.StoreKey, tkey sdk.StoreKey, name string) Subspace { return Subspace{ cdc: cdc, legacyAmino: legacyAmino, diff --git a/x/params/types/subspace_test.go b/x/params/types/subspace_test.go index ed508d00e93c..a347a5f5427e 100644 --- a/x/params/types/subspace_test.go +++ b/x/params/types/subspace_test.go @@ -20,7 +20,7 @@ import ( type SubspaceTestSuite struct { suite.Suite - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec amino *codec.LegacyAmino ctx sdk.Context ss types.Subspace diff --git a/x/simulation/params.go b/x/simulation/params.go index b0569e94898c..e11e9764bc97 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -151,7 +151,7 @@ func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulato // Param change proposals // randomConsensusParams returns random simulation consensus parameters, it extracts the Evidence from the Staking genesis state. -func randomConsensusParams(r *rand.Rand, appState json.RawMessage, cdc codec.JSONMarshaler) *abci.ConsensusParams { +func randomConsensusParams(r *rand.Rand, appState json.RawMessage, cdc codec.JSONCodec) *abci.ConsensusParams { var genesisState map[string]json.RawMessage err := json.Unmarshal(appState, &genesisState) if err != nil { diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 6e391aa2eb08..ab0dfdcda7d0 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -24,7 +24,7 @@ const AverageBlockTime = 6 * time.Second // initialize the chain for the simulation func initChain( r *rand.Rand, params Params, accounts []simulation.Account, app *baseapp.BaseApp, - appStateFn simulation.AppStateFn, config simulation.Config, cdc codec.JSONMarshaler, + appStateFn simulation.AppStateFn, config simulation.Config, cdc codec.JSONCodec, ) (mockValidators, time.Time, []simulation.Account, string) { appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, config) @@ -53,7 +53,7 @@ func SimulateFromSeed( ops WeightedOperations, blockedAddrs map[string]bool, config simulation.Config, - cdc codec.JSONMarshaler, + cdc codec.JSONCodec, ) (stopEarly bool, exportedParams Params, err error) { // in case we have to end early, don't os.Exit so that we can run cleanup code. testingMode, _, b := getTestingMode(tb) diff --git a/x/slashing/keeper/grpc_query.go b/x/slashing/keeper/grpc_query.go index 982d0939970a..324fcd1cd12c 100644 --- a/x/slashing/keeper/grpc_query.go +++ b/x/slashing/keeper/grpc_query.go @@ -60,7 +60,7 @@ func (k Keeper) SigningInfos(c context.Context, req *types.QuerySigningInfosRequ sigInfoStore := prefix.NewStore(store, types.ValidatorSigningInfoKeyPrefix) pageRes, err := query.Paginate(sigInfoStore, req.Pagination, func(key []byte, value []byte) error { var info types.ValidatorSigningInfo - err := k.cdc.UnmarshalBinaryBare(value, &info) + err := k.cdc.Unmarshal(value, &info) if err != nil { return err } diff --git a/x/slashing/keeper/keeper.go b/x/slashing/keeper/keeper.go index 69a5e25b4a4c..12a943c84c69 100644 --- a/x/slashing/keeper/keeper.go +++ b/x/slashing/keeper/keeper.go @@ -14,13 +14,13 @@ import ( // Keeper of the slashing store type Keeper struct { storeKey sdk.StoreKey - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec sk types.StakingKeeper paramspace types.ParamSubspace } // NewKeeper creates a slashing keeper -func NewKeeper(cdc codec.BinaryMarshaler, key sdk.StoreKey, sk types.StakingKeeper, paramspace types.ParamSubspace) Keeper { +func NewKeeper(cdc codec.BinaryCodec, key sdk.StoreKey, sk types.StakingKeeper, paramspace types.ParamSubspace) Keeper { // set KeyTable if it has not already been set if !paramspace.HasKeyTable() { paramspace = paramspace.WithKeyTable(types.ParamKeyTable()) diff --git a/x/slashing/keeper/signing_info.go b/x/slashing/keeper/signing_info.go index 0a4473d60e62..ed15ae3e4ff3 100644 --- a/x/slashing/keeper/signing_info.go +++ b/x/slashing/keeper/signing_info.go @@ -18,7 +18,7 @@ func (k Keeper) GetValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress found = false return } - k.cdc.MustUnmarshalBinaryBare(bz, &info) + k.cdc.MustUnmarshal(bz, &info) found = true return } @@ -33,7 +33,7 @@ func (k Keeper) HasValidatorSigningInfo(ctx sdk.Context, consAddr sdk.ConsAddres // SetValidatorSigningInfo sets the validator signing info to a consensus address key func (k Keeper) SetValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress, info types.ValidatorSigningInfo) { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshalBinaryBare(&info) + bz := k.cdc.MustMarshal(&info) store.Set(types.ValidatorSigningInfoKey(address), bz) } @@ -47,7 +47,7 @@ func (k Keeper) IterateValidatorSigningInfos(ctx sdk.Context, for ; iter.Valid(); iter.Next() { address := types.ValidatorSigningInfoAddress(iter.Key()) var info types.ValidatorSigningInfo - k.cdc.MustUnmarshalBinaryBare(iter.Value(), &info) + k.cdc.MustUnmarshal(iter.Value(), &info) if handler(address, info) { break } @@ -63,7 +63,7 @@ func (k Keeper) GetValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.Con // lazy: treat empty key as not missed return false } - k.cdc.MustUnmarshalBinaryBare(bz, &missed) + k.cdc.MustUnmarshal(bz, &missed) return missed.Value } @@ -83,7 +83,7 @@ func (k Keeper) IterateValidatorMissedBlockBitArray(ctx sdk.Context, continue } - k.cdc.MustUnmarshalBinaryBare(bz, &missed) + k.cdc.MustUnmarshal(bz, &missed) if handler(index, missed.Value) { break } @@ -143,7 +143,7 @@ func (k Keeper) IsTombstoned(ctx sdk.Context, consAddr sdk.ConsAddress) bool { // missed a block in the current window func (k Keeper) SetValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.ConsAddress, index int64, missed bool) { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshalBinaryBare(&gogotypes.BoolValue{Value: missed}) + bz := k.cdc.MustMarshal(&gogotypes.BoolValue{Value: missed}) store.Set(types.ValidatorMissedBlockBitArrayKey(address, index), bz) } diff --git a/x/slashing/module.go b/x/slashing/module.go index 22a627f433b8..d837a16e5c01 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -35,7 +35,7 @@ var ( // AppModuleBasic defines the basic application module used by the slashing module. type AppModuleBasic struct { - cdc codec.Marshaler + cdc codec.Codec } var _ module.AppModuleBasic = AppModuleBasic{} @@ -57,12 +57,12 @@ func (b AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) // DefaultGenesis returns default genesis state as raw bytes for the slashing // module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the slashing module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, config client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { var data types.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -102,7 +102,7 @@ type AppModule struct { } // NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Marshaler, keeper keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper, sk stakingkeeper.Keeper) AppModule { +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper, sk stakingkeeper.Keeper) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc}, keeper: keeper, @@ -146,7 +146,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { // InitGenesis performs genesis initialization for the slashing module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.keeper, am.stakingKeeper, &genesisState) @@ -155,7 +155,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data j // ExportGenesis returns the exported genesis state as raw bytes for the slashing // module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return cdc.MustMarshalJSON(gs) } diff --git a/x/slashing/simulation/decoder.go b/x/slashing/simulation/decoder.go index 6855f6709662..6c845ace7174 100644 --- a/x/slashing/simulation/decoder.go +++ b/x/slashing/simulation/decoder.go @@ -14,19 +14,19 @@ import ( // NewDecodeStore returns a decoder function closure that unmarshals the KVPair's // Value to the corresponding slashing type. -func NewDecodeStore(cdc codec.BinaryMarshaler) func(kvA, kvB kv.Pair) string { +func NewDecodeStore(cdc codec.BinaryCodec) func(kvA, kvB kv.Pair) string { return func(kvA, kvB kv.Pair) string { switch { case bytes.Equal(kvA.Key[:1], types.ValidatorSigningInfoKeyPrefix): var infoA, infoB types.ValidatorSigningInfo - cdc.MustUnmarshalBinaryBare(kvA.Value, &infoA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &infoB) + cdc.MustUnmarshal(kvA.Value, &infoA) + cdc.MustUnmarshal(kvB.Value, &infoB) return fmt.Sprintf("%v\n%v", infoA, infoB) case bytes.Equal(kvA.Key[:1], types.ValidatorMissedBlockBitArrayKeyPrefix): var missedA, missedB gogotypes.BoolValue - cdc.MustUnmarshalBinaryBare(kvA.Value, &missedA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &missedB) + cdc.MustUnmarshal(kvA.Value, &missedA) + cdc.MustUnmarshal(kvB.Value, &missedB) return fmt.Sprintf("missedA: %v\nmissedB: %v", missedA.Value, missedB.Value) case bytes.Equal(kvA.Key[:1], types.AddrPubkeyRelationKeyPrefix): diff --git a/x/slashing/simulation/decoder_test.go b/x/slashing/simulation/decoder_test.go index 271995d9bd95..94b9f5a1c88c 100644 --- a/x/slashing/simulation/decoder_test.go +++ b/x/slashing/simulation/decoder_test.go @@ -35,8 +35,8 @@ func TestDecodeStore(t *testing.T) { kvPairs := kv.Pairs{ Pairs: []kv.Pair{ - {Key: types.ValidatorSigningInfoKey(consAddr1), Value: cdc.MustMarshalBinaryBare(&info)}, - {Key: types.ValidatorMissedBlockBitArrayKey(consAddr1, 6), Value: cdc.MustMarshalBinaryBare(&missed)}, + {Key: types.ValidatorSigningInfoKey(consAddr1), Value: cdc.MustMarshal(&info)}, + {Key: types.ValidatorMissedBlockBitArrayKey(consAddr1, 6), Value: cdc.MustMarshal(&missed)}, {Key: types.AddrPubkeyRelationKey(delAddr1), Value: bz}, {Key: []byte{0x99}, Value: []byte{0x99}}, // This test should panic }, diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 19f106ddb7ee..3b98b2af05a4 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -23,7 +23,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONMarshaler, ak types.AccountKeeper, + appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper, ) simulation.WeightedOperations { diff --git a/x/slashing/types/signing_info.go b/x/slashing/types/signing_info.go index ad359c3a5180..43a052d22f7d 100644 --- a/x/slashing/types/signing_info.go +++ b/x/slashing/types/signing_info.go @@ -39,7 +39,7 @@ func (i ValidatorSigningInfo) String() string { } // unmarshal a validator signing info from a store value -func UnmarshalValSigningInfo(cdc codec.Marshaler, value []byte) (signingInfo ValidatorSigningInfo, err error) { - err = cdc.UnmarshalBinaryBare(value, &signingInfo) +func UnmarshalValSigningInfo(cdc codec.Codec, value []byte) (signingInfo ValidatorSigningInfo, err error) { + err = cdc.Unmarshal(value, &signingInfo) return signingInfo, err } diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 283b308e767b..abeea8b181b3 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -259,7 +259,7 @@ func (k Keeper) GetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvPa } pairs := types.DVPairs{} - k.cdc.MustUnmarshalBinaryBare(bz, &pairs) + k.cdc.MustUnmarshal(bz, &pairs) return pairs.Pairs } @@ -267,7 +267,7 @@ func (k Keeper) GetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvPa // Sets a specific unbonding queue timeslice. func (k Keeper) SetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys []types.DVPair) { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshalBinaryBare(&types.DVPairs{Pairs: keys}) + bz := k.cdc.MustMarshal(&types.DVPairs{Pairs: keys}) store.Set(types.GetUnbondingDelegationTimeKey(timestamp), bz) } @@ -304,7 +304,7 @@ func (k Keeper) DequeueAllMatureUBDQueue(ctx sdk.Context, currTime time.Time) (m for ; unbondingTimesliceIterator.Valid(); unbondingTimesliceIterator.Next() { timeslice := types.DVPairs{} value := unbondingTimesliceIterator.Value() - k.cdc.MustUnmarshalBinaryBare(value, ×lice) + k.cdc.MustUnmarshal(value, ×lice) matureUnbonds = append(matureUnbonds, timeslice.Pairs...) @@ -485,7 +485,7 @@ func (k Keeper) GetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Ti } triplets := types.DVVTriplets{} - k.cdc.MustUnmarshalBinaryBare(bz, &triplets) + k.cdc.MustUnmarshal(bz, &triplets) return triplets.Triplets } @@ -493,7 +493,7 @@ func (k Keeper) GetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Ti // Sets a specific redelegation queue timeslice. func (k Keeper) SetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys []types.DVVTriplet) { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshalBinaryBare(&types.DVVTriplets{Triplets: keys}) + bz := k.cdc.MustMarshal(&types.DVVTriplets{Triplets: keys}) store.Set(types.GetRedelegationTimeKey(timestamp), bz) } @@ -532,7 +532,7 @@ func (k Keeper) DequeueAllMatureRedelegationQueue(ctx sdk.Context, currTime time for ; redelegationTimesliceIterator.Valid(); redelegationTimesliceIterator.Next() { timeslice := types.DVVTriplets{} value := redelegationTimesliceIterator.Value() - k.cdc.MustUnmarshalBinaryBare(value, ×lice) + k.cdc.MustUnmarshal(value, ×lice) matureRedelegations = append(matureRedelegations, timeslice.Triplets...) diff --git a/x/staking/keeper/historical_info.go b/x/staking/keeper/historical_info.go index f56f49eb145f..df13dff357f1 100644 --- a/x/staking/keeper/historical_info.go +++ b/x/staking/keeper/historical_info.go @@ -22,7 +22,7 @@ func (k Keeper) GetHistoricalInfo(ctx sdk.Context, height int64) (types.Historic func (k Keeper) SetHistoricalInfo(ctx sdk.Context, height int64, hi *types.HistoricalInfo) { store := ctx.KVStore(k.storeKey) key := types.GetHistoricalInfoKey(height) - value := k.cdc.MustMarshalBinaryBare(hi) + value := k.cdc.MustMarshal(hi) store.Set(key, value) } diff --git a/x/staking/keeper/keeper.go b/x/staking/keeper/keeper.go index 6335ff46a70a..6211dcf6ad94 100644 --- a/x/staking/keeper/keeper.go +++ b/x/staking/keeper/keeper.go @@ -20,7 +20,7 @@ var _ types.DelegationSet = Keeper{} // keeper of the staking store type Keeper struct { storeKey sdk.StoreKey - cdc codec.BinaryMarshaler + cdc codec.BinaryCodec authKeeper types.AccountKeeper bankKeeper types.BankKeeper hooks types.StakingHooks @@ -29,7 +29,7 @@ type Keeper struct { // NewKeeper creates a new staking Keeper instance func NewKeeper( - cdc codec.BinaryMarshaler, key sdk.StoreKey, ak types.AccountKeeper, bk types.BankKeeper, + cdc codec.BinaryCodec, key sdk.StoreKey, ak types.AccountKeeper, bk types.BankKeeper, ps paramtypes.Subspace, ) Keeper { // set KeyTable if it has not already been set @@ -82,7 +82,7 @@ func (k Keeper) GetLastTotalPower(ctx sdk.Context) sdk.Int { } ip := sdk.IntProto{} - k.cdc.MustUnmarshalBinaryBare(bz, &ip) + k.cdc.MustUnmarshal(bz, &ip) return ip.Int } @@ -90,6 +90,6 @@ func (k Keeper) GetLastTotalPower(ctx sdk.Context) sdk.Int { // Set the last total validator power. func (k Keeper) SetLastTotalPower(ctx sdk.Context, power sdk.Int) { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshalBinaryBare(&sdk.IntProto{Int: power}) + bz := k.cdc.MustMarshal(&sdk.IntProto{Int: power}) store.Set(types.LastTotalPowerKey, bz) } diff --git a/x/staking/keeper/val_state_change.go b/x/staking/keeper/val_state_change.go index c1d6c3f3d1b5..166688af5892 100644 --- a/x/staking/keeper/val_state_change.go +++ b/x/staking/keeper/val_state_change.go @@ -171,7 +171,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab } oldPowerBytes, found := last[valAddrStr] newPower := validator.ConsensusPower(powerReduction) - newPowerBytes := k.cdc.MustMarshalBinaryBare(&gogotypes.Int64Value{Value: newPower}) + newPowerBytes := k.cdc.MustMarshal(&gogotypes.Int64Value{Value: newPower}) // update the validator set if power has changed if !found || !bytes.Equal(oldPowerBytes, newPowerBytes) { diff --git a/x/staking/keeper/validator.go b/x/staking/keeper/validator.go index bab77510603f..ca6830697438 100644 --- a/x/staking/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -253,7 +253,7 @@ func (k Keeper) GetLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress) } intV := gogotypes.Int64Value{} - k.cdc.MustUnmarshalBinaryBare(bz, &intV) + k.cdc.MustUnmarshal(bz, &intV) return intV.GetValue() } @@ -261,7 +261,7 @@ func (k Keeper) GetLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress) // Set the last validator power. func (k Keeper) SetLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress, power int64) { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshalBinaryBare(&gogotypes.Int64Value{Value: power}) + bz := k.cdc.MustMarshal(&gogotypes.Int64Value{Value: power}) store.Set(types.GetLastValidatorPowerKey(operator), bz) } @@ -290,7 +290,7 @@ func (k Keeper) IterateLastValidatorPowers(ctx sdk.Context, handler func(operato addr := sdk.ValAddress(types.AddressFromLastValidatorPowerKey(iter.Key())) intV := &gogotypes.Int64Value{} - k.cdc.MustUnmarshalBinaryBare(iter.Value(), intV) + k.cdc.MustUnmarshal(iter.Value(), intV) if handler(addr, intV.GetValue()) { break @@ -337,7 +337,7 @@ func (k Keeper) GetUnbondingValidators(ctx sdk.Context, endTime time.Time, endHe } addrs := types.ValAddresses{} - k.cdc.MustUnmarshalBinaryBare(bz, &addrs) + k.cdc.MustUnmarshal(bz, &addrs) return addrs.Addresses } @@ -346,7 +346,7 @@ func (k Keeper) GetUnbondingValidators(ctx sdk.Context, endTime time.Time, endHe // the unbonding validator queue by a given height and time. func (k Keeper) SetUnbondingValidatorsQueue(ctx sdk.Context, endTime time.Time, endHeight int64, addrs []string) { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshalBinaryBare(&types.ValAddresses{Addresses: addrs}) + bz := k.cdc.MustMarshal(&types.ValAddresses{Addresses: addrs}) store.Set(types.GetValidatorQueueKey(endTime, endHeight), bz) } @@ -419,7 +419,7 @@ func (k Keeper) UnbondAllMatureValidators(ctx sdk.Context) { // and time. if keyHeight <= blockHeight && (keyTime.Before(blockTime) || keyTime.Equal(blockTime)) { addrs := types.ValAddresses{} - k.cdc.MustUnmarshalBinaryBare(unbondingValIterator.Value(), &addrs) + k.cdc.MustUnmarshal(unbondingValIterator.Value(), &addrs) for _, valAddr := range addrs.Addresses { addr, err := sdk.ValAddressFromBech32(valAddr) diff --git a/x/staking/module.go b/x/staking/module.go index 067620cc6f38..3892a8aa93ac 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -33,7 +33,7 @@ var ( // AppModuleBasic defines the basic application module used by the staking module. type AppModuleBasic struct { - cdc codec.Marshaler + cdc codec.Codec } var _ module.AppModuleBasic = AppModuleBasic{} @@ -55,12 +55,12 @@ func (b AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) // DefaultGenesis returns default genesis state as raw bytes for the staking // module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the staking module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, config client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { var data types.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -99,7 +99,7 @@ type AppModule struct { } // NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Marshaler, keeper keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper) AppModule { +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc}, keeper: keeper, @@ -145,7 +145,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { // InitGenesis performs genesis initialization for the staking module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) @@ -155,7 +155,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data j // ExportGenesis returns the exported genesis state as raw bytes for the staking // module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return cdc.MustMarshalJSON(gs) } diff --git a/x/staking/simulation/decoder.go b/x/staking/simulation/decoder.go index 696aee7d2292..eec0ce22a01a 100644 --- a/x/staking/simulation/decoder.go +++ b/x/staking/simulation/decoder.go @@ -12,21 +12,21 @@ import ( // NewDecodeStore returns a decoder function closure that unmarshals the KVPair's // Value to the corresponding staking type. -func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string { +func NewDecodeStore(cdc codec.Codec) func(kvA, kvB kv.Pair) string { return func(kvA, kvB kv.Pair) string { switch { case bytes.Equal(kvA.Key[:1], types.LastTotalPowerKey): var powerA, powerB sdk.IntProto - cdc.MustUnmarshalBinaryBare(kvA.Value, &powerA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &powerB) + cdc.MustUnmarshal(kvA.Value, &powerA) + cdc.MustUnmarshal(kvB.Value, &powerB) return fmt.Sprintf("%v\n%v", powerA, powerB) case bytes.Equal(kvA.Key[:1], types.ValidatorsKey): var validatorA, validatorB types.Validator - cdc.MustUnmarshalBinaryBare(kvA.Value, &validatorA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &validatorB) + cdc.MustUnmarshal(kvA.Value, &validatorA) + cdc.MustUnmarshal(kvB.Value, &validatorB) return fmt.Sprintf("%v\n%v", validatorA, validatorB) case bytes.Equal(kvA.Key[:1], types.LastValidatorPowerKey), @@ -37,24 +37,24 @@ func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string { case bytes.Equal(kvA.Key[:1], types.DelegationKey): var delegationA, delegationB types.Delegation - cdc.MustUnmarshalBinaryBare(kvA.Value, &delegationA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &delegationB) + cdc.MustUnmarshal(kvA.Value, &delegationA) + cdc.MustUnmarshal(kvB.Value, &delegationB) return fmt.Sprintf("%v\n%v", delegationA, delegationB) case bytes.Equal(kvA.Key[:1], types.UnbondingDelegationKey), bytes.Equal(kvA.Key[:1], types.UnbondingDelegationByValIndexKey): var ubdA, ubdB types.UnbondingDelegation - cdc.MustUnmarshalBinaryBare(kvA.Value, &ubdA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &ubdB) + cdc.MustUnmarshal(kvA.Value, &ubdA) + cdc.MustUnmarshal(kvB.Value, &ubdB) return fmt.Sprintf("%v\n%v", ubdA, ubdB) case bytes.Equal(kvA.Key[:1], types.RedelegationKey), bytes.Equal(kvA.Key[:1], types.RedelegationByValSrcIndexKey): var redA, redB types.Redelegation - cdc.MustUnmarshalBinaryBare(kvA.Value, &redA) - cdc.MustUnmarshalBinaryBare(kvB.Value, &redB) + cdc.MustUnmarshal(kvA.Value, &redA) + cdc.MustUnmarshal(kvB.Value, &redB) return fmt.Sprintf("%v\n%v", redA, redB) default: diff --git a/x/staking/simulation/decoder_test.go b/x/staking/simulation/decoder_test.go index 36b7404fb282..6584df24f508 100644 --- a/x/staking/simulation/decoder_test.go +++ b/x/staking/simulation/decoder_test.go @@ -44,12 +44,12 @@ func TestDecodeStore(t *testing.T) { kvPairs := kv.Pairs{ Pairs: []kv.Pair{ - {Key: types.LastTotalPowerKey, Value: cdc.MustMarshalBinaryBare(&sdk.IntProto{Int: sdk.OneInt()})}, - {Key: types.GetValidatorKey(valAddr1), Value: cdc.MustMarshalBinaryBare(&val)}, + {Key: types.LastTotalPowerKey, Value: cdc.MustMarshal(&sdk.IntProto{Int: sdk.OneInt()})}, + {Key: types.GetValidatorKey(valAddr1), Value: cdc.MustMarshal(&val)}, {Key: types.LastValidatorPowerKey, Value: valAddr1.Bytes()}, - {Key: types.GetDelegationKey(delAddr1, valAddr1), Value: cdc.MustMarshalBinaryBare(&del)}, - {Key: types.GetUBDKey(delAddr1, valAddr1), Value: cdc.MustMarshalBinaryBare(&ubd)}, - {Key: types.GetREDKey(delAddr1, valAddr1, valAddr1), Value: cdc.MustMarshalBinaryBare(&red)}, + {Key: types.GetDelegationKey(delAddr1, valAddr1), Value: cdc.MustMarshal(&del)}, + {Key: types.GetUBDKey(delAddr1, valAddr1), Value: cdc.MustMarshal(&ubd)}, + {Key: types.GetREDKey(delAddr1, valAddr1, valAddr1), Value: cdc.MustMarshal(&red)}, {Key: []byte{0x99}, Value: []byte{0x99}}, }, } diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index cf99446b9f3d..8af20a4c6c5e 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -26,7 +26,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONMarshaler, ak types.AccountKeeper, + appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, ) simulation.WeightedOperations { var ( diff --git a/x/staking/types/delegation.go b/x/staking/types/delegation.go index a83321597297..84951e0a34c7 100644 --- a/x/staking/types/delegation.go +++ b/x/staking/types/delegation.go @@ -38,13 +38,13 @@ func NewDelegation(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, s } // MustMarshalDelegation returns the delegation bytes. Panics if fails -func MustMarshalDelegation(cdc codec.BinaryMarshaler, delegation Delegation) []byte { - return cdc.MustMarshalBinaryBare(&delegation) +func MustMarshalDelegation(cdc codec.BinaryCodec, delegation Delegation) []byte { + return cdc.MustMarshal(&delegation) } // MustUnmarshalDelegation return the unmarshaled delegation from bytes. // Panics if fails. -func MustUnmarshalDelegation(cdc codec.BinaryMarshaler, value []byte) Delegation { +func MustUnmarshalDelegation(cdc codec.BinaryCodec, value []byte) Delegation { delegation, err := UnmarshalDelegation(cdc, value) if err != nil { panic(err) @@ -54,8 +54,8 @@ func MustUnmarshalDelegation(cdc codec.BinaryMarshaler, value []byte) Delegation } // return the delegation -func UnmarshalDelegation(cdc codec.BinaryMarshaler, value []byte) (delegation Delegation, err error) { - err = cdc.UnmarshalBinaryBare(value, &delegation) +func UnmarshalDelegation(cdc codec.BinaryCodec, value []byte) (delegation Delegation, err error) { + err = cdc.Unmarshal(value, &delegation) return delegation, err } @@ -139,12 +139,12 @@ func (ubd *UnbondingDelegation) RemoveEntry(i int64) { } // return the unbonding delegation -func MustMarshalUBD(cdc codec.BinaryMarshaler, ubd UnbondingDelegation) []byte { - return cdc.MustMarshalBinaryBare(&ubd) +func MustMarshalUBD(cdc codec.BinaryCodec, ubd UnbondingDelegation) []byte { + return cdc.MustMarshal(&ubd) } // unmarshal a unbonding delegation from a store value -func MustUnmarshalUBD(cdc codec.BinaryMarshaler, value []byte) UnbondingDelegation { +func MustUnmarshalUBD(cdc codec.BinaryCodec, value []byte) UnbondingDelegation { ubd, err := UnmarshalUBD(cdc, value) if err != nil { panic(err) @@ -154,8 +154,8 @@ func MustUnmarshalUBD(cdc codec.BinaryMarshaler, value []byte) UnbondingDelegati } // unmarshal a unbonding delegation from a store value -func UnmarshalUBD(cdc codec.BinaryMarshaler, value []byte) (ubd UnbondingDelegation, err error) { - err = cdc.UnmarshalBinaryBare(value, &ubd) +func UnmarshalUBD(cdc codec.BinaryCodec, value []byte) (ubd UnbondingDelegation, err error) { + err = cdc.Unmarshal(value, &ubd) return ubd, err } @@ -234,12 +234,12 @@ func (red *Redelegation) RemoveEntry(i int64) { } // MustMarshalRED returns the Redelegation bytes. Panics if fails. -func MustMarshalRED(cdc codec.BinaryMarshaler, red Redelegation) []byte { - return cdc.MustMarshalBinaryBare(&red) +func MustMarshalRED(cdc codec.BinaryCodec, red Redelegation) []byte { + return cdc.MustMarshal(&red) } // MustUnmarshalRED unmarshals a redelegation from a store value. Panics if fails. -func MustUnmarshalRED(cdc codec.BinaryMarshaler, value []byte) Redelegation { +func MustUnmarshalRED(cdc codec.BinaryCodec, value []byte) Redelegation { red, err := UnmarshalRED(cdc, value) if err != nil { panic(err) @@ -249,8 +249,8 @@ func MustUnmarshalRED(cdc codec.BinaryMarshaler, value []byte) Redelegation { } // UnmarshalRED unmarshals a redelegation from a store value -func UnmarshalRED(cdc codec.BinaryMarshaler, value []byte) (red Redelegation, err error) { - err = cdc.UnmarshalBinaryBare(value, &red) +func UnmarshalRED(cdc codec.BinaryCodec, value []byte) (red Redelegation, err error) { + err = cdc.Unmarshal(value, &red) return red, err } diff --git a/x/staking/types/genesis.go b/x/staking/types/genesis.go index a0a510f6b467..a3355a1d29c5 100644 --- a/x/staking/types/genesis.go +++ b/x/staking/types/genesis.go @@ -25,7 +25,7 @@ func DefaultGenesisState() *GenesisState { // GetGenesisStateFromAppState returns x/staking GenesisState given raw application // genesis state. -func GetGenesisStateFromAppState(cdc codec.JSONMarshaler, appState map[string]json.RawMessage) *GenesisState { +func GetGenesisStateFromAppState(cdc codec.JSONCodec, appState map[string]json.RawMessage) *GenesisState { var genesisState GenesisState if appState[ModuleName] != nil { diff --git a/x/staking/types/historical_info.go b/x/staking/types/historical_info.go index 6e474bb0c673..447a559bda7b 100644 --- a/x/staking/types/historical_info.go +++ b/x/staking/types/historical_info.go @@ -27,7 +27,7 @@ func NewHistoricalInfo(header tmproto.Header, valSet Validators, powerReduction } // MustUnmarshalHistoricalInfo wll unmarshal historical info and panic on error -func MustUnmarshalHistoricalInfo(cdc codec.BinaryMarshaler, value []byte) HistoricalInfo { +func MustUnmarshalHistoricalInfo(cdc codec.BinaryCodec, value []byte) HistoricalInfo { hi, err := UnmarshalHistoricalInfo(cdc, value) if err != nil { panic(err) @@ -37,8 +37,8 @@ func MustUnmarshalHistoricalInfo(cdc codec.BinaryMarshaler, value []byte) Histor } // UnmarshalHistoricalInfo will unmarshal historical info and return any error -func UnmarshalHistoricalInfo(cdc codec.BinaryMarshaler, value []byte) (hi HistoricalInfo, err error) { - err = cdc.UnmarshalBinaryBare(value, &hi) +func UnmarshalHistoricalInfo(cdc codec.BinaryCodec, value []byte) (hi HistoricalInfo, err error) { + err = cdc.Unmarshal(value, &hi) return hi, err } diff --git a/x/staking/types/historical_info_test.go b/x/staking/types/historical_info_test.go index b465a3db6ae5..45305de91c56 100644 --- a/x/staking/types/historical_info_test.go +++ b/x/staking/types/historical_info_test.go @@ -32,7 +32,7 @@ func TestHistoricalInfo(t *testing.T) { var value []byte require.NotPanics(t, func() { - value = types.ModuleCdc.MustMarshalBinaryBare(&hi) + value = types.ModuleCdc.MustMarshal(&hi) }) require.NotNil(t, value, "Marshalled HistoricalInfo is nil") diff --git a/x/staking/types/params.go b/x/staking/types/params.go index 1f5e81b44e05..1b5a4f1949b4 100644 --- a/x/staking/types/params.go +++ b/x/staking/types/params.go @@ -102,7 +102,7 @@ func MustUnmarshalParams(cdc *codec.LegacyAmino, value []byte) Params { // unmarshal the current staking params value from store key func UnmarshalParams(cdc *codec.LegacyAmino, value []byte) (params Params, err error) { - err = cdc.UnmarshalBinaryBare(value, ¶ms) + err = cdc.Unmarshal(value, ¶ms) if err != nil { return } diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index 73290966d1a2..ed394acf4969 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -142,12 +142,12 @@ func (v Validators) UnpackInterfaces(c codectypes.AnyUnpacker) error { } // return the redelegation -func MustMarshalValidator(cdc codec.BinaryMarshaler, validator *Validator) []byte { - return cdc.MustMarshalBinaryBare(validator) +func MustMarshalValidator(cdc codec.BinaryCodec, validator *Validator) []byte { + return cdc.MustMarshal(validator) } // unmarshal a redelegation from a store value -func MustUnmarshalValidator(cdc codec.BinaryMarshaler, value []byte) Validator { +func MustUnmarshalValidator(cdc codec.BinaryCodec, value []byte) Validator { validator, err := UnmarshalValidator(cdc, value) if err != nil { panic(err) @@ -157,8 +157,8 @@ func MustUnmarshalValidator(cdc codec.BinaryMarshaler, value []byte) Validator { } // unmarshal a redelegation from a store value -func UnmarshalValidator(cdc codec.BinaryMarshaler, value []byte) (v Validator, err error) { - err = cdc.UnmarshalBinaryBare(value, &v) +func UnmarshalValidator(cdc codec.BinaryCodec, value []byte) (v Validator, err error) { + err = cdc.Unmarshal(value, &v) return v, err } diff --git a/x/upgrade/keeper/keeper.go b/x/upgrade/keeper/keeper.go index 8f32277b803c..fe5c2cb98923 100644 --- a/x/upgrade/keeper/keeper.go +++ b/x/upgrade/keeper/keeper.go @@ -28,7 +28,7 @@ type Keeper struct { homePath string // root directory of app config skipUpgradeHeights map[int64]bool // map of heights to skip for an upgrade storeKey sdk.StoreKey // key to access x/upgrade store - cdc codec.BinaryMarshaler // App-wide binary codec + cdc codec.BinaryCodec // App-wide binary codec upgradeHandlers map[string]types.UpgradeHandler // map of plan name to upgrade handler versionSetter xp.ProtocolVersionSetter // implements setting the protocol version field on BaseApp } @@ -39,7 +39,7 @@ type Keeper struct { // cdc - the app-wide binary codec // homePath - root directory of the application's config // vs - the interface implemented by baseapp which allows setting baseapp's protocol version field -func NewKeeper(skipUpgradeHeights map[int64]bool, storeKey sdk.StoreKey, cdc codec.BinaryMarshaler, homePath string, vs xp.ProtocolVersionSetter) Keeper { +func NewKeeper(skipUpgradeHeights map[int64]bool, storeKey sdk.StoreKey, cdc codec.BinaryCodec, homePath string, vs xp.ProtocolVersionSetter) Keeper { return Keeper{ homePath: homePath, skipUpgradeHeights: skipUpgradeHeights, @@ -138,7 +138,7 @@ func (k Keeper) ScheduleUpgrade(ctx sdk.Context, plan types.Plan) error { k.ClearIBCState(ctx, oldPlan.Height) } - bz := k.cdc.MustMarshalBinaryBare(&plan) + bz := k.cdc.MustMarshal(&plan) store.Set(types.PlanKey(), bz) return nil @@ -226,7 +226,7 @@ func (k Keeper) GetUpgradePlan(ctx sdk.Context) (plan types.Plan, havePlan bool) return plan, false } - k.cdc.MustUnmarshalBinaryBare(bz, &plan) + k.cdc.MustUnmarshal(bz, &plan) return plan, true } diff --git a/x/upgrade/module.go b/x/upgrade/module.go index 23311c22d5f3..b80b56f92a1f 100644 --- a/x/upgrade/module.go +++ b/x/upgrade/module.go @@ -101,22 +101,22 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { } // InitGenesis is ignored, no sense in serializing future upgrades -func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONMarshaler, _ json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } // DefaultGenesis is an empty object -func (AppModuleBasic) DefaultGenesis(_ codec.JSONMarshaler) json.RawMessage { +func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { return []byte("{}") } // ValidateGenesis is always successful, as we ignore the value -func (AppModuleBasic) ValidateGenesis(_ codec.JSONMarshaler, config client.TxEncodingConfig, _ json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, config client.TxEncodingConfig, _ json.RawMessage) error { return nil } // ExportGenesis is always empty, as InitGenesis does nothing either -func (am AppModule) ExportGenesis(_ sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { +func (am AppModule) ExportGenesis(_ sdk.Context, cdc codec.JSONCodec) json.RawMessage { return am.DefaultGenesis(cdc) } diff --git a/x/upgrade/types/proposal_test.go b/x/upgrade/types/proposal_test.go index 19c5321ce7e3..716e201091bd 100644 --- a/x/upgrade/types/proposal_test.go +++ b/x/upgrade/types/proposal_test.go @@ -59,10 +59,10 @@ func TestContentAccessors(t *testing.T) { // try to encode and decode type to ensure codec works wrap := ProposalWrapper{tc.p} - bz, err := cdc.MarshalBinaryBare(&wrap) + bz, err := cdc.Marshal(&wrap) require.NoError(t, err) unwrap := ProposalWrapper{} - err = cdc.UnmarshalBinaryBare(bz, &unwrap) + err = cdc.Unmarshal(bz, &unwrap) require.NoError(t, err) // all methods should look the same