From 92c9a77fb8b076feb068223bfbeb8a58a5ab3ddf Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 10 Jun 2020 14:12:01 -0400 Subject: [PATCH 01/26] Migrate encode, decode, and broadcast cmd's to use TxGenerator marshal methods --- client/tx/tx.go | 4 ++-- client/tx_generator.go | 6 +++++- simapp/cmd/simcli/main.go | 12 ++++++------ x/auth/client/cli/broadcast.go | 9 ++++----- x/auth/client/cli/decode.go | 19 ++++++++----------- x/auth/client/cli/encode.go | 11 +++++------ x/auth/client/cli/tx.go | 11 +++++------ x/auth/client/cli/tx_multisign.go | 12 +++++++----- x/auth/client/cli/tx_sign.go | 11 ++++++----- x/auth/client/cli/validate_sigs.go | 18 +++++++++--------- x/auth/client/tx.go | 8 ++------ x/auth/module.go | 2 +- x/auth/types/client_tx.go | 18 ++++++++++++++++-- x/auth/types/stdtx.go | 19 +++++++++++++++++++ 14 files changed, 95 insertions(+), 65 deletions(-) diff --git a/client/tx/tx.go b/client/tx/tx.go index 234f5e986be8..724d739b6517 100644 --- a/client/tx/tx.go +++ b/client/tx/tx.go @@ -248,7 +248,7 @@ func BuildSimTx(txf Factory, msgs ...sdk.Msg) ([]byte, error) { return nil, err } - return txf.txGenerator.MarshalTx(tx.GetTx()) + return txf.txGenerator.TxEncoder()(tx.GetTx()) } // CalculateGas simulates the execution of a transaction and returns the @@ -338,7 +338,7 @@ func Sign(txf Factory, name, passphrase string, tx client.TxBuilder) ([]byte, er return nil, err } - return txf.txGenerator.MarshalTx(tx.GetTx()) + return txf.txGenerator.TxEncoder()(tx.GetTx()) } // GasEstimateResponse defines a response definition for tx gas estimation. diff --git a/client/tx_generator.go b/client/tx_generator.go index f840bd39e922..9a252e78649e 100644 --- a/client/tx_generator.go +++ b/client/tx_generator.go @@ -14,7 +14,11 @@ type ( NewTx() TxBuilder NewFee() Fee NewSignature() Signature - MarshalTx(tx types.Tx) ([]byte, error) + + TxEncoder() types.TxEncoder + TxDecoder() types.TxDecoder + TxJSONEncoder() types.TxEncoder + TxJSONDecoder() types.TxDecoder } Fee interface { diff --git a/simapp/cmd/simcli/main.go b/simapp/cmd/simcli/main.go index ee849b9189f3..a1fd5d7e8dff 100644 --- a/simapp/cmd/simcli/main.go +++ b/simapp/cmd/simcli/main.go @@ -131,14 +131,14 @@ func txCmd(cdc *codec.Codec) *cobra.Command { txCmd.AddCommand( bankcmd.NewSendTxCmd(clientCtx), flags.LineBreak, - authcmd.GetSignCommand(cdc), + authcmd.GetSignCommand(clientCtx), authcmd.GetSignBatchCommand(cdc), - authcmd.GetMultiSignCommand(cdc), - authcmd.GetValidateSignaturesCommand(cdc), + authcmd.GetMultiSignCommand(clientCtx), + authcmd.GetValidateSignaturesCommand(clientCtx), flags.LineBreak, - authcmd.GetBroadcastCommand(cdc), - authcmd.GetEncodeCommand(cdc), - authcmd.GetDecodeCommand(cdc), + authcmd.GetBroadcastCommand(clientCtx), + authcmd.GetEncodeCommand(clientCtx), + authcmd.GetDecodeCommand(clientCtx), flags.LineBreak, ) diff --git a/x/auth/client/cli/broadcast.go b/x/auth/client/cli/broadcast.go index 9e24d63e5a38..0802219867ad 100644 --- a/x/auth/client/cli/broadcast.go +++ b/x/auth/client/cli/broadcast.go @@ -8,12 +8,11 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" ) // GetBroadcastCommand returns the tx broadcast command. -func GetBroadcastCommand(cdc *codec.Codec) *cobra.Command { +func GetBroadcastCommand(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "broadcast [file_path]", Short: "Broadcast transactions generated offline", @@ -26,18 +25,18 @@ $ tx broadcast ./mytxn.json `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - clientCtx := client.NewContext().WithCodec(cdc) + clientCtx = clientCtx.Init() if clientCtx.Offline { return errors.New("cannot broadcast tx during offline mode") } - stdTx, err := authclient.ReadStdTxFromFile(clientCtx.Codec, args[0]) + stdTx, err := authclient.ReadTxFromFile(clientCtx, args[0]) if err != nil { return err } - txBytes, err := clientCtx.Codec.MarshalBinaryBare(stdTx) + txBytes, err := clientCtx.TxGenerator.TxEncoder()(stdTx) if err != nil { return err } diff --git a/x/auth/client/cli/decode.go b/x/auth/client/cli/decode.go index efd124921b52..2fde4790a39c 100644 --- a/x/auth/client/cli/decode.go +++ b/x/auth/client/cli/decode.go @@ -9,29 +9,27 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) const flagHex = "hex" -// GetDecodeCommand returns the decode command to take Amino-serialized bytes +// GetDecodeCommand returns the decode command to take serialized bytes // and turn it into a JSONified transaction. -func GetDecodeCommand(codec *codec.Codec) *cobra.Command { +func GetDecodeCommand(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "decode [amino-byte-string]", - Short: "Decode an amino-encoded transaction string.", + Short: "Decode an binary encoded transaction string.", Args: cobra.ExactArgs(1), - RunE: runDecodeTxString(codec), + RunE: runDecodeTxString(clientCtx), } cmd.Flags().BoolP(flagHex, "x", false, "Treat input as hexadecimal instead of base64") return flags.PostCommands(cmd)[0] } -func runDecodeTxString(codec *codec.Codec) func(cmd *cobra.Command, args []string) (err error) { +func runDecodeTxString(clientCtx client.Context) func(cmd *cobra.Command, args []string) (err error) { return func(cmd *cobra.Command, args []string) (err error) { - clientCtx := client.NewContext().WithCodec(codec).WithOutput(cmd.OutOrStdout()) + clientCtx = clientCtx.Init().WithOutput(cmd.OutOrStdout()) var txBytes []byte if viper.GetBool(flagHex) { @@ -43,12 +41,11 @@ func runDecodeTxString(codec *codec.Codec) func(cmd *cobra.Command, args []strin return err } - var stdTx authtypes.StdTx - err = clientCtx.Codec.UnmarshalBinaryBare(txBytes, &stdTx) + tx, err := clientCtx.TxGenerator.TxDecoder()(txBytes) if err != nil { return err } - return clientCtx.PrintOutput(stdTx) + return clientCtx.PrintOutput(tx) } } diff --git a/x/auth/client/cli/encode.go b/x/auth/client/cli/encode.go index c97533c859ef..653f8b389a1a 100644 --- a/x/auth/client/cli/encode.go +++ b/x/auth/client/cli/encode.go @@ -7,7 +7,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" ) @@ -20,7 +19,7 @@ func (txr txEncodeRespStr) String() string { // GetEncodeCommand returns the encode command to take a JSONified transaction and turn it into // Amino-serialized bytes -func GetEncodeCommand(cdc *codec.Codec) *cobra.Command { +func GetEncodeCommand(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "encode [file]", Short: "Encode transactions generated offline", @@ -29,15 +28,15 @@ Read a transaction from , serialize it to the Amino wire protocol, and out If you supply a dash (-) argument in place of an input filename, the command reads from standard input.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) (err error) { - clientCtx := client.NewContext().WithCodec(cdc) + cliCtx := clientCtx.Init() - stdTx, err := authclient.ReadStdTxFromFile(clientCtx.Codec, args[0]) + tx, err := authclient.ReadTxFromFile(cliCtx, args[0]) if err != nil { return } - // re-encode it via the Amino wire protocol - txBytes, err := clientCtx.Codec.MarshalBinaryBare(stdTx) + // re-encode it + txBytes, err := cliCtx.TxGenerator.TxEncoder()(tx) if err != nil { return err } diff --git a/x/auth/client/cli/tx.go b/x/auth/client/cli/tx.go index 132d61ed3080..9bc30f396ec0 100644 --- a/x/auth/client/cli/tx.go +++ b/x/auth/client/cli/tx.go @@ -4,12 +4,11 @@ import ( "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/auth/types" ) // GetTxCmd returns the transaction commands for this module -func GetTxCmd(cdc *codec.Codec) *cobra.Command { +func GetTxCmd(clientCtx client.Context) *cobra.Command { txCmd := &cobra.Command{ Use: types.ModuleName, Short: "Auth transaction subcommands", @@ -18,10 +17,10 @@ func GetTxCmd(cdc *codec.Codec) *cobra.Command { RunE: client.ValidateCmd, } txCmd.AddCommand( - GetMultiSignCommand(cdc), - GetSignCommand(cdc), - GetValidateSignaturesCommand(cdc), - GetSignBatchCommand(cdc), + GetMultiSignCommand(clientCtx), + GetSignCommand(clientCtx), + GetValidateSignaturesCommand(clientCtx), + GetSignBatchCommand(clientCtx.Codec), ) return txCmd } diff --git a/x/auth/client/cli/tx_multisign.go b/x/auth/client/cli/tx_multisign.go index 58002e4a1244..c4a3459715ee 100644 --- a/x/auth/client/cli/tx_multisign.go +++ b/x/auth/client/cli/tx_multisign.go @@ -22,7 +22,7 @@ import ( ) // GetSignCommand returns the sign command -func GetMultiSignCommand(cdc *codec.Codec) *cobra.Command { +func GetMultiSignCommand(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "multisign [file] [name] [[signature]...]", Short: "Generate multisig signatures for transactions generated offline", @@ -45,7 +45,7 @@ recommended to set such parameters manually. version.ClientName, ), ), - RunE: makeMultiSignCmd(cdc), + RunE: makeMultiSignCmd(clientCtx), Args: cobra.MinimumNArgs(3), } @@ -56,9 +56,12 @@ recommended to set such parameters manually. return flags.PostCommands(cmd)[0] } -func makeMultiSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { +func makeMultiSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) (err error) { - stdTx, err := authclient.ReadStdTxFromFile(cdc, args[0]) + clientCtx = clientCtx.Init() + cdc := clientCtx.Codec + tx, err := authclient.ReadTxFromFile(clientCtx, args[0]) + stdTx := tx.(types.StdTx) if err != nil { return } @@ -80,7 +83,6 @@ func makeMultiSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) multisigPub := multisigInfo.GetPubKey().(multisig.PubKeyMultisigThreshold) multisigSig := multisig.NewMultisig(len(multisigPub.PubKeys)) - clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) txBldr := types.NewTxBuilderFromCLI(inBuf) if !clientCtx.Offline { diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index dbeabf05600a..43341469e2ef 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -150,7 +150,7 @@ func setOutputFile(cmd *cobra.Command) (func(), error) { } // GetSignCommand returns the transaction sign command. -func GetSignCommand(codec *codec.Codec) *cobra.Command { +func GetSignCommand(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "sign [file]", Short: "Sign transactions generated offline", @@ -170,7 +170,7 @@ key. It implies --signature-only. Full multisig signed transactions may eventual be generated via the 'multisign' command. `, PreRun: preSignCmd, - RunE: makeSignCmd(codec), + RunE: makeSignCmd(clientCtx), Args: cobra.ExactArgs(1), } @@ -199,12 +199,13 @@ func preSignCmd(cmd *cobra.Command, _ []string) { } } -func makeSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { +func makeSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { - clientCtx, txBldr, stdTx, err := readStdTxAndInitContexts(cdc, cmd, args[0]) + clientCtx, txBldr, tx, err := readStdTxAndInitContexts(clientCtx, cmd, args[0]) if err != nil { return err } + stdTx := tx.(types.StdTx) // if --signature-only is on, then override --append var newTx types.StdTx @@ -231,7 +232,7 @@ func makeSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error return err } - json, err := getSignatureJSON(cdc, newTx, clientCtx.Indent, generateSignatureOnly) + json, err := getSignatureJSON(clientCtx.Codec, newTx, clientCtx.Indent, generateSignatureOnly) if err != nil { return err } diff --git a/x/auth/client/cli/validate_sigs.go b/x/auth/client/cli/validate_sigs.go index 7782021a78bf..1118e57130e1 100644 --- a/x/auth/client/cli/validate_sigs.go +++ b/x/auth/client/cli/validate_sigs.go @@ -9,14 +9,13 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdk "github.com/cosmos/cosmos-sdk/types" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" "github.com/cosmos/cosmos-sdk/x/auth/types" ) -func GetValidateSignaturesCommand(codec *codec.Codec) *cobra.Command { +func GetValidateSignaturesCommand(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "validate-signatures [file]", Short: "Validate transactions signatures", @@ -29,19 +28,20 @@ given transaction. If the --offline flag is also set, signature validation over transaction will be not be performed as that will require RPC communication with a full node. `, PreRun: preSignCmd, - RunE: makeValidateSignaturesCmd(codec), + RunE: makeValidateSignaturesCmd(clientCtx), Args: cobra.ExactArgs(1), } return flags.PostCommands(cmd)[0] } -func makeValidateSignaturesCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { +func makeValidateSignaturesCmd(clientCtx client.Context) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { - clientCtx, txBldr, stdTx, err := readStdTxAndInitContexts(cdc, cmd, args[0]) + clientCtx, txBldr, tx, err := readStdTxAndInitContexts(clientCtx, cmd, args[0]) if err != nil { return err } + stdTx := tx.(types.StdTx) if !printAndValidateSigs(cmd, clientCtx, txBldr.ChainID(), stdTx, clientCtx.Offline) { return fmt.Errorf("signatures validation failed") @@ -133,16 +133,16 @@ func printAndValidateSigs( return success } -func readStdTxAndInitContexts(cdc *codec.Codec, cmd *cobra.Command, filename string) ( - client.Context, types.TxBuilder, types.StdTx, error, +func readStdTxAndInitContexts(clientCtx client.Context, cmd *cobra.Command, filename string) ( + client.Context, types.TxBuilder, sdk.Tx, error, ) { - stdTx, err := authclient.ReadStdTxFromFile(cdc, filename) + stdTx, err := authclient.ReadTxFromFile(clientCtx, filename) if err != nil { return client.Context{}, types.TxBuilder{}, types.StdTx{}, err } inBuf := bufio.NewReader(cmd.InOrStdin()) - clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) + clientCtx = clientCtx.InitWithInput(inBuf) txBldr := types.NewTxBuilderFromCLI(inBuf) return clientCtx, txBldr, stdTx, nil diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index d8dfb531b051..7f64f2e5aa96 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -231,7 +231,7 @@ func SignStdTxWithSignerAddress( } // Read and decode a StdTx from the given filename. Can pass "-" to read from stdin. -func ReadStdTxFromFile(cdc *codec.Codec, filename string) (stdTx authtypes.StdTx, err error) { +func ReadTxFromFile(ctx client.Context, filename string) (tx sdk.Tx, err error) { var bytes []byte if filename == "-" { @@ -244,11 +244,7 @@ func ReadStdTxFromFile(cdc *codec.Codec, filename string) (stdTx authtypes.StdTx return } - if err = cdc.UnmarshalJSON(bytes, &stdTx); err != nil { - return - } - - return + return ctx.TxGenerator.TxJSONDecoder()(bytes) } // NewBatchScanner returns a new BatchScanner to read newline-delimited StdTx transactions from r. diff --git a/x/auth/module.go b/x/auth/module.go index 291654a114a3..17a4727069e1 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -66,7 +66,7 @@ func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Rout // GetTxCmd returns the root tx command for the auth module. func (AppModuleBasic) GetTxCmd(clientCtx client.Context) *cobra.Command { - return cli.GetTxCmd(clientCtx.Codec) + return cli.GetTxCmd(clientCtx) } // GetQueryCmd returns the root query command for the auth module. diff --git a/x/auth/types/client_tx.go b/x/auth/types/client_tx.go index 0dcbe3ffc7d2..a1d132bbe16e 100644 --- a/x/auth/types/client_tx.go +++ b/x/auth/types/client_tx.go @@ -97,8 +97,22 @@ func (s StdTxGenerator) NewSignature() client.Signature { } // MarshalTx implements TxGenerator.MarshalTx -func (s StdTxGenerator) MarshalTx(tx sdk.Tx) ([]byte, error) { - return DefaultTxEncoder(s.Cdc)(tx) +func (s StdTxGenerator) TxEncoder() sdk.TxEncoder { + return DefaultTxEncoder(s.Cdc) +} + +func (s StdTxGenerator) TxDecoder() sdk.TxDecoder { + return DefaultTxDecoder(s.Cdc) +} + +func (s StdTxGenerator) TxJSONEncoder() sdk.TxEncoder { + return func(tx sdk.Tx) ([]byte, error) { + return s.Cdc.MarshalJSON(tx) + } +} + +func (s StdTxGenerator) TxJSONDecoder() sdk.TxDecoder { + return DefaultJSONTxDecoder(s.Cdc) } var _ client.Fee = &StdFee{} diff --git a/x/auth/types/stdtx.go b/x/auth/types/stdtx.go index 6b6f8ac51030..be373df2dcd5 100644 --- a/x/auth/types/stdtx.go +++ b/x/auth/types/stdtx.go @@ -338,6 +338,25 @@ func DefaultTxDecoder(cdc *codec.Codec) sdk.TxDecoder { } } +func DefaultJSONTxDecoder(cdc *codec.Codec) sdk.TxDecoder { + return func(txBytes []byte) (sdk.Tx, error) { + var tx = StdTx{} + + if len(txBytes) == 0 { + return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "tx bytes are empty") + } + + // StdTx.Msg is an interface. The concrete types + // are registered by MakeTxCodec + err := cdc.UnmarshalJSON(txBytes, &tx) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error()) + } + + return tx, nil + } +} + // DefaultTxEncoder logic for standard transaction encoding func DefaultTxEncoder(cdc *codec.Codec) sdk.TxEncoder { return func(tx sdk.Tx) ([]byte, error) { From fed32e2f1302f210abc7c924f5a892eeaf9d9016 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 10 Jun 2020 15:10:57 -0400 Subject: [PATCH 02/26] Fix tests, add EncodingConfig --- simapp/params/amino.go | 20 ++++++++++++++++++++ simapp/params/encoding.go | 14 ++++++++++++++ x/auth/client/cli/broadcast_test.go | 14 +++++++++----- x/auth/client/tx_test.go | 20 +++++++++++++++----- 4 files changed, 58 insertions(+), 10 deletions(-) create mode 100644 simapp/params/amino.go create mode 100644 simapp/params/encoding.go diff --git a/simapp/params/amino.go b/simapp/params/amino.go new file mode 100644 index 000000000000..81233bc8fac2 --- /dev/null +++ b/simapp/params/amino.go @@ -0,0 +1,20 @@ +package params + +import ( + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +func MakeEncodingConfig() EncodingConfig { + cdc := codec.New() + interfaceRegistry := types.NewInterfaceRegistry() + marshaler := codec.NewHybridCodec(cdc, interfaceRegistry) + + return EncodingConfig{ + InterfaceRegistry: interfaceRegistry, + Marshaler: marshaler, + TxGenerator: authtypes.StdTxGenerator{Cdc: cdc}, + Amino: cdc, + } +} diff --git a/simapp/params/encoding.go b/simapp/params/encoding.go new file mode 100644 index 000000000000..040e06ddb247 --- /dev/null +++ b/simapp/params/encoding.go @@ -0,0 +1,14 @@ +package params + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" +) + +type EncodingConfig struct { + InterfaceRegistry types.InterfaceRegistry + Marshaler codec.Marshaler + TxGenerator client.TxGenerator + Amino *codec.Codec +} diff --git a/x/auth/client/cli/broadcast_test.go b/x/auth/client/cli/broadcast_test.go index 11d41df89e51..2aa881bb0bcc 100644 --- a/x/auth/client/cli/broadcast_test.go +++ b/x/auth/client/cli/broadcast_test.go @@ -5,17 +5,20 @@ import ( "path/filepath" "testing" + "github.com/cosmos/cosmos-sdk/client" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + "github.com/spf13/viper" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/tests" ) func TestGetBroadcastCommand_OfflineFlag(t *testing.T) { - cdc := codec.New() - cmd := GetBroadcastCommand(cdc) + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + cmd := GetBroadcastCommand(clientCtx) viper.Set(flags.FlagOffline, true) @@ -24,8 +27,9 @@ func TestGetBroadcastCommand_OfflineFlag(t *testing.T) { } func TestGetBroadcastCommand_WithoutOfflineFlag(t *testing.T) { - cdc := codec.New() - cmd := GetBroadcastCommand(cdc) + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + cmd := GetBroadcastCommand(clientCtx) viper.Set(flags.FlagOffline, false) diff --git a/x/auth/client/tx_test.go b/x/auth/client/tx_test.go index 3e4bd6adec79..f979349317c0 100644 --- a/x/auth/client/tx_test.go +++ b/x/auth/client/tx_test.go @@ -8,6 +8,10 @@ import ( "strings" "testing" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto/ed25519" @@ -118,22 +122,28 @@ func TestConfiguredTxEncoder(t *testing.T) { func TestReadStdTxFromFile(t *testing.T) { t.Parallel() - cdc := codec.New() - sdk.RegisterCodec(cdc) + + encodingConfig := simappparams.MakeEncodingConfig() + sdk.RegisterCodec(encodingConfig.Amino) + + txGen := encodingConfig.TxGenerator + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(txGen) // Build a test transaction fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") // Write it to the file - encodedTx, _ := cdc.MarshalJSON(stdTx) + encodedTx, err := txGen.TxJSONEncoder()(stdTx) + require.NoError(t, err) jsonTxFile := writeToNewTempFile(t, string(encodedTx)) defer os.Remove(jsonTxFile.Name()) // Read it back - decodedTx, err := ReadStdTxFromFile(cdc, jsonTxFile.Name()) + decodedTx, err := ReadTxFromFile(clientCtx, jsonTxFile.Name()) require.NoError(t, err) - require.Equal(t, decodedTx.Memo, "foomemo") + require.Equal(t, decodedTx.(authtypes.StdTx).Memo, "foomemo") } func TestBatchScanner_Scan(t *testing.T) { From 826785e1b7c98facd480c50b39694c3a351241ec Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 10 Jun 2020 15:26:43 -0400 Subject: [PATCH 03/26] Add simapp/encoding.go and wire up with simcli --- simapp/app.go | 15 +++++---------- simapp/cmd/simcli/main.go | 28 ++++++++++++++++------------ simapp/encoding.go | 15 +++++++++++++++ simapp/params/amino.go | 2 ++ std/codec.go | 24 ++++++------------------ 5 files changed, 44 insertions(+), 40 deletions(-) create mode 100644 simapp/encoding.go diff --git a/simapp/app.go b/simapp/app.go index 7835fa284368..2aaa5802be68 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -12,7 +12,6 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/testdata" - "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/std" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -97,7 +96,7 @@ var _ App = (*SimApp)(nil) type SimApp struct { *baseapp.BaseApp cdc *codec.Codec - appCodec *std.Codec + appCodec codec.Marshaler invCheckPeriod uint @@ -368,13 +367,9 @@ func NewSimApp( // MakeCodecs constructs the *std.Codec and *codec.Codec instances used by // simapp. It is useful for tests and clients who do not want to construct the // full simapp -func MakeCodecs() (*std.Codec, *codec.Codec) { - cdc := std.MakeCodec(ModuleBasics) - interfaceRegistry := types.NewInterfaceRegistry() - std.RegisterInterfaces(interfaceRegistry) - ModuleBasics.RegisterInterfaceModules(interfaceRegistry) - appCodec := std.NewAppCodec(cdc, interfaceRegistry) - return appCodec, cdc +func MakeCodecs() (codec.Marshaler, *codec.Codec) { + config := MakeEncodingConfig() + return config.Marshaler, config.Amino } // Name returns the name of the App @@ -434,7 +429,7 @@ func (app *SimApp) Codec() *codec.Codec { // // NOTE: This is solely to be used for testing purposes as it may be desirable // for modules to register their own custom testing types. -func (app *SimApp) AppCodec() *std.Codec { +func (app *SimApp) AppCodec() codec.Marshaler { return app.appCodec } diff --git a/simapp/cmd/simcli/main.go b/simapp/cmd/simcli/main.go index a1fd5d7e8dff..c0ba7cd92338 100644 --- a/simapp/cmd/simcli/main.go +++ b/simapp/cmd/simcli/main.go @@ -5,6 +5,8 @@ import ( "os" "path" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/tendermint/tendermint/libs/cli" @@ -14,7 +16,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/lcd" "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" @@ -25,11 +26,11 @@ import ( ) var ( - appCodec, cdc = simapp.MakeCodecs() + encodingConfig = simapp.MakeEncodingConfig() ) func init() { - authclient.Codec = appCodec + authclient.Codec = encodingConfig.Marshaler } func main() { @@ -62,10 +63,10 @@ func main() { rootCmd.AddCommand( rpc.StatusCommand(), client.ConfigCmd(simapp.DefaultCLIHome), - queryCmd(cdc), - txCmd(cdc), + queryCmd(encodingConfig), + txCmd(encodingConfig), flags.LineBreak, - lcd.ServeCommand(cdc, registerRoutes), + lcd.ServeCommand(encodingConfig.Amino, registerRoutes), flags.LineBreak, keys.Commands(), flags.LineBreak, @@ -82,7 +83,7 @@ func main() { } } -func queryCmd(cdc *codec.Codec) *cobra.Command { +func queryCmd(config simappparams.EncodingConfig) *cobra.Command { queryCmd := &cobra.Command{ Use: "query", Aliases: []string{"q"}, @@ -92,6 +93,8 @@ func queryCmd(cdc *codec.Codec) *cobra.Command { RunE: client.ValidateCmd, } + cdc := config.Amino + queryCmd.AddCommand( authcmd.GetAccountCmd(cdc), flags.LineBreak, @@ -105,14 +108,14 @@ func queryCmd(cdc *codec.Codec) *cobra.Command { // add modules' query commands clientCtx := client.Context{} clientCtx = clientCtx. - WithJSONMarshaler(appCodec). + WithJSONMarshaler(config.Marshaler). WithCodec(cdc) simapp.ModuleBasics.AddQueryCommands(queryCmd, clientCtx) return queryCmd } -func txCmd(cdc *codec.Codec) *cobra.Command { +func txCmd(config simappparams.EncodingConfig) *cobra.Command { txCmd := &cobra.Command{ Use: "tx", Short: "Transactions subcommands", @@ -121,11 +124,12 @@ func txCmd(cdc *codec.Codec) *cobra.Command { RunE: client.ValidateCmd, } + cdc := config.Amino clientCtx := client.Context{} clientCtx = clientCtx. - WithJSONMarshaler(appCodec). - WithTxGenerator(types.StdTxGenerator{Cdc: cdc}). - WithAccountRetriever(types.NewAccountRetriever(appCodec)). + WithJSONMarshaler(config.Marshaler). + WithTxGenerator(config.TxGenerator). + WithAccountRetriever(types.NewAccountRetriever(config.Marshaler)). WithCodec(cdc) txCmd.AddCommand( diff --git a/simapp/encoding.go b/simapp/encoding.go new file mode 100644 index 000000000000..2081ace016fc --- /dev/null +++ b/simapp/encoding.go @@ -0,0 +1,15 @@ +package simapp + +import ( + "github.com/cosmos/cosmos-sdk/simapp/params" + "github.com/cosmos/cosmos-sdk/std" +) + +func MakeEncodingConfig() params.EncodingConfig { + encodingConfig := params.MakeEncodingConfig() + std.RegisterCodec(encodingConfig.Amino) + std.RegisterInterfaces(encodingConfig.InterfaceRegistry) + ModuleBasics.RegisterCodec(encodingConfig.Amino) + ModuleBasics.RegisterInterfaceModules(encodingConfig.InterfaceRegistry) + return encodingConfig +} diff --git a/simapp/params/amino.go b/simapp/params/amino.go index 81233bc8fac2..c5c5db3db1e5 100644 --- a/simapp/params/amino.go +++ b/simapp/params/amino.go @@ -6,6 +6,8 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) +// TODO this file will add a "+build test_amino" flag in the future for #6190 + func MakeEncodingConfig() EncodingConfig { cdc := codec.New() interfaceRegistry := types.NewInterfaceRegistry() diff --git a/std/codec.go b/std/codec.go index ce9ded25a9c0..80f6072a5fac 100644 --- a/std/codec.go +++ b/std/codec.go @@ -9,22 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/vesting" ) -// Codec defines the application-level codec. This codec contains all the -// required module-specific codecs that are to be provided upon initialization. -type Codec struct { - codec.Marshaler - - // Keep reference to the amino codec to allow backwards compatibility along - // with type, and interface registration. - amino *codec.Codec - - anyUnpacker types.AnyUnpacker -} - -func NewAppCodec(amino *codec.Codec, anyUnpacker types.AnyUnpacker) *Codec { - return &Codec{Marshaler: codec.NewHybridCodec(amino, anyUnpacker), amino: amino, anyUnpacker: anyUnpacker} -} - // ---------------------------------------------------------------------------- // necessary types and interfaces registered. This codec is provided to all the // modules the application depends on. @@ -35,11 +19,15 @@ func MakeCodec(bm module.BasicManager) *codec.Codec { cdc := codec.New() bm.RegisterCodec(cdc) + RegisterCodec(cdc) + + return cdc +} + +func RegisterCodec(cdc *codec.Codec) { vesting.RegisterCodec(cdc) sdk.RegisterCodec(cdc) cryptocodec.RegisterCrypto(cdc) - - return cdc } // RegisterInterfaces registers Interfaces from sdk/types and vesting From 91cf4296b35f2b7bea96d46523732521ab06c24b Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 10 Jun 2020 15:33:23 -0400 Subject: [PATCH 04/26] add godocs --- simapp/encoding.go | 3 +++ simapp/params/amino.go | 5 +++-- simapp/params/encoding.go | 2 ++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/simapp/encoding.go b/simapp/encoding.go index 2081ace016fc..58f899edd7a5 100644 --- a/simapp/encoding.go +++ b/simapp/encoding.go @@ -5,6 +5,9 @@ import ( "github.com/cosmos/cosmos-sdk/std" ) +// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. +// +// TODO: this file should add a "+build test_amino" flag for #6190 and a proto.go file with a protobuf configuration func MakeEncodingConfig() params.EncodingConfig { encodingConfig := params.MakeEncodingConfig() std.RegisterCodec(encodingConfig.Amino) diff --git a/simapp/params/amino.go b/simapp/params/amino.go index c5c5db3db1e5..f16dda4c67fb 100644 --- a/simapp/params/amino.go +++ b/simapp/params/amino.go @@ -6,8 +6,9 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) -// TODO this file will add a "+build test_amino" flag in the future for #6190 - +// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. +// +// TODO: this file should add a "+build test_amino" flag for #6190 and a proto.go file with a protobuf configuration func MakeEncodingConfig() EncodingConfig { cdc := codec.New() interfaceRegistry := types.NewInterfaceRegistry() diff --git a/simapp/params/encoding.go b/simapp/params/encoding.go index 040e06ddb247..bb63e6002237 100644 --- a/simapp/params/encoding.go +++ b/simapp/params/encoding.go @@ -6,6 +6,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec/types" ) +// EncodingConfig specifies the concrete encoding types to use for a given app. +// This is provided for compatibility between protobuf and amino implementations. type EncodingConfig struct { InterfaceRegistry types.InterfaceRegistry Marshaler codec.Marshaler From 1e265f8230555a2c3b2200762ddb7d73e72cc27b Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 10 Jun 2020 16:14:38 -0400 Subject: [PATCH 05/26] fix tests --- simapp/cmd/simd/genaccounts.go | 4 +--- x/auth/client/tx.go | 4 ++-- x/auth/keeper/keeper_test.go | 6 ++---- x/evidence/keeper/querier_test.go | 12 +++++------- 4 files changed, 10 insertions(+), 16 deletions(-) diff --git a/simapp/cmd/simd/genaccounts.go b/simapp/cmd/simd/genaccounts.go index 0268b5405420..7e6d395abaac 100644 --- a/simapp/cmd/simd/genaccounts.go +++ b/simapp/cmd/simd/genaccounts.go @@ -7,8 +7,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/std" - "github.com/spf13/cobra" "github.com/spf13/viper" @@ -34,7 +32,7 @@ const ( // AddGenesisAccountCmd returns add-genesis-account cobra Command. func AddGenesisAccountCmd( - ctx *server.Context, depCdc *codec.Codec, cdc *std.Codec, defaultNodeHome, defaultClientHome string, + ctx *server.Context, depCdc *codec.Codec, cdc codec.Marshaler, defaultNodeHome, defaultClientHome string, ) *cobra.Command { cmd := &cobra.Command{ diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index 7f64f2e5aa96..2895136533a1 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -285,7 +285,7 @@ func populateAccountFromState( txBldr authtypes.TxBuilder, clientCtx client.Context, addr sdk.AccAddress, ) (authtypes.TxBuilder, error) { - num, seq, err := authtypes.NewAccountRetriever(Codec).GetAccountNumberSequence(clientCtx, addr) + num, seq, err := clientCtx.AccountRetriever.GetAccountNumberSequence(clientCtx, addr) if err != nil { return txBldr, err } @@ -332,7 +332,7 @@ func parseQueryResponse(bz []byte) (sdk.SimulationResponse, error) { func PrepareTxBuilder(txBldr authtypes.TxBuilder, clientCtx client.Context) (authtypes.TxBuilder, error) { from := clientCtx.GetFromAddress() - accGetter := authtypes.NewAccountRetriever(Codec) + accGetter := clientCtx.AccountRetriever if err := accGetter.EnsureExists(clientCtx, from); err != nil { return txBldr, err } diff --git a/x/auth/keeper/keeper_test.go b/x/auth/keeper/keeper_test.go index e3f5d7f3d88b..ddc7636d365c 100644 --- a/x/auth/keeper/keeper_test.go +++ b/x/auth/keeper/keeper_test.go @@ -5,9 +5,7 @@ import ( "github.com/stretchr/testify/require" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/std" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -108,9 +106,9 @@ func TestSupply_ValidatePermissions(t *testing.T) { maccPerms[multiPerm] = []string{types.Burner, types.Minter, types.Staking} maccPerms[randomPerm] = []string{"random"} - appCodec := std.NewAppCodec(app.Codec(), codectypes.NewInterfaceRegistry()) + cdc, _ := simapp.MakeCodecs() keeper := auth.NewAccountKeeper( - appCodec, app.GetKey(types.StoreKey), app.GetSubspace(types.ModuleName), + cdc, app.GetKey(types.StoreKey), app.GetSubspace(types.ModuleName), types.ProtoBaseAccount, maccPerms, ) diff --git a/x/evidence/keeper/querier_test.go b/x/evidence/keeper/querier_test.go index 7433f099a074..24dcb1d1c019 100644 --- a/x/evidence/keeper/querier_test.go +++ b/x/evidence/keeper/querier_test.go @@ -3,9 +3,7 @@ package keeper_test import ( "strings" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - - "github.com/cosmos/cosmos-sdk/std" + "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/x/evidence/exported" "github.com/cosmos/cosmos-sdk/x/evidence/types" @@ -20,7 +18,7 @@ const ( func (suite *KeeperTestSuite) TestQueryEvidence_Existing() { ctx := suite.ctx.WithIsCheckTx(false) numEvidence := 100 - cdc := std.NewAppCodec(suite.app.Codec(), codectypes.NewInterfaceRegistry()) + cdc, _ := simapp.MakeCodecs() evidence := suite.populateEvidence(ctx, numEvidence) query := abci.RequestQuery{ @@ -39,7 +37,7 @@ func (suite *KeeperTestSuite) TestQueryEvidence_Existing() { func (suite *KeeperTestSuite) TestQueryEvidence_NonExisting() { ctx := suite.ctx.WithIsCheckTx(false) - cdc := std.NewAppCodec(suite.app.Codec(), codectypes.NewInterfaceRegistry()) + cdc, _ := simapp.MakeCodecs() numEvidence := 100 suite.populateEvidence(ctx, numEvidence) @@ -55,7 +53,7 @@ func (suite *KeeperTestSuite) TestQueryEvidence_NonExisting() { func (suite *KeeperTestSuite) TestQueryAllEvidence() { ctx := suite.ctx.WithIsCheckTx(false) - cdc := std.NewAppCodec(suite.app.Codec(), codectypes.NewInterfaceRegistry()) + cdc, _ := simapp.MakeCodecs() numEvidence := 100 suite.populateEvidence(ctx, numEvidence) @@ -75,7 +73,7 @@ func (suite *KeeperTestSuite) TestQueryAllEvidence() { func (suite *KeeperTestSuite) TestQueryAllEvidence_InvalidPagination() { ctx := suite.ctx.WithIsCheckTx(false) - cdc := std.NewAppCodec(suite.app.Codec(), codectypes.NewInterfaceRegistry()) + cdc, _ := simapp.MakeCodecs() numEvidence := 100 suite.populateEvidence(ctx, numEvidence) From 1467cd490ec582150f482f521161e8390fbe997e Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 10 Jun 2020 16:55:19 -0400 Subject: [PATCH 06/26] Debugging CLI Tests --- tests/cli/fixtures.go | 58 ++++++++++++++++++------------------- tests/cli/simd_test.go | 5 +--- x/auth/client/cli/encode.go | 4 +-- 3 files changed, 32 insertions(+), 35 deletions(-) diff --git a/tests/cli/fixtures.go b/tests/cli/fixtures.go index 564514ddc114..b5837f5c9ae3 100644 --- a/tests/cli/fixtures.go +++ b/tests/cli/fixtures.go @@ -7,33 +7,30 @@ import ( "testing" "github.com/stretchr/testify/require" - tmtypes "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/std" + tmtypes "github.com/tendermint/tendermint/types" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/simapp" -) - -var ( - cdc = std.MakeCodec(simapp.ModuleBasics) + "github.com/cosmos/cosmos-sdk/simapp/params" ) // Fixtures is used to setup the testing environment type Fixtures struct { - BuildDir string - RootDir string - SimdBinary string - SimcliBinary string - ChainID string - RPCAddr string - Port string - SimdHome string - SimcliHome string - P2PAddr string - Cdc *codec.Codec - T *testing.T + BuildDir string + RootDir string + SimdBinary string + SimcliBinary string + ChainID string + RPCAddr string + Port string + SimdHome string + SimcliHome string + P2PAddr string + Cdc *codec.Codec + EncodingConfig params.EncodingConfig + T *testing.T } // NewFixtures creates a new instance of Fixtures with many vars set @@ -52,18 +49,21 @@ func NewFixtures(t *testing.T) *Fixtures { t.Skip("builddir is empty, skipping") } + encodingConfig := simapp.MakeEncodingConfig() + return &Fixtures{ - T: t, - BuildDir: buildDir, - RootDir: tmpDir, - SimdBinary: filepath.Join(buildDir, "simd"), - SimcliBinary: filepath.Join(buildDir, "simcli"), - SimdHome: filepath.Join(tmpDir, ".simd"), - SimcliHome: filepath.Join(tmpDir, ".simcli"), - RPCAddr: servAddr, - P2PAddr: p2pAddr, - Cdc: cdc, - Port: port, + T: t, + BuildDir: buildDir, + RootDir: tmpDir, + SimdBinary: filepath.Join(buildDir, "simd"), + SimcliBinary: filepath.Join(buildDir, "simcli"), + SimdHome: filepath.Join(tmpDir, ".simd"), + SimcliHome: filepath.Join(tmpDir, ".simcli"), + RPCAddr: servAddr, + P2PAddr: p2pAddr, + Cdc: encodingConfig.Amino, + EncodingConfig: encodingConfig, + Port: port, } } diff --git a/tests/cli/simd_test.go b/tests/cli/simd_test.go index 2be36dc8e93a..8bcabdc16ce9 100644 --- a/tests/cli/simd_test.go +++ b/tests/cli/simd_test.go @@ -11,8 +11,6 @@ import ( "github.com/stretchr/testify/require" tmtypes "github.com/tendermint/tendermint/types" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/std" "github.com/cosmos/cosmos-sdk/tests/cli" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" @@ -99,8 +97,7 @@ func TestCLISimdAddGenesisAccount(t *testing.T) { genesisState := f.GenesisState() - interfaceRegistry := codectypes.NewInterfaceRegistry() - appCodec := std.NewAppCodec(f.Cdc, interfaceRegistry) + appCodec := f.EncodingConfig.Marshaler accounts := auth.GetGenesisStateFromAppState(appCodec, genesisState).Accounts balances := bank.GetGenesisStateFromAppState(f.Cdc, genesisState).Balances diff --git a/x/auth/client/cli/encode.go b/x/auth/client/cli/encode.go index 653f8b389a1a..3ca0b46b3aed 100644 --- a/x/auth/client/cli/encode.go +++ b/x/auth/client/cli/encode.go @@ -27,12 +27,12 @@ func GetEncodeCommand(clientCtx client.Context) *cobra.Command { Read a transaction from , serialize it to the Amino wire protocol, and output it as base64. If you supply a dash (-) argument in place of an input filename, the command reads from standard input.`, Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) (err error) { + RunE: func(cmd *cobra.Command, args []string) error { cliCtx := clientCtx.Init() tx, err := authclient.ReadTxFromFile(cliCtx, args[0]) if err != nil { - return + return err } // re-encode it From 23cdeebdb4f40ba8bab936bd39a916b8e28e0008 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Thu, 11 Jun 2020 17:34:32 -0400 Subject: [PATCH 07/26] Fix integration test --- x/auth/client/cli/encode.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/x/auth/client/cli/encode.go b/x/auth/client/cli/encode.go index 3ca0b46b3aed..755e3acf6e70 100644 --- a/x/auth/client/cli/encode.go +++ b/x/auth/client/cli/encode.go @@ -2,6 +2,7 @@ package cli import ( "encoding/base64" + "fmt" "github.com/spf13/cobra" @@ -44,8 +45,9 @@ If you supply a dash (-) argument in place of an input filename, the command rea // base64 encode the encoded tx bytes txBytesBase64 := base64.StdEncoding.EncodeToString(txBytes) - response := txEncodeRespStr(txBytesBase64) - return clientCtx.PrintOutput(response) + fmt.Println(txBytesBase64) + + return nil }, } From b878734077a692357094f2619ba0b2c3db76f696 Mon Sep 17 00:00:00 2001 From: atheeshp <59333759+atheeshp@users.noreply.github.com> Date: Tue, 16 Jun 2020 00:58:18 +0530 Subject: [PATCH 08/26] 6391 - lint issues and code coverage (#6414) * fixed lint issue of "txEncodeRespStr" * added tests for encode.go * WIP: added tests for decode.go * added txEncoder at bytes * updated decode test * updated txBytes to use TxEncoder in decoder test * added a require after TxEncoder * removed file save * debug decode command * fixed decode tests * added decode cli * updated encode and decode in a single file * separated decode test from encode test * review changes * removed register interface * review change --- x/auth/client/cli/cli_test.go | 12 ++---- x/auth/client/cli/encode.go | 7 ---- x/auth/client/cli/encode_test.go | 66 +++++++++++++++++++++++++++++++ x/auth/client/testutil/helpers.go | 6 +++ 4 files changed, 75 insertions(+), 16 deletions(-) create mode 100644 x/auth/client/cli/encode_test.go diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index b831ee348a72..f90361cb2126 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -3,7 +3,6 @@ package cli_test import ( - "encoding/base64" "fmt" "strings" "testing" @@ -14,7 +13,6 @@ import ( "github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/tests/cli" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/client/testutil" bankcli "github.com/cosmos/cosmos-sdk/x/bank/client/testutil" ) @@ -301,15 +299,11 @@ func TestCLIEncode(t *testing.T) { // Run the encode command, and trim the extras from the stdout capture success, base64Encoded, _ := testutil.TxEncode(f, jsonTxFile.Name()) require.True(t, success) - trimmedBase64 := strings.Trim(base64Encoded, "\"\n") - // Decode the base64 - decodedBytes, err := base64.StdEncoding.DecodeString(trimmedBase64) - require.Nil(t, err) + // Check that the transaction decodes as expected + success, stdout, stderr = testutil.TxDecode(f, base64Encoded) + decodedTx := cli.UnmarshalStdTx(t, f.Cdc, stdout) - // Check that the transaction decodes as epxceted - var decodedTx auth.StdTx - require.Nil(t, f.Cdc.UnmarshalBinaryBare(decodedBytes, &decodedTx)) require.Equal(t, "deadbeef", decodedTx.Memo) } diff --git a/x/auth/client/cli/encode.go b/x/auth/client/cli/encode.go index 755e3acf6e70..7b4c88cc52d1 100644 --- a/x/auth/client/cli/encode.go +++ b/x/auth/client/cli/encode.go @@ -11,13 +11,6 @@ import ( authclient "github.com/cosmos/cosmos-sdk/x/auth/client" ) -// txEncodeRespStr implements a simple Stringer wrapper for a encoded tx. -type txEncodeRespStr string - -func (txr txEncodeRespStr) String() string { - return string(txr) -} - // GetEncodeCommand returns the encode command to take a JSONified transaction and turn it into // Amino-serialized bytes func GetEncodeCommand(clientCtx client.Context) *cobra.Command { diff --git a/x/auth/client/cli/encode_test.go b/x/auth/client/cli/encode_test.go new file mode 100644 index 000000000000..c4419e1fccdc --- /dev/null +++ b/x/auth/client/cli/encode_test.go @@ -0,0 +1,66 @@ +package cli + +import ( + "encoding/base64" + "testing" + + "github.com/cosmos/cosmos-sdk/client" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + "github.com/cosmos/cosmos-sdk/tests" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/stretchr/testify/require" +) + +func TestGetCommandEncode(t *testing.T) { + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + + cmd := GetEncodeCommand(clientCtx) + encodingConfig := simappparams.MakeEncodingConfig() + authtypes.RegisterCodec(encodingConfig.Amino) + sdk.RegisterCodec(encodingConfig.Amino) + + txGen := encodingConfig.TxGenerator + + // Build a test transaction + fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) + stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") + JSONEncoded, err := txGen.TxJSONEncoder()(stdTx) + require.NoError(t, err) + + txFile, cleanup := tests.WriteToNewTempFile(t, string(JSONEncoded)) + txFileName := txFile.Name() + t.Cleanup(cleanup) + + err = cmd.RunE(cmd, []string{txFileName}) + require.NoError(t, err) +} + +func TestGetCommandDecode(t *testing.T) { + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + + cmd := GetDecodeCommand(clientCtx) + + encodingConfig := simappparams.MakeEncodingConfig() + sdk.RegisterCodec(encodingConfig.Amino) + + txGen := encodingConfig.TxGenerator + clientCtx = clientCtx.WithTxGenerator(txGen) + + // Build a test transaction + fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) + stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") + + // Encode transaction + txBytes, err := clientCtx.TxGenerator.TxEncoder()(stdTx) + require.NoError(t, err) + + // Convert the transaction into base64 encoded string + base64Encoded := base64.StdEncoding.EncodeToString(txBytes) + + // Execute the command + err = runDecodeTxString(clientCtx)(cmd, []string{base64Encoded}) + require.NoError(t, err) +} diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index d04c51b9dbd8..23aa367cf27c 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -51,4 +51,10 @@ func TxSignBatch(f *cli.Fixtures, signer, fileName string, flags ...string) (boo return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } +// TxDecode is simcli tx decode +func TxDecode(f *cli.Fixtures, encodedTx string, flags ...string) (bool, string, string) { + cmd := fmt.Sprintf("%s tx decode %v %v", f.SimcliBinary, f.Flags(), encodedTx) + return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) +} + // DONTCOVER From e4db34209fabbd863f6c57e92887320e65ce4833 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Mon, 15 Jun 2020 15:36:09 -0400 Subject: [PATCH 09/26] Fix tests --- simapp/app.go | 1 - simapp/cmd/simcli/main.go | 1 - 2 files changed, 2 deletions(-) diff --git a/simapp/app.go b/simapp/app.go index dc6cd582331b..4ccb83dfa691 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -13,7 +13,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/rpc" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/testdata" - "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/server/api" "github.com/cosmos/cosmos-sdk/std" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/simapp/cmd/simcli/main.go b/simapp/cmd/simcli/main.go index 948e597349a9..1b3eae7194c9 100644 --- a/simapp/cmd/simcli/main.go +++ b/simapp/cmd/simcli/main.go @@ -64,7 +64,6 @@ func main() { queryCmd(encodingConfig), txCmd(encodingConfig), flags.LineBreak, - lcd.ServeCommand(encodingConfig.Amino, registerRoutes), flags.LineBreak, keys.Commands(), flags.LineBreak, From 50b56e2ca45322d5f7f300faf18ca92dbbb58db7 Mon Sep 17 00:00:00 2001 From: atheesh Date: Tue, 16 Jun 2020 19:56:52 +0530 Subject: [PATCH 10/26] WIP add test for tx sign --- x/auth/client/cli/sign_test.go | 62 ++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 x/auth/client/cli/sign_test.go diff --git a/x/auth/client/cli/sign_test.go b/x/auth/client/cli/sign_test.go new file mode 100644 index 000000000000..6dd3f7f73002 --- /dev/null +++ b/x/auth/client/cli/sign_test.go @@ -0,0 +1,62 @@ +package cli + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + "github.com/cosmos/cosmos-sdk/tests" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/spf13/viper" + "github.com/stretchr/testify/require" +) + +func TestGetTxSign(t *testing.T) { + clientCtx := client.Context{} + // clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator).WithChainID("test") + + dir, clean := tests.NewTestCaseDir(t) + t.Cleanup(clean) + + path := hd.CreateHDPath(118, 0, 0).String() + kr, err := keyring.New(t.Name(), "test", dir, nil) + require.NoError(t, err) + + var from = "test_sign" + + _, seed, err := kr.NewMnemonic(from, keyring.English, path, hd.Secp256k1) + require.NoError(t, err) + require.NoError(t, kr.Delete(from)) + + info, err := kr.NewAccount(from, seed, "", path, hd.Secp256k1) + require.NoError(t, err) + + viper.Set(flags.FlagGenerateOnly, true) + viper.Set(flags.FlagFrom, info.GetAddress()) + + clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator).WithChainID("test").WithKeyring(kr).WithFrom(from) + + cmd := GetSignCommand(clientCtx) + encodingConfig := simappparams.MakeEncodingConfig() + authtypes.RegisterCodec(encodingConfig.Amino) + sdk.RegisterCodec(encodingConfig.Amino) + + txGen := encodingConfig.TxGenerator + + // Build a test transaction + fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) + stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") + txJSONEncoded, err := txGen.TxJSONEncoder()(stdTx) + require.NoError(t, err) + + txFile, cleanup := tests.WriteToNewTempFile(t, string(txJSONEncoded)) + txFileName := txFile.Name() + t.Cleanup(cleanup) + + err = cmd.RunE(cmd, []string{txFileName}) + require.NoError(t, err) +} From 796352ba116fd81bc50bc71802c881f4a8c10383 Mon Sep 17 00:00:00 2001 From: atheesh Date: Tue, 16 Jun 2020 20:05:45 +0530 Subject: [PATCH 11/26] removed commented code --- x/auth/client/cli/sign_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/x/auth/client/cli/sign_test.go b/x/auth/client/cli/sign_test.go index 6dd3f7f73002..56131eae3465 100644 --- a/x/auth/client/cli/sign_test.go +++ b/x/auth/client/cli/sign_test.go @@ -17,7 +17,6 @@ import ( func TestGetTxSign(t *testing.T) { clientCtx := client.Context{} - // clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator).WithChainID("test") dir, clean := tests.NewTestCaseDir(t) t.Cleanup(clean) From ec3bdfa0b741938e70ce802f521b7c9a379ae784 Mon Sep 17 00:00:00 2001 From: anilCSE Date: Wed, 17 Jun 2020 00:08:11 +0530 Subject: [PATCH 12/26] Fix flags --- x/auth/client/cli/sign_test.go | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/x/auth/client/cli/sign_test.go b/x/auth/client/cli/sign_test.go index 56131eae3465..6ac087d413ca 100644 --- a/x/auth/client/cli/sign_test.go +++ b/x/auth/client/cli/sign_test.go @@ -1,8 +1,10 @@ -package cli +package cli_test import ( "testing" + "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" @@ -15,7 +17,7 @@ import ( "github.com/stretchr/testify/require" ) -func TestGetTxSign(t *testing.T) { +func TestGetSignCommand(t *testing.T) { clientCtx := client.Context{} dir, clean := tests.NewTestCaseDir(t) @@ -34,12 +36,14 @@ func TestGetTxSign(t *testing.T) { info, err := kr.NewAccount(from, seed, "", path, hd.Secp256k1) require.NoError(t, err) - viper.Set(flags.FlagGenerateOnly, true) - viper.Set(flags.FlagFrom, info.GetAddress()) + //viper.Set(flags.FlagGenerateOnly, true) + viper.Set(flags.FlagFrom, from) + viper.Set(flags.FlagKeyringBackend, "test") + viper.Set(flags.FlagHome, dir) - clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator).WithChainID("test").WithKeyring(kr).WithFrom(from) + clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator).WithChainID("test").WithKeyring(kr) - cmd := GetSignCommand(clientCtx) + cmd := cli.GetSignCommand(clientCtx) encodingConfig := simappparams.MakeEncodingConfig() authtypes.RegisterCodec(encodingConfig.Amino) sdk.RegisterCodec(encodingConfig.Amino) @@ -48,7 +52,9 @@ func TestGetTxSign(t *testing.T) { // Build a test transaction fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) + stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") + txJSONEncoded, err := txGen.TxJSONEncoder()(stdTx) require.NoError(t, err) From 709b09f1592a96c41f0be767ef4a75e9de397faa Mon Sep 17 00:00:00 2001 From: atheesh Date: Wed, 17 Jun 2020 12:03:09 +0530 Subject: [PATCH 13/26] WIP add test for sign --- x/auth/client/cli/sign_test.go | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/x/auth/client/cli/sign_test.go b/x/auth/client/cli/sign_test.go index 56131eae3465..2e038738b887 100644 --- a/x/auth/client/cli/sign_test.go +++ b/x/auth/client/cli/sign_test.go @@ -1,6 +1,8 @@ package cli import ( + "fmt" + "io/ioutil" "testing" "github.com/cosmos/cosmos-sdk/client" @@ -31,20 +33,20 @@ func TestGetTxSign(t *testing.T) { require.NoError(t, err) require.NoError(t, kr.Delete(from)) - info, err := kr.NewAccount(from, seed, "", path, hd.Secp256k1) + _, err = kr.NewAccount(from, seed, "", path, hd.Secp256k1) require.NoError(t, err) - viper.Set(flags.FlagGenerateOnly, true) - viper.Set(flags.FlagFrom, info.GetAddress()) + // viper.Set(flags.FlagGenerateOnly, true) + viper.Set(flags.FlagFrom, from) - clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator).WithChainID("test").WithKeyring(kr).WithFrom(from) - - cmd := GetSignCommand(clientCtx) encodingConfig := simappparams.MakeEncodingConfig() authtypes.RegisterCodec(encodingConfig.Amino) sdk.RegisterCodec(encodingConfig.Amino) - txGen := encodingConfig.TxGenerator + clientCtx = clientCtx.WithTxGenerator(encodingConfig.TxGenerator).WithChainID("test").WithKeyring(kr).WithFrom(from) + + cmd := GetSignCommand(clientCtx) + txGen := clientCtx.TxGenerator // Build a test transaction fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) @@ -54,6 +56,8 @@ func TestGetTxSign(t *testing.T) { txFile, cleanup := tests.WriteToNewTempFile(t, string(txJSONEncoded)) txFileName := txFile.Name() + fileData, err := ioutil.ReadFile(txFileName) + fmt.Println("fileData", string(fileData)) t.Cleanup(cleanup) err = cmd.RunE(cmd, []string{txFileName}) From 7745688c7634d859e6b1bf576c4d203fa371cc37 Mon Sep 17 00:00:00 2001 From: sahith-narahari Date: Thu, 18 Jun 2020 00:42:21 +0530 Subject: [PATCH 14/26] Address review suggestions --- x/auth/client/cli/cli_test.go | 3 +- x/auth/client/cli/sign_test.go | 61 +++++++++++++++++++++++++++++----- x/auth/client/cli/tx_sign.go | 2 +- 3 files changed, 54 insertions(+), 12 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index f90361cb2126..8fb2d4c82086 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -296,14 +296,13 @@ func TestCLIEncode(t *testing.T) { jsonTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) - // Run the encode command, and trim the extras from the stdout capture + // Run the encode command success, base64Encoded, _ := testutil.TxEncode(f, jsonTxFile.Name()) require.True(t, success) // Check that the transaction decodes as expected success, stdout, stderr = testutil.TxDecode(f, base64Encoded) decodedTx := cli.UnmarshalStdTx(t, f.Cdc, stdout) - require.Equal(t, "deadbeef", decodedTx.Memo) } diff --git a/x/auth/client/cli/sign_test.go b/x/auth/client/cli/sign_test.go index f235da743d4d..af813d67bd42 100644 --- a/x/auth/client/cli/sign_test.go +++ b/x/auth/client/cli/sign_test.go @@ -22,20 +22,26 @@ import ( func TestGetSignCommand(t *testing.T) { clientCtx := client.Context{} + encodingConfig := simappparams.MakeEncodingConfig() + authtypes.RegisterCodec(encodingConfig.Amino) + sdk.RegisterCodec(encodingConfig.Amino) + encodingConfig.Amino.RegisterConcrete(sdk.TestMsg{}, "cosmos-sdk/Test", nil) + dir, clean := tests.NewTestCaseDir(t) t.Cleanup(clean) path := hd.CreateHDPath(118, 0, 0).String() - kr, err := keyring.New(t.Name(), "test", dir, nil) + kr, err := keyring.New(sdk.KeyringServiceName(), "test", dir, nil) require.NoError(t, err) var from = "test_sign" - _, seed, err := kr.NewMnemonic(from, keyring.English, path, hd.Secp256k1) + _, _, err = kr.NewMnemonic(from, keyring.English, path, hd.Secp256k1) require.NoError(t, err) require.NoError(t, kr.Delete(from)) - _, err = kr.NewAccount(from, seed, "", path, hd.Secp256k1) + info, err := kr.NewAccount(from, tests.TestMnemonic, "", path, hd.Secp256k1) + addr := info.GetAddress() require.NoError(t, err) //viper.Set(flags.FlagGenerateOnly, true) @@ -47,19 +53,15 @@ func TestGetSignCommand(t *testing.T) { cmd := cli.GetSignCommand(clientCtx) - encodingConfig := simappparams.MakeEncodingConfig() - authtypes.RegisterCodec(encodingConfig.Amino) - sdk.RegisterCodec(encodingConfig.Amino) - clientCtx = clientCtx.WithTxGenerator(encodingConfig.TxGenerator).WithChainID("test").WithKeyring(kr).WithFrom(from) - cmd := GetSignCommand(clientCtx) + cmd = cli.GetSignCommand(clientCtx) txGen := clientCtx.TxGenerator // Build a test transaction fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) - stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") + stdTx := authtypes.NewStdTx([]sdk.Msg{authtypes.NewTestMsg(addr)}, fee, []authtypes.StdSignature{}, "foomemo") txJSONEncoded, err := txGen.TxJSONEncoder()(stdTx) require.NoError(t, err) @@ -73,3 +75,44 @@ func TestGetSignCommand(t *testing.T) { err = cmd.RunE(cmd, []string{txFileName}) require.NoError(t, err) } + +func TestMultiSign(t *testing.T) { + clientCtx := client.Context{} + + encodingConfig := simappparams.MakeEncodingConfig() + authtypes.RegisterCodec(encodingConfig.Amino) + sdk.RegisterCodec(encodingConfig.Amino) + encodingConfig.Amino.RegisterConcrete(sdk.TestMsg{}, "cosmos-sdk/Test", nil) + + dir, clean := tests.NewTestCaseDir(t) + t.Cleanup(clean) + + path := hd.CreateHDPath(118, 0, 0).String() + kr, err := keyring.New(sdk.KeyringServiceName(), "test", dir, nil) + require.NoError(t, err) + + var from = "test_sign" + + _, _, err = kr.NewMnemonic(from, keyring.English, path, hd.Secp256k1) + require.NoError(t, err) + require.NoError(t, kr.Delete(from)) + + info, err := kr.NewAccount(from, tests.TestMnemonic, "", path, hd.Secp256k1) + addr := info.GetAddress() + require.NoError(t, err) + + clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator).WithChainID("test").WithKeyring(kr) + + cmd := cli.GetSignCommand(clientCtx) + + clientCtx = clientCtx.WithTxGenerator(encodingConfig.TxGenerator).WithChainID("test").WithKeyring(kr).WithFrom(from) + + cmd = cli.GetSignCommand(clientCtx) + txGen := clientCtx.TxGenerator + + // Build a test transaction + fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) + + stdTx := authtypes.NewStdTx([]sdk.Msg{authtypes.NewTestMsg(addr)}, fee, []authtypes.StdSignature{}, "foomemo") + +} diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 43341469e2ef..5fba10f6f877 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -225,7 +225,7 @@ func makeSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args []strin generateSignatureOnly = true } else { appendSig := viper.GetBool(flagAppend) && !generateSignatureOnly - newTx, err = authclient.SignStdTx(txBldr, clientCtx, clientCtx.GetFromName(), stdTx, appendSig, clientCtx.Offline) + newTx, err = authclient.SignStdTx(txBldr, clientCtx, clientCtx.From, stdTx, appendSig, clientCtx.Offline) } if err != nil { From 17016241a1664cf12a96502655937b3e4651703b Mon Sep 17 00:00:00 2001 From: atheesh Date: Thu, 18 Jun 2020 14:54:55 +0530 Subject: [PATCH 15/26] fixed command issue --- x/auth/client/cli/sign_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/x/auth/client/cli/sign_test.go b/x/auth/client/cli/sign_test.go index f235da743d4d..cd7667049884 100644 --- a/x/auth/client/cli/sign_test.go +++ b/x/auth/client/cli/sign_test.go @@ -53,7 +53,6 @@ func TestGetSignCommand(t *testing.T) { clientCtx = clientCtx.WithTxGenerator(encodingConfig.TxGenerator).WithChainID("test").WithKeyring(kr).WithFrom(from) - cmd := GetSignCommand(clientCtx) txGen := clientCtx.TxGenerator // Build a test transaction From 5063d7cbcec01bd054307015f230b721787b137b Mon Sep 17 00:00:00 2001 From: sahith-narahari Date: Thu, 18 Jun 2020 20:15:44 +0530 Subject: [PATCH 16/26] Add tests for TxEncoder --- x/auth/client/tx.go | 4 +++- x/auth/client/tx_test.go | 22 ++++++++++++++++++++++ x/auth/types/client_tx_test.go | 30 ++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 x/auth/types/client_tx_test.go diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index 2895136533a1..cc12aa9a0cc1 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -331,7 +331,9 @@ func parseQueryResponse(bz []byte) (sdk.SimulationResponse, error) { // PrepareTxBuilder populates a TxBuilder in preparation for the build of a Tx. func PrepareTxBuilder(txBldr authtypes.TxBuilder, clientCtx client.Context) (authtypes.TxBuilder, error) { from := clientCtx.GetFromAddress() - + if from == nil { + return authtypes.TxBuilder{}, fmt.Errorf("unable to fetch from address from clientCtx") + } accGetter := clientCtx.AccountRetriever if err := accGetter.EnsureExists(clientCtx, from); err != nil { return txBldr, err diff --git a/x/auth/client/tx_test.go b/x/auth/client/tx_test.go index f979349317c0..14103d3e33d6 100644 --- a/x/auth/client/tx_test.go +++ b/x/auth/client/tx_test.go @@ -205,6 +205,28 @@ func compareEncoders(t *testing.T, expected sdk.TxEncoder, actual sdk.TxEncoder) require.Equal(t, defaultEncoderBytes, encoderBytes) } +func TestPrepareTxBuilder(t *testing.T) { + cdc := makeCodec() + + encodingConfig := simappparams.MakeEncodingConfig() + sdk.RegisterCodec(encodingConfig.Amino) + + txGen := encodingConfig.TxGenerator + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(txGen) + + bldr := authtypes.NewTxBuilder( + authtypes.DefaultTxEncoder(cdc), 1, 1, + 200000, 1.1, false, "test-chain", + "test-builder", sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))), + sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDecWithPrec(10000, sdk.Precision))}) + + bldr, err := PrepareTxBuilder(bldr, clientCtx) + require.NoError(t, err) + require.Equal(t, 1, bldr.AccountNumber()) + require.Equal(t, 1, bldr.Sequence()) +} + func writeToNewTempFile(t *testing.T, data string) *os.File { fp, err := ioutil.TempFile(os.TempDir(), "client_tx_test") require.NoError(t, err) diff --git a/x/auth/types/client_tx_test.go b/x/auth/types/client_tx_test.go new file mode 100644 index 000000000000..c922484d6bde --- /dev/null +++ b/x/auth/types/client_tx_test.go @@ -0,0 +1,30 @@ +package types_test + +import ( + "github.com/cosmos/cosmos-sdk/client" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/stretchr/testify/require" + "testing" +) + +func TestTxEncoder(t *testing.T) { + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + + encodingConfig := simappparams.MakeEncodingConfig() + sdk.RegisterCodec(encodingConfig.Amino) + + txGen := encodingConfig.TxGenerator + clientCtx = clientCtx.WithTxGenerator(txGen) + + // Build a test transaction + fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) + stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") + + // Encode transaction + txBytes, err := clientCtx.TxGenerator.TxEncoder()(stdTx) + require.NoError(t, err) + require.NotNil(t, txBytes) +} From 893e26596192664ddb0d40a65ecb62041f2d02b7 Mon Sep 17 00:00:00 2001 From: sahith-narahari Date: Thu, 18 Jun 2020 20:37:27 +0530 Subject: [PATCH 17/26] Revert sign changes --- x/auth/client/cli/sign_test.go | 126 --------------------------------- x/auth/types/client_tx_test.go | 30 -------- 2 files changed, 156 deletions(-) delete mode 100644 x/auth/client/cli/sign_test.go delete mode 100644 x/auth/types/client_tx_test.go diff --git a/x/auth/client/cli/sign_test.go b/x/auth/client/cli/sign_test.go deleted file mode 100644 index 8e036ee7da4e..000000000000 --- a/x/auth/client/cli/sign_test.go +++ /dev/null @@ -1,126 +0,0 @@ -package cli_test - -import ( - "testing" - - "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" - "github.com/cosmos/cosmos-sdk/tests" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/spf13/viper" - "github.com/stretchr/testify/require" -) - -func TestGetSignCommand(t *testing.T) { - clientCtx := client.Context{} - - encodingConfig := simappparams.MakeEncodingConfig() - authtypes.RegisterCodec(encodingConfig.Amino) - sdk.RegisterCodec(encodingConfig.Amino) - encodingConfig.Amino.RegisterConcrete(sdk.TestMsg{}, "cosmos-sdk/Test", nil) - - dir, clean := tests.NewTestCaseDir(t) - t.Cleanup(clean) - - path := hd.CreateHDPath(118, 0, 0).String() - kr, err := keyring.New(sdk.KeyringServiceName(), "test", dir, nil) - require.NoError(t, err) - - var from = "test_sign" - - _, _, err = kr.NewMnemonic(from, keyring.English, path, hd.Secp256k1) - require.NoError(t, err) - require.NoError(t, kr.Delete(from)) - - info, err := kr.NewAccount(from, tests.TestMnemonic, "", path, hd.Secp256k1) - addr := info.GetAddress() - require.NoError(t, err) - - //viper.Set(flags.FlagGenerateOnly, true) - viper.Set(flags.FlagFrom, from) - viper.Set(flags.FlagKeyringBackend, "test") - viper.Set(flags.FlagHome, dir) - - clientCtx = clientCtx.WithTxGenerator(encodingConfig.TxGenerator).WithChainID("test").WithKeyring(kr).WithFrom(from) - cmd := cli.GetSignCommand(clientCtx) - - txGen := clientCtx.TxGenerator - - // Build a test transaction - fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) - - stdTx := authtypes.NewStdTx([]sdk.Msg{authtypes.NewTestMsg(addr)}, fee, []authtypes.StdSignature{}, "foomemo") - - txJSONEncoded, err := txGen.TxJSONEncoder()(stdTx) - require.NoError(t, err) - - txFile, cleanup := tests.WriteToNewTempFile(t, string(txJSONEncoded)) - txFileName := txFile.Name() - // added for debugging purpose, (remove this lines after debugged) - // fileData, err := ioutil.ReadFile(txFileName) - // fmt.Println("fileData", string(fileData)) - t.Cleanup(cleanup) - - err = cmd.RunE(cmd, []string{txFileName}) - require.NoError(t, err) -} - -func TestMultiSign(t *testing.T) { - clientCtx := client.Context{} - - encodingConfig := simappparams.MakeEncodingConfig() - authtypes.RegisterCodec(encodingConfig.Amino) - sdk.RegisterCodec(encodingConfig.Amino) - encodingConfig.Amino.RegisterConcrete(sdk.TestMsg{}, "cosmos-sdk/Test", nil) - - dir, clean := tests.NewTestCaseDir(t) - t.Cleanup(clean) - - path := hd.CreateHDPath(118, 0, 0).String() - kr, err := keyring.New(sdk.KeyringServiceName(), "test", dir, nil) - require.NoError(t, err) - - var from = "test_sign" - - _, _, err = kr.NewMnemonic(from, keyring.English, path, hd.Secp256k1) - require.NoError(t, err) - require.NoError(t, kr.Delete(from)) - - info, err := kr.NewAccount(from, tests.TestMnemonic, "", path, hd.Secp256k1) - addr := info.GetAddress() - require.NoError(t, err) - - //viper.Set(flags.FlagGenerateOnly, true) - viper.Set(flags.FlagFrom, from) - viper.Set(flags.FlagKeyringBackend, "test") - viper.Set(flags.FlagHome, dir) - - clientCtx = clientCtx.WithTxGenerator(encodingConfig.TxGenerator).WithChainID("test").WithKeyring(kr).WithFrom(from) - cmd := cli.GetMultiSignCommand(clientCtx) - - txGen := clientCtx.TxGenerator - - // Build a test transaction - fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) - - stdTx := authtypes.NewStdTx([]sdk.Msg{authtypes.NewTestMsg(addr)}, fee, []authtypes.StdSignature{}, "foomemo") - - txJSONEncoded, err := txGen.TxJSONEncoder()(stdTx) - require.NoError(t, err) - - txFile, cleanup := tests.WriteToNewTempFile(t, string(txJSONEncoded)) - txFileName := txFile.Name() - // added for debugging purpose, (remove this lines after debugged) - // fileData, err := ioutil.ReadFile(txFileName) - // fmt.Println("fileData", string(fileData)) - t.Cleanup(cleanup) - - err = cmd.RunE(cmd, []string{txFileName}) - require.NoError(t, err) -} diff --git a/x/auth/types/client_tx_test.go b/x/auth/types/client_tx_test.go deleted file mode 100644 index c922484d6bde..000000000000 --- a/x/auth/types/client_tx_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package types_test - -import ( - "github.com/cosmos/cosmos-sdk/client" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/stretchr/testify/require" - "testing" -) - -func TestTxEncoder(t *testing.T) { - clientCtx := client.Context{} - clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) - - encodingConfig := simappparams.MakeEncodingConfig() - sdk.RegisterCodec(encodingConfig.Amino) - - txGen := encodingConfig.TxGenerator - clientCtx = clientCtx.WithTxGenerator(txGen) - - // Build a test transaction - fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) - stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") - - // Encode transaction - txBytes, err := clientCtx.TxGenerator.TxEncoder()(stdTx) - require.NoError(t, err) - require.NotNil(t, txBytes) -} From 32bbf12cc56635981521a9577fdad54528d42463 Mon Sep 17 00:00:00 2001 From: sahith-narahari Date: Thu, 18 Jun 2020 20:45:37 +0530 Subject: [PATCH 18/26] Fix TxEncoder tests --- x/auth/client/tx_test.go | 247 --------------------------------- x/auth/types/client_tx_test.go | 30 ++++ 2 files changed, 30 insertions(+), 247 deletions(-) delete mode 100644 x/auth/client/tx_test.go create mode 100644 x/auth/types/client_tx_test.go diff --git a/x/auth/client/tx_test.go b/x/auth/client/tx_test.go deleted file mode 100644 index 14103d3e33d6..000000000000 --- a/x/auth/client/tx_test.go +++ /dev/null @@ -1,247 +0,0 @@ -package client - -import ( - "encoding/json" - "errors" - "io/ioutil" - "os" - "strings" - "testing" - - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" - - "github.com/cosmos/cosmos-sdk/client" - - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/ed25519" - - "github.com/cosmos/cosmos-sdk/codec" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -var ( - priv = ed25519.GenPrivKey() - addr = sdk.AccAddress(priv.PubKey().Address()) -) - -func TestParseQueryResponse(t *testing.T) { - simRes := &sdk.SimulationResponse{ - GasInfo: sdk.GasInfo{GasUsed: 10, GasWanted: 20}, - Result: &sdk.Result{Data: []byte("tx data"), Log: "log"}, - } - - bz, err := codec.ProtoMarshalJSON(simRes) - require.NoError(t, err) - - res, err := parseQueryResponse(bz) - require.NoError(t, err) - require.Equal(t, 10, int(res.GasInfo.GasUsed)) - require.NotNil(t, res.Result) - - res, err = parseQueryResponse([]byte("fuzzy")) - require.Error(t, err) -} - -func TestCalculateGas(t *testing.T) { - cdc := makeCodec() - makeQueryFunc := func(gasUsed uint64, wantErr bool) func(string, []byte) ([]byte, int64, error) { - return func(string, []byte) ([]byte, int64, error) { - if wantErr { - return nil, 0, errors.New("query failed") - } - simRes := &sdk.SimulationResponse{ - GasInfo: sdk.GasInfo{GasUsed: gasUsed, GasWanted: gasUsed}, - Result: &sdk.Result{Data: []byte("tx data"), Log: "log"}, - } - - bz, _ := codec.ProtoMarshalJSON(simRes) - return bz, 0, nil - } - } - - type args struct { - queryFuncGasUsed uint64 - queryFuncWantErr bool - adjustment float64 - } - - tests := []struct { - name string - args args - wantEstimate uint64 - wantAdjusted uint64 - expPass bool - }{ - {"error", args{0, true, 1.2}, 0, 0, false}, - {"adjusted gas", args{10, false, 1.2}, 10, 12, true}, - } - - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - queryFunc := makeQueryFunc(tt.args.queryFuncGasUsed, tt.args.queryFuncWantErr) - simRes, gotAdjusted, err := CalculateGas(queryFunc, cdc, []byte(""), tt.args.adjustment) - if tt.expPass { - require.NoError(t, err) - require.Equal(t, simRes.GasInfo.GasUsed, tt.wantEstimate) - require.Equal(t, gotAdjusted, tt.wantAdjusted) - require.NotNil(t, simRes.Result) - } else { - require.Error(t, err) - require.Nil(t, simRes.Result) - } - }) - } -} - -func TestDefaultTxEncoder(t *testing.T) { - cdc := makeCodec() - - defaultEncoder := authtypes.DefaultTxEncoder(cdc) - encoder := GetTxEncoder(cdc) - - compareEncoders(t, defaultEncoder, encoder) -} - -func TestConfiguredTxEncoder(t *testing.T) { - cdc := makeCodec() - - customEncoder := func(tx sdk.Tx) ([]byte, error) { - return json.Marshal(tx) - } - - config := sdk.GetConfig() - config.SetTxEncoder(customEncoder) - - encoder := GetTxEncoder(cdc) - - compareEncoders(t, customEncoder, encoder) -} - -func TestReadStdTxFromFile(t *testing.T) { - t.Parallel() - - encodingConfig := simappparams.MakeEncodingConfig() - sdk.RegisterCodec(encodingConfig.Amino) - - txGen := encodingConfig.TxGenerator - clientCtx := client.Context{} - clientCtx = clientCtx.WithTxGenerator(txGen) - - // Build a test transaction - fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) - stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") - - // Write it to the file - encodedTx, err := txGen.TxJSONEncoder()(stdTx) - require.NoError(t, err) - jsonTxFile := writeToNewTempFile(t, string(encodedTx)) - defer os.Remove(jsonTxFile.Name()) - - // Read it back - decodedTx, err := ReadTxFromFile(clientCtx, jsonTxFile.Name()) - require.NoError(t, err) - require.Equal(t, decodedTx.(authtypes.StdTx).Memo, "foomemo") -} - -func TestBatchScanner_Scan(t *testing.T) { - t.Parallel() - cdc := codec.New() - sdk.RegisterCodec(cdc) - - batch1 := `{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"150"}],"gas":"50000"},"signatures":[],"memo":"foomemo"} -{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"150"}],"gas":"10000"},"signatures":[],"memo":"foomemo"} -{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"1"}],"gas":"10000"},"signatures":[],"memo":"foomemo"} -` - batch2 := `{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"150"}],"gas":"50000"},"signatures":[],"memo":"foomemo"} -malformed -{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"1"}],"gas":"10000"},"signatures":[],"memo":"foomemo"} -` - batch3 := `{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"150"}],"gas":"50000"},"signatures":[],"memo":"foomemo"} -{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"1"}],"gas":"10000"},"signatures":[],"memo":"foomemo"}` - batch4 := `{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"150"}],"gas":"50000"},"signatures":[],"memo":"foomemo"} - -{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"1"}],"gas":"10000"},"signatures":[],"memo":"foomemo"} -` - tests := []struct { - name string - batch string - wantScannerError bool - wantUnmarshalError bool - numTxs int - }{ - {"good batch", batch1, false, false, 3}, - {"malformed", batch2, false, true, 1}, - {"missing trailing newline", batch3, false, false, 2}, - {"empty line", batch4, false, true, 1}, - } - - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - scanner, i := NewBatchScanner(cdc, strings.NewReader(tt.batch)), 0 - for scanner.Scan() { - _ = scanner.StdTx() - i++ - } - - require.Equal(t, tt.wantScannerError, scanner.Err() != nil) - require.Equal(t, tt.wantUnmarshalError, scanner.UnmarshalErr() != nil) - require.Equal(t, tt.numTxs, i) - }) - } -} - -func compareEncoders(t *testing.T, expected sdk.TxEncoder, actual sdk.TxEncoder) { - msgs := []sdk.Msg{sdk.NewTestMsg(addr)} - tx := authtypes.NewStdTx(msgs, authtypes.StdFee{}, []authtypes.StdSignature{}, "") - - defaultEncoderBytes, err := expected(tx) - require.NoError(t, err) - encoderBytes, err := actual(tx) - require.NoError(t, err) - require.Equal(t, defaultEncoderBytes, encoderBytes) -} - -func TestPrepareTxBuilder(t *testing.T) { - cdc := makeCodec() - - encodingConfig := simappparams.MakeEncodingConfig() - sdk.RegisterCodec(encodingConfig.Amino) - - txGen := encodingConfig.TxGenerator - clientCtx := client.Context{} - clientCtx = clientCtx.WithTxGenerator(txGen) - - bldr := authtypes.NewTxBuilder( - authtypes.DefaultTxEncoder(cdc), 1, 1, - 200000, 1.1, false, "test-chain", - "test-builder", sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))), - sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDecWithPrec(10000, sdk.Precision))}) - - bldr, err := PrepareTxBuilder(bldr, clientCtx) - require.NoError(t, err) - require.Equal(t, 1, bldr.AccountNumber()) - require.Equal(t, 1, bldr.Sequence()) -} - -func writeToNewTempFile(t *testing.T, data string) *os.File { - fp, err := ioutil.TempFile(os.TempDir(), "client_tx_test") - require.NoError(t, err) - - _, err = fp.WriteString(data) - require.NoError(t, err) - - return fp -} - -func makeCodec() *codec.Codec { - var cdc = codec.New() - sdk.RegisterCodec(cdc) - cryptocodec.RegisterCrypto(cdc) - authtypes.RegisterCodec(cdc) - cdc.RegisterConcrete(sdk.TestMsg{}, "cosmos-sdk/Test", nil) - return cdc -} diff --git a/x/auth/types/client_tx_test.go b/x/auth/types/client_tx_test.go new file mode 100644 index 000000000000..c922484d6bde --- /dev/null +++ b/x/auth/types/client_tx_test.go @@ -0,0 +1,30 @@ +package types_test + +import ( + "github.com/cosmos/cosmos-sdk/client" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/stretchr/testify/require" + "testing" +) + +func TestTxEncoder(t *testing.T) { + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + + encodingConfig := simappparams.MakeEncodingConfig() + sdk.RegisterCodec(encodingConfig.Amino) + + txGen := encodingConfig.TxGenerator + clientCtx = clientCtx.WithTxGenerator(txGen) + + // Build a test transaction + fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) + stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") + + // Encode transaction + txBytes, err := clientCtx.TxGenerator.TxEncoder()(stdTx) + require.NoError(t, err) + require.NotNil(t, txBytes) +} From a51b36e04e658f20912b817464df13b5960b2460 Mon Sep 17 00:00:00 2001 From: sahith-narahari Date: Thu, 18 Jun 2020 20:50:09 +0530 Subject: [PATCH 19/26] Fix GetSign Cmd --- x/auth/client/cli/tx_sign.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 5fba10f6f877..43341469e2ef 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -225,7 +225,7 @@ func makeSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args []strin generateSignatureOnly = true } else { appendSig := viper.GetBool(flagAppend) && !generateSignatureOnly - newTx, err = authclient.SignStdTx(txBldr, clientCtx, clientCtx.From, stdTx, appendSig, clientCtx.Offline) + newTx, err = authclient.SignStdTx(txBldr, clientCtx, clientCtx.GetFromName(), stdTx, appendSig, clientCtx.Offline) } if err != nil { From c33987dce5de1a4d0b727cc0ac83174498ee40da Mon Sep 17 00:00:00 2001 From: sahith-narahari Date: Thu, 18 Jun 2020 20:54:46 +0530 Subject: [PATCH 20/26] Add tx test --- x/auth/client/tx_test.go | 247 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 247 insertions(+) create mode 100644 x/auth/client/tx_test.go diff --git a/x/auth/client/tx_test.go b/x/auth/client/tx_test.go new file mode 100644 index 000000000000..14103d3e33d6 --- /dev/null +++ b/x/auth/client/tx_test.go @@ -0,0 +1,247 @@ +package client + +import ( + "encoding/json" + "errors" + "io/ioutil" + "os" + "strings" + "testing" + + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + + "github.com/cosmos/cosmos-sdk/client" + + "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/crypto/ed25519" + + "github.com/cosmos/cosmos-sdk/codec" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +var ( + priv = ed25519.GenPrivKey() + addr = sdk.AccAddress(priv.PubKey().Address()) +) + +func TestParseQueryResponse(t *testing.T) { + simRes := &sdk.SimulationResponse{ + GasInfo: sdk.GasInfo{GasUsed: 10, GasWanted: 20}, + Result: &sdk.Result{Data: []byte("tx data"), Log: "log"}, + } + + bz, err := codec.ProtoMarshalJSON(simRes) + require.NoError(t, err) + + res, err := parseQueryResponse(bz) + require.NoError(t, err) + require.Equal(t, 10, int(res.GasInfo.GasUsed)) + require.NotNil(t, res.Result) + + res, err = parseQueryResponse([]byte("fuzzy")) + require.Error(t, err) +} + +func TestCalculateGas(t *testing.T) { + cdc := makeCodec() + makeQueryFunc := func(gasUsed uint64, wantErr bool) func(string, []byte) ([]byte, int64, error) { + return func(string, []byte) ([]byte, int64, error) { + if wantErr { + return nil, 0, errors.New("query failed") + } + simRes := &sdk.SimulationResponse{ + GasInfo: sdk.GasInfo{GasUsed: gasUsed, GasWanted: gasUsed}, + Result: &sdk.Result{Data: []byte("tx data"), Log: "log"}, + } + + bz, _ := codec.ProtoMarshalJSON(simRes) + return bz, 0, nil + } + } + + type args struct { + queryFuncGasUsed uint64 + queryFuncWantErr bool + adjustment float64 + } + + tests := []struct { + name string + args args + wantEstimate uint64 + wantAdjusted uint64 + expPass bool + }{ + {"error", args{0, true, 1.2}, 0, 0, false}, + {"adjusted gas", args{10, false, 1.2}, 10, 12, true}, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + queryFunc := makeQueryFunc(tt.args.queryFuncGasUsed, tt.args.queryFuncWantErr) + simRes, gotAdjusted, err := CalculateGas(queryFunc, cdc, []byte(""), tt.args.adjustment) + if tt.expPass { + require.NoError(t, err) + require.Equal(t, simRes.GasInfo.GasUsed, tt.wantEstimate) + require.Equal(t, gotAdjusted, tt.wantAdjusted) + require.NotNil(t, simRes.Result) + } else { + require.Error(t, err) + require.Nil(t, simRes.Result) + } + }) + } +} + +func TestDefaultTxEncoder(t *testing.T) { + cdc := makeCodec() + + defaultEncoder := authtypes.DefaultTxEncoder(cdc) + encoder := GetTxEncoder(cdc) + + compareEncoders(t, defaultEncoder, encoder) +} + +func TestConfiguredTxEncoder(t *testing.T) { + cdc := makeCodec() + + customEncoder := func(tx sdk.Tx) ([]byte, error) { + return json.Marshal(tx) + } + + config := sdk.GetConfig() + config.SetTxEncoder(customEncoder) + + encoder := GetTxEncoder(cdc) + + compareEncoders(t, customEncoder, encoder) +} + +func TestReadStdTxFromFile(t *testing.T) { + t.Parallel() + + encodingConfig := simappparams.MakeEncodingConfig() + sdk.RegisterCodec(encodingConfig.Amino) + + txGen := encodingConfig.TxGenerator + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(txGen) + + // Build a test transaction + fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) + stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") + + // Write it to the file + encodedTx, err := txGen.TxJSONEncoder()(stdTx) + require.NoError(t, err) + jsonTxFile := writeToNewTempFile(t, string(encodedTx)) + defer os.Remove(jsonTxFile.Name()) + + // Read it back + decodedTx, err := ReadTxFromFile(clientCtx, jsonTxFile.Name()) + require.NoError(t, err) + require.Equal(t, decodedTx.(authtypes.StdTx).Memo, "foomemo") +} + +func TestBatchScanner_Scan(t *testing.T) { + t.Parallel() + cdc := codec.New() + sdk.RegisterCodec(cdc) + + batch1 := `{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"150"}],"gas":"50000"},"signatures":[],"memo":"foomemo"} +{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"150"}],"gas":"10000"},"signatures":[],"memo":"foomemo"} +{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"1"}],"gas":"10000"},"signatures":[],"memo":"foomemo"} +` + batch2 := `{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"150"}],"gas":"50000"},"signatures":[],"memo":"foomemo"} +malformed +{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"1"}],"gas":"10000"},"signatures":[],"memo":"foomemo"} +` + batch3 := `{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"150"}],"gas":"50000"},"signatures":[],"memo":"foomemo"} +{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"1"}],"gas":"10000"},"signatures":[],"memo":"foomemo"}` + batch4 := `{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"150"}],"gas":"50000"},"signatures":[],"memo":"foomemo"} + +{"msg":[],"fee":{"amount":[{"denom":"atom","amount":"1"}],"gas":"10000"},"signatures":[],"memo":"foomemo"} +` + tests := []struct { + name string + batch string + wantScannerError bool + wantUnmarshalError bool + numTxs int + }{ + {"good batch", batch1, false, false, 3}, + {"malformed", batch2, false, true, 1}, + {"missing trailing newline", batch3, false, false, 2}, + {"empty line", batch4, false, true, 1}, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + scanner, i := NewBatchScanner(cdc, strings.NewReader(tt.batch)), 0 + for scanner.Scan() { + _ = scanner.StdTx() + i++ + } + + require.Equal(t, tt.wantScannerError, scanner.Err() != nil) + require.Equal(t, tt.wantUnmarshalError, scanner.UnmarshalErr() != nil) + require.Equal(t, tt.numTxs, i) + }) + } +} + +func compareEncoders(t *testing.T, expected sdk.TxEncoder, actual sdk.TxEncoder) { + msgs := []sdk.Msg{sdk.NewTestMsg(addr)} + tx := authtypes.NewStdTx(msgs, authtypes.StdFee{}, []authtypes.StdSignature{}, "") + + defaultEncoderBytes, err := expected(tx) + require.NoError(t, err) + encoderBytes, err := actual(tx) + require.NoError(t, err) + require.Equal(t, defaultEncoderBytes, encoderBytes) +} + +func TestPrepareTxBuilder(t *testing.T) { + cdc := makeCodec() + + encodingConfig := simappparams.MakeEncodingConfig() + sdk.RegisterCodec(encodingConfig.Amino) + + txGen := encodingConfig.TxGenerator + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(txGen) + + bldr := authtypes.NewTxBuilder( + authtypes.DefaultTxEncoder(cdc), 1, 1, + 200000, 1.1, false, "test-chain", + "test-builder", sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))), + sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDecWithPrec(10000, sdk.Precision))}) + + bldr, err := PrepareTxBuilder(bldr, clientCtx) + require.NoError(t, err) + require.Equal(t, 1, bldr.AccountNumber()) + require.Equal(t, 1, bldr.Sequence()) +} + +func writeToNewTempFile(t *testing.T, data string) *os.File { + fp, err := ioutil.TempFile(os.TempDir(), "client_tx_test") + require.NoError(t, err) + + _, err = fp.WriteString(data) + require.NoError(t, err) + + return fp +} + +func makeCodec() *codec.Codec { + var cdc = codec.New() + sdk.RegisterCodec(cdc) + cryptocodec.RegisterCrypto(cdc) + authtypes.RegisterCodec(cdc) + cdc.RegisterConcrete(sdk.TestMsg{}, "cosmos-sdk/Test", nil) + return cdc +} From 766f8087a6e839b323346087f7b35f1c2e1ddb62 Mon Sep 17 00:00:00 2001 From: sahith-narahari Date: Thu, 18 Jun 2020 20:58:13 +0530 Subject: [PATCH 21/26] Remove duplicate validation --- x/auth/client/tx.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index cc12aa9a0cc1..5f1b6a9cafb7 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -331,9 +331,6 @@ func parseQueryResponse(bz []byte) (sdk.SimulationResponse, error) { // PrepareTxBuilder populates a TxBuilder in preparation for the build of a Tx. func PrepareTxBuilder(txBldr authtypes.TxBuilder, clientCtx client.Context) (authtypes.TxBuilder, error) { from := clientCtx.GetFromAddress() - if from == nil { - return authtypes.TxBuilder{}, fmt.Errorf("unable to fetch from address from clientCtx") - } accGetter := clientCtx.AccountRetriever if err := accGetter.EnsureExists(clientCtx, from); err != nil { return txBldr, err From e0cb1d47ffbb113b26b59ea95807cdf1a5f47f77 Mon Sep 17 00:00:00 2001 From: sahith-narahari Date: Thu, 18 Jun 2020 21:17:49 +0530 Subject: [PATCH 22/26] Add tests for TxDecoder --- x/auth/types/client_tx_test.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/x/auth/types/client_tx_test.go b/x/auth/types/client_tx_test.go index c922484d6bde..8e1888da9126 100644 --- a/x/auth/types/client_tx_test.go +++ b/x/auth/types/client_tx_test.go @@ -21,10 +21,14 @@ func TestTxEncoder(t *testing.T) { // Build a test transaction fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) - stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") + stdTx := authtypes.NewStdTx([]sdk.Msg{nil}, fee, []authtypes.StdSignature{}, "foomemo") // Encode transaction txBytes, err := clientCtx.TxGenerator.TxEncoder()(stdTx) require.NoError(t, err) require.NotNil(t, txBytes) + + tx, err := clientCtx.TxGenerator.TxDecoder()(txBytes) + require.NoError(t, err) + require.Equal(t, []sdk.Msg{nil}, tx.GetMsgs()) } From 78daa5e128f32dceb213b147e5a3449eccbff3b5 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Thu, 18 Jun 2020 12:24:16 -0400 Subject: [PATCH 23/26] Fix tests --- client/tx/tx.go | 2 +- x/auth/client/cli/broadcast.go | 2 +- x/auth/client/cli/cli_test.go | 1 - x/auth/client/cli/encode.go | 2 +- x/auth/client/cli/encode_test.go | 13 +++++++++---- 5 files changed, 12 insertions(+), 8 deletions(-) diff --git a/client/tx/tx.go b/client/tx/tx.go index 90a68557016c..384093852a9b 100644 --- a/client/tx/tx.go +++ b/client/tx/tx.go @@ -114,7 +114,7 @@ func BroadcastTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error { return err } - txBytes, err := clientCtx.TxGenerator.MarshalTx(tx.GetTx()) + txBytes, err := clientCtx.TxGenerator.TxEncoder()(tx.GetTx()) if err != nil { return err } diff --git a/x/auth/client/cli/broadcast.go b/x/auth/client/cli/broadcast.go index e17e6d774eeb..0802219867ad 100644 --- a/x/auth/client/cli/broadcast.go +++ b/x/auth/client/cli/broadcast.go @@ -25,7 +25,7 @@ $ tx broadcast ./mytxn.json `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - clientCtx = clientCtx.Init().WithJSONMarshaler(cdc) + clientCtx = clientCtx.Init() if clientCtx.Offline { return errors.New("cannot broadcast tx during offline mode") diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index a2bb90f735a0..8fb2d4c82086 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -14,7 +14,6 @@ import ( "github.com/cosmos/cosmos-sdk/tests/cli" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/client/testutil" - "github.com/cosmos/cosmos-sdk/x/auth/types" bankcli "github.com/cosmos/cosmos-sdk/x/bank/client/testutil" ) diff --git a/x/auth/client/cli/encode.go b/x/auth/client/cli/encode.go index 53cbcb6380b0..7b4c88cc52d1 100644 --- a/x/auth/client/cli/encode.go +++ b/x/auth/client/cli/encode.go @@ -22,7 +22,7 @@ Read a transaction from , serialize it to the Amino wire protocol, and out If you supply a dash (-) argument in place of an input filename, the command reads from standard input.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := clientCtx.Init().WithJSONMarshaler(cdc) + cliCtx := clientCtx.Init() tx, err := authclient.ReadTxFromFile(cliCtx, args[0]) if err != nil { diff --git a/x/auth/client/cli/encode_test.go b/x/auth/client/cli/encode_test.go index c4419e1fccdc..296160325405 100644 --- a/x/auth/client/cli/encode_test.go +++ b/x/auth/client/cli/encode_test.go @@ -13,11 +13,13 @@ import ( ) func TestGetCommandEncode(t *testing.T) { + encodingConfig := simappparams.MakeEncodingConfig() clientCtx := client.Context{} - clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + clientCtx = clientCtx. + WithTxGenerator(encodingConfig.TxGenerator). + WithJSONMarshaler(encodingConfig.Marshaler) cmd := GetEncodeCommand(clientCtx) - encodingConfig := simappparams.MakeEncodingConfig() authtypes.RegisterCodec(encodingConfig.Amino) sdk.RegisterCodec(encodingConfig.Amino) @@ -38,12 +40,15 @@ func TestGetCommandEncode(t *testing.T) { } func TestGetCommandDecode(t *testing.T) { + encodingConfig := simappparams.MakeEncodingConfig() + clientCtx := client.Context{} - clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + clientCtx = clientCtx. + WithTxGenerator(encodingConfig.TxGenerator). + WithJSONMarshaler(encodingConfig.Marshaler) cmd := GetDecodeCommand(clientCtx) - encodingConfig := simappparams.MakeEncodingConfig() sdk.RegisterCodec(encodingConfig.Amino) txGen := encodingConfig.TxGenerator From c1d5bf33757c8677ae155c732ecd245c4a032b56 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Thu, 18 Jun 2020 12:58:27 -0400 Subject: [PATCH 24/26] Fix tests --- client/test_helpers.go | 36 ++++++++++++++++++++++++++++++++++++ x/auth/client/tx.go | 2 +- x/auth/client/tx_test.go | 28 ++++++++++++++++++++++++---- 3 files changed, 61 insertions(+), 5 deletions(-) create mode 100644 client/test_helpers.go diff --git a/client/test_helpers.go b/client/test_helpers.go new file mode 100644 index 000000000000..4c16ce63bfbc --- /dev/null +++ b/client/test_helpers.go @@ -0,0 +1,36 @@ +package client + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// TestAccountRetriever is an AccountRetriever that can be used in unit tests +type TestAccountRetriever struct { + Accounts map[string]struct { + Address sdk.AccAddress + Num uint64 + Seq uint64 + } +} + +var _ AccountRetriever = TestAccountRetriever{} + +// EnsureExists implements AccountRetriever.EnsureExists +func (t TestAccountRetriever) EnsureExists(_ NodeQuerier, addr sdk.AccAddress) error { + _, ok := t.Accounts[addr.String()] + if !ok { + return fmt.Errorf("account %s not found", addr) + } + return nil +} + +// GetAccountNumberSequence implements AccountRetriever.GetAccountNumberSequence +func (t TestAccountRetriever) GetAccountNumberSequence(_ NodeQuerier, addr sdk.AccAddress) (accNum uint64, accSeq uint64, err error) { + acc, ok := t.Accounts[addr.String()] + if !ok { + return 0, 0, fmt.Errorf("account %s not found", addr) + } + return acc.Num, acc.Seq, nil +} diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index 2a17166997a8..a2bad734a4d2 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -340,7 +340,7 @@ func PrepareTxBuilder(txBldr authtypes.TxBuilder, clientCtx client.Context) (aut // TODO: (ref #1903) Allow for user supplied account number without // automatically doing a manual lookup. if txbldrAccNum == 0 || txbldrAccSeq == 0 { - num, seq, err := authtypes.NewAccountRetriever(Codec).GetAccountNumberSequence(clientCtx, from) + num, seq, err := accGetter.GetAccountNumberSequence(clientCtx, from) if err != nil { return txBldr, err } diff --git a/x/auth/client/tx_test.go b/x/auth/client/tx_test.go index 14103d3e33d6..ed09f31580ba 100644 --- a/x/auth/client/tx_test.go +++ b/x/auth/client/tx_test.go @@ -211,20 +211,40 @@ func TestPrepareTxBuilder(t *testing.T) { encodingConfig := simappparams.MakeEncodingConfig() sdk.RegisterCodec(encodingConfig.Amino) + fromAddr := sdk.AccAddress("test-addr0000000000") + fromAddrStr := fromAddr.String() + + var accNum uint64 = 10 + var accSeq uint64 = 17 + txGen := encodingConfig.TxGenerator clientCtx := client.Context{} - clientCtx = clientCtx.WithTxGenerator(txGen) + clientCtx = clientCtx. + WithTxGenerator(txGen). + WithJSONMarshaler(encodingConfig.Marshaler). + WithAccountRetriever(client.TestAccountRetriever{Accounts: map[string]struct { + Address sdk.AccAddress + Num uint64 + Seq uint64 + }{ + fromAddrStr: { + Address: fromAddr, + Num: accNum, + Seq: accSeq, + }, + }}). + WithFromAddress(fromAddr) bldr := authtypes.NewTxBuilder( - authtypes.DefaultTxEncoder(cdc), 1, 1, + authtypes.DefaultTxEncoder(cdc), 0, 0, 200000, 1.1, false, "test-chain", "test-builder", sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))), sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDecWithPrec(10000, sdk.Precision))}) bldr, err := PrepareTxBuilder(bldr, clientCtx) require.NoError(t, err) - require.Equal(t, 1, bldr.AccountNumber()) - require.Equal(t, 1, bldr.Sequence()) + require.Equal(t, accNum, bldr.AccountNumber()) + require.Equal(t, accSeq, bldr.Sequence()) } func writeToNewTempFile(t *testing.T, data string) *os.File { From 6cf5831496766154fd08f9d70cebf5d6fd53a997 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Thu, 18 Jun 2020 13:11:20 -0400 Subject: [PATCH 25/26] Output to clientCtx.Output --- x/auth/client/cli/encode.go | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/x/auth/client/cli/encode.go b/x/auth/client/cli/encode.go index 7b4c88cc52d1..3ca0b46b3aed 100644 --- a/x/auth/client/cli/encode.go +++ b/x/auth/client/cli/encode.go @@ -2,7 +2,6 @@ package cli import ( "encoding/base64" - "fmt" "github.com/spf13/cobra" @@ -11,6 +10,13 @@ import ( authclient "github.com/cosmos/cosmos-sdk/x/auth/client" ) +// txEncodeRespStr implements a simple Stringer wrapper for a encoded tx. +type txEncodeRespStr string + +func (txr txEncodeRespStr) String() string { + return string(txr) +} + // GetEncodeCommand returns the encode command to take a JSONified transaction and turn it into // Amino-serialized bytes func GetEncodeCommand(clientCtx client.Context) *cobra.Command { @@ -38,9 +44,8 @@ If you supply a dash (-) argument in place of an input filename, the command rea // base64 encode the encoded tx bytes txBytesBase64 := base64.StdEncoding.EncodeToString(txBytes) - fmt.Println(txBytesBase64) - - return nil + response := txEncodeRespStr(txBytesBase64) + return clientCtx.PrintOutput(response) }, } From 2f5ac90dc053c2e249f2bb8005630dfe3d6d7375 Mon Sep 17 00:00:00 2001 From: sahith-narahari Date: Fri, 19 Jun 2020 01:50:48 +0530 Subject: [PATCH 26/26] Fix cli_tests --- x/auth/client/cli/cli_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 8fb2d4c82086..c09915a30b49 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -299,9 +299,9 @@ func TestCLIEncode(t *testing.T) { // Run the encode command success, base64Encoded, _ := testutil.TxEncode(f, jsonTxFile.Name()) require.True(t, success) - + trimmedBase64 := strings.Trim(base64Encoded, "\"\n") // Check that the transaction decodes as expected - success, stdout, stderr = testutil.TxDecode(f, base64Encoded) + success, stdout, stderr = testutil.TxDecode(f, trimmedBase64) decodedTx := cli.UnmarshalStdTx(t, f.Cdc, stdout) require.Equal(t, "deadbeef", decodedTx.Memo) }