From 9a02e1a1388aea4860a8a64fea07d92411e3ef52 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 2 Jul 2020 01:04:54 +0200 Subject: [PATCH 01/46] remove unused functions --- x/auth/client/cli/cli_test.go | 124 +++++++++++++++++++++--------- x/bank/client/testutil/helpers.go | 43 ----------- 2 files changed, 89 insertions(+), 78 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index c09915a30b49..d887494347a4 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -1,22 +1,72 @@ -// +build cli_test - package cli_test import ( + "bytes" "fmt" "strings" "testing" + cli2 "github.com/cosmos/cosmos-sdk/x/bank/client/cli" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/tests/cli" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/client/testutil" + authtest "github.com/cosmos/cosmos-sdk/x/auth/client/testutil" bankcli "github.com/cosmos/cosmos-sdk/x/bank/client/testutil" ) +type IntegrationTestSuite struct { + suite.Suite + + cfg testutil.Config + network *testutil.Network +} + +func (s *IntegrationTestSuite) SetupSuite() { + s.T().Log("setting up integration test suite") + + cfg := testutil.DefaultConfig() + cfg.NumValidators = 1 + + s.cfg = cfg + s.network = testutil.NewTestNetwork(s.T(), cfg) + + _, err := s.network.WaitForHeight(1) + s.Require().NoError(err) +} + +func (s *IntegrationTestSuite) TearDownSuite() { + s.T().Log("tearing down integration test suite") + s.network.Cleanup() +} + +func (s *IntegrationTestSuite) TestCLIValidateSignatures() { + val := s.network.Validators[0] + buf := new(bytes.Buffer) + + val.ClientCtx = val.ClientCtx.WithOutput(buf) + cmd := cli2.NewSendTxCmd(val.ClientCtx) + cmd.SetArgs([]string{ + val.Address.String(), + val.Address.String(), + sdk.NewCoins( + sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), + sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), + ).String(), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), + }) + err := cmd.Execute() + s.Require().NoError(err) +} + func TestCLIValidateSignatures(t *testing.T) { t.Parallel() f := cli.InitFixtures(t) @@ -40,7 +90,7 @@ func TestCLIValidateSignatures(t *testing.T) { t.Cleanup(cleanup) // validate we can successfully sign - success, stdout, _ = testutil.TxSign(f, cli.KeyFoo, unsignedTxFile.Name()) + success, stdout, _ = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name()) require.True(t, success) stdTx := cli.UnmarshalStdTx(t, f.Cdc, stdout) @@ -54,7 +104,7 @@ func TestCLIValidateSignatures(t *testing.T) { t.Cleanup(cleanup) // validate signatures - success, _, _ = testutil.TxValidateSignatures(f, signedTxFile.Name()) + success, _, _ = authtest.TxValidateSignatures(f, signedTxFile.Name()) require.True(t, success) // modify the transaction @@ -64,7 +114,7 @@ func TestCLIValidateSignatures(t *testing.T) { t.Cleanup(cleanup) // validate signature validation failure due to different transaction sig bytes - success, _, _ = testutil.TxValidateSignatures(f, modSignedTxFile.Name()) + success, _, _ = authtest.TxValidateSignatures(f, modSignedTxFile.Name()) require.False(t, success) // Cleanup testing directories @@ -89,18 +139,18 @@ func TestCLISignBatch(t *testing.T) { t.Cleanup(cleanup1) // sign-batch file - offline is set but account-number and sequence are not - success, _, stderr = testutil.TxSignBatch(f, cli.KeyFoo, batchfile.Name(), "--offline") + success, _, stderr = authtest.TxSignBatch(f, cli.KeyFoo, batchfile.Name(), "--offline") require.Contains(t, stderr, "required flag(s) \"account-number\", \"sequence\" not set") require.False(t, success) // sign-batch file - success, stdout, stderr := testutil.TxSignBatch(f, cli.KeyFoo, batchfile.Name()) + success, stdout, stderr := authtest.TxSignBatch(f, cli.KeyFoo, batchfile.Name()) require.True(t, success) require.Empty(t, stderr) require.Equal(t, 3, len(strings.Split(strings.Trim(stdout, "\n"), "\n"))) // sign-batch file - success, stdout, stderr = testutil.TxSignBatch(f, cli.KeyFoo, batchfile.Name(), "--signature-only") + success, stdout, stderr = authtest.TxSignBatch(f, cli.KeyFoo, batchfile.Name(), "--signature-only") require.True(t, success) require.Empty(t, stderr) require.Equal(t, 3, len(strings.Split(strings.Trim(stdout, "\n"), "\n"))) @@ -109,13 +159,13 @@ func TestCLISignBatch(t *testing.T) { t.Cleanup(cleanup2) // sign-batch file - success, stdout, stderr = testutil.TxSignBatch(f, cli.KeyFoo, malformedFile.Name()) + success, stdout, stderr = authtest.TxSignBatch(f, cli.KeyFoo, malformedFile.Name()) require.False(t, success) require.Equal(t, 1, len(strings.Split(strings.Trim(stdout, "\n"), "\n"))) require.Equal(t, "ERROR: cannot parse disfix JSON wrapper: invalid character 'm' looking for beginning of value\n", stderr) // sign-batch file - success, stdout, _ = testutil.TxSignBatch(f, cli.KeyFoo, malformedFile.Name(), "--signature-only") + success, stdout, _ = authtest.TxSignBatch(f, cli.KeyFoo, malformedFile.Name(), "--signature-only") require.False(t, success) require.Equal(t, 1, len(strings.Split(strings.Trim(stdout, "\n"), "\n"))) @@ -166,23 +216,23 @@ func TestCLISendGenerateSignAndBroadcast(t *testing.T) { t.Cleanup(cleanup) // Test validate-signatures - success, stdout, _ = testutil.TxValidateSignatures(f, unsignedTxFile.Name()) + success, stdout, _ = authtest.TxValidateSignatures(f, unsignedTxFile.Name()) require.False(t, success) require.Equal(t, fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n\n", fooAddr.String()), stdout) // Test sign // Does not work in offline mode - success, stdout, stderr = testutil.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--offline") + success, stdout, stderr = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--offline") require.Contains(t, stderr, "required flag(s) \"account-number\", \"sequence\" not set") require.False(t, success) // But works offline if we set account number and sequence - success, _, _ = testutil.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--offline", "--account-number", "1", "--sequence", "1") + success, _, _ = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--offline", "--account-number", "1", "--sequence", "1") require.True(t, success) // Sign transaction - success, stdout, _ = testutil.TxSign(f, cli.KeyFoo, unsignedTxFile.Name()) + success, stdout, _ = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name()) require.True(t, success) msg = cli.UnmarshalStdTx(t, f.Cdc, stdout) require.Equal(t, len(msg.Msgs), 1) @@ -194,7 +244,7 @@ func TestCLISendGenerateSignAndBroadcast(t *testing.T) { t.Cleanup(cleanup) // Test validate-signatures - success, stdout, _ = testutil.TxValidateSignatures(f, signedTxFile.Name()) + success, stdout, _ = authtest.TxValidateSignatures(f, signedTxFile.Name()) require.True(t, success) require.Equal(t, fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n 0: %v\t\t\t[OK]\n\n", fooAddr.String(), fooAddr.String()), stdout) @@ -206,12 +256,12 @@ func TestCLISendGenerateSignAndBroadcast(t *testing.T) { // Test broadcast // Does not work in offline mode - success, _, stderr = testutil.TxBroadcast(f, signedTxFile.Name(), "--offline") + success, _, stderr = authtest.TxBroadcast(f, signedTxFile.Name(), "--offline") require.Contains(t, stderr, "cannot broadcast tx during offline mode") require.False(t, success) tests.WaitForNextNBlocksTM(1, f.Port) - success, stdout, _ = testutil.TxBroadcast(f, signedTxFile.Name()) + success, stdout, _ = authtest.TxBroadcast(f, signedTxFile.Name()) require.True(t, success) tests.WaitForNextNBlocksTM(1, f.Port) @@ -247,7 +297,7 @@ func TestCLIMultisignInsufficientCosigners(t *testing.T) { t.Cleanup(cleanup) // Sign with foo's key - success, stdout, _ = testutil.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") + success, stdout, _ = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") require.True(t, success) // Write the output to disk @@ -255,7 +305,7 @@ func TestCLIMultisignInsufficientCosigners(t *testing.T) { t.Cleanup(cleanup) // Multisign, not enough signatures - success, stdout, _ = testutil.TxMultisign(f, unsignedTxFile.Name(), cli.KeyFooBarBaz, []string{fooSignatureFile.Name()}) + success, stdout, _ = authtest.TxMultisign(f, unsignedTxFile.Name(), cli.KeyFooBarBaz, []string{fooSignatureFile.Name()}) require.True(t, success) // Write the output to disk @@ -263,11 +313,11 @@ func TestCLIMultisignInsufficientCosigners(t *testing.T) { t.Cleanup(cleanup) // Validate the multisignature - success, _, _ = testutil.TxValidateSignatures(f, signedTxFile.Name()) + success, _, _ = authtest.TxValidateSignatures(f, signedTxFile.Name()) require.False(t, success) // Broadcast the transaction - success, stdOut, _ := testutil.TxBroadcast(f, signedTxFile.Name()) + success, stdOut, _ := authtest.TxBroadcast(f, signedTxFile.Name()) require.Contains(t, stdOut, "signature verification failed") require.True(t, success) @@ -297,11 +347,11 @@ func TestCLIEncode(t *testing.T) { t.Cleanup(cleanup) // Run the encode command - success, base64Encoded, _ := testutil.TxEncode(f, jsonTxFile.Name()) + success, base64Encoded, _ := authtest.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, trimmedBase64) + success, stdout, stderr = authtest.TxDecode(f, trimmedBase64) decodedTx := cli.UnmarshalStdTx(t, f.Cdc, stdout) require.Equal(t, "deadbeef", decodedTx.Memo) } @@ -334,7 +384,7 @@ func TestCLIMultisignSortSignatures(t *testing.T) { t.Cleanup(cleanup) // Sign with foo's key - success, stdout, _ = testutil.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String()) + success, stdout, _ = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String()) require.True(t, success) // Write the output to disk @@ -342,7 +392,7 @@ func TestCLIMultisignSortSignatures(t *testing.T) { t.Cleanup(cleanup) // Sign with baz's key - success, stdout, _ = testutil.TxSign(f, cli.KeyBaz, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String()) + success, stdout, _ = authtest.TxSign(f, cli.KeyBaz, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String()) require.True(t, success) // Write the output to disk @@ -350,7 +400,7 @@ func TestCLIMultisignSortSignatures(t *testing.T) { t.Cleanup(cleanup) // Multisign, keys in different order - success, stdout, _ = testutil.TxMultisign(f, unsignedTxFile.Name(), cli.KeyFooBarBaz, []string{ + success, stdout, _ = authtest.TxMultisign(f, unsignedTxFile.Name(), cli.KeyFooBarBaz, []string{ bazSignatureFile.Name(), fooSignatureFile.Name()}) require.True(t, success) @@ -359,11 +409,11 @@ func TestCLIMultisignSortSignatures(t *testing.T) { t.Cleanup(cleanup) // Validate the multisignature - success, _, _ = testutil.TxValidateSignatures(f, signedTxFile.Name()) + success, _, _ = authtest.TxValidateSignatures(f, signedTxFile.Name()) require.True(t, success) // Broadcast the transaction - success, _, _ = testutil.TxBroadcast(f, signedTxFile.Name()) + success, _, _ = authtest.TxBroadcast(f, signedTxFile.Name()) require.True(t, success) // Cleanup testing directories @@ -399,7 +449,7 @@ func TestCLIMultisign(t *testing.T) { t.Cleanup(cleanup) // Sign with foo's key - success, stdout, _ = testutil.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") + success, stdout, _ = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") require.True(t, success) // Write the output to disk @@ -407,7 +457,7 @@ func TestCLIMultisign(t *testing.T) { t.Cleanup(cleanup) // Sign with bar's key - success, stdout, _ = testutil.TxSign(f, cli.KeyBar, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") + success, stdout, _ = authtest.TxSign(f, cli.KeyBar, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") require.True(t, success) // Write the output to disk @@ -417,13 +467,13 @@ func TestCLIMultisign(t *testing.T) { // Multisign // Does not work in offline mode - success, stdout, _ = testutil.TxMultisign(f, unsignedTxFile.Name(), cli.KeyFooBarBaz, []string{ + success, stdout, _ = authtest.TxMultisign(f, unsignedTxFile.Name(), cli.KeyFooBarBaz, []string{ fooSignatureFile.Name(), barSignatureFile.Name()}, "--offline") require.Contains(t, "couldn't verify signature", stdout) require.False(t, success) // Success multisign - success, stdout, _ = testutil.TxMultisign(f, unsignedTxFile.Name(), cli.KeyFooBarBaz, []string{ + success, stdout, _ = authtest.TxMultisign(f, unsignedTxFile.Name(), cli.KeyFooBarBaz, []string{ fooSignatureFile.Name(), barSignatureFile.Name()}) require.True(t, success) @@ -432,13 +482,17 @@ func TestCLIMultisign(t *testing.T) { t.Cleanup(cleanup) // Validate the multisignature - success, _, _ = testutil.TxValidateSignatures(f, signedTxFile.Name()) + success, _, _ = authtest.TxValidateSignatures(f, signedTxFile.Name()) require.True(t, success) // Broadcast the transaction - success, _, _ = testutil.TxBroadcast(f, signedTxFile.Name()) + success, _, _ = authtest.TxBroadcast(f, signedTxFile.Name()) require.True(t, success) // Cleanup testing directories f.Cleanup() } + +func TestIntegrationTestSuite(t *testing.T) { + suite.Run(t, new(IntegrationTestSuite)) +} diff --git a/x/bank/client/testutil/helpers.go b/x/bank/client/testutil/helpers.go index 1a440ce3df5e..8ecbf8da692c 100644 --- a/x/bank/client/testutil/helpers.go +++ b/x/bank/client/testutil/helpers.go @@ -1,7 +1,6 @@ package testutil import ( - "encoding/json" "fmt" "github.com/stretchr/testify/require" @@ -10,7 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/tests/cli" sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) // TODO: REMOVE OR COMPLETELY REFACTOR THIS FILE. @@ -21,24 +19,6 @@ func TxSend(f *cli.Fixtures, from string, to sdk.AccAddress, amount sdk.Coin, fl return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } -// QueryAccount is simcli query account -func QueryAccount(f *cli.Fixtures, address sdk.AccAddress, flags ...string) authtypes.BaseAccount { - cmd := fmt.Sprintf("%s query account %s %v", f.SimcliBinary, address, f.Flags()) - - out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") - - var initRes map[string]json.RawMessage - err := json.Unmarshal([]byte(out), &initRes) - require.NoError(f.T, err, "out %v, err %v", out, err) - value := initRes["value"] - - var acc authtypes.BaseAccount - err = f.Cdc.UnmarshalJSON(value, &acc) - require.NoError(f.T, err, "value %v, err %v", string(value), err) - - return acc -} - // QueryBalances executes the bank query balances command for a given address and // flag set. func QueryBalances(f *cli.Fixtures, address sdk.AccAddress, flags ...string) sdk.Coins { @@ -51,26 +31,3 @@ func QueryBalances(f *cli.Fixtures, address sdk.AccAddress, flags ...string) sdk return balances } - -// QueryTotalSupply returns the total supply of coins -func QueryTotalSupply(f *cli.Fixtures, flags ...string) (totalSupply sdk.Coins) { - cmd := fmt.Sprintf("%s query bank total %s", f.SimcliBinary, f.Flags()) - res, errStr := tests.ExecuteT(f.T, cmd, "") - require.Empty(f.T, errStr) - - err := f.Cdc.UnmarshalJSON([]byte(res), &totalSupply) - require.NoError(f.T, err) - return totalSupply -} - -// QueryTotalSupplyOf returns the total supply of a given coin denom -func QueryTotalSupplyOf(f *cli.Fixtures, denom string, flags ...string) sdk.Int { - cmd := fmt.Sprintf("%s query bank total %s %s", f.SimcliBinary, denom, f.Flags()) - res, errStr := tests.ExecuteT(f.T, cmd, "") - require.Empty(f.T, errStr) - - var supplyOf sdk.Int - err := f.Cdc.UnmarshalJSON([]byte(res), &supplyOf) - require.NoError(f.T, err) - return supplyOf -} From 55cabc91d3e1892a71e132e678753900aa39f813 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 2 Jul 2020 01:19:39 +0200 Subject: [PATCH 02/46] create helper func to send tx --- x/auth/client/cli/cli_test.go | 16 +++++----------- x/bank/client/testutil/helpers.go | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index d887494347a4..9631a3e1f551 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -1,13 +1,10 @@ package cli_test import ( - "bytes" "fmt" "strings" "testing" - cli2 "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -47,24 +44,21 @@ func (s *IntegrationTestSuite) TearDownSuite() { func (s *IntegrationTestSuite) TestCLIValidateSignatures() { val := s.network.Validators[0] - buf := new(bytes.Buffer) - - val.ClientCtx = val.ClientCtx.WithOutput(buf) - cmd := cli2.NewSendTxCmd(val.ClientCtx) - cmd.SetArgs([]string{ + tx, err := bankcli.SendTx( + val.ClientCtx, val.Address.String(), val.Address.String(), sdk.NewCoins( sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), - ).String(), + ), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), - }) - err := cmd.Execute() + ) s.Require().NoError(err) + fmt.Printf("%s", tx) } func TestCLIValidateSignatures(t *testing.T) { diff --git a/x/bank/client/testutil/helpers.go b/x/bank/client/testutil/helpers.go index 8ecbf8da692c..8863d146f39a 100644 --- a/x/bank/client/testutil/helpers.go +++ b/x/bank/client/testutil/helpers.go @@ -1,14 +1,17 @@ package testutil import ( + "bytes" "fmt" "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/client" clientkeys "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/tests/cli" sdk "github.com/cosmos/cosmos-sdk/types" + bankcli "github.com/cosmos/cosmos-sdk/x/bank/client/cli" ) // TODO: REMOVE OR COMPLETELY REFACTOR THIS FILE. @@ -19,6 +22,22 @@ func TxSend(f *cli.Fixtures, from string, to sdk.AccAddress, amount sdk.Coin, fl return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } +func SendTx(ctx client.Context, from string, to string, amount sdk.Coins, flags ...string) ([]byte, error) { + buf := new(bytes.Buffer) + ctx = ctx.WithOutput(buf) + + cmd := bankcli.NewSendTxCmd(ctx) + args := append([]string{from, to, amount.String()}, flags...) + cmd.SetArgs(args) + + err := cmd.Execute() + if err != nil { + return nil, err + } + + return buf.Bytes(), nil +} + // QueryBalances executes the bank query balances command for a given address and // flag set. func QueryBalances(f *cli.Fixtures, address sdk.AccAddress, flags ...string) sdk.Coins { From 3c5dec40e3a22ba4c45abda549b8b300666fddca Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 2 Jul 2020 01:31:10 +0200 Subject: [PATCH 03/46] refactor to use test help to send tx by client --- x/bank/client/cli/cli_test.go | 65 ++++++++++++++----------------- x/bank/client/testutil/helpers.go | 1 + 2 files changed, 31 insertions(+), 35 deletions(-) diff --git a/x/bank/client/cli/cli_test.go b/x/bank/client/cli/cli_test.go index baeba0605bcf..602f00c08305 100644 --- a/x/bank/client/cli/cli_test.go +++ b/x/bank/client/cli/cli_test.go @@ -12,6 +12,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/bank/client/cli" + banktest "github.com/cosmos/cosmos-sdk/x/bank/client/testutil" ) type IntegrationTestSuite struct { @@ -176,12 +177,13 @@ func (s *IntegrationTestSuite) TestGetCmdQueryTotalSupply() { } func (s *IntegrationTestSuite) TestNewSendTxCmd() { - buf := new(bytes.Buffer) val := s.network.Validators[0] - clientCtx := val.ClientCtx.WithOutput(buf) testCases := []struct { name string + from string + to string + amount sdk.Coins args []string expectErr bool respType fmt.Stringer @@ -189,13 +191,13 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { }{ { "valid transaction (gen-only)", + val.Address.String(), + val.Address.String(), + sdk.NewCoins( + sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), + sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), + ), []string{ - val.Address.String(), - val.Address.String(), - sdk.NewCoins( - sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), - sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), - ).String(), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), @@ -207,13 +209,13 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { }, { "valid transaction", + val.Address.String(), + val.Address.String(), + sdk.NewCoins( + sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), + sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), + ), []string{ - val.Address.String(), - val.Address.String(), - sdk.NewCoins( - sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), - sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), - ).String(), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), @@ -224,13 +226,13 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { }, { "not enough fees", + val.Address.String(), + val.Address.String(), + sdk.NewCoins( + sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), + sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), + ), []string{ - val.Address.String(), - val.Address.String(), - sdk.NewCoins( - sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), - sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), - ).String(), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(1))).String()), @@ -241,13 +243,13 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { }, { "not enough gas", + val.Address.String(), + val.Address.String(), + sdk.NewCoins( + sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), + sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), + ), []string{ - val.Address.String(), - val.Address.String(), - sdk.NewCoins( - sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), - sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), - ).String(), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), @@ -263,19 +265,12 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { tc := tc s.Run(tc.name, func() { - buf.Reset() - - cmd := cli.NewSendTxCmd(clientCtx) - cmd.SetErr(buf) - cmd.SetOut(buf) - cmd.SetArgs(tc.args) - - err := cmd.Execute() + res, err := banktest.SendTx(val.ClientCtx, tc.from, tc.to, tc.amount, tc.args...) if tc.expectErr { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(buf.Bytes(), tc.respType), buf.String()) + s.Require().NoError(val.ClientCtx.JSONMarshaler.UnmarshalJSON(res, tc.respType), string(res)) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) diff --git a/x/bank/client/testutil/helpers.go b/x/bank/client/testutil/helpers.go index 8863d146f39a..14a37fe77bd5 100644 --- a/x/bank/client/testutil/helpers.go +++ b/x/bank/client/testutil/helpers.go @@ -22,6 +22,7 @@ func TxSend(f *cli.Fixtures, from string, to sdk.AccAddress, amount sdk.Coin, fl return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } +// SendTx sends a transaction using Client Command and returns the response as bytes or error if there is ap problem. func SendTx(ctx client.Context, from string, to string, amount sdk.Coins, flags ...string) ([]byte, error) { buf := new(bytes.Buffer) ctx = ctx.WithOutput(buf) From e8242f08f613fe67433fe3b660be9bf34e974ec1 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 2 Jul 2020 21:17:02 +0200 Subject: [PATCH 04/46] Commit before getting backend. --- x/auth/client/cli/cli_test.go | 21 ++++++++++++++---- x/auth/client/testutil/helpers.go | 37 +++++++++++++++++++++++++++++++ x/bank/client/cli/cli_test.go | 2 ++ 3 files changed, 56 insertions(+), 4 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 9631a3e1f551..076e47cb0c71 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" authtest "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" ) @@ -44,10 +45,10 @@ func (s *IntegrationTestSuite) TearDownSuite() { func (s *IntegrationTestSuite) TestCLIValidateSignatures() { val := s.network.Validators[0] - tx, err := bankcli.SendTx( + res, err := bankcli.MsgSendExec( val.ClientCtx, - val.Address.String(), - val.Address.String(), + val.Address, + val.Address, sdk.NewCoins( sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), @@ -58,7 +59,19 @@ func (s *IntegrationTestSuite) TestCLIValidateSignatures() { fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), ) s.Require().NoError(err) - fmt.Printf("%s", tx) + + var tx types.StdTx + err = val.ClientCtx.JSONMarshaler.UnmarshalJSON(res, &tx) + s.Require().NoError(err) + + // write unsigned tx to file + unsignedTx, cleanup := tests.WriteToNewTempFile(s.T(), string(res)) + defer cleanup() + + exec, err := authtest.TxSignExec(val.ClientCtx, val.Address, unsignedTx.Name()) + s.Require().NoError(err) + + fmt.Printf("%s", exec) } func TestCLIValidateSignatures(t *testing.T) { diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 23aa367cf27c..df053ce29057 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -1,13 +1,50 @@ package testutil import ( + "bytes" + "context" "fmt" "strings" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + + "github.com/cosmos/cosmos-sdk/client/flags" + + "github.com/cosmos/cosmos-sdk/types" + + "github.com/cosmos/cosmos-sdk/client" + cli2 "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + clientkeys "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/tests/cli" ) +func TxSignExec(clientCtx client.Context, from types.Address, filename string) ([]byte, error) { + buf := new(bytes.Buffer) + clientCtx = clientCtx.WithOutput(buf) + + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + + cmd := cli2.GetSignCommand(clientCtx) + cmd.SetErr(buf) + cmd.SetOut(buf) + + args := []string{ + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendFile), + fmt.Sprintf("--from=%s", from.String()), + filename, + } + + cmd.SetArgs(args) + + if err := cmd.Execute(); err != nil { + return nil, err + } + + return buf.Bytes(), nil +} + // TxSign is simcli sign func TxSign(f *cli.Fixtures, signer, fileName string, flags ...string) (bool, string, string) { cmd := fmt.Sprintf("%s tx sign %v --keyring-backend=test --from=%s %v", f.SimcliBinary, f.Flags(), signer, fileName) diff --git a/x/bank/client/cli/cli_test.go b/x/bank/client/cli/cli_test.go index 77082da33919..3b6228c56e58 100644 --- a/x/bank/client/cli/cli_test.go +++ b/x/bank/client/cli/cli_test.go @@ -288,8 +288,10 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { if tc.expectErr { s.Require().Error(err) } else { + fmt.Printf("%s\n", out) s.Require().NoError(err) s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out, tc.respType), string(out)) + fmt.Printf("%v\n", tc.respType) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) From 836b6858f8a60305aa750ac09da1cafbbfc8fdb9 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 3 Jul 2020 15:38:24 +0200 Subject: [PATCH 05/46] Temporal commit --- x/auth/client/cli/tx_sign.go | 1 - x/auth/client/testutil/helpers.go | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 4a83b103f589..3c5fde8ec5d0 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -227,7 +227,6 @@ func makeSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args []strin appendSig := viper.GetBool(flagAppend) && !generateSignatureOnly newTx, err = authclient.SignStdTx(txBldr, clientCtx, clientCtx.GetFromName(), stdTx, appendSig, clientCtx.Offline) } - if err != nil { return err } diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index df053ce29057..4e9233d0db78 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -31,7 +31,7 @@ func TxSignExec(clientCtx client.Context, from types.Address, filename string) ( cmd.SetOut(buf) args := []string{ - fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendFile), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), fmt.Sprintf("--from=%s", from.String()), filename, } From 2827d29cb2352a083d05b55ff8f16a9078bf8411 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 3 Jul 2020 18:18:00 +0200 Subject: [PATCH 06/46] temp commit --- x/auth/client/cli/tx_sign.go | 7 +++++++ x/auth/client/testutil/helpers.go | 9 +++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 3c5fde8ec5d0..17dea1e92b8d 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -201,12 +201,19 @@ func preSignCmd(cmd *cobra.Command, _ []string) { func makeSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } + clientCtx, txBldr, tx, err := readStdTxAndInitContexts(clientCtx, cmd, args[0]) if err != nil { return err } stdTx := tx.(types.StdTx) + fmt.Printf("FROOOOOOM %s\n", viper.GetString(flags.FlagFrom)) + // if --signature-only is on, then override --append var newTx types.StdTx generateSignatureOnly := viper.GetBool(flagSigOnly) diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 4e9233d0db78..c9a40d9cbefb 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -6,12 +6,12 @@ import ( "fmt" "strings" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/client" cli2 "github.com/cosmos/cosmos-sdk/x/auth/client/cli" @@ -19,7 +19,7 @@ import ( "github.com/cosmos/cosmos-sdk/tests/cli" ) -func TxSignExec(clientCtx client.Context, from types.Address, filename string) ([]byte, error) { +func TxSignExec(clientCtx client.Context, from sdk.AccAddress, filename string) ([]byte, error) { buf := new(bytes.Buffer) clientCtx = clientCtx.WithOutput(buf) @@ -33,12 +33,13 @@ func TxSignExec(clientCtx client.Context, from types.Address, filename string) ( args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), fmt.Sprintf("--from=%s", from.String()), + fmt.Sprintf("--%s=%s", flags.FlagHome, strings.Replace(clientCtx.HomeDir, "simd", "simcli", 0)), filename, } cmd.SetArgs(args) - if err := cmd.Execute(); err != nil { + if err := cmd.ExecuteContext(ctx); err != nil { return nil, err } From 5376b5f96a1e01e6c0f9c93c876e75b786787aee Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 9 Jul 2020 00:10:22 +0200 Subject: [PATCH 07/46] remove the creation of txbuilder from cli --- simapp/simd/cmd/testnet.go | 6 +++++- x/auth/client/cli/tx_multisign.go | 7 ++++++- x/auth/client/cli/tx_sign.go | 9 +++++++-- x/auth/client/cli/validate_sigs.go | 7 ++++++- x/auth/types/txbuilder.go | 25 ------------------------- 5 files changed, 24 insertions(+), 30 deletions(-) diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index a5bce72881f1..7c74df825dec 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -207,7 +207,11 @@ func InitTestnet( ) tx := authtypes.NewStdTx([]sdk.Msg{msg}, authtypes.StdFee{}, []authtypes.StdSignature{}, memo) //nolint:staticcheck // SA1019: authtypes.StdFee is deprecated - txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithChainID(chainID).WithMemo(memo).WithKeybase(kb) + txBldr, err := authtypes.NewTxBuilderFromFlags(inBuf, cmd.Flags(), clientDir) + if err != nil { + return fmt.Errorf("error creating tx: %w", err) + } + txBldr.WithChainID(chainID).WithMemo(memo).WithKeybase(kb) signedTx, err := txBldr.SignStdTx(nodeDirName, tx, false) if err != nil { diff --git a/x/auth/client/cli/tx_multisign.go b/x/auth/client/cli/tx_multisign.go index db4eacc23ab4..4a505e76eb0a 100644 --- a/x/auth/client/cli/tx_multisign.go +++ b/x/auth/client/cli/tx_multisign.go @@ -7,6 +7,8 @@ import ( "os" "strings" + "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" @@ -83,7 +85,10 @@ func makeMultiSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args [] multisigPub := multisigInfo.GetPubKey().(multisig.PubKeyMultisigThreshold) multisigSig := multisig.NewMultisig(len(multisigPub.PubKeys)) - txBldr := types.NewTxBuilderFromCLI(inBuf) + txBldr, err := types.NewTxBuilderFromFlags(inBuf, cmd.Flags(), homeDir) + if err != nil { + return errors.Wrap(err, "error creating tx builder from flags") + } if !clientCtx.Offline { accnum, seq, err := types.NewAccountRetriever(authclient.Codec).GetAccountNumberSequence(clientCtx, multisigInfo.GetAddress()) diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index c515c9c56d42..61173563ebe2 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -64,11 +64,16 @@ func makeSignBatchCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) return func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) - txBldr := types.NewTxBuilderFromCLI(inBuf) + + home, _ := cmd.Flags().GetString(flags.FlagHome) + txBldr, err := types.NewTxBuilderFromFlags(inBuf, cmd.Flags(), home) + if err != nil { + return err + } + generateSignatureOnly, _ := cmd.Flags().GetBool(flagSigOnly) var ( - err error multisigAddr sdk.AccAddress infile = os.Stdin ) diff --git a/x/auth/client/cli/validate_sigs.go b/x/auth/client/cli/validate_sigs.go index e6d90509fc03..76b82c0bac6e 100644 --- a/x/auth/client/cli/validate_sigs.go +++ b/x/auth/client/cli/validate_sigs.go @@ -143,7 +143,12 @@ func readStdTxAndInitContexts(clientCtx client.Context, cmd *cobra.Command, file inBuf := bufio.NewReader(cmd.InOrStdin()) clientCtx = clientCtx.InitWithInput(inBuf) - txBldr := types.NewTxBuilderFromCLI(inBuf) + + home, _ := cmd.Flags().GetString(flags.FlagHome) + txBldr, err := types.NewTxBuilderFromFlags(inBuf, cmd.Flags(), home) + if err != nil { + return client.Context{}, types.TxBuilder{}, types.StdTx{}, err + } return clientCtx, txBldr, stdTx, nil } diff --git a/x/auth/types/txbuilder.go b/x/auth/types/txbuilder.go index e13aa135e4a8..1eb7f465cfbf 100644 --- a/x/auth/types/txbuilder.go +++ b/x/auth/types/txbuilder.go @@ -52,31 +52,6 @@ func NewTxBuilder( } } -// NewTxBuilderFromCLI returns a new initialized TxBuilder with parameters from -// the command line using Viper. -// Deprecated in favor of NewTxBuilderFromFlagSet -func NewTxBuilderFromCLI(input io.Reader) TxBuilder { - kb, err := keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), viper.GetString(flags.FlagHome), input) - if err != nil { - panic(err) - } - txbldr := TxBuilder{ - keybase: kb, - accountNumber: viper.GetUint64(flags.FlagAccountNumber), - sequence: viper.GetUint64(flags.FlagSequence), - gas: flags.GasFlagVar.Gas, - gasAdjustment: viper.GetFloat64(flags.FlagGasAdjustment), - simulateAndExecute: flags.GasFlagVar.Simulate, - chainID: viper.GetString(flags.FlagChainID), - memo: viper.GetString(flags.FlagMemo), - } - - txbldr = txbldr.WithFees(viper.GetString(flags.FlagFees)) - txbldr = txbldr.WithGasPrices(viper.GetString(flags.FlagGasPrices)) - - return txbldr -} - // NewTxBuilderFromCLI returns a new initialized TxBuilder with parameters extracted from // FlagSet (It should deprecate NewTxBuilderFromCLI). func NewTxBuilderFromFlags(input io.Reader, fs *pflag.FlagSet, keyringPath string) (TxBuilder, error) { From 0a6690f85361693d0bca50ad218dbe3983318442 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 9 Jul 2020 00:19:26 +0200 Subject: [PATCH 08/46] fix imports --- x/auth/client/cli/tx_multisign.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/x/auth/client/cli/tx_multisign.go b/x/auth/client/cli/tx_multisign.go index 4a505e76eb0a..f01d8592d9ff 100644 --- a/x/auth/client/cli/tx_multisign.go +++ b/x/auth/client/cli/tx_multisign.go @@ -7,8 +7,6 @@ import ( "os" "strings" - "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" @@ -17,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/version" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" "github.com/cosmos/cosmos-sdk/x/auth/types" From 204aa7102f504a9c270f73c0ce92dbc25876b19c Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 9 Jul 2020 00:22:21 +0200 Subject: [PATCH 09/46] update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c46c5f336560..50c00ea288e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -65,6 +65,7 @@ older clients. ### API Breaking Changes +* (auth) [\#6653](https://github.com/cosmos/cosmos-sdk/pull/6653) `NewTxBuilderFromCLI` is removed due to removal of viper dependency, use NewTxBuilderFromFlags instead. * (modules) [\#6564](https://github.com/cosmos/cosmos-sdk/pull/6564) Constant `DefaultParamspace` is removed from all modules, use ModuleName instead. * (client) [\#6525](https://github.com/cosmos/cosmos-sdk/pull/6525) Removed support for `indent` in JSON responses. Clients should consider piping to an external tool such as `jq`. * (x/staking) [\#6451](https://github.com/cosmos/cosmos-sdk/pull/6451) `DefaultParamspace` and `ParamKeyTable` in staking module are moved from keeper to types to enforce consistency. From 58774c3b48fe71ae69f067e3530a3e023b026bfc Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 9 Jul 2020 00:28:36 +0200 Subject: [PATCH 10/46] Remove unused function. --- client/context.go | 6 ------ x/auth/client/cli/tx_sign.go | 2 +- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/client/context.go b/client/context.go index 525c851ae8a7..638ba1b9973b 100644 --- a/client/context.go +++ b/client/context.go @@ -83,12 +83,6 @@ func NewContextWithFrom(from string) Context { // command line using Viper. func NewContext() Context { return NewContextWithFrom(viper.GetString(flags.FlagFrom)) } -// NewContextWithInput returns a new initialized Context with a io.Reader and parameters -// from the command line using Viper. -func NewContextWithInput(input io.Reader) Context { - return NewContextWithInputAndFrom(input, viper.GetString(flags.FlagFrom)) -} - // InitWithInputAndFrom returns a new Context re-initialized from an existing // Context with a new io.Reader and from parameter func (ctx Context) InitWithInputAndFrom(input io.Reader, from string) Context { diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 61173563ebe2..b0c6723eb5e9 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -63,7 +63,7 @@ account key. It implies --signature-only. func makeSignBatchCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) - clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.Context{}.WithInput(inBuf).WithCodec(cdc) home, _ := cmd.Flags().GetString(flags.FlagHome) txBldr, err := types.NewTxBuilderFromFlags(inBuf, cmd.Flags(), home) From af4752566fded9a9c1bd39d52caf6a26a0e67584 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 9 Jul 2020 09:23:00 +0200 Subject: [PATCH 11/46] Add flag home into tx sign command. --- x/auth/client/cli/tx_sign.go | 1 + 1 file changed, 1 insertion(+) diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index b0c6723eb5e9..67c652d99ae9 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -189,6 +189,7 @@ be generated via the 'multisign' command. ) cmd.Flags().Bool(flagSigOnly, false, "Print only the generated signature, then exit") cmd.Flags().String(flags.FlagOutputDocument, "", "The document will be written to the given file instead of STDOUT") + cmd.Flags().String(flags.FlagHome, "", "The application home directory") cmd = flags.PostCommands(cmd)[0] cmd.MarkFlagRequired(flags.FlagFrom) From 3962c8203eed311e04197f9a1234c1e9e4d0dff3 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 9 Jul 2020 14:44:43 +0200 Subject: [PATCH 12/46] migrade TestCLIValidateSignatures to use new test suite --- x/auth/client/cli/cli_test.go | 67 +++++++----------------------- x/auth/client/cli/tx_sign.go | 9 ++-- x/auth/client/cli/validate_sigs.go | 6 ++- x/auth/client/testutil/helpers.go | 29 ++++++++++++- x/auth/types/account_retriever.go | 4 +- 5 files changed, 53 insertions(+), 62 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 198077164328..5ffe81ba0b43 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -68,65 +68,28 @@ func (s *IntegrationTestSuite) TestCLIValidateSignatures() { unsignedTx, cleanup := tests.WriteToNewTempFile(s.T(), string(res)) defer cleanup() - exec, err := authtest.TxSignExec(val.ClientCtx, val.Address, unsignedTx.Name()) + res, err = authtest.TxSignExec(val.ClientCtx, val.Address, unsignedTx.Name()) s.Require().NoError(err) - fmt.Printf("%s", exec) -} - -func TestCLIValidateSignatures(t *testing.T) { - t.SkipNow() - t.Parallel() - f := cli.InitFixtures(t) - - // start simd server - proc := f.SDStart() - t.Cleanup(func() { proc.Stop(false) }) - - f.ValidateGenesis() - - fooAddr := f.KeyAddress(cli.KeyFoo) - barAddr := f.KeyAddress(cli.KeyBar) - - // generate sendTx with default gas - success, stdout, stderr := bankcli.TxSend(f, fooAddr.String(), barAddr, sdk.NewInt64Coin("stake", 10), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - - // write unsigned tx to file - unsignedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) - - // validate we can successfully sign - success, stdout, _ = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name()) - require.True(t, success) - - stdTx := cli.UnmarshalStdTx(t, f.Cdc, stdout) - - require.Equal(t, len(stdTx.Msgs), 1) - require.Equal(t, 1, len(stdTx.GetSignatures())) - require.Equal(t, fooAddr.String(), stdTx.GetSigners()[0].String()) + var signedTx types.StdTx + err = val.ClientCtx.JSONMarshaler.UnmarshalJSON(res, &signedTx) + s.Require().NoError(err) - // write signed tx to file - signedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) + signedTxFile, cleanup := tests.WriteToNewTempFile(s.T(), string(res)) + defer cleanup() - // validate signatures - success, _, _ = authtest.TxValidateSignatures(f, signedTxFile.Name()) - require.True(t, success) + res, err = authtest.TxValidateSignaturesExec(val.ClientCtx, signedTxFile.Name()) + s.Require().NoError(err) - // modify the transaction - stdTx.Memo = "MODIFIED-ORIGINAL-TX-BAD" - bz := cli.MarshalStdTx(t, f.Cdc, stdTx) - modSignedTxFile, cleanup := tests.WriteToNewTempFile(t, string(bz)) - t.Cleanup(cleanup) + signedTx.Memo = "MODIFIED STD TX" + bz, err := val.ClientCtx.JSONMarshaler.MarshalJSON(signedTx) + s.Require().NoError(err) - // validate signature validation failure due to different transaction sig bytes - success, _, _ = authtest.TxValidateSignatures(f, modSignedTxFile.Name()) - require.False(t, success) + modifiedTxFile, cleanup := tests.WriteToNewTempFile(s.T(), string(bz)) + defer cleanup() - // Cleanup testing directories - f.Cleanup() + res, err = authtest.TxValidateSignaturesExec(val.ClientCtx, modifiedTxFile.Name()) + s.Require().EqualError(err, "signatures validation failed") } func TestCLISignBatch(t *testing.T) { diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index db1f7ab0d708..95ab7da693a9 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -190,6 +190,7 @@ be generated via the 'multisign' command. cmd.Flags().Bool(flagSigOnly, false, "Print only the generated signature, then exit") cmd.Flags().String(flags.FlagOutputDocument, "", "The document will be written to the given file instead of STDOUT") cmd.Flags().String(flags.FlagHome, "", "The application home directory") + cmd.Flags().String(flags.FlagChainID, "", "The network chain ID") cmd = flags.PostCommands(cmd)[0] cmd.MarkFlagRequired(flags.FlagFrom) @@ -218,8 +219,6 @@ func makeSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args []strin } stdTx := tx.(types.StdTx) - fmt.Printf("FROOOOOOM %s\n", viper.GetString(flags.FlagFrom)) - // if --signature-only is on, then override --append var newTx types.StdTx generateSignatureOnly, _ := cmd.Flags().GetBool(flagSigOnly) @@ -245,14 +244,14 @@ func makeSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args []strin return err } - json, err := getSignatureJSON(clientCtx.Codec, newTx, generateSignatureOnly) + json, err := getSignatureJSON(clientCtx.JSONMarshaler, newTx, generateSignatureOnly) if err != nil { return err } outputDoc, _ := cmd.Flags().GetString(flags.FlagOutputDocument) if outputDoc == "" { - fmt.Printf("%s\n", json) + cmd.Printf("%s\n", json) return nil } @@ -267,7 +266,7 @@ func makeSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args []strin } } -func getSignatureJSON(cdc *codec.Codec, newTx types.StdTx, generateSignatureOnly bool) ([]byte, error) { +func getSignatureJSON(cdc codec.JSONMarshaler, newTx types.StdTx, generateSignatureOnly bool) ([]byte, error) { if generateSignatureOnly { return cdc.MarshalJSON(newTx.Signatures[0]) } diff --git a/x/auth/client/cli/validate_sigs.go b/x/auth/client/cli/validate_sigs.go index 76b82c0bac6e..6570d7df3154 100644 --- a/x/auth/client/cli/validate_sigs.go +++ b/x/auth/client/cli/validate_sigs.go @@ -32,6 +32,8 @@ transaction will be not be performed as that will require RPC communication with Args: cobra.ExactArgs(1), } + cmd.Flags().String(flags.FlagChainID, "", "The network chain ID") + return flags.PostCommands(cmd)[0] } @@ -89,7 +91,7 @@ func printAndValidateSigs( // Validate the actual signature over the transaction bytes since we can // reach out to a full node to query accounts. if !offline && success { - acc, err := types.NewAccountRetriever(authclient.Codec).GetAccount(clientCtx, sigAddr) + acc, err := types.NewAccountRetriever(clientCtx.JSONMarshaler).GetAccount(clientCtx, sigAddr) if err != nil { cmd.Printf("failed to get account: %s\n", sigAddr) return false @@ -142,7 +144,7 @@ func readStdTxAndInitContexts(clientCtx client.Context, cmd *cobra.Command, file } inBuf := bufio.NewReader(cmd.InOrStdin()) - clientCtx = clientCtx.InitWithInput(inBuf) + clientCtx.WithInput(inBuf) home, _ := cmd.Flags().GetString(flags.FlagHome) txBldr, err := types.NewTxBuilderFromFlags(inBuf, cmd.Flags(), home) diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index ecfb6f3a528a..2c0868a8bf17 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -33,7 +33,8 @@ func TxSignExec(clientCtx client.Context, from sdk.AccAddress, filename string) args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), fmt.Sprintf("--from=%s", from.String()), - fmt.Sprintf("--%s=%s", flags.FlagHome, strings.Replace(clientCtx.HomeDir, "simd", "simcli", 0)), + fmt.Sprintf("--%s=%s", flags.FlagHome, strings.Replace(clientCtx.HomeDir, "simd", "simcli", 1)), + fmt.Sprintf("--%s=%s", flags.FlagChainID, clientCtx.ChainID), filename, } @@ -65,6 +66,32 @@ func TxEncode(f *cli.Fixtures, fileName string, flags ...string) (bool, string, return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } +func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte, error) { + buf := new(bytes.Buffer) + clientCtx = clientCtx.WithOutput(buf) + + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + + cmd := cli2.GetValidateSignaturesCommand(clientCtx) + cmd.SetErr(buf) + cmd.SetOut(buf) + + args := []string{ + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=%s", flags.FlagChainID, clientCtx.ChainID), + filename, + } + + cmd.SetArgs(args) + + if err := cmd.ExecuteContext(ctx); err != nil { + return nil, err + } + + return buf.Bytes(), nil +} + // TxValidateSignatures is simcli tx validate-signatures func TxValidateSignatures(f *cli.Fixtures, fileName string, flags ...string) (bool, string, string) { cmd := fmt.Sprintf("%s tx validate-signatures %v --keyring-backend=test %v", f.SimdBinary, diff --git a/x/auth/types/account_retriever.go b/x/auth/types/account_retriever.go index 295b78e337d0..07bd5e3347a9 100644 --- a/x/auth/types/account_retriever.go +++ b/x/auth/types/account_retriever.go @@ -11,11 +11,11 @@ import ( // AccountRetriever defines the properties of a type that can be used to // retrieve accounts. type AccountRetriever struct { - codec codec.Marshaler + codec codec.JSONMarshaler } // NewAccountRetriever initialises a new AccountRetriever instance. -func NewAccountRetriever(codec codec.Marshaler) AccountRetriever { +func NewAccountRetriever(codec codec.JSONMarshaler) AccountRetriever { return AccountRetriever{codec: codec} } From 47767d60573d25b2ceb1556d54fee398482e6e36 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 9 Jul 2020 21:00:30 +0200 Subject: [PATCH 13/46] migrate test one --- testutil/ioutil.go | 2 +- x/auth/client/cli/cli_test.go | 48 ++++++++++++++++++----------------- 2 files changed, 26 insertions(+), 24 deletions(-) diff --git a/testutil/ioutil.go b/testutil/ioutil.go index ab0ccaec588a..37d560cd16c3 100644 --- a/testutil/ioutil.go +++ b/testutil/ioutil.go @@ -36,7 +36,7 @@ func ApplyMockIO(c *cobra.Command) (*strings.Reader, *bytes.Buffer, *bytes.Buffe // the caller must call to remove the file when it is // no longer needed. func WriteToNewTempFile(t testing.TB, s string) (*os.File, func()) { - fp, err := ioutil.TempFile("", t.Name()+"_") + fp, err := ioutil.TempFile("", strings.ReplaceAll(t.Name(), "/", "_")+"_") require.Nil(t, err) _, err = fp.WriteString(s) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 5ffe81ba0b43..0db5e1464e28 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -5,6 +5,8 @@ import ( "strings" "testing" + "github.com/cosmos/cosmos-sdk/testutil/network" + "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -21,18 +23,18 @@ import ( type IntegrationTestSuite struct { suite.Suite - cfg testutil.Config - network *testutil.Network + cfg network.Config + network *network.Network } func (s *IntegrationTestSuite) SetupSuite() { s.T().Log("setting up integration test suite") - cfg := testutil.DefaultConfig() + cfg := network.DefaultConfig() cfg.NumValidators = 1 s.cfg = cfg - s.network = testutil.NewTestNetwork(s.T(), cfg) + s.network = network.New(s.T(), cfg) _, err := s.network.WaitForHeight(1) s.Require().NoError(err) @@ -65,7 +67,7 @@ func (s *IntegrationTestSuite) TestCLIValidateSignatures() { s.Require().NoError(err) // write unsigned tx to file - unsignedTx, cleanup := tests.WriteToNewTempFile(s.T(), string(res)) + unsignedTx, cleanup := testutil.WriteToNewTempFile(s.T(), string(res)) defer cleanup() res, err = authtest.TxSignExec(val.ClientCtx, val.Address, unsignedTx.Name()) @@ -75,7 +77,7 @@ func (s *IntegrationTestSuite) TestCLIValidateSignatures() { err = val.ClientCtx.JSONMarshaler.UnmarshalJSON(res, &signedTx) s.Require().NoError(err) - signedTxFile, cleanup := tests.WriteToNewTempFile(s.T(), string(res)) + signedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(res)) defer cleanup() res, err = authtest.TxValidateSignaturesExec(val.ClientCtx, signedTxFile.Name()) @@ -85,7 +87,7 @@ func (s *IntegrationTestSuite) TestCLIValidateSignatures() { bz, err := val.ClientCtx.JSONMarshaler.MarshalJSON(signedTx) s.Require().NoError(err) - modifiedTxFile, cleanup := tests.WriteToNewTempFile(s.T(), string(bz)) + modifiedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(bz)) defer cleanup() res, err = authtest.TxValidateSignaturesExec(val.ClientCtx, modifiedTxFile.Name()) @@ -107,7 +109,7 @@ func TestCLISignBatch(t *testing.T) { require.Empty(t, stderr) // Write the output to disk - batchfile, cleanup1 := tests.WriteToNewTempFile(t, strings.Repeat(generatedStdTx, 3)) + batchfile, cleanup1 := testutil.WriteToNewTempFile(t, strings.Repeat(generatedStdTx, 3)) t.Cleanup(cleanup1) // sign-batch file - offline is set but account-number and sequence are not @@ -127,7 +129,7 @@ func TestCLISignBatch(t *testing.T) { require.Empty(t, stderr) require.Equal(t, 3, len(strings.Split(strings.Trim(stdout, "\n"), "\n"))) - malformedFile, cleanup2 := tests.WriteToNewTempFile(t, fmt.Sprintf("%smalformed", generatedStdTx)) + malformedFile, cleanup2 := testutil.WriteToNewTempFile(t, fmt.Sprintf("%smalformed", generatedStdTx)) t.Cleanup(cleanup2) // sign-batch file @@ -185,7 +187,7 @@ func TestCLISendGenerateSignAndBroadcast(t *testing.T) { require.Equal(t, len(msg.Msgs), 1) // Write the output to disk - unsignedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + unsignedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Test validate-signatures @@ -213,7 +215,7 @@ func TestCLISendGenerateSignAndBroadcast(t *testing.T) { require.Equal(t, fooAddr.String(), msg.GetSigners()[0].String()) // Write the output to disk - signedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + signedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Test validate-signatures @@ -267,7 +269,7 @@ func TestCLIMultisignInsufficientCosigners(t *testing.T) { require.True(t, success) // Write the output to disk - unsignedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + unsignedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Sign with foo's key @@ -275,7 +277,7 @@ func TestCLIMultisignInsufficientCosigners(t *testing.T) { require.True(t, success) // Write the output to disk - fooSignatureFile, cleanup := tests.WriteToNewTempFile(t, stdout) + fooSignatureFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Multisign, not enough signatures @@ -283,7 +285,7 @@ func TestCLIMultisignInsufficientCosigners(t *testing.T) { require.True(t, success) // Write the output to disk - signedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + signedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Validate the multisignature @@ -318,7 +320,7 @@ func TestCLIEncode(t *testing.T) { require.Empty(t, stderr) // Write it to disk - jsonTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + jsonTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Run the encode command @@ -356,7 +358,7 @@ func TestCLIMultisignSortSignatures(t *testing.T) { require.True(t, success) // Write the output to disk - unsignedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + unsignedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Sign with foo's key @@ -364,7 +366,7 @@ func TestCLIMultisignSortSignatures(t *testing.T) { require.True(t, success) // Write the output to disk - fooSignatureFile, cleanup := tests.WriteToNewTempFile(t, stdout) + fooSignatureFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Sign with baz's key @@ -372,7 +374,7 @@ func TestCLIMultisignSortSignatures(t *testing.T) { require.True(t, success) // Write the output to disk - bazSignatureFile, cleanup := tests.WriteToNewTempFile(t, stdout) + bazSignatureFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Multisign, keys in different order @@ -381,7 +383,7 @@ func TestCLIMultisignSortSignatures(t *testing.T) { require.True(t, success) // Write the output to disk - signedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + signedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Validate the multisignature @@ -422,7 +424,7 @@ func TestCLIMultisign(t *testing.T) { require.Empty(t, stderr) // Write the output to disk - unsignedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + unsignedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Sign with foo's key @@ -430,7 +432,7 @@ func TestCLIMultisign(t *testing.T) { require.True(t, success) // Write the output to disk - fooSignatureFile, cleanup := tests.WriteToNewTempFile(t, stdout) + fooSignatureFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Sign with bar's key @@ -438,7 +440,7 @@ func TestCLIMultisign(t *testing.T) { require.True(t, success) // Write the output to disk - barSignatureFile, cleanup := tests.WriteToNewTempFile(t, stdout) + barSignatureFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Multisign @@ -455,7 +457,7 @@ func TestCLIMultisign(t *testing.T) { require.True(t, success) // Write the output to disk - signedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + signedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Validate the multisignature From ea95899d253b8afaeb1c16e6b221a2c2eba9f28b Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 9 Jul 2020 21:20:05 +0200 Subject: [PATCH 14/46] Add changes to make sign batch. --- x/auth/client/cli/tx_sign.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 95ab7da693a9..5d5ebc605321 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -63,10 +63,9 @@ account key. It implies --signature-only. func makeSignBatchCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) - clientCtx := client.Context{}.WithInput(inBuf).WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) - home, _ := cmd.Flags().GetString(flags.FlagHome) - txBldr, err := types.NewTxBuilderFromFlags(inBuf, cmd.Flags(), home) + txBldr, err := types.NewTxBuilderFromFlags(inBuf, cmd.Flags(), clientCtx.HomeDir) if err != nil { return err } From f0c22e5bc3d035c5117d91f87051ac0e11a3a450 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 10 Jul 2020 11:15:54 +0200 Subject: [PATCH 15/46] make test pass --- x/auth/client/cli/tx_sign.go | 1 - x/auth/client/cli/validate_sigs.go | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index c39d05858efd..5d5ebc605321 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -190,7 +190,6 @@ be generated via the 'multisign' command. cmd.Flags().String(flags.FlagOutputDocument, "", "The document will be written to the given file instead of STDOUT") cmd.Flags().String(flags.FlagHome, "", "The application home directory") cmd.Flags().String(flags.FlagChainID, "", "The network chain ID") - cmd.Flags().String(flags.FlagHome, "", "The application home directory") cmd = flags.PostCommands(cmd)[0] cmd.MarkFlagRequired(flags.FlagFrom) diff --git a/x/auth/client/cli/validate_sigs.go b/x/auth/client/cli/validate_sigs.go index cb8b4d19a65b..18010b5ae418 100644 --- a/x/auth/client/cli/validate_sigs.go +++ b/x/auth/client/cli/validate_sigs.go @@ -32,6 +32,8 @@ transaction will be not be performed as that will require RPC communication with Args: cobra.ExactArgs(1), } + cmd.Flags().String(flags.FlagChainID, "", "The network chain ID") + return flags.PostCommands(cmd)[0] } From 1e9e3e20c7ead143e5b5e05ec2bec99f5f286a9a Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 10 Jul 2020 12:06:23 +0200 Subject: [PATCH 16/46] refactor common logic --- x/auth/client/cli/cli_test.go | 23 ++++++++++++++++ x/auth/client/testutil/helpers.go | 44 ++++++++++++------------------- 2 files changed, 40 insertions(+), 27 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 0db5e1464e28..7932210d8c75 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -94,6 +94,29 @@ func (s *IntegrationTestSuite) TestCLIValidateSignatures() { s.Require().EqualError(err, "signatures validation failed") } +func (s *IntegrationTestSuite) TestCLISignBatch() { + val := s.network.Validators[0] + res, err := bankcli.MsgSendExec( + val.ClientCtx, + val.Address, + val.Address, + sdk.NewCoins( + sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), + sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), + ), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), + ) + + s.Require().NoError(err) + + // Write the output to disk + _, cleanup1 := testutil.WriteToNewTempFile(s.T(), strings.Repeat(string(res), 3)) + defer cleanup1() +} + func TestCLISignBatch(t *testing.T) { t.SkipNow() t.Parallel() diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 2c0868a8bf17..1772b0e00b2e 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -6,6 +6,8 @@ import ( "fmt" "strings" + "github.com/spf13/cobra" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -20,25 +22,29 @@ import ( ) func TxSignExec(clientCtx client.Context, from sdk.AccAddress, filename string) ([]byte, error) { + args := []string{ + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--from=%s", from.String()), + fmt.Sprintf("--%s=%s", flags.FlagHome, strings.Replace(clientCtx.HomeDir, "simd", "simcli", 1)), + fmt.Sprintf("--%s=%s", flags.FlagChainID, clientCtx.ChainID), + filename, + } + + return callCmd(clientCtx, cli2.GetSignCommand, args) +} + +func callCmd(clientCtx client.Context, theCmd func(clientCtx client.Context) *cobra.Command, extraArgs []string) ([]byte, error) { buf := new(bytes.Buffer) clientCtx = clientCtx.WithOutput(buf) ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - cmd := cli2.GetSignCommand(clientCtx) + cmd := theCmd(clientCtx) cmd.SetErr(buf) cmd.SetOut(buf) - args := []string{ - fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), - fmt.Sprintf("--from=%s", from.String()), - fmt.Sprintf("--%s=%s", flags.FlagHome, strings.Replace(clientCtx.HomeDir, "simd", "simcli", 1)), - fmt.Sprintf("--%s=%s", flags.FlagChainID, clientCtx.ChainID), - filename, - } - - cmd.SetArgs(args) + cmd.SetArgs(extraArgs) if err := cmd.ExecuteContext(ctx); err != nil { return nil, err @@ -67,29 +73,13 @@ func TxEncode(f *cli.Fixtures, fileName string, flags ...string) (bool, string, } func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte, error) { - buf := new(bytes.Buffer) - clientCtx = clientCtx.WithOutput(buf) - - ctx := context.Background() - ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - - cmd := cli2.GetValidateSignaturesCommand(clientCtx) - cmd.SetErr(buf) - cmd.SetOut(buf) - args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), fmt.Sprintf("--%s=%s", flags.FlagChainID, clientCtx.ChainID), filename, } - cmd.SetArgs(args) - - if err := cmd.ExecuteContext(ctx); err != nil { - return nil, err - } - - return buf.Bytes(), nil + return callCmd(clientCtx, cli2.GetValidateSignaturesCommand, args) } // TxValidateSignatures is simcli tx validate-signatures From dbe63bd1ec5dd87e26e7d2af48adf772e870bf22 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 10 Jul 2020 13:37:52 +0200 Subject: [PATCH 17/46] First part of cli sign. --- x/auth/client/cli/cli_test.go | 8 +++++++- x/auth/client/cli/tx.go | 2 +- x/auth/client/cli/tx_sign.go | 23 ++++++++++++++--------- x/auth/client/testutil/helpers.go | 12 ++++++++++++ x/auth/client/tx.go | 4 ++-- 5 files changed, 36 insertions(+), 13 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 7932210d8c75..cea0eb544dcb 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -113,8 +113,14 @@ func (s *IntegrationTestSuite) TestCLISignBatch() { s.Require().NoError(err) // Write the output to disk - _, cleanup1 := testutil.WriteToNewTempFile(s.T(), strings.Repeat(string(res), 3)) + filename, cleanup1 := testutil.WriteToNewTempFile(s.T(), strings.Repeat(string(res), 3)) defer cleanup1() + + // sign-batch file - offline is set but account-number and sequence are not + cliHome := strings.Replace(val.ClientCtx.HomeDir, "simd", "simcli", 1) + val.ClientCtx.HomeDir = cliHome + res, err = authtest.TxSignBatchExec(val.ClientCtx, val.Address, filename.Name(), fmt.Sprintf("--%s=%s", flags.FlagChainID, val.ClientCtx.ChainID), "--offline") + s.Require().EqualError(err, "required flag(s) \"account-number\", \"sequence\" not set") } func TestCLISignBatch(t *testing.T) { diff --git a/x/auth/client/cli/tx.go b/x/auth/client/cli/tx.go index 9bc30f396ec0..6ac7ea846791 100644 --- a/x/auth/client/cli/tx.go +++ b/x/auth/client/cli/tx.go @@ -20,7 +20,7 @@ func GetTxCmd(clientCtx client.Context) *cobra.Command { GetMultiSignCommand(clientCtx), GetSignCommand(clientCtx), GetValidateSignaturesCommand(clientCtx), - GetSignBatchCommand(clientCtx.Codec), + GetSignBatchCommand(clientCtx), ) return txCmd } diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 5d5ebc605321..75a54121972b 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -22,7 +22,7 @@ const ( ) // GetSignBatchCommand returns the transaction sign-batch command. -func GetSignBatchCommand(codec *codec.Codec) *cobra.Command { +func GetSignBatchCommand(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "sign-batch [file]", Short: "Sign transaction batch files", @@ -44,7 +44,7 @@ The --multisig= flag generates a signature on behalf of a multisig account key. It implies --signature-only. `, PreRun: preSignCmd, - RunE: makeSignBatchCmd(codec), + RunE: makeSignBatchCmd(), Args: cobra.ExactArgs(1), } @@ -54,18 +54,18 @@ account key. It implies --signature-only. ) cmd.Flags().String(flags.FlagOutputDocument, "", "The document will be written to the given file instead of STDOUT") cmd.Flags().Bool(flagSigOnly, true, "Print only the generated signature, then exit") + cmd.Flags().String(flags.FlagChainID, "", "network chain ID") cmd = flags.PostCommands(cmd)[0] cmd.MarkFlagRequired(flags.FlagFrom) return cmd } -func makeSignBatchCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { +func makeSignBatchCmd() func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) clientCtx := client.GetClientContextFromCmd(cmd) - txBldr, err := types.NewTxBuilderFromFlags(inBuf, cmd.Flags(), clientCtx.HomeDir) + txBldr, err := types.NewTxBuilderFromFlags(bufio.NewReader(cmd.InOrStdin()), cmd.Flags(), clientCtx.HomeDir) if err != nil { return err } @@ -101,7 +101,7 @@ func makeSignBatchCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) } } - scanner := authclient.NewBatchScanner(cdc, infile) + scanner := authclient.NewBatchScanner(clientCtx.JSONMarshaler, infile) for sequence := txBldr.Sequence(); scanner.Scan(); sequence++ { var stdTx types.StdTx @@ -110,8 +110,13 @@ func makeSignBatchCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) txBldr = txBldr.WithSequence(sequence) if multisigAddr.Empty() { - homeDir, _ := cmd.Flags().GetString(flags.FlagFrom) - stdTx, err = authclient.SignStdTx(txBldr, clientCtx, homeDir, unsignedStdTx, false, true) + from, _ := cmd.Flags().GetString(flags.FlagFrom) + _, fromName, err := client.GetFromFields(txBldr.Keybase(), from, clientCtx.GenerateOnly) + if err != nil { + return fmt.Errorf("error getting account from keybase: %w", err) + } + + stdTx, err = authclient.SignStdTx(txBldr, clientCtx, fromName, unsignedStdTx, false, true) } else { stdTx, err = authclient.SignStdTxWithSignerAddress(txBldr, clientCtx, multisigAddr, clientCtx.GetFromName(), unsignedStdTx, true) } @@ -120,7 +125,7 @@ func makeSignBatchCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) return err } - json, err := getSignatureJSON(cdc, stdTx, generateSignatureOnly) + json, err := getSignatureJSON(clientCtx.JSONMarshaler, stdTx, generateSignatureOnly) if err != nil { return err } diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 1772b0e00b2e..a10563c0f8e6 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -100,6 +100,18 @@ func TxMultisign(f *cli.Fixtures, fileName, name string, signaturesFiles []strin return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags)) } +func TxSignBatchExec(clientCtx client.Context, from sdk.AccAddress, filename string, extraArgs ...string) ([]byte, error) { + args := []string{ + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--from=%s", from.String()), + filename, + } + + args = append(args, extraArgs...) + + return callCmd(clientCtx, cli2.GetSignBatchCommand, args) +} + func TxSignBatch(f *cli.Fixtures, signer, fileName string, flags ...string) (bool, string, string) { cmd := fmt.Sprintf("%s tx sign-batch %v --keyring-backend=test --from=%s %v", f.SimdBinary, f.Flags(), signer, fileName) diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index bafdf3b74daf..14f914655070 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -236,7 +236,7 @@ func ReadTxFromFile(ctx client.Context, filename string) (tx sdk.Tx, err error) } // NewBatchScanner returns a new BatchScanner to read newline-delimited StdTx transactions from r. -func NewBatchScanner(cdc *codec.Codec, r io.Reader) *BatchScanner { +func NewBatchScanner(cdc codec.JSONMarshaler, r io.Reader) *BatchScanner { return &BatchScanner{Scanner: bufio.NewScanner(r), cdc: cdc} } @@ -245,7 +245,7 @@ func NewBatchScanner(cdc *codec.Codec, r io.Reader) *BatchScanner { type BatchScanner struct { *bufio.Scanner stdTx authtypes.StdTx - cdc *codec.Codec + cdc codec.JSONMarshaler unmarshalErr error } From 604a936d363cfb52e27be238cbbdff0949c74da0 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 10 Jul 2020 13:46:58 +0200 Subject: [PATCH 18/46] Add test for sign batch. --- x/auth/client/cli/cli_test.go | 67 +++++++++-------------------------- 1 file changed, 17 insertions(+), 50 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index cea0eb544dcb..f19c4d7b7377 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -96,7 +96,7 @@ func (s *IntegrationTestSuite) TestCLIValidateSignatures() { func (s *IntegrationTestSuite) TestCLISignBatch() { val := s.network.Validators[0] - res, err := bankcli.MsgSendExec( + generatedStd, err := bankcli.MsgSendExec( val.ClientCtx, val.Address, val.Address, @@ -113,66 +113,33 @@ func (s *IntegrationTestSuite) TestCLISignBatch() { s.Require().NoError(err) // Write the output to disk - filename, cleanup1 := testutil.WriteToNewTempFile(s.T(), strings.Repeat(string(res), 3)) + filename, cleanup1 := testutil.WriteToNewTempFile(s.T(), strings.Repeat(string(generatedStd), 3)) defer cleanup1() // sign-batch file - offline is set but account-number and sequence are not - cliHome := strings.Replace(val.ClientCtx.HomeDir, "simd", "simcli", 1) - val.ClientCtx.HomeDir = cliHome - res, err = authtest.TxSignBatchExec(val.ClientCtx, val.Address, filename.Name(), fmt.Sprintf("--%s=%s", flags.FlagChainID, val.ClientCtx.ChainID), "--offline") + val.ClientCtx.HomeDir = strings.Replace(val.ClientCtx.HomeDir, "simd", "simcli", 1) + res, err := authtest.TxSignBatchExec(val.ClientCtx, val.Address, filename.Name(), fmt.Sprintf("--%s=%s", flags.FlagChainID, val.ClientCtx.ChainID), "--offline") s.Require().EqualError(err, "required flag(s) \"account-number\", \"sequence\" not set") -} - -func TestCLISignBatch(t *testing.T) { - t.SkipNow() - t.Parallel() - f := cli.InitFixtures(t) - - fooAddr := f.KeyAddress(cli.KeyFoo) - barAddr := f.KeyAddress(cli.KeyBar) - - sendTokens := sdk.TokensFromConsensusPower(10) - success, generatedStdTx, stderr := bankcli.TxSend(f, fooAddr.String(), barAddr, sdk.NewCoin(cli.Denom, sendTokens), "--generate-only") - - require.True(t, success) - require.Empty(t, stderr) - - // Write the output to disk - batchfile, cleanup1 := testutil.WriteToNewTempFile(t, strings.Repeat(generatedStdTx, 3)) - t.Cleanup(cleanup1) - - // sign-batch file - offline is set but account-number and sequence are not - success, _, stderr = authtest.TxSignBatch(f, cli.KeyFoo, batchfile.Name(), "--offline") - require.Contains(t, stderr, "required flag(s) \"account-number\", \"sequence\" not set") - require.False(t, success) // sign-batch file - success, stdout, stderr := authtest.TxSignBatch(f, cli.KeyFoo, batchfile.Name()) - require.True(t, success) - require.Empty(t, stderr) - require.Equal(t, 3, len(strings.Split(strings.Trim(stdout, "\n"), "\n"))) + res, err = authtest.TxSignBatchExec(val.ClientCtx, val.Address, filename.Name(), fmt.Sprintf("--%s=%s", flags.FlagChainID, val.ClientCtx.ChainID)) + s.Require().NoError(err) + s.Require().Equal(3, len(strings.Split(strings.Trim(string(res), "\n"), "\n"))) // sign-batch file - success, stdout, stderr = authtest.TxSignBatch(f, cli.KeyFoo, batchfile.Name(), "--signature-only") - require.True(t, success) - require.Empty(t, stderr) - require.Equal(t, 3, len(strings.Split(strings.Trim(stdout, "\n"), "\n"))) + res, err = authtest.TxSignBatchExec(val.ClientCtx, val.Address, filename.Name(), fmt.Sprintf("--%s=%s", flags.FlagChainID, val.ClientCtx.ChainID), "--signature-only") + s.Require().Equal(3, len(strings.Split(strings.Trim(string(res), "\n"), "\n"))) - malformedFile, cleanup2 := testutil.WriteToNewTempFile(t, fmt.Sprintf("%smalformed", generatedStdTx)) - t.Cleanup(cleanup2) + // Sign batch malformed tx file. + malformedFile, cleanup2 := testutil.WriteToNewTempFile(s.T(), fmt.Sprintf("%smalformed", generatedStd)) + defer cleanup2() - // sign-batch file - success, stdout, stderr = authtest.TxSignBatch(f, cli.KeyFoo, malformedFile.Name()) - require.False(t, success) - require.Equal(t, 1, len(strings.Split(strings.Trim(stdout, "\n"), "\n"))) - require.Equal(t, "ERROR: cannot parse disfix JSON wrapper: invalid character 'm' looking for beginning of value\n", stderr) + res, err = authtest.TxSignBatchExec(val.ClientCtx, val.Address, malformedFile.Name(), fmt.Sprintf("--%s=%s", flags.FlagChainID, val.ClientCtx.ChainID)) + s.Require().EqualError(err, "cannot parse disfix JSON wrapper: invalid character 'm' looking for beginning of value") - // sign-batch file - success, stdout, _ = authtest.TxSignBatch(f, cli.KeyFoo, malformedFile.Name(), "--signature-only") - require.False(t, success) - require.Equal(t, 1, len(strings.Split(strings.Trim(stdout, "\n"), "\n"))) - - f.Cleanup() + // Sign batch malformed tx file signature only. + res, err = authtest.TxSignBatchExec(val.ClientCtx, val.Address, malformedFile.Name(), fmt.Sprintf("--%s=%s", flags.FlagChainID, val.ClientCtx.ChainID), "--signature-only") + s.Require().EqualError(err, "cannot parse disfix JSON wrapper: invalid character 'm' looking for beginning of value") } func TestCLISendGenerateSignAndBroadcast(t *testing.T) { From 0f26ab0366ec6332508197171f5e3fd05bdc4c43 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 10 Jul 2020 15:51:45 +0200 Subject: [PATCH 19/46] refactor a little and improve the test --- tests/cli/helpers.go | 2 +- x/auth/client/cli/cli_test.go | 112 ++++++++++++++++++++++++++ x/auth/client/testutil/helpers.go | 24 ++---- x/bank/client/testutil/cli_helpers.go | 69 +++++----------- 4 files changed, 141 insertions(+), 66 deletions(-) diff --git a/tests/cli/helpers.go b/tests/cli/helpers.go index daaa7dacdec6..945b2f3decd3 100644 --- a/tests/cli/helpers.go +++ b/tests/cli/helpers.go @@ -181,7 +181,7 @@ func AddFlags(cmd string, flags []string) string { return strings.TrimSpace(cmd) } -func UnmarshalStdTx(t require.TestingT, c *codec.Codec, s string) (stdTx authtypes.StdTx) { +func UnmarshalStdTx(t require.TestingT, c codec.JSONMarshaler, s string) (stdTx authtypes.StdTx) { require.Nil(t, c.UnmarshalJSON([]byte(s), &stdTx)) return } diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index f19c4d7b7377..67add48c109e 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -142,6 +142,118 @@ func (s *IntegrationTestSuite) TestCLISignBatch() { s.Require().EqualError(err, "cannot parse disfix JSON wrapper: invalid character 'm' looking for beginning of value") } +func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { + val := s.network.Validators[0] + generatedStd, err := bankcli.MsgSendExec( + val.ClientCtx, + val.Address, + val.Address, + sdk.NewCoins( + sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), + sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), + ), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), + ) + s.Require().NoError(err) + + stdTx := cli.UnmarshalStdTx(s.T(), val.ClientCtx.JSONMarshaler, string(generatedStd)) + s.Require().Equal(stdTx.Fee.Gas, uint64(flags.DefaultGasLimit)) + s.Require().Equal(len(stdTx.Msgs), 1) + s.Require().Equal(0, len(stdTx.GetSignatures())) + + // Test generate sendTx with --gas=$amount + generatedStd, err = bankcli.MsgSendExec( + val.ClientCtx, + val.Address, + val.Address, + sdk.NewCoins( + sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), + sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), + ), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--gas=%d", 100), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), + ) + s.Require().NoError(err) + + stdTx = cli.UnmarshalStdTx(s.T(), val.ClientCtx.JSONMarshaler, string(generatedStd)) + s.Require().Equal(stdTx.Fee.Gas, uint64(100)) + s.Require().Equal(len(stdTx.Msgs), 1) + s.Require().Equal(0, len(stdTx.GetSignatures())) + + // Test generate sendTx, estimate gas + generatedStd, err = bankcli.MsgSendExec( + val.ClientCtx, + val.Address, + val.Address, + sdk.NewCoins( + sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), + sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), + ), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), + ) + s.Require().NoError(err) + + stdTx = cli.UnmarshalStdTx(s.T(), val.ClientCtx.JSONMarshaler, string(generatedStd)) + s.Require().True(stdTx.Fee.Gas > 0) + s.Require().Equal(len(stdTx.Msgs), 1) + + // Write the output to disk + unsignedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(generatedStd)) + defer cleanup() + + // Test validate-signatures + res, err := authtest.TxValidateSignaturesExec(val.ClientCtx, unsignedTxFile.Name()) + s.Require().EqualError(err, "signatures validation failed") + s.Require().True(strings.Contains(string(res), fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n\n", val.Address.String()))) + + // Test sign + + // Does not work in offline mode + res, err = authtest.TxSignExec(val.ClientCtx, val.Address, unsignedTxFile.Name(), "--offline") + s.Require().EqualError(err, "required flag(s) \"account-number\", \"sequence\" not set") + + // But works offline if we set account number and sequence + res, err = authtest.TxSignExec(val.ClientCtx, val.Address, unsignedTxFile.Name(), "--offline", "--offline", "--account-number", "1", "--sequence", "1") + s.Require().NoError(err) + + // Sign transaction + generatedStd, err = authtest.TxSignExec(val.ClientCtx, val.Address, unsignedTxFile.Name()) + s.Require().NoError(err) + + stdTx = cli.UnmarshalStdTx(s.T(), val.ClientCtx.JSONMarshaler, string(generatedStd)) + s.Require().Equal(len(stdTx.Msgs), 1) + s.Require().Equal(1, len(stdTx.GetSignatures())) + s.Require().Equal(val.Address.String(), stdTx.GetSigners()[0].String()) + + // Write the output to disk + unsignedTxFile, cleanup2 := testutil.WriteToNewTempFile(s.T(), string(generatedStd)) + defer cleanup2() + + // Validate Signature + res, err = authtest.TxValidateSignaturesExec(val.ClientCtx, unsignedTxFile.Name()) + s.Require().NoError(err) + s.Require().True(strings.Contains(string(res), "[OK]")) + + // Ensure foo has right amount of funds + startTokens := sdk.TokensFromConsensusPower(400) + resp, err := bankcli.QueryBalancesExec(val.ClientCtx, val.Address) + s.Require().NoError(err) + + var coins sdk.Coins + err = val.ClientCtx.JSONMarshaler.UnmarshalJSON(resp, &coins) + s.Require().NoError(err) + s.Require().Equal(startTokens, coins.AmountOf(cli.Denom)) +} + func TestCLISendGenerateSignAndBroadcast(t *testing.T) { t.SkipNow() t.Parallel() diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index a10563c0f8e6..babea0c88c23 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -8,20 +8,16 @@ import ( "github.com/spf13/cobra" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/cosmos/cosmos-sdk/crypto/keyring" - - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client" - cli2 "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - + "github.com/cosmos/cosmos-sdk/client/flags" clientkeys "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/tests/cli" + sdk "github.com/cosmos/cosmos-sdk/types" + cli2 "github.com/cosmos/cosmos-sdk/x/auth/client/cli" ) -func TxSignExec(clientCtx client.Context, from sdk.AccAddress, filename string) ([]byte, error) { +func TxSignExec(clientCtx client.Context, from sdk.AccAddress, filename string, extraArgs ...string) ([]byte, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), fmt.Sprintf("--from=%s", from.String()), @@ -30,6 +26,8 @@ func TxSignExec(clientCtx client.Context, from sdk.AccAddress, filename string) filename, } + args = append(args, extraArgs...) + return callCmd(clientCtx, cli2.GetSignCommand, args) } @@ -47,7 +45,7 @@ func callCmd(clientCtx client.Context, theCmd func(clientCtx client.Context) *co cmd.SetArgs(extraArgs) if err := cmd.ExecuteContext(ctx); err != nil { - return nil, err + return buf.Bytes(), err } return buf.Bytes(), nil @@ -112,12 +110,6 @@ func TxSignBatchExec(clientCtx client.Context, from sdk.AccAddress, filename str return callCmd(clientCtx, cli2.GetSignBatchCommand, args) } -func TxSignBatch(f *cli.Fixtures, signer, fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx sign-batch %v --keyring-backend=test --from=%s %v", f.SimdBinary, f.Flags(), signer, fileName) - - 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.SimdBinary, f.Flags(), encodedTx) diff --git a/x/bank/client/testutil/cli_helpers.go b/x/bank/client/testutil/cli_helpers.go index 6ba757e1fd71..b36670736702 100644 --- a/x/bank/client/testutil/cli_helpers.go +++ b/x/bank/client/testutil/cli_helpers.go @@ -3,9 +3,10 @@ package testutil import ( "bytes" "context" - "encoding/json" "fmt" + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" @@ -13,27 +14,38 @@ import ( "github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/tests/cli" sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" bankcli "github.com/cosmos/cosmos-sdk/x/bank/client/cli" ) func MsgSendExec(clientCtx client.Context, from, to, amount fmt.Stringer, extraArgs ...string) ([]byte, error) { + args := []string{from.String(), to.String(), amount.String()} + args = append(args, extraArgs...) + + return callCmd(clientCtx, bankcli.NewSendTxCmd, args) +} + +func QueryBalancesExec(clientCtx client.Context, address sdk.AccAddress, extraArgs ...string) ([]byte, error) { + args := []string{address.String()} + args = append(args, extraArgs...) + + return callCmd(clientCtx, bankcli.GetBalancesCmd, args) +} + +func callCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { buf := new(bytes.Buffer) clientCtx = clientCtx.WithOutput(buf) ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - args := []string{from.String(), to.String(), amount.String()} - args = append(args, extraArgs...) - - cmd := bankcli.NewSendTxCmd() + cmd := theCmd() cmd.SetErr(buf) cmd.SetOut(buf) - cmd.SetArgs(args) + + cmd.SetArgs(extraArgs) if err := cmd.ExecuteContext(ctx); err != nil { - return nil, err + return buf.Bytes(), err } return buf.Bytes(), nil @@ -51,24 +63,6 @@ func TxSend(f *cli.Fixtures, from string, to sdk.AccAddress, amount sdk.Coin, fl return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } -// QueryAccount is simcli query account -func QueryAccount(f *cli.Fixtures, address sdk.AccAddress, flags ...string) authtypes.BaseAccount { - cmd := fmt.Sprintf("%s query account %s %v", f.SimdBinary, address, f.Flags()) - - out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") - - var initRes map[string]json.RawMessage - err := json.Unmarshal([]byte(out), &initRes) - require.NoError(f.T, err, "out %v, err %v", out, err) - value := initRes["value"] - - var acc authtypes.BaseAccount - err = f.Cdc.UnmarshalJSON(value, &acc) - require.NoError(f.T, err, "value %v, err %v", string(value), err) - - return acc -} - // QueryBalances executes the bank query balances command for a given address and // flag set. func QueryBalances(f *cli.Fixtures, address sdk.AccAddress, flags ...string) sdk.Coins { @@ -81,26 +75,3 @@ func QueryBalances(f *cli.Fixtures, address sdk.AccAddress, flags ...string) sdk return balances } - -// QueryTotalSupply returns the total supply of coins -func QueryTotalSupply(f *cli.Fixtures, flags ...string) (totalSupply sdk.Coins) { - cmd := fmt.Sprintf("%s query bank total %s", f.SimdBinary, f.Flags()) - res, errStr := tests.ExecuteT(f.T, cmd, "") - require.Empty(f.T, errStr) - - err := f.Cdc.UnmarshalJSON([]byte(res), &totalSupply) - require.NoError(f.T, err) - return totalSupply -} - -// QueryTotalSupplyOf returns the total supply of a given coin denom -func QueryTotalSupplyOf(f *cli.Fixtures, denom string, flags ...string) sdk.Int { - cmd := fmt.Sprintf("%s query bank total %s %s", f.SimdBinary, denom, f.Flags()) - res, errStr := tests.ExecuteT(f.T, cmd, "") - require.Empty(f.T, errStr) - - var supplyOf sdk.Int - err := f.Cdc.UnmarshalJSON([]byte(res), &supplyOf) - require.NoError(f.T, err) - return supplyOf -} From 6670230100e2c6377bcdcadb9cb7a49d8449303c Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 10 Jul 2020 17:44:08 +0200 Subject: [PATCH 20/46] migrate broadcast command --- testutil/network/network.go | 33 +++++ x/auth/client/cli/broadcast.go | 2 +- x/auth/client/cli/cli_test.go | 212 +++++++++++------------------- x/auth/client/testutil/helpers.go | 10 ++ 4 files changed, 121 insertions(+), 136 deletions(-) diff --git a/testutil/network/network.go b/testutil/network/network.go index e029878bc921..4ebb124f476a 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -331,6 +331,39 @@ func New(t *testing.T, cfg Config) *Network { return network } +func (n *Network) WaitForNBlocks(b int64, t time.Duration) error { + ticker := time.NewTicker(time.Second) + timeout := time.After(t) + + if len(n.Validators) == 0 { + return errors.New("no validators available") + } + + val := n.Validators[0] + + status, err := val.RPCClient.Status() + if err != nil || status == nil { + return fmt.Errorf("error getting node status") + } + + initialHeight := status.SyncInfo.LatestBlockHeight + + for { + select { + case <-timeout: + return fmt.Errorf("timeout exceeded waiting for block %d", initialHeight+b) + case <-ticker.C: + status, err := val.RPCClient.Status() + if err == nil && status != nil { + curHeight := status.SyncInfo.LatestBlockHeight + if curHeight >= initialHeight+b { + return nil + } + } + } + } +} + // WaitForHeight performs a blocking check where it waits for a block to be // committed after a given block. If that height is not reached within a timeout, // an error is returned. Regardless, the latest height queried is returned. diff --git a/x/auth/client/cli/broadcast.go b/x/auth/client/cli/broadcast.go index 1d91d9e5b54d..027d7c8ee5a2 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() + clientCtx = client.GetClientContextFromCmd(cmd) if offline, _ := cmd.Flags().GetBool(flags.FlagOffline); 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 67add48c109e..e006ed70cef7 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -4,6 +4,10 @@ import ( "fmt" "strings" "testing" + "time" + + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/testutil/network" @@ -31,7 +35,7 @@ func (s *IntegrationTestSuite) SetupSuite() { s.T().Log("setting up integration test suite") cfg := network.DefaultConfig() - cfg.NumValidators = 1 + cfg.NumValidators = 2 s.cfg = cfg s.network = network.New(s.T(), cfg) @@ -143,14 +147,19 @@ func (s *IntegrationTestSuite) TestCLISignBatch() { } func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { - val := s.network.Validators[0] - generatedStd, err := bankcli.MsgSendExec( - val.ClientCtx, - val.Address, - val.Address, + val1 := s.network.Validators[0] + + account, _, err := val1.ClientCtx.Keyring.NewMnemonic("newAccount", keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) + s.Require().NoError(err) + + sendTokens := sdk.TokensFromConsensusPower(10) + + normalGeneratedTx, err := bankcli.MsgSendExec( + val1.ClientCtx, + val1.Address, + account.GetAddress(), sdk.NewCoins( - sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), - sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), + sdk.NewCoin(s.cfg.BondDenom, sendTokens), ), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), @@ -159,19 +168,18 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { ) s.Require().NoError(err) - stdTx := cli.UnmarshalStdTx(s.T(), val.ClientCtx.JSONMarshaler, string(generatedStd)) - s.Require().Equal(stdTx.Fee.Gas, uint64(flags.DefaultGasLimit)) - s.Require().Equal(len(stdTx.Msgs), 1) - s.Require().Equal(0, len(stdTx.GetSignatures())) + normalGeneratedStdTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, string(normalGeneratedTx)) + s.Require().Equal(normalGeneratedStdTx.Fee.Gas, uint64(flags.DefaultGasLimit)) + s.Require().Equal(len(normalGeneratedStdTx.Msgs), 1) + s.Require().Equal(0, len(normalGeneratedStdTx.GetSignatures())) // Test generate sendTx with --gas=$amount - generatedStd, err = bankcli.MsgSendExec( - val.ClientCtx, - val.Address, - val.Address, + limitedGasGeneratedTx, err := bankcli.MsgSendExec( + val1.ClientCtx, + val1.Address, + account.GetAddress(), sdk.NewCoins( - sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), - sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), + sdk.NewCoin(s.cfg.BondDenom, sendTokens), ), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), @@ -181,178 +189,112 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { ) s.Require().NoError(err) - stdTx = cli.UnmarshalStdTx(s.T(), val.ClientCtx.JSONMarshaler, string(generatedStd)) - s.Require().Equal(stdTx.Fee.Gas, uint64(100)) - s.Require().Equal(len(stdTx.Msgs), 1) - s.Require().Equal(0, len(stdTx.GetSignatures())) + limitedGasStdTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, string(limitedGasGeneratedTx)) + s.Require().Equal(limitedGasStdTx.Fee.Gas, uint64(100)) + s.Require().Equal(len(limitedGasStdTx.Msgs), 1) + s.Require().Equal(0, len(limitedGasStdTx.GetSignatures())) // Test generate sendTx, estimate gas - generatedStd, err = bankcli.MsgSendExec( - val.ClientCtx, - val.Address, - val.Address, + finalGeneratedTx, err := bankcli.MsgSendExec( + val1.ClientCtx, + val1.Address, + account.GetAddress(), sdk.NewCoins( - sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), - sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), + sdk.NewCoin(s.cfg.BondDenom, sendTokens), ), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--gas=%d", flags.DefaultGasLimit), fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), ) s.Require().NoError(err) - stdTx = cli.UnmarshalStdTx(s.T(), val.ClientCtx.JSONMarshaler, string(generatedStd)) - s.Require().True(stdTx.Fee.Gas > 0) - s.Require().Equal(len(stdTx.Msgs), 1) + finalStdTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, string(finalGeneratedTx)) + s.Require().Equal(uint64(flags.DefaultGasLimit), finalStdTx.Fee.Gas) + s.Require().Equal(len(finalStdTx.Msgs), 1) // Write the output to disk - unsignedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(generatedStd)) + unsignedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(finalGeneratedTx)) defer cleanup() // Test validate-signatures - res, err := authtest.TxValidateSignaturesExec(val.ClientCtx, unsignedTxFile.Name()) + res, err := authtest.TxValidateSignaturesExec(val1.ClientCtx, unsignedTxFile.Name()) s.Require().EqualError(err, "signatures validation failed") - s.Require().True(strings.Contains(string(res), fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n\n", val.Address.String()))) + s.Require().True(strings.Contains(string(res), fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n\n", val1.Address.String()))) // Test sign // Does not work in offline mode - res, err = authtest.TxSignExec(val.ClientCtx, val.Address, unsignedTxFile.Name(), "--offline") + res, err = authtest.TxSignExec(val1.ClientCtx, val1.Address, unsignedTxFile.Name(), "--offline") s.Require().EqualError(err, "required flag(s) \"account-number\", \"sequence\" not set") // But works offline if we set account number and sequence - res, err = authtest.TxSignExec(val.ClientCtx, val.Address, unsignedTxFile.Name(), "--offline", "--offline", "--account-number", "1", "--sequence", "1") + res, err = authtest.TxSignExec(val1.ClientCtx, val1.Address, unsignedTxFile.Name(), "--offline", "--offline", "--account-number", "1", "--sequence", "1") s.Require().NoError(err) // Sign transaction - generatedStd, err = authtest.TxSignExec(val.ClientCtx, val.Address, unsignedTxFile.Name()) + signedTx, err := authtest.TxSignExec(val1.ClientCtx, val1.Address, unsignedTxFile.Name()) s.Require().NoError(err) - stdTx = cli.UnmarshalStdTx(s.T(), val.ClientCtx.JSONMarshaler, string(generatedStd)) - s.Require().Equal(len(stdTx.Msgs), 1) - s.Require().Equal(1, len(stdTx.GetSignatures())) - s.Require().Equal(val.Address.String(), stdTx.GetSigners()[0].String()) + signedFinalTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, string(signedTx)) + s.Require().Equal(len(signedFinalTx.Msgs), 1) + s.Require().Equal(1, len(signedFinalTx.GetSignatures())) + s.Require().Equal(val1.Address.String(), signedFinalTx.GetSigners()[0].String()) // Write the output to disk - unsignedTxFile, cleanup2 := testutil.WriteToNewTempFile(s.T(), string(generatedStd)) + signedTxFile, cleanup2 := testutil.WriteToNewTempFile(s.T(), string(signedTx)) defer cleanup2() // Validate Signature - res, err = authtest.TxValidateSignaturesExec(val.ClientCtx, unsignedTxFile.Name()) + res, err = authtest.TxValidateSignaturesExec(val1.ClientCtx, signedTxFile.Name()) s.Require().NoError(err) s.Require().True(strings.Contains(string(res), "[OK]")) // Ensure foo has right amount of funds startTokens := sdk.TokensFromConsensusPower(400) - resp, err := bankcli.QueryBalancesExec(val.ClientCtx, val.Address) + resp, err := bankcli.QueryBalancesExec(val1.ClientCtx, val1.Address) s.Require().NoError(err) var coins sdk.Coins - err = val.ClientCtx.JSONMarshaler.UnmarshalJSON(resp, &coins) + err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp, &coins) s.Require().NoError(err) s.Require().Equal(startTokens, coins.AmountOf(cli.Denom)) -} - -func TestCLISendGenerateSignAndBroadcast(t *testing.T) { - t.SkipNow() - t.Parallel() - f := cli.InitFixtures(t) - - // start simd server - proc := f.SDStart() - t.Cleanup(func() { proc.Stop(false) }) - - fooAddr := f.KeyAddress(cli.KeyFoo) - barAddr := f.KeyAddress(cli.KeyBar) - - // Test generate sendTx with default gas - sendTokens := sdk.TokensFromConsensusPower(10) - success, stdout, stderr := bankcli.TxSend(f, fooAddr.String(), barAddr, sdk.NewCoin(cli.Denom, sendTokens), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - msg := cli.UnmarshalStdTx(t, f.Cdc, stdout) - require.Equal(t, msg.Fee.Gas, uint64(flags.DefaultGasLimit)) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Test generate sendTx with --gas=$amount - success, stdout, stderr = bankcli.TxSend(f, fooAddr.String(), barAddr, sdk.NewCoin(cli.Denom, sendTokens), "--gas=100", "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - msg = cli.UnmarshalStdTx(t, f.Cdc, stdout) - require.Equal(t, msg.Fee.Gas, uint64(100)) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Test generate sendTx, estimate gas - success, stdout, stderr = bankcli.TxSend(f, fooAddr.String(), barAddr, sdk.NewCoin(cli.Denom, sendTokens), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - msg = cli.UnmarshalStdTx(t, f.Cdc, stdout) - require.True(t, msg.Fee.Gas > 0) - require.Equal(t, len(msg.Msgs), 1) - - // Write the output to disk - unsignedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) - - // Test validate-signatures - success, stdout, _ = authtest.TxValidateSignatures(f, unsignedTxFile.Name()) - require.False(t, success) - require.Equal(t, fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n\n", fooAddr.String()), stdout) - - // Test sign + // Test broadcast // Does not work in offline mode - success, stdout, stderr = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--offline") - require.Contains(t, stderr, "required flag(s) \"account-number\", \"sequence\" not set") - require.False(t, success) - - // But works offline if we set account number and sequence - success, _, _ = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--offline", "--account-number", "1", "--sequence", "1") - require.True(t, success) - - // Sign transaction - success, stdout, _ = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name()) - require.True(t, success) - msg = cli.UnmarshalStdTx(t, f.Cdc, stdout) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 1, len(msg.GetSignatures())) - require.Equal(t, fooAddr.String(), msg.GetSigners()[0].String()) + res, err = authtest.TxBroadcastExec(val1.ClientCtx, signedTxFile.Name(), "--offline") + s.Require().EqualError(err, "cannot broadcast tx during offline mode") - // Write the output to disk - signedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) + err = s.network.WaitForNBlocks(1, 10*time.Second) + s.Require().NoError(err) - // Test validate-signatures - success, stdout, _ = authtest.TxValidateSignatures(f, signedTxFile.Name()) - require.True(t, success) - require.Equal(t, fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n 0: %v\t\t\t[OK]\n\n", fooAddr.String(), - fooAddr.String()), stdout) + // Broadcast correct transaction. + val1.ClientCtx.BroadcastMode = flags.BroadcastBlock + res, err = authtest.TxBroadcastExec(val1.ClientCtx, signedTxFile.Name()) + s.Require().NoError(err) - // Ensure foo has right amount of funds - startTokens := sdk.TokensFromConsensusPower(50) - require.Equal(t, startTokens, bankcli.QueryBalances(f, fooAddr).AmountOf(cli.Denom)) + fmt.Printf("%s \n", res) - // Test broadcast + err = s.network.WaitForNBlocks(1, 10*time.Second) + s.Require().NoError(err) - // Does not work in offline mode - success, _, stderr = authtest.TxBroadcast(f, signedTxFile.Name(), "--offline") - require.Contains(t, stderr, "cannot broadcast tx during offline mode") - require.False(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) + // Ensure destiny account state + resp, err = bankcli.QueryBalancesExec(val1.ClientCtx, account.GetAddress()) + s.Require().NoError(err) - success, stdout, _ = authtest.TxBroadcast(f, signedTxFile.Name()) - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) + err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp, &coins) + s.Require().NoError(err) + s.Require().Equal(sendTokens, coins.AmountOf(cli.Denom)) - // Ensure account state - require.Equal(t, sendTokens, bankcli.QueryBalances(f, barAddr).AmountOf(cli.Denom)) - require.Equal(t, startTokens.Sub(sendTokens), bankcli.QueryBalances(f, fooAddr).AmountOf(cli.Denom)) + // Ensure origin account state + resp, err = bankcli.QueryBalancesExec(val1.ClientCtx, val1.Address) + s.Require().NoError(err) - f.Cleanup() + err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp, &coins) + s.Require().NoError(err) + s.Require().Equal(sdk.NewInt(389999990), coins.AmountOf(cli.Denom)) } func TestCLIMultisignInsufficientCosigners(t *testing.T) { diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index babea0c88c23..2e86bf62d21a 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -31,6 +31,16 @@ func TxSignExec(clientCtx client.Context, from sdk.AccAddress, filename string, return callCmd(clientCtx, cli2.GetSignCommand, args) } +func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { + args := []string{ + filename, + } + + args = append(args, extraArgs...) + + return callCmd(clientCtx, cli2.GetBroadcastCommand, args) +} + func callCmd(clientCtx client.Context, theCmd func(clientCtx client.Context) *cobra.Command, extraArgs []string) ([]byte, error) { buf := new(bytes.Buffer) clientCtx = clientCtx.WithOutput(buf) From ff460e8f519e14fd977bb346d2662604933fb32a Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 10 Jul 2020 18:11:08 +0200 Subject: [PATCH 21/46] fix linter --- simapp/simd/cmd/root.go | 2 +- x/auth/client/cli/tx.go | 2 +- x/auth/client/cli/tx_sign.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index d29ba512351f..301e83d9fc52 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -130,7 +130,7 @@ func txCommand() *cobra.Command { cmd.AddCommand( authcmd.GetSignCommand(initClientCtx), - authcmd.GetSignBatchCommand(encodingConfig.Amino), + authcmd.GetSignBatchCommand(), authcmd.GetMultiSignCommand(initClientCtx), authcmd.GetValidateSignaturesCommand(initClientCtx), flags.LineBreak, diff --git a/x/auth/client/cli/tx.go b/x/auth/client/cli/tx.go index 6ac7ea846791..01960ff96f2c 100644 --- a/x/auth/client/cli/tx.go +++ b/x/auth/client/cli/tx.go @@ -20,7 +20,7 @@ func GetTxCmd(clientCtx client.Context) *cobra.Command { GetMultiSignCommand(clientCtx), GetSignCommand(clientCtx), GetValidateSignaturesCommand(clientCtx), - GetSignBatchCommand(clientCtx), + GetSignBatchCommand(), ) return txCmd } diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 75a54121972b..10b86afb3537 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -22,7 +22,7 @@ const ( ) // GetSignBatchCommand returns the transaction sign-batch command. -func GetSignBatchCommand(clientCtx client.Context) *cobra.Command { +func GetSignBatchCommand() *cobra.Command { cmd := &cobra.Command{ Use: "sign-batch [file]", Short: "Sign transaction batch files", From 3bab3e5d8fd6ffede24be51f39a9b6c33732b0ea Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 10 Jul 2020 18:12:17 +0200 Subject: [PATCH 22/46] Remove printf for debug in bank module. --- x/bank/client/cli/cli_test.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/x/bank/client/cli/cli_test.go b/x/bank/client/cli/cli_test.go index 464477f125e4..0666b3e754dc 100644 --- a/x/bank/client/cli/cli_test.go +++ b/x/bank/client/cli/cli_test.go @@ -285,10 +285,8 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { if tc.expectErr { s.Require().Error(err) } else { - fmt.Printf("%s\n", out) s.Require().NoError(err) s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out, tc.respType), string(out)) - fmt.Printf("%v\n", tc.respType) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) From 500637640f52ee27449c09ae58765b2a2f088206 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 10 Jul 2020 18:14:49 +0200 Subject: [PATCH 23/46] Fix unused err var. --- 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 10b86afb3537..ab3d3720ba3d 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -109,6 +109,7 @@ func makeSignBatchCmd() func(cmd *cobra.Command, args []string) error { unsignedStdTx := scanner.StdTx() txBldr = txBldr.WithSequence(sequence) + var err error if multisigAddr.Empty() { from, _ := cmd.Flags().GetString(flags.FlagFrom) _, fromName, err := client.GetFromFields(txBldr.Keybase(), from, clientCtx.GenerateOnly) @@ -120,7 +121,6 @@ func makeSignBatchCmd() func(cmd *cobra.Command, args []string) error { } else { stdTx, err = authclient.SignStdTxWithSignerAddress(txBldr, clientCtx, multisigAddr, clientCtx.GetFromName(), unsignedStdTx, true) } - if err != nil { return err } From 3a86663700f5b32a912c234c1060b854e448ffbe Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 10 Jul 2020 18:28:38 +0200 Subject: [PATCH 24/46] fix linter --- simapp/simd/cmd/root.go | 6 +++--- x/auth/client/cli/broadcast.go | 4 ++-- x/auth/client/cli/tx.go | 4 ++-- x/auth/client/cli/tx_sign.go | 21 ++++++++++----------- x/auth/client/cli/validate_sigs.go | 7 ++++--- x/auth/client/testutil/helpers.go | 9 ++++----- x/bank/client/testutil/cli_helpers.go | 2 +- 7 files changed, 26 insertions(+), 27 deletions(-) diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 301e83d9fc52..e19b2d6d7bfa 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -129,12 +129,12 @@ func txCommand() *cobra.Command { } cmd.AddCommand( - authcmd.GetSignCommand(initClientCtx), + authcmd.GetSignCommand(), authcmd.GetSignBatchCommand(), authcmd.GetMultiSignCommand(initClientCtx), - authcmd.GetValidateSignaturesCommand(initClientCtx), + authcmd.GetValidateSignaturesCommand(), flags.LineBreak, - authcmd.GetBroadcastCommand(initClientCtx), + authcmd.GetBroadcastCommand(), authcmd.GetEncodeCommand(initClientCtx), authcmd.GetDecodeCommand(initClientCtx), flags.LineBreak, diff --git a/x/auth/client/cli/broadcast.go b/x/auth/client/cli/broadcast.go index 027d7c8ee5a2..9a4b9494609c 100644 --- a/x/auth/client/cli/broadcast.go +++ b/x/auth/client/cli/broadcast.go @@ -12,7 +12,7 @@ import ( ) // GetBroadcastCommand returns the tx broadcast command. -func GetBroadcastCommand(clientCtx client.Context) *cobra.Command { +func GetBroadcastCommand() *cobra.Command { cmd := &cobra.Command{ Use: "broadcast [file_path]", Short: "Broadcast transactions generated offline", @@ -25,7 +25,7 @@ $ tx broadcast ./mytxn.json `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - clientCtx = client.GetClientContextFromCmd(cmd) + clientCtx := client.GetClientContextFromCmd(cmd) if offline, _ := cmd.Flags().GetBool(flags.FlagOffline); offline { return errors.New("cannot broadcast tx during offline mode") diff --git a/x/auth/client/cli/tx.go b/x/auth/client/cli/tx.go index 01960ff96f2c..99f2109fb3d8 100644 --- a/x/auth/client/cli/tx.go +++ b/x/auth/client/cli/tx.go @@ -18,8 +18,8 @@ func GetTxCmd(clientCtx client.Context) *cobra.Command { } txCmd.AddCommand( GetMultiSignCommand(clientCtx), - GetSignCommand(clientCtx), - GetValidateSignaturesCommand(clientCtx), + GetSignCommand(), + GetValidateSignaturesCommand(), GetSignBatchCommand(), ) return txCmd diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index ab3d3720ba3d..fb1eb27fd99a 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -109,7 +109,6 @@ func makeSignBatchCmd() func(cmd *cobra.Command, args []string) error { unsignedStdTx := scanner.StdTx() txBldr = txBldr.WithSequence(sequence) - var err error if multisigAddr.Empty() { from, _ := cmd.Flags().GetString(flags.FlagFrom) _, fromName, err := client.GetFromFields(txBldr.Keybase(), from, clientCtx.GenerateOnly) @@ -118,11 +117,14 @@ func makeSignBatchCmd() func(cmd *cobra.Command, args []string) error { } stdTx, err = authclient.SignStdTx(txBldr, clientCtx, fromName, unsignedStdTx, false, true) + if err != nil { + return err + } } else { stdTx, err = authclient.SignStdTxWithSignerAddress(txBldr, clientCtx, multisigAddr, clientCtx.GetFromName(), unsignedStdTx, true) - } - if err != nil { - return err + if err != nil { + return err + } } json, err := getSignatureJSON(clientCtx.JSONMarshaler, stdTx, generateSignatureOnly) @@ -159,7 +161,7 @@ func setOutputFile(cmd *cobra.Command) (func(), error) { } // GetSignCommand returns the transaction sign command. -func GetSignCommand(clientCtx client.Context) *cobra.Command { +func GetSignCommand() *cobra.Command { cmd := &cobra.Command{ Use: "sign [file]", Short: "Sign transactions generated offline", @@ -179,7 +181,7 @@ key. It implies --signature-only. Full multisig signed transactions may eventual be generated via the 'multisign' command. `, PreRun: preSignCmd, - RunE: makeSignCmd(clientCtx), + RunE: makeSignCmd(), Args: cobra.ExactArgs(1), } @@ -210,12 +212,9 @@ func preSignCmd(cmd *cobra.Command, _ []string) { } } -func makeSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args []string) error { +func makeSignCmd() func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) - if err != nil { - return err - } + clientCtx := client.GetClientContextFromCmd(cmd) clientCtx, txBldr, tx, err := readStdTxAndInitContexts(clientCtx, cmd, args[0]) if err != nil { diff --git a/x/auth/client/cli/validate_sigs.go b/x/auth/client/cli/validate_sigs.go index 18010b5ae418..a47787d96539 100644 --- a/x/auth/client/cli/validate_sigs.go +++ b/x/auth/client/cli/validate_sigs.go @@ -15,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/types" ) -func GetValidateSignaturesCommand(clientCtx client.Context) *cobra.Command { +func GetValidateSignaturesCommand() *cobra.Command { cmd := &cobra.Command{ Use: "validate-signatures [file]", Short: "Validate transactions signatures", @@ -28,7 +28,7 @@ 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(clientCtx), + RunE: makeValidateSignaturesCmd(), Args: cobra.ExactArgs(1), } @@ -37,8 +37,9 @@ transaction will be not be performed as that will require RPC communication with return flags.PostCommands(cmd)[0] } -func makeValidateSignaturesCmd(clientCtx client.Context) func(cmd *cobra.Command, args []string) error { +func makeValidateSignaturesCmd() func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) clientCtx, txBldr, tx, err := readStdTxAndInitContexts(clientCtx, cmd, args[0]) if err != nil { return err diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 2e86bf62d21a..814ecd790848 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -13,11 +13,10 @@ import ( clientkeys "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/tests/cli" - sdk "github.com/cosmos/cosmos-sdk/types" cli2 "github.com/cosmos/cosmos-sdk/x/auth/client/cli" ) -func TxSignExec(clientCtx client.Context, from sdk.AccAddress, filename string, extraArgs ...string) ([]byte, error) { +func TxSignExec(clientCtx client.Context, from fmt.Stringer, filename string, extraArgs ...string) ([]byte, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), fmt.Sprintf("--from=%s", from.String()), @@ -41,14 +40,14 @@ func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...str return callCmd(clientCtx, cli2.GetBroadcastCommand, args) } -func callCmd(clientCtx client.Context, theCmd func(clientCtx client.Context) *cobra.Command, extraArgs []string) ([]byte, error) { +func callCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { buf := new(bytes.Buffer) clientCtx = clientCtx.WithOutput(buf) ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - cmd := theCmd(clientCtx) + cmd := theCmd() cmd.SetErr(buf) cmd.SetOut(buf) @@ -108,7 +107,7 @@ func TxMultisign(f *cli.Fixtures, fileName, name string, signaturesFiles []strin return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags)) } -func TxSignBatchExec(clientCtx client.Context, from sdk.AccAddress, filename string, extraArgs ...string) ([]byte, error) { +func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename string, extraArgs ...string) ([]byte, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), fmt.Sprintf("--from=%s", from.String()), diff --git a/x/bank/client/testutil/cli_helpers.go b/x/bank/client/testutil/cli_helpers.go index b36670736702..710a9033b0ec 100644 --- a/x/bank/client/testutil/cli_helpers.go +++ b/x/bank/client/testutil/cli_helpers.go @@ -24,7 +24,7 @@ func MsgSendExec(clientCtx client.Context, from, to, amount fmt.Stringer, extraA return callCmd(clientCtx, bankcli.NewSendTxCmd, args) } -func QueryBalancesExec(clientCtx client.Context, address sdk.AccAddress, extraArgs ...string) ([]byte, error) { +func QueryBalancesExec(clientCtx client.Context, address fmt.Stringer, extraArgs ...string) ([]byte, error) { args := []string{address.String()} args = append(args, extraArgs...) From ebe54b862c84de0732258db7d82434eaf39df135 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 10 Jul 2020 18:39:12 +0200 Subject: [PATCH 25/46] fix test --- x/auth/client/cli/broadcast_test.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/x/auth/client/cli/broadcast_test.go b/x/auth/client/cli/broadcast_test.go index fee6de1c2a14..69a46c23ddb4 100644 --- a/x/auth/client/cli/broadcast_test.go +++ b/x/auth/client/cli/broadcast_test.go @@ -1,6 +1,7 @@ package cli import ( + "context" "fmt" "io/ioutil" "path/filepath" @@ -18,7 +19,7 @@ func TestGetBroadcastCommand_OfflineFlag(t *testing.T) { clientCtx := client.Context{}.WithOffline(true) clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) - cmd := GetBroadcastCommand(clientCtx) + cmd := GetBroadcastCommand() _ = testutil.ApplyMockIODiscardOutErr(cmd) cmd.SetArgs([]string{fmt.Sprintf("--%s=true", flags.FlagOffline), ""}) @@ -28,7 +29,11 @@ func TestGetBroadcastCommand_OfflineFlag(t *testing.T) { func TestGetBroadcastCommand_WithoutOfflineFlag(t *testing.T) { clientCtx := client.Context{} clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) - cmd := GetBroadcastCommand(clientCtx) + + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + + cmd := GetBroadcastCommand() testDir, cleanFunc := testutil.NewTestCaseDir(t) t.Cleanup(cleanFunc) @@ -39,7 +44,8 @@ func TestGetBroadcastCommand_WithoutOfflineFlag(t *testing.T) { err := ioutil.WriteFile(txFileName, txContents, 0644) require.NoError(t, err) - err = cmd.RunE(cmd, []string{txFileName}) + cmd.SetArgs([]string{txFileName}) + err = cmd.ExecuteContext(ctx) // We test it tries to broadcast but we set unsupported tx to get the error. require.EqualError(t, err, "unsupported return type ; supported types: sync, async, block") From 21810a57ead792971d74dd2969a4882f0e6eb880 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 10 Jul 2020 18:53:52 +0200 Subject: [PATCH 26/46] fix tests client --- x/auth/client/cli/cli_test.go | 5 +++-- x/auth/client/cli/tx_sign.go | 8 +++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index e006ed70cef7..29d39030b7ce 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -35,7 +35,7 @@ func (s *IntegrationTestSuite) SetupSuite() { s.T().Log("setting up integration test suite") cfg := network.DefaultConfig() - cfg.NumValidators = 2 + cfg.NumValidators = 1 s.cfg = cfg s.network = network.New(s.T(), cfg) @@ -230,7 +230,8 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { s.Require().EqualError(err, "required flag(s) \"account-number\", \"sequence\" not set") // But works offline if we set account number and sequence - res, err = authtest.TxSignExec(val1.ClientCtx, val1.Address, unsignedTxFile.Name(), "--offline", "--offline", "--account-number", "1", "--sequence", "1") + val1.ClientCtx.HomeDir = strings.Replace(val1.ClientCtx.HomeDir, "simd", "simcli", 1) + res, err = authtest.TxSignExec(val1.ClientCtx, val1.Address, unsignedTxFile.Name(), "--offline", "--account-number", "1", "--sequence", "1") s.Require().NoError(err) // Sign transaction diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index fb1eb27fd99a..977cdcde7896 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -239,9 +239,15 @@ func makeSignCmd() func(cmd *cobra.Command, args []string) error { ) generateSignatureOnly = true } else { + from, _ := cmd.Flags().GetString(flags.FlagFrom) + _, fromName, err := client.GetFromFields(txBldr.Keybase(), from, clientCtx.GenerateOnly) + if err != nil { + return fmt.Errorf("error getting account from keybase: %w", err) + } + append, _ := cmd.Flags().GetBool(flagAppend) appendSig := append && !generateSignatureOnly - newTx, err = authclient.SignStdTx(txBldr, clientCtx, clientCtx.GetFromName(), stdTx, appendSig, clientCtx.Offline) + newTx, err = authclient.SignStdTx(txBldr, clientCtx, fromName, stdTx, appendSig, clientCtx.Offline) } if err != nil { return err From 7046e76d7f4cf26d54fee0c2feda1be2417c7900 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 10 Jul 2020 18:57:19 +0200 Subject: [PATCH 27/46] Fix linter. --- x/auth/client/cli/tx_sign.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 977cdcde7896..23d576b0195e 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -248,6 +248,9 @@ func makeSignCmd() func(cmd *cobra.Command, args []string) error { append, _ := cmd.Flags().GetBool(flagAppend) appendSig := append && !generateSignatureOnly newTx, err = authclient.SignStdTx(txBldr, clientCtx, fromName, stdTx, appendSig, clientCtx.Offline) + if err != nil { + return err + } } if err != nil { return err From 286492c79faca49d3e55c0b1944c2d3ee0cfcaf4 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 13 Jul 2020 12:29:34 +0200 Subject: [PATCH 28/46] Temp commit signature. --- x/auth/client/cli/cli_test.go | 88 ++++++++++++++++++++++++++++++- x/auth/client/cli/tx.go | 4 +- x/auth/client/cli/tx_multisign.go | 18 +++---- x/auth/client/cli/tx_sign.go | 15 +++--- x/auth/client/testutil/helpers.go | 13 +++++ x/auth/module.go | 2 +- 6 files changed, 119 insertions(+), 21 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 29d39030b7ce..4ba58003c46d 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -6,6 +6,14 @@ import ( "testing" "time" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + + codec2 "github.com/cosmos/cosmos-sdk/codec" + + tmcrypto "github.com/tendermint/tendermint/crypto" + + "github.com/cosmos/cosmos-sdk/crypto/types/multisig" + "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -276,8 +284,6 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { res, err = authtest.TxBroadcastExec(val1.ClientCtx, signedTxFile.Name()) s.Require().NoError(err) - fmt.Printf("%s \n", res) - err = s.network.WaitForNBlocks(1, 10*time.Second) s.Require().NoError(err) @@ -298,6 +304,84 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { s.Require().Equal(sdk.NewInt(389999990), coins.AmountOf(cli.Denom)) } +func (s *IntegrationTestSuite) TestCLIMultisignInsufficientCosigners() { + s.T().SkipNow() + val1 := s.network.Validators[0] + + codec := codec2.New() + sdk.RegisterCodec(codec) + banktypes.RegisterCodec(codec) + val1.ClientCtx.Codec = codec + + // Generate 2 accounts and a multisig. + account1, _, err := val1.ClientCtx.Keyring.NewMnemonic("newAccount1", keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) + s.Require().NoError(err) + + account2, _, err := val1.ClientCtx.Keyring.NewMnemonic("newAccount2", keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) + s.Require().NoError(err) + + multi := multisig.NewPubKeyMultisigThreshold(2, []tmcrypto.PubKey{account1.GetPubKey(), account2.GetPubKey()}) + multisigInfo, err := val1.ClientCtx.Keyring.SaveMultisig("multi", multi) + s.Require().NoError(err) + + // Send coins from validator to multisig. + _, err = bankcli.MsgSendExec( + val1.ClientCtx, + val1.Address, + multisigInfo.GetAddress(), + sdk.NewCoins( + sdk.NewInt64Coin(cli.Denom, 10), + ), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--gas=%d", flags.DefaultGasLimit), + ) + s.Require().NoError(err) + + err = s.network.WaitForNBlocks(1, 10*time.Second) + s.Require().NoError(err) + + // Generate multisig transaction. + multiGeneratedTx, err := bankcli.MsgSendExec( + val1.ClientCtx, + multisigInfo.GetAddress(), + val1.Address, + sdk.NewCoins( + sdk.NewInt64Coin(cli.Denom, 5), + ), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), + ) + s.Require().NoError(err) + + // Save tx to file + multiGeneratedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(multiGeneratedTx)) + defer cleanup() + + // Multisign, sign with one signature + val1.ClientCtx.HomeDir = strings.Replace(val1.ClientCtx.HomeDir, "simd", "simcli", 1) + account1Signature, err := authtest.TxSignExec(val1.ClientCtx, account1.GetAddress(), multiGeneratedTxFile.Name(), "--multisig", multisigInfo.GetAddress().String()) + s.Require().NoError(err) + + sign1File, cleanup2 := testutil.WriteToNewTempFile(s.T(), string(account1Signature)) + defer cleanup2() + + multiSigWith1Signature, err := authtest.TxMultiSignExec(val1.ClientCtx, multisigInfo.GetName(), multiGeneratedTxFile.Name(), sign1File.Name()) + s.Require().NoError(err) + + // Save tx to file + multiSigWith1SignatureFile, cleanup3 := testutil.WriteToNewTempFile(s.T(), string(multiSigWith1Signature)) + defer cleanup3() + + exec, err := authtest.TxValidateSignaturesExec(val1.ClientCtx, multiSigWith1SignatureFile.Name()) + s.Require().NoError(err) + + fmt.Printf("%s", exec) +} + func TestCLIMultisignInsufficientCosigners(t *testing.T) { t.SkipNow() t.Parallel() diff --git a/x/auth/client/cli/tx.go b/x/auth/client/cli/tx.go index 99f2109fb3d8..42b20ae8d5f3 100644 --- a/x/auth/client/cli/tx.go +++ b/x/auth/client/cli/tx.go @@ -8,7 +8,7 @@ import ( ) // GetTxCmd returns the transaction commands for this module -func GetTxCmd(clientCtx client.Context) *cobra.Command { +func GetTxCmd() *cobra.Command { txCmd := &cobra.Command{ Use: types.ModuleName, Short: "Auth transaction subcommands", @@ -17,7 +17,7 @@ func GetTxCmd(clientCtx client.Context) *cobra.Command { RunE: client.ValidateCmd, } txCmd.AddCommand( - GetMultiSignCommand(clientCtx), + GetMultiSignCommand(), GetSignCommand(), GetValidateSignaturesCommand(), GetSignBatchCommand(), diff --git a/x/auth/client/cli/tx_multisign.go b/x/auth/client/cli/tx_multisign.go index f01d8592d9ff..a05797e3e680 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(clientCtx client.Context) *cobra.Command { +func GetMultiSignCommand() *cobra.Command { cmd := &cobra.Command{ Use: "multisign [file] [name] [[signature]...]", Short: "Generate multisig signatures for transactions generated offline", @@ -45,19 +45,20 @@ recommended to set such parameters manually. version.AppName, ), ), - RunE: makeMultiSignCmd(clientCtx), + RunE: makeMultiSignCmd(), Args: cobra.MinimumNArgs(3), } cmd.Flags().Bool(flagSigOnly, false, "Print only the generated signature, then exit") cmd.Flags().String(flags.FlagOutputDocument, "", "The document will be written to the given file instead of STDOUT") + cmd.Flags().String(flags.FlagChainID, "", "network chain ID") return flags.PostCommands(cmd)[0] } -func makeMultiSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args []string) error { +func makeMultiSignCmd() func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) (err error) { - clientCtx = clientCtx.Init() + clientCtx := client.GetClientContextFromCmd(cmd) cdc := clientCtx.Codec tx, err := authclient.ReadTxFromFile(clientCtx, args[0]) stdTx := tx.(types.StdTx) @@ -66,10 +67,9 @@ func makeMultiSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args [] } backend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) - homeDir, _ := cmd.Flags().GetString(flags.FlagHome) inBuf := bufio.NewReader(cmd.InOrStdin()) - kb, err := keyring.New(sdk.KeyringServiceName(), backend, homeDir, inBuf) + kb, err := keyring.New(sdk.KeyringServiceName(), backend, clientCtx.HomeDir, inBuf) if err != nil { return } @@ -84,13 +84,13 @@ func makeMultiSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args [] multisigPub := multisigInfo.GetPubKey().(multisig.PubKeyMultisigThreshold) multisigSig := multisig.NewMultisig(len(multisigPub.PubKeys)) - txBldr, err := types.NewTxBuilderFromFlags(inBuf, cmd.Flags(), homeDir) + txBldr, err := types.NewTxBuilderFromFlags(inBuf, cmd.Flags(), clientCtx.HomeDir) if err != nil { return errors.Wrap(err, "error creating tx builder from flags") } if !clientCtx.Offline { - accnum, seq, err := types.NewAccountRetriever(authclient.Codec).GetAccountNumberSequence(clientCtx, multisigInfo.GetAddress()) + accnum, seq, err := types.NewAccountRetriever(clientCtx.JSONMarshaler).GetAccountNumberSequence(clientCtx, multisigInfo.GetAddress()) if err != nil { return err } @@ -147,7 +147,7 @@ func makeMultiSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args [] outputDoc, _ := cmd.Flags().GetString(flags.FlagOutputDocument) if outputDoc == "" { - fmt.Printf("%s\n", json) + cmd.Printf("%s\n", json) return } diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 23d576b0195e..892cda9ae146 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -227,6 +227,12 @@ func makeSignCmd() func(cmd *cobra.Command, args []string) error { generateSignatureOnly, _ := cmd.Flags().GetBool(flagSigOnly) multisigAddrStr, _ := cmd.Flags().GetString(flagMultisig) + from, _ := cmd.Flags().GetString(flags.FlagFrom) + _, fromName, err := client.GetFromFields(txBldr.Keybase(), from, clientCtx.GenerateOnly) + if err != nil { + return fmt.Errorf("error getting account from keybase: %w", err) + } + if multisigAddrStr != "" { var multisigAddr sdk.AccAddress @@ -234,17 +240,12 @@ func makeSignCmd() func(cmd *cobra.Command, args []string) error { if err != nil { return err } + newTx, err = authclient.SignStdTxWithSignerAddress( - txBldr, clientCtx, multisigAddr, clientCtx.GetFromName(), stdTx, clientCtx.Offline, + txBldr, clientCtx, multisigAddr, fromName, stdTx, clientCtx.Offline, ) generateSignatureOnly = true } else { - from, _ := cmd.Flags().GetString(flags.FlagFrom) - _, fromName, err := client.GetFromFields(txBldr.Keybase(), from, clientCtx.GenerateOnly) - if err != nil { - return fmt.Errorf("error getting account from keybase: %w", err) - } - append, _ := cmd.Flags().GetBool(flagAppend) appendSig := append && !generateSignatureOnly newTx, err = authclient.SignStdTx(txBldr, clientCtx, fromName, stdTx, appendSig, clientCtx.Offline) diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 814ecd790848..c869461b6afd 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -97,6 +97,19 @@ func TxValidateSignatures(f *cli.Fixtures, fileName string, flags ...string) (bo return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } +func TxMultiSignExec(clientCtx client.Context, from string, filename string, extraArgs ...string) ([]byte, error) { + args := []string{ + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=%s", flags.FlagChainID, clientCtx.ChainID), + filename, + from, + } + + args = append(args, extraArgs...) + + return callCmd(clientCtx, cli2.GetMultiSignCommand, args) +} + // TxMultisign is simcli tx multisign func TxMultisign(f *cli.Fixtures, fileName, name string, signaturesFiles []string, flags ...string) (bool, string, string) { diff --git a/x/auth/module.go b/x/auth/module.go index 7ef1a83a2493..3bf8136a45ba 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -67,7 +67,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) + return cli.GetTxCmd() } // GetQueryCmd returns the root query command for the auth module. From 8e9a1d5749ba5bbd516fcb097f59249db6d7fb4d Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 13 Jul 2020 16:19:59 +0200 Subject: [PATCH 29/46] encode tx --- x/auth/client/cli/cli_test.go | 107 ++++++++---------------------- x/auth/client/cli/decode.go | 4 +- x/auth/client/cli/encode.go | 8 +-- x/auth/client/cli/encode_test.go | 7 +- x/auth/client/testutil/helpers.go | 22 ++++++ 5 files changed, 59 insertions(+), 89 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 4ba58003c46d..d5773ef9dcbe 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -305,7 +305,7 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { } func (s *IntegrationTestSuite) TestCLIMultisignInsufficientCosigners() { - s.T().SkipNow() + s.T().SkipNow() // TODO check encoding. val1 := s.network.Validators[0] codec := codec2.New() @@ -382,90 +382,41 @@ func (s *IntegrationTestSuite) TestCLIMultisignInsufficientCosigners() { fmt.Printf("%s", exec) } -func TestCLIMultisignInsufficientCosigners(t *testing.T) { - t.SkipNow() - t.Parallel() - f := cli.InitFixtures(t) - - // start simd server with minimum fees - proc := f.SDStart() - t.Cleanup(func() { proc.Stop(false) }) - - fooBarBazAddr := f.KeyAddress(cli.KeyFooBarBaz) - barAddr := f.KeyAddress(cli.KeyBar) - - // Send some tokens from one account to the other - success, _, _ := bankcli.TxSend(f, cli.KeyFoo, fooBarBazAddr, sdk.NewInt64Coin(cli.Denom, 10), "-y") - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Test generate sendTx with multisig - success, stdout, _ := bankcli.TxSend(f, fooBarBazAddr.String(), barAddr, sdk.NewInt64Coin(cli.Denom, 5), "--generate-only") - require.True(t, success) - - // Write the output to disk - unsignedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) - - // Sign with foo's key - success, stdout, _ = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") - require.True(t, success) - - // Write the output to disk - fooSignatureFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) - - // Multisign, not enough signatures - success, stdout, _ = authtest.TxMultisign(f, unsignedTxFile.Name(), cli.KeyFooBarBaz, []string{fooSignatureFile.Name()}) - require.True(t, success) - - // Write the output to disk - signedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) - - // Validate the multisignature - success, _, _ = authtest.TxValidateSignatures(f, signedTxFile.Name()) - require.False(t, success) - - // Broadcast the transaction - success, stdOut, _ := authtest.TxBroadcast(f, signedTxFile.Name()) - require.Contains(t, stdOut, "signature verification failed") - require.True(t, success) +func (s *IntegrationTestSuite) TestCLIEncode() { + val1 := s.network.Validators[0] - // Cleanup testing directories - f.Cleanup() -} + sendTokens := sdk.TokensFromConsensusPower(10) -func TestCLIEncode(t *testing.T) { - t.SkipNow() - t.Parallel() - f := cli.InitFixtures(t) + normalGeneratedTx, err := bankcli.MsgSendExec( + val1.ClientCtx, + val1.Address, + val1.Address, + sdk.NewCoins( + sdk.NewCoin(s.cfg.BondDenom, sendTokens), + ), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), "--memo", "deadbeef", + ) + s.Require().NoError(err) - // start simd server - proc := f.SDStart() - t.Cleanup(func() { proc.Stop(false) }) + // Save tx to file + savedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(normalGeneratedTx)) + defer cleanup() - // Build a testing transaction and write it to disk - barAddr := f.KeyAddress(cli.KeyBar) - keyAddr := f.KeyAddress(cli.KeyFoo) + // Enconde + encodeExec, err := authtest.TxEncodeExec(val1.ClientCtx, savedTxFile.Name()) + s.Require().NoError(err) - sendTokens := sdk.TokensFromConsensusPower(10) - success, stdout, stderr := bankcli.TxSend(f, keyAddr.String(), barAddr, sdk.NewCoin(cli.Denom, sendTokens), "--generate-only", "--memo", "deadbeef") - require.True(t, success) - require.Empty(t, stderr) + trimmedBase64 := strings.Trim(string(encodeExec), "\"\n") + // Check that the transaction decodes as expected - // Write it to disk - jsonTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) + decodedTx, err := authtest.TxDecodeExec(val1.ClientCtx, trimmedBase64) + s.Require().NoError(err) - // Run the encode command - success, base64Encoded, _ := authtest.TxEncode(f, jsonTxFile.Name()) - require.True(t, success) - trimmedBase64 := strings.Trim(base64Encoded, "\"\n") - // Check that the transaction decodes as expected - success, stdout, stderr = authtest.TxDecode(f, trimmedBase64) - decodedTx := cli.UnmarshalStdTx(t, f.Cdc, stdout) - require.Equal(t, "deadbeef", decodedTx.Memo) + theTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, string(decodedTx)) + s.Require().Equal("deadbeef", theTx.Memo) } func TestCLIMultisignSortSignatures(t *testing.T) { diff --git a/x/auth/client/cli/decode.go b/x/auth/client/cli/decode.go index bf69aee4019e..18dd4f73a163 100644 --- a/x/auth/client/cli/decode.go +++ b/x/auth/client/cli/decode.go @@ -14,13 +14,13 @@ const flagHex = "hex" // GetDecodeCommand returns the decode command to take serialized bytes and turn // it into a JSON-encoded transaction. -func GetDecodeCommand(clientCtx client.Context) *cobra.Command { +func GetDecodeCommand() *cobra.Command { cmd := &cobra.Command{ Use: "decode [amino-byte-string]", Short: "Decode an binary encoded transaction string.", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) (err error) { - clientCtx = clientCtx.Init().WithOutput(cmd.OutOrStdout()) + clientCtx := client.GetClientContextFromCmd(cmd) var txBytes []byte if useHex, _ := cmd.Flags().GetBool(flagHex); useHex { diff --git a/x/auth/client/cli/encode.go b/x/auth/client/cli/encode.go index 3ca0b46b3aed..ddb55cf89afb 100644 --- a/x/auth/client/cli/encode.go +++ b/x/auth/client/cli/encode.go @@ -19,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(clientCtx client.Context) *cobra.Command { +func GetEncodeCommand() *cobra.Command { cmd := &cobra.Command{ Use: "encode [file]", Short: "Encode transactions generated offline", @@ -28,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) error { - cliCtx := clientCtx.Init() + clientCtx := client.GetClientContextFromCmd(cmd) - tx, err := authclient.ReadTxFromFile(cliCtx, args[0]) + tx, err := authclient.ReadTxFromFile(clientCtx, args[0]) if err != nil { return err } // re-encode it - txBytes, err := cliCtx.TxGenerator.TxEncoder()(tx) + txBytes, err := clientCtx.TxGenerator.TxEncoder()(tx) if err != nil { return err } diff --git a/x/auth/client/cli/encode_test.go b/x/auth/client/cli/encode_test.go index 550e1133cc96..f6ab14b3326d 100644 --- a/x/auth/client/cli/encode_test.go +++ b/x/auth/client/cli/encode_test.go @@ -15,11 +15,8 @@ import ( func TestGetCommandEncode(t *testing.T) { encodingConfig := simappparams.MakeEncodingConfig() - clientCtx := client.Context{}. - WithTxGenerator(encodingConfig.TxGenerator). - WithJSONMarshaler(encodingConfig.Marshaler) - cmd := GetEncodeCommand(clientCtx) + cmd := GetEncodeCommand() _ = testutil.ApplyMockIODiscardOutErr(cmd) authtypes.RegisterCodec(encodingConfig.Amino) @@ -48,7 +45,7 @@ func TestGetCommandDecode(t *testing.T) { WithTxGenerator(encodingConfig.TxGenerator). WithJSONMarshaler(encodingConfig.Marshaler) - cmd := GetDecodeCommand(clientCtx) + cmd := GetDecodeCommand() _ = testutil.ApplyMockIODiscardOutErr(cmd) sdk.RegisterCodec(encodingConfig.Amino) diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index c869461b6afd..4d9e0da11749 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -73,6 +73,17 @@ func TxBroadcast(f *cli.Fixtures, fileName string, flags ...string) (bool, strin return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } +func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { + args := []string{ + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + filename, + } + + args = append(args, extraArgs...) + + return callCmd(clientCtx, cli2.GetEncodeCommand, args) +} + // TxEncode is simcli tx encode func TxEncode(f *cli.Fixtures, fileName string, flags ...string) (bool, string, string) { cmd := fmt.Sprintf("%s tx encode %v %v", f.SimdBinary, f.Flags(), fileName) @@ -132,6 +143,17 @@ func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename strin return callCmd(clientCtx, cli2.GetSignBatchCommand, args) } +func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...string) ([]byte, error) { + args := []string{ + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + encodedTx, + } + + args = append(args, extraArgs...) + + return callCmd(clientCtx, cli2.GetDecodeCommand, args) +} + // 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.SimdBinary, f.Flags(), encodedTx) From 9f96ef9aecfa21707d8d05582533030fa2739a7f Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 13 Jul 2020 17:34:58 +0200 Subject: [PATCH 30/46] migrate tests --- x/auth/client/cli/cli_test.go | 269 +++++++++++++++++++++------------- 1 file changed, 166 insertions(+), 103 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index d5773ef9dcbe..97dabed741ae 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -19,11 +19,9 @@ import ( "github.com/cosmos/cosmos-sdk/testutil/network" - "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/tests/cli" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" @@ -419,143 +417,208 @@ func (s *IntegrationTestSuite) TestCLIEncode() { s.Require().Equal("deadbeef", theTx.Memo) } -func TestCLIMultisignSortSignatures(t *testing.T) { - t.SkipNow() - t.Parallel() - f := cli.InitFixtures(t) +func (s *IntegrationTestSuite) TestCLIMultisignSortSignatures() { + s.T().SkipNow() + val1 := s.network.Validators[0] - // start simd server with minimum fees - proc := f.SDStart() - t.Cleanup(func() { proc.Stop(false) }) + codec := codec2.New() + sdk.RegisterCodec(codec) + banktypes.RegisterCodec(codec) + val1.ClientCtx.Codec = codec - fooBarBazAddr := f.KeyAddress(cli.KeyFooBarBaz) - barAddr := f.KeyAddress(cli.KeyBar) + // Generate 2 accounts and a multisig. + account1, _, err := val1.ClientCtx.Keyring.NewMnemonic("newAccount1", keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) + s.Require().NoError(err) - // Send some tokens from one account to the other - success, _, _ := bankcli.TxSend(f, cli.KeyFoo, fooBarBazAddr, sdk.NewInt64Coin(cli.Denom, 10), "-y") - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) + account2, _, err := val1.ClientCtx.Keyring.NewMnemonic("newAccount2", keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) + s.Require().NoError(err) - // Ensure account balances match expected - require.Equal(t, int64(10), bankcli.QueryBalances(f, fooBarBazAddr).AmountOf(cli.Denom).Int64()) + multi := multisig.NewPubKeyMultisigThreshold(2, []tmcrypto.PubKey{account1.GetPubKey(), account2.GetPubKey()}) + multisigInfo, err := val1.ClientCtx.Keyring.SaveMultisig("multi", multi) + s.Require().NoError(err) - // Test generate sendTx with multisig - success, stdout, _ := bankcli.TxSend(f, fooBarBazAddr.String(), barAddr, sdk.NewInt64Coin(cli.Denom, 5), "--generate-only") - require.True(t, success) + // Send coins from validator to multisig. + sendTokens := sdk.NewInt64Coin(cli.Denom, 10) + _, err = bankcli.MsgSendExec( + val1.ClientCtx, + val1.Address, + multisigInfo.GetAddress(), + sdk.NewCoins( + sendTokens, + ), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--gas=%d", flags.DefaultGasLimit), + ) + s.Require().NoError(err) - // Write the output to disk - unsignedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) + err = s.network.WaitForNBlocks(1, 10*time.Second) + s.Require().NoError(err) - // Sign with foo's key - success, stdout, _ = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String()) - require.True(t, success) + resp, err := bankcli.QueryBalancesExec(val1.ClientCtx, multisigInfo.GetAddress()) + s.Require().NoError(err) - // Write the output to disk - fooSignatureFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) + var coins sdk.Coins + err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp, &coins) + s.Require().NoError(err) + s.Require().Equal(sendTokens.Amount, coins.AmountOf(cli.Denom)) - // Sign with baz's key - success, stdout, _ = authtest.TxSign(f, cli.KeyBaz, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String()) - require.True(t, success) + // Generate multisig transaction. + multiGeneratedTx, err := bankcli.MsgSendExec( + val1.ClientCtx, + multisigInfo.GetAddress(), + val1.Address, + sdk.NewCoins( + sdk.NewInt64Coin(cli.Denom, 5), + ), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), + ) + s.Require().NoError(err) - // Write the output to disk - bazSignatureFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) + // Save tx to file + multiGeneratedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(multiGeneratedTx)) + defer cleanup() - // Multisign, keys in different order - success, stdout, _ = authtest.TxMultisign(f, unsignedTxFile.Name(), cli.KeyFooBarBaz, []string{ - bazSignatureFile.Name(), fooSignatureFile.Name()}) - require.True(t, success) + // Sign with account1 + val1.ClientCtx.HomeDir = strings.Replace(val1.ClientCtx.HomeDir, "simd", "simcli", 1) + account1Signature, err := authtest.TxSignExec(val1.ClientCtx, account1.GetAddress(), multiGeneratedTxFile.Name(), "--multisig", multisigInfo.GetAddress().String()) + s.Require().NoError(err) + + sign1File, cleanup2 := testutil.WriteToNewTempFile(s.T(), string(account1Signature)) + defer cleanup2() + + // Sign with account1 + account2Signature, err := authtest.TxSignExec(val1.ClientCtx, account2.GetAddress(), multiGeneratedTxFile.Name(), "--multisig", multisigInfo.GetAddress().String()) + s.Require().NoError(err) + + sign2File, cleanup3 := testutil.WriteToNewTempFile(s.T(), string(account2Signature)) + defer cleanup3() + + multiSigWith2Signatures, err := authtest.TxMultiSignExec(val1.ClientCtx, multisigInfo.GetName(), multiGeneratedTxFile.Name(), sign1File.Name(), sign2File.Name()) + s.Require().NoError(err) // Write the output to disk - signedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) + signedTxFile, cleanup4 := testutil.WriteToNewTempFile(s.T(), string(multiSigWith2Signatures)) + defer cleanup4() - // Validate the multisignature - success, _, _ = authtest.TxValidateSignatures(f, signedTxFile.Name()) - require.True(t, success) + _, err = authtest.TxValidateSignaturesExec(val1.ClientCtx, signedTxFile.Name()) + s.Require().NoError(err) - // Broadcast the transaction - success, _, _ = authtest.TxBroadcast(f, signedTxFile.Name()) - require.True(t, success) + val1.ClientCtx.BroadcastMode = flags.BroadcastBlock + _, err = authtest.TxBroadcastExec(val1.ClientCtx, signedTxFile.Name()) + s.Require().NoError(err) - // Cleanup testing directories - f.Cleanup() + err = s.network.WaitForNBlocks(1, 10*time.Second) + s.Require().NoError(err) } -func TestCLIMultisign(t *testing.T) { - t.SkipNow() - t.Parallel() - f := cli.InitFixtures(t) +func (s *IntegrationTestSuite) TestCLIMultisign() { + s.T().SkipNow() + val1 := s.network.Validators[0] - // start simd server with minimum fees - proc := f.SDStart() - t.Cleanup(func() { proc.Stop(false) }) + codec := codec2.New() + sdk.RegisterCodec(codec) + banktypes.RegisterCodec(codec) + val1.ClientCtx.Codec = codec - fooBarBazAddr := f.KeyAddress(cli.KeyFooBarBaz) - bazAddr := f.KeyAddress(cli.KeyBaz) + // Generate 2 accounts and a multisig. + account1, _, err := val1.ClientCtx.Keyring.NewMnemonic("newAccount1", keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) + s.Require().NoError(err) - // Send some tokens from one account to the other - success, _, _ := bankcli.TxSend(f, cli.KeyFoo, fooBarBazAddr, sdk.NewInt64Coin(cli.Denom, 10), "-y") - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) + account2, _, err := val1.ClientCtx.Keyring.NewMnemonic("newAccount2", keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) + s.Require().NoError(err) - // Ensure account balances match expected - require.Equal(t, int64(10), bankcli.QueryBalances(f, fooBarBazAddr).AmountOf(cli.Denom).Int64()) + multi := multisig.NewPubKeyMultisigThreshold(2, []tmcrypto.PubKey{account1.GetPubKey(), account2.GetPubKey()}) + multisigInfo, err := val1.ClientCtx.Keyring.SaveMultisig("multi", multi) + s.Require().NoError(err) - // Test generate sendTx with multisig - success, stdout, stderr := bankcli.TxSend(f, fooBarBazAddr.String(), bazAddr, sdk.NewInt64Coin(cli.Denom, 10), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) + // Send coins from validator to multisig. + sendTokens := sdk.NewInt64Coin(cli.Denom, 10) + _, err = bankcli.MsgSendExec( + val1.ClientCtx, + val1.Address, + multisigInfo.GetAddress(), + sdk.NewCoins( + sendTokens, + ), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--gas=%d", flags.DefaultGasLimit), + ) + s.Require().NoError(err) - // Write the output to disk - unsignedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) + err = s.network.WaitForNBlocks(1, 10*time.Second) + s.Require().NoError(err) - // Sign with foo's key - success, stdout, _ = authtest.TxSign(f, cli.KeyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") - require.True(t, success) + resp, err := bankcli.QueryBalancesExec(val1.ClientCtx, multisigInfo.GetAddress()) + s.Require().NoError(err) - // Write the output to disk - fooSignatureFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) + var coins sdk.Coins + err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp, &coins) + s.Require().NoError(err) + s.Require().Equal(sendTokens.Amount, coins.AmountOf(cli.Denom)) - // Sign with bar's key - success, stdout, _ = authtest.TxSign(f, cli.KeyBar, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") - require.True(t, success) + // Generate multisig transaction. + multiGeneratedTx, err := bankcli.MsgSendExec( + val1.ClientCtx, + multisigInfo.GetAddress(), + val1.Address, + sdk.NewCoins( + sdk.NewInt64Coin(cli.Denom, 5), + ), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), + ) + s.Require().NoError(err) - // Write the output to disk - barSignatureFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) + // Save tx to file + multiGeneratedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(multiGeneratedTx)) + defer cleanup() - // Multisign + // Sign with account1 + val1.ClientCtx.HomeDir = strings.Replace(val1.ClientCtx.HomeDir, "simd", "simcli", 1) + account1Signature, err := authtest.TxSignExec(val1.ClientCtx, account1.GetAddress(), multiGeneratedTxFile.Name(), "--multisig", multisigInfo.GetAddress().String()) + s.Require().NoError(err) - // Does not work in offline mode - success, stdout, _ = authtest.TxMultisign(f, unsignedTxFile.Name(), cli.KeyFooBarBaz, []string{ - fooSignatureFile.Name(), barSignatureFile.Name()}, "--offline") - require.Contains(t, "couldn't verify signature", stdout) - require.False(t, success) + sign1File, cleanup2 := testutil.WriteToNewTempFile(s.T(), string(account1Signature)) + defer cleanup2() + + // Sign with account1 + account2Signature, err := authtest.TxSignExec(val1.ClientCtx, account2.GetAddress(), multiGeneratedTxFile.Name(), "--multisig", multisigInfo.GetAddress().String()) + s.Require().NoError(err) - // Success multisign - success, stdout, _ = authtest.TxMultisign(f, unsignedTxFile.Name(), cli.KeyFooBarBaz, []string{ - fooSignatureFile.Name(), barSignatureFile.Name()}) - require.True(t, success) + sign2File, cleanup3 := testutil.WriteToNewTempFile(s.T(), string(account2Signature)) + defer cleanup3() + + // Does not work in offline mode. + val1.ClientCtx.Offline = true + _, err = authtest.TxMultiSignExec(val1.ClientCtx, multisigInfo.GetName(), multiGeneratedTxFile.Name(), sign1File.Name(), sign2File.Name()) + s.Require().EqualError(err, "couldn't verify signature") + + val1.ClientCtx.Offline = false + multiSigWith2Signatures, err := authtest.TxMultiSignExec(val1.ClientCtx, multisigInfo.GetName(), multiGeneratedTxFile.Name(), sign1File.Name(), sign2File.Name()) + s.Require().NoError(err) // Write the output to disk - signedTxFile, cleanup := testutil.WriteToNewTempFile(t, stdout) - t.Cleanup(cleanup) + signedTxFile, cleanup4 := testutil.WriteToNewTempFile(s.T(), string(multiSigWith2Signatures)) + defer cleanup4() - // Validate the multisignature - success, _, _ = authtest.TxValidateSignatures(f, signedTxFile.Name()) - require.True(t, success) + _, err = authtest.TxValidateSignaturesExec(val1.ClientCtx, signedTxFile.Name()) + s.Require().NoError(err) - // Broadcast the transaction - success, _, _ = authtest.TxBroadcast(f, signedTxFile.Name()) - require.True(t, success) + val1.ClientCtx.BroadcastMode = flags.BroadcastBlock + _, err = authtest.TxBroadcastExec(val1.ClientCtx, signedTxFile.Name()) + s.Require().NoError(err) - // Cleanup testing directories - f.Cleanup() + err = s.network.WaitForNBlocks(1, 10*time.Second) + s.Require().NoError(err) } func TestIntegrationTestSuite(t *testing.T) { From 67805a4d403594950ae66997b24e59e12446bfd7 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 13 Jul 2020 17:43:22 +0200 Subject: [PATCH 31/46] Fix imports. --- x/auth/client/cli/cli_test.go | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 97dabed741ae..046d96b9f035 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -6,28 +6,23 @@ import ( "testing" "time" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - - codec2 "github.com/cosmos/cosmos-sdk/codec" - tmcrypto "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/crypto/types/multisig" - - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - - "github.com/cosmos/cosmos-sdk/testutil/network" - "github.com/stretchr/testify/suite" "github.com/cosmos/cosmos-sdk/client/flags" + codec2 "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/crypto/types/multisig" "github.com/cosmos/cosmos-sdk/tests/cli" "github.com/cosmos/cosmos-sdk/testutil" + "github.com/cosmos/cosmos-sdk/testutil/network" sdk "github.com/cosmos/cosmos-sdk/types" authtest "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" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ) type IntegrationTestSuite struct { From 4973b9a81ab2cd812a3bf0051b917a3cf4adba88 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 13 Jul 2020 17:45:47 +0200 Subject: [PATCH 32/46] Remove changelog --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50c00ea288e5..c46c5f336560 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -65,7 +65,6 @@ older clients. ### API Breaking Changes -* (auth) [\#6653](https://github.com/cosmos/cosmos-sdk/pull/6653) `NewTxBuilderFromCLI` is removed due to removal of viper dependency, use NewTxBuilderFromFlags instead. * (modules) [\#6564](https://github.com/cosmos/cosmos-sdk/pull/6564) Constant `DefaultParamspace` is removed from all modules, use ModuleName instead. * (client) [\#6525](https://github.com/cosmos/cosmos-sdk/pull/6525) Removed support for `indent` in JSON responses. Clients should consider piping to an external tool such as `jq`. * (x/staking) [\#6451](https://github.com/cosmos/cosmos-sdk/pull/6451) `DefaultParamspace` and `ParamKeyTable` in staking module are moved from keeper to types to enforce consistency. From 1f4db6ea484cd746c517083332e2515454574ed6 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 13 Jul 2020 18:47:34 +0200 Subject: [PATCH 33/46] fix tests --- simapp/simd/cmd/root.go | 6 ++--- x/auth/client/cli/encode_test.go | 15 +++++++++-- x/auth/client/testutil/helpers.go | 45 ------------------------------- 3 files changed, 16 insertions(+), 50 deletions(-) diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index e19b2d6d7bfa..b8f05b4958af 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -131,12 +131,12 @@ func txCommand() *cobra.Command { cmd.AddCommand( authcmd.GetSignCommand(), authcmd.GetSignBatchCommand(), - authcmd.GetMultiSignCommand(initClientCtx), + authcmd.GetMultiSignCommand(), authcmd.GetValidateSignaturesCommand(), flags.LineBreak, authcmd.GetBroadcastCommand(), - authcmd.GetEncodeCommand(initClientCtx), - authcmd.GetDecodeCommand(initClientCtx), + authcmd.GetEncodeCommand(), + authcmd.GetDecodeCommand(), flags.LineBreak, ) diff --git a/x/auth/client/cli/encode_test.go b/x/auth/client/cli/encode_test.go index f6ab14b3326d..cbb5b0a1827b 100644 --- a/x/auth/client/cli/encode_test.go +++ b/x/auth/client/cli/encode_test.go @@ -1,6 +1,7 @@ package cli import ( + "context" "encoding/base64" "testing" @@ -34,7 +35,14 @@ func TestGetCommandEncode(t *testing.T) { txFileName := txFile.Name() t.Cleanup(cleanup) - err = cmd.RunE(cmd, []string{txFileName}) + ctx := context.Background() + clientCtx := client.Context{}. + WithTxGenerator(encodingConfig.TxGenerator). + WithJSONMarshaler(encodingConfig.Marshaler) + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + + cmd.SetArgs([]string{txFileName}) + err = cmd.ExecuteContext(ctx) require.NoError(t, err) } @@ -64,7 +72,10 @@ func TestGetCommandDecode(t *testing.T) { // Convert the transaction into base64 encoded string base64Encoded := base64.StdEncoding.EncodeToString(txBytes) + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + // Execute the command cmd.SetArgs([]string{base64Encoded}) - require.NoError(t, cmd.Execute()) + require.NoError(t, cmd.ExecuteContext(ctx)) } diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 4d9e0da11749..b165709d1bf5 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -10,9 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - clientkeys "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/tests/cli" cli2 "github.com/cosmos/cosmos-sdk/x/auth/client/cli" ) @@ -60,19 +58,6 @@ func callCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs [ return buf.Bytes(), nil } -// TxSign is simcli sign -func TxSign(f *cli.Fixtures, signer, fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx sign %v --keyring-backend=test --from=%s %v", f.SimdBinary, f.Flags(), signer, fileName) - - return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - -// TxBroadcast is simcli tx broadcast -func TxBroadcast(f *cli.Fixtures, fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx broadcast %v %v", f.SimdBinary, f.Flags(), fileName) - return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), @@ -84,12 +69,6 @@ func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string return callCmd(clientCtx, cli2.GetEncodeCommand, args) } -// TxEncode is simcli tx encode -func TxEncode(f *cli.Fixtures, fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx encode %v %v", f.SimdBinary, f.Flags(), fileName) - return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), @@ -100,14 +79,6 @@ func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte return callCmd(clientCtx, cli2.GetValidateSignaturesCommand, args) } -// TxValidateSignatures is simcli tx validate-signatures -func TxValidateSignatures(f *cli.Fixtures, fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx validate-signatures %v --keyring-backend=test %v", f.SimdBinary, - f.Flags(), fileName) - - return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - func TxMultiSignExec(clientCtx client.Context, from string, filename string, extraArgs ...string) ([]byte, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), @@ -121,16 +92,6 @@ func TxMultiSignExec(clientCtx client.Context, from string, filename string, ext return callCmd(clientCtx, cli2.GetMultiSignCommand, args) } -// TxMultisign is simcli tx multisign -func TxMultisign(f *cli.Fixtures, fileName, name string, signaturesFiles []string, - flags ...string) (bool, string, string) { - - cmd := fmt.Sprintf("%s tx multisign --keyring-backend=test %v %s %s %s", f.SimdBinary, f.Flags(), - fileName, name, strings.Join(signaturesFiles, " "), - ) - return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags)) -} - func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename string, extraArgs ...string) ([]byte, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), @@ -154,10 +115,4 @@ func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...strin return callCmd(clientCtx, cli2.GetDecodeCommand, args) } -// 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.SimdBinary, f.Flags(), encodedTx) - return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - // DONTCOVER From 54fa3cc5f0b41017be57e0f24c5542659ebce9c5 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 13 Jul 2020 19:30:47 +0200 Subject: [PATCH 34/46] Fix tests. --- testutil/network/network.go | 1 + x/auth/client/cli/broadcast_test.go | 52 ----------------------------- x/auth/client/cli/cli_test.go | 44 ++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 52 deletions(-) delete mode 100644 x/auth/client/cli/broadcast_test.go diff --git a/testutil/network/network.go b/testutil/network/network.go index e59fe7504fd6..4d75ad6e330a 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -334,6 +334,7 @@ func New(t *testing.T, cfg Config) *Network { return network } +// WaitForNBlocks waits for N blocks or timeout. func (n *Network) WaitForNBlocks(b int64, t time.Duration) error { ticker := time.NewTicker(time.Second) timeout := time.After(t) diff --git a/x/auth/client/cli/broadcast_test.go b/x/auth/client/cli/broadcast_test.go deleted file mode 100644 index 69a46c23ddb4..000000000000 --- a/x/auth/client/cli/broadcast_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package cli - -import ( - "context" - "fmt" - "io/ioutil" - "path/filepath" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" - "github.com/cosmos/cosmos-sdk/testutil" -) - -func TestGetBroadcastCommand_OfflineFlag(t *testing.T) { - clientCtx := client.Context{}.WithOffline(true) - clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) - - cmd := GetBroadcastCommand() - _ = testutil.ApplyMockIODiscardOutErr(cmd) - cmd.SetArgs([]string{fmt.Sprintf("--%s=true", flags.FlagOffline), ""}) - - require.EqualError(t, cmd.Execute(), "cannot broadcast tx during offline mode") -} - -func TestGetBroadcastCommand_WithoutOfflineFlag(t *testing.T) { - clientCtx := client.Context{} - clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) - - ctx := context.Background() - ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - - cmd := GetBroadcastCommand() - - testDir, cleanFunc := testutil.NewTestCaseDir(t) - t.Cleanup(cleanFunc) - - // Create new file with tx - txContents := []byte("{\"type\":\"cosmos-sdk/StdTx\",\"value\":{\"msg\":[{\"type\":\"cosmos-sdk/MsgSend\",\"value\":{\"from_address\":\"cosmos1cxlt8kznps92fwu3j6npahx4mjfutydyene2qw\",\"to_address\":\"cosmos1wc8mpr8m3sy3ap3j7fsgqfzx36um05pystems4\",\"amount\":[{\"denom\":\"stake\",\"amount\":\"10000\"}]}}],\"fee\":{\"amount\":[],\"gas\":\"200000\"},\"signatures\":null,\"memo\":\"\"}}") - txFileName := filepath.Join(testDir, "tx.json") - err := ioutil.WriteFile(txFileName, txContents, 0644) - require.NoError(t, err) - - cmd.SetArgs([]string{txFileName}) - err = cmd.ExecuteContext(ctx) - - // We test it tries to broadcast but we set unsupported tx to get the error. - require.EqualError(t, err, "unsupported return type ; supported types: sync, async, block") -} diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 046d96b9f035..6672ec8873a8 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -1,11 +1,19 @@ package cli_test import ( + "context" "fmt" + "io/ioutil" + "path/filepath" "strings" "testing" "time" + "github.com/cosmos/cosmos-sdk/client" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + cli2 "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + "github.com/stretchr/testify/require" + tmcrypto "github.com/tendermint/tendermint/crypto" "github.com/stretchr/testify/suite" @@ -616,6 +624,42 @@ func (s *IntegrationTestSuite) TestCLIMultisign() { s.Require().NoError(err) } +func TestGetBroadcastCommand_OfflineFlag(t *testing.T) { + clientCtx := client.Context{}.WithOffline(true) + clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + + cmd := cli2.GetBroadcastCommand() + _ = testutil.ApplyMockIODiscardOutErr(cmd) + cmd.SetArgs([]string{fmt.Sprintf("--%s=true", flags.FlagOffline), ""}) + + require.EqualError(t, cmd.Execute(), "cannot broadcast tx during offline mode") +} + +func TestGetBroadcastCommand_WithoutOfflineFlag(t *testing.T) { + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + + cmd := cli2.GetBroadcastCommand() + + testDir, cleanFunc := testutil.NewTestCaseDir(t) + t.Cleanup(cleanFunc) + + // Create new file with tx + txContents := []byte("{\"type\":\"cosmos-sdk/StdTx\",\"value\":{\"msg\":[{\"type\":\"cosmos-sdk/MsgSend\",\"value\":{\"from_address\":\"cosmos1cxlt8kznps92fwu3j6npahx4mjfutydyene2qw\",\"to_address\":\"cosmos1wc8mpr8m3sy3ap3j7fsgqfzx36um05pystems4\",\"amount\":[{\"denom\":\"stake\",\"amount\":\"10000\"}]}}],\"fee\":{\"amount\":[],\"gas\":\"200000\"},\"signatures\":null,\"memo\":\"\"}}") + txFileName := filepath.Join(testDir, "tx.json") + err := ioutil.WriteFile(txFileName, txContents, 0644) + require.NoError(t, err) + + cmd.SetArgs([]string{txFileName}) + err = cmd.ExecuteContext(ctx) + + // We test it tries to broadcast but we set unsupported tx to get the error. + require.EqualError(t, err, "unsupported return type ; supported types: sync, async, block") +} + func TestIntegrationTestSuite(t *testing.T) { suite.Run(t, new(IntegrationTestSuite)) } From a3f7647a531cc114967eb3bf696ffdf1843a3146 Mon Sep 17 00:00:00 2001 From: Alessio Treglia Date: Mon, 13 Jul 2020 18:46:20 +0100 Subject: [PATCH 35/46] Update x/bank/client/testutil/cli_helpers.go --- x/bank/client/testutil/cli_helpers.go | 1 - 1 file changed, 1 deletion(-) diff --git a/x/bank/client/testutil/cli_helpers.go b/x/bank/client/testutil/cli_helpers.go index 710a9033b0ec..833ae238a22e 100644 --- a/x/bank/client/testutil/cli_helpers.go +++ b/x/bank/client/testutil/cli_helpers.go @@ -6,7 +6,6 @@ import ( "fmt" "github.com/spf13/cobra" - "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" From 61ad3cf35fcf080a063a7dea71bee1a9c72d892e Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 13 Jul 2020 20:26:02 +0200 Subject: [PATCH 36/46] Remove alias. --- x/auth/client/testutil/helpers.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index b165709d1bf5..732629e1cc86 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -11,7 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" - cli2 "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + "github.com/cosmos/cosmos-sdk/x/auth/client/cli" ) func TxSignExec(clientCtx client.Context, from fmt.Stringer, filename string, extraArgs ...string) ([]byte, error) { @@ -25,7 +25,7 @@ func TxSignExec(clientCtx client.Context, from fmt.Stringer, filename string, ex args = append(args, extraArgs...) - return callCmd(clientCtx, cli2.GetSignCommand, args) + return callCmd(clientCtx, cli.GetSignCommand, args) } func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { @@ -35,7 +35,7 @@ func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...str args = append(args, extraArgs...) - return callCmd(clientCtx, cli2.GetBroadcastCommand, args) + return callCmd(clientCtx, cli.GetBroadcastCommand, args) } func callCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { @@ -66,7 +66,7 @@ func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string args = append(args, extraArgs...) - return callCmd(clientCtx, cli2.GetEncodeCommand, args) + return callCmd(clientCtx, cli.GetEncodeCommand, args) } func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte, error) { @@ -76,7 +76,7 @@ func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte filename, } - return callCmd(clientCtx, cli2.GetValidateSignaturesCommand, args) + return callCmd(clientCtx, cli.GetValidateSignaturesCommand, args) } func TxMultiSignExec(clientCtx client.Context, from string, filename string, extraArgs ...string) ([]byte, error) { @@ -89,7 +89,7 @@ func TxMultiSignExec(clientCtx client.Context, from string, filename string, ext args = append(args, extraArgs...) - return callCmd(clientCtx, cli2.GetMultiSignCommand, args) + return callCmd(clientCtx, cli.GetMultiSignCommand, args) } func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename string, extraArgs ...string) ([]byte, error) { @@ -101,7 +101,7 @@ func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename strin args = append(args, extraArgs...) - return callCmd(clientCtx, cli2.GetSignBatchCommand, args) + return callCmd(clientCtx, cli.GetSignBatchCommand, args) } func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...string) ([]byte, error) { @@ -112,7 +112,7 @@ func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...strin args = append(args, extraArgs...) - return callCmd(clientCtx, cli2.GetDecodeCommand, args) + return callCmd(clientCtx, cli.GetDecodeCommand, args) } // DONTCOVER From 57baa45f44c440ec8271b207ba4122e863abc8dc Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 13 Jul 2020 23:00:19 +0200 Subject: [PATCH 37/46] Remove wait for N block func. --- testutil/network/network.go | 34 ---------------------------------- x/auth/client/cli/cli_test.go | 32 +++++++++++++++++++++++--------- 2 files changed, 23 insertions(+), 43 deletions(-) diff --git a/testutil/network/network.go b/testutil/network/network.go index 4d75ad6e330a..d682e9c742b9 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -334,40 +334,6 @@ func New(t *testing.T, cfg Config) *Network { return network } -// WaitForNBlocks waits for N blocks or timeout. -func (n *Network) WaitForNBlocks(b int64, t time.Duration) error { - ticker := time.NewTicker(time.Second) - timeout := time.After(t) - - if len(n.Validators) == 0 { - return errors.New("no validators available") - } - - val := n.Validators[0] - - status, err := val.RPCClient.Status() - if err != nil || status == nil { - return fmt.Errorf("error getting node status") - } - - initialHeight := status.SyncInfo.LatestBlockHeight - - for { - select { - case <-timeout: - return fmt.Errorf("timeout exceeded waiting for block %d", initialHeight+b) - case <-ticker.C: - status, err := val.RPCClient.Status() - if err == nil && status != nil { - curHeight := status.SyncInfo.LatestBlockHeight - if curHeight >= initialHeight+b { - return nil - } - } - } - } -} - // WaitForHeight performs a blocking check where it waits for a block to be // committed after a given block. If that height is not reached within a timeout, // an error is returned. Regardless, the latest height queried is returned. diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 6672ec8873a8..f41e775bd666 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -9,10 +9,11 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/client" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" cli2 "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "github.com/stretchr/testify/require" tmcrypto "github.com/tendermint/tendermint/crypto" @@ -277,7 +278,7 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { res, err = authtest.TxBroadcastExec(val1.ClientCtx, signedTxFile.Name(), "--offline") s.Require().EqualError(err, "cannot broadcast tx during offline mode") - err = s.network.WaitForNBlocks(1, 10*time.Second) + err = waitForNextBlock(val1, s.network) s.Require().NoError(err) // Broadcast correct transaction. @@ -285,7 +286,7 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { res, err = authtest.TxBroadcastExec(val1.ClientCtx, signedTxFile.Name()) s.Require().NoError(err) - err = s.network.WaitForNBlocks(1, 10*time.Second) + err = waitForNextBlock(val1, s.network) s.Require().NoError(err) // Ensure destiny account state @@ -340,7 +341,7 @@ func (s *IntegrationTestSuite) TestCLIMultisignInsufficientCosigners() { ) s.Require().NoError(err) - err = s.network.WaitForNBlocks(1, 10*time.Second) + err = waitForNextBlock(val1, s.network) s.Require().NoError(err) // Generate multisig transaction. @@ -456,7 +457,7 @@ func (s *IntegrationTestSuite) TestCLIMultisignSortSignatures() { ) s.Require().NoError(err) - err = s.network.WaitForNBlocks(1, 10*time.Second) + err = waitForNextBlock(val1, s.network) s.Require().NoError(err) resp, err := bankcli.QueryBalancesExec(val1.ClientCtx, multisigInfo.GetAddress()) @@ -515,7 +516,7 @@ func (s *IntegrationTestSuite) TestCLIMultisignSortSignatures() { _, err = authtest.TxBroadcastExec(val1.ClientCtx, signedTxFile.Name()) s.Require().NoError(err) - err = s.network.WaitForNBlocks(1, 10*time.Second) + err = waitForNextBlock(val1, s.network) s.Require().NoError(err) } @@ -553,9 +554,8 @@ func (s *IntegrationTestSuite) TestCLIMultisign() { fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), fmt.Sprintf("--gas=%d", flags.DefaultGasLimit), ) - s.Require().NoError(err) - err = s.network.WaitForNBlocks(1, 10*time.Second) + err = waitForNextBlock(val1, s.network) s.Require().NoError(err) resp, err := bankcli.QueryBalancesExec(val1.ClientCtx, multisigInfo.GetAddress()) @@ -620,10 +620,24 @@ func (s *IntegrationTestSuite) TestCLIMultisign() { _, err = authtest.TxBroadcastExec(val1.ClientCtx, signedTxFile.Name()) s.Require().NoError(err) - err = s.network.WaitForNBlocks(1, 10*time.Second) + err = waitForNextBlock(val1, s.network) s.Require().NoError(err) } +func waitForNextBlock(val1 *network.Validator, network *network.Network) error { + status, err := val1.RPCClient.Status() + if err != nil { + return err + } + lastBlock := status.SyncInfo.LatestBlockHeight + _, err = network.WaitForHeightWithTimeout(lastBlock+1, 10*time.Second) + if err != nil { + return err + } + + return err +} + func TestGetBroadcastCommand_OfflineFlag(t *testing.T) { clientCtx := client.Context{}.WithOffline(true) clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) From b9667fe21fabe86b2ba8ca0165f0c3dc67cbc0d4 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 13 Jul 2020 23:20:47 +0200 Subject: [PATCH 38/46] export callCmd function into its own file. --- testutil/cmd.go | 31 ++++++++++++++++ x/auth/client/cli/cli_test.go | 53 +++++++++++++-------------- x/auth/client/testutil/helpers.go | 38 ++++--------------- x/bank/client/testutil/cli_helpers.go | 29 ++------------- 4 files changed, 68 insertions(+), 83 deletions(-) create mode 100644 testutil/cmd.go diff --git a/testutil/cmd.go b/testutil/cmd.go new file mode 100644 index 000000000000..47028bac28b6 --- /dev/null +++ b/testutil/cmd.go @@ -0,0 +1,31 @@ +package testutil + +import ( + "bytes" + "context" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" +) + +// CallCliCmd calls theCmd cobra command and returns the output in bytes. +func CallCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { + buf := new(bytes.Buffer) + clientCtx = clientCtx.WithOutput(buf) + + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + + cmd := theCmd() + cmd.SetErr(buf) + cmd.SetOut(buf) + + cmd.SetArgs(extraArgs) + + if err := cmd.ExecuteContext(ctx); err != nil { + return buf.Bytes(), err + } + + return buf.Bytes(), nil +} diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index f41e775bd666..06e515770034 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -10,24 +10,21 @@ import ( "time" "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" - cli2 "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - - tmcrypto "github.com/tendermint/tendermint/crypto" - "github.com/stretchr/testify/suite" + tmcrypto "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" codec2 "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" "github.com/cosmos/cosmos-sdk/tests/cli" "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/testutil/network" sdk "github.com/cosmos/cosmos-sdk/types" + cli2 "github.com/cosmos/cosmos-sdk/x/auth/client/cli" authtest "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" @@ -278,7 +275,7 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { res, err = authtest.TxBroadcastExec(val1.ClientCtx, signedTxFile.Name(), "--offline") s.Require().EqualError(err, "cannot broadcast tx during offline mode") - err = waitForNextBlock(val1, s.network) + err = waitForNextBlock(s.network) s.Require().NoError(err) // Broadcast correct transaction. @@ -286,7 +283,7 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { res, err = authtest.TxBroadcastExec(val1.ClientCtx, signedTxFile.Name()) s.Require().NoError(err) - err = waitForNextBlock(val1, s.network) + err = waitForNextBlock(s.network) s.Require().NoError(err) // Ensure destiny account state @@ -341,7 +338,7 @@ func (s *IntegrationTestSuite) TestCLIMultisignInsufficientCosigners() { ) s.Require().NoError(err) - err = waitForNextBlock(val1, s.network) + err = waitForNextBlock(s.network) s.Require().NoError(err) // Generate multisig transaction. @@ -457,7 +454,7 @@ func (s *IntegrationTestSuite) TestCLIMultisignSortSignatures() { ) s.Require().NoError(err) - err = waitForNextBlock(val1, s.network) + err = waitForNextBlock(s.network) s.Require().NoError(err) resp, err := bankcli.QueryBalancesExec(val1.ClientCtx, multisigInfo.GetAddress()) @@ -516,7 +513,7 @@ func (s *IntegrationTestSuite) TestCLIMultisignSortSignatures() { _, err = authtest.TxBroadcastExec(val1.ClientCtx, signedTxFile.Name()) s.Require().NoError(err) - err = waitForNextBlock(val1, s.network) + err = waitForNextBlock(s.network) s.Require().NoError(err) } @@ -555,7 +552,7 @@ func (s *IntegrationTestSuite) TestCLIMultisign() { fmt.Sprintf("--gas=%d", flags.DefaultGasLimit), ) - err = waitForNextBlock(val1, s.network) + err = waitForNextBlock(s.network) s.Require().NoError(err) resp, err := bankcli.QueryBalancesExec(val1.ClientCtx, multisigInfo.GetAddress()) @@ -620,24 +617,10 @@ func (s *IntegrationTestSuite) TestCLIMultisign() { _, err = authtest.TxBroadcastExec(val1.ClientCtx, signedTxFile.Name()) s.Require().NoError(err) - err = waitForNextBlock(val1, s.network) + err = waitForNextBlock(s.network) s.Require().NoError(err) } -func waitForNextBlock(val1 *network.Validator, network *network.Network) error { - status, err := val1.RPCClient.Status() - if err != nil { - return err - } - lastBlock := status.SyncInfo.LatestBlockHeight - _, err = network.WaitForHeightWithTimeout(lastBlock+1, 10*time.Second) - if err != nil { - return err - } - - return err -} - func TestGetBroadcastCommand_OfflineFlag(t *testing.T) { clientCtx := client.Context{}.WithOffline(true) clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) @@ -677,3 +660,17 @@ func TestGetBroadcastCommand_WithoutOfflineFlag(t *testing.T) { func TestIntegrationTestSuite(t *testing.T) { suite.Run(t, new(IntegrationTestSuite)) } + +func waitForNextBlock(network *network.Network) error { + lastBlock, err := network.LatestHeight() + if err != nil { + return err + } + + _, err = network.WaitForHeightWithTimeout(lastBlock+1, 10*time.Second) + if err != nil { + return err + } + + return err +} diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 732629e1cc86..9751c994d0de 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -1,12 +1,10 @@ package testutil import ( - "bytes" - "context" "fmt" "strings" - "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" @@ -25,7 +23,7 @@ func TxSignExec(clientCtx client.Context, from fmt.Stringer, filename string, ex args = append(args, extraArgs...) - return callCmd(clientCtx, cli.GetSignCommand, args) + return testutil.CallCliCmd(clientCtx, cli.GetSignCommand, args) } func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { @@ -35,27 +33,7 @@ func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...str args = append(args, extraArgs...) - return callCmd(clientCtx, cli.GetBroadcastCommand, args) -} - -func callCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { - buf := new(bytes.Buffer) - clientCtx = clientCtx.WithOutput(buf) - - ctx := context.Background() - ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - - cmd := theCmd() - cmd.SetErr(buf) - cmd.SetOut(buf) - - cmd.SetArgs(extraArgs) - - if err := cmd.ExecuteContext(ctx); err != nil { - return buf.Bytes(), err - } - - return buf.Bytes(), nil + return testutil.CallCliCmd(clientCtx, cli.GetBroadcastCommand, args) } func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { @@ -66,7 +44,7 @@ func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string args = append(args, extraArgs...) - return callCmd(clientCtx, cli.GetEncodeCommand, args) + return testutil.CallCliCmd(clientCtx, cli.GetEncodeCommand, args) } func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte, error) { @@ -76,7 +54,7 @@ func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte filename, } - return callCmd(clientCtx, cli.GetValidateSignaturesCommand, args) + return testutil.CallCliCmd(clientCtx, cli.GetValidateSignaturesCommand, args) } func TxMultiSignExec(clientCtx client.Context, from string, filename string, extraArgs ...string) ([]byte, error) { @@ -89,7 +67,7 @@ func TxMultiSignExec(clientCtx client.Context, from string, filename string, ext args = append(args, extraArgs...) - return callCmd(clientCtx, cli.GetMultiSignCommand, args) + return testutil.CallCliCmd(clientCtx, cli.GetMultiSignCommand, args) } func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename string, extraArgs ...string) ([]byte, error) { @@ -101,7 +79,7 @@ func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename strin args = append(args, extraArgs...) - return callCmd(clientCtx, cli.GetSignBatchCommand, args) + return testutil.CallCliCmd(clientCtx, cli.GetSignBatchCommand, args) } func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...string) ([]byte, error) { @@ -112,7 +90,7 @@ func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...strin args = append(args, extraArgs...) - return callCmd(clientCtx, cli.GetDecodeCommand, args) + return testutil.CallCliCmd(clientCtx, cli.GetDecodeCommand, args) } // DONTCOVER diff --git a/x/bank/client/testutil/cli_helpers.go b/x/bank/client/testutil/cli_helpers.go index 833ae238a22e..9b6076d3677e 100644 --- a/x/bank/client/testutil/cli_helpers.go +++ b/x/bank/client/testutil/cli_helpers.go @@ -1,11 +1,10 @@ package testutil import ( - "bytes" - "context" "fmt" - "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/testutil" + "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" @@ -20,34 +19,14 @@ func MsgSendExec(clientCtx client.Context, from, to, amount fmt.Stringer, extraA args := []string{from.String(), to.String(), amount.String()} args = append(args, extraArgs...) - return callCmd(clientCtx, bankcli.NewSendTxCmd, args) + return testutil.CallCliCmd(clientCtx, bankcli.NewSendTxCmd, args) } func QueryBalancesExec(clientCtx client.Context, address fmt.Stringer, extraArgs ...string) ([]byte, error) { args := []string{address.String()} args = append(args, extraArgs...) - return callCmd(clientCtx, bankcli.GetBalancesCmd, args) -} - -func callCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { - buf := new(bytes.Buffer) - clientCtx = clientCtx.WithOutput(buf) - - ctx := context.Background() - ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - - cmd := theCmd() - cmd.SetErr(buf) - cmd.SetOut(buf) - - cmd.SetArgs(extraArgs) - - if err := cmd.ExecuteContext(ctx); err != nil { - return buf.Bytes(), err - } - - return buf.Bytes(), nil + return testutil.CallCliCmd(clientCtx, bankcli.GetBalancesCmd, args) } // ---------------------------------------------------------------------------- From 7bf3912aa17442089e3434a50c2bd9f2a2092ed5 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 13 Jul 2020 23:40:45 +0200 Subject: [PATCH 39/46] fix imports --- client/test_helpers.go | 25 +++++++++++++++++++++ testutil/cmd.go | 31 --------------------------- x/auth/client/testutil/helpers.go | 16 ++++++-------- x/bank/client/testutil/cli_helpers.go | 6 ++---- 4 files changed, 34 insertions(+), 44 deletions(-) delete mode 100644 testutil/cmd.go diff --git a/client/test_helpers.go b/client/test_helpers.go index 4c16ce63bfbc..e8b833556bf0 100644 --- a/client/test_helpers.go +++ b/client/test_helpers.go @@ -1,8 +1,12 @@ package client import ( + "bytes" + "context" "fmt" + "github.com/spf13/cobra" + sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -34,3 +38,24 @@ func (t TestAccountRetriever) GetAccountNumberSequence(_ NodeQuerier, addr sdk.A } return acc.Num, acc.Seq, nil } + +// CallCliCmd calls theCmd cobra command and returns the output in bytes. +func CallCliCmd(clientCtx Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { + buf := new(bytes.Buffer) + clientCtx = clientCtx.WithOutput(buf) + + ctx := context.Background() + ctx = context.WithValue(ctx, ClientContextKey, &clientCtx) + + cmd := theCmd() + cmd.SetErr(buf) + cmd.SetOut(buf) + + cmd.SetArgs(extraArgs) + + if err := cmd.ExecuteContext(ctx); err != nil { + return buf.Bytes(), err + } + + return buf.Bytes(), nil +} diff --git a/testutil/cmd.go b/testutil/cmd.go deleted file mode 100644 index 47028bac28b6..000000000000 --- a/testutil/cmd.go +++ /dev/null @@ -1,31 +0,0 @@ -package testutil - -import ( - "bytes" - "context" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" -) - -// CallCliCmd calls theCmd cobra command and returns the output in bytes. -func CallCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { - buf := new(bytes.Buffer) - clientCtx = clientCtx.WithOutput(buf) - - ctx := context.Background() - ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - - cmd := theCmd() - cmd.SetErr(buf) - cmd.SetOut(buf) - - cmd.SetArgs(extraArgs) - - if err := cmd.ExecuteContext(ctx); err != nil { - return buf.Bytes(), err - } - - return buf.Bytes(), nil -} diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 9751c994d0de..d874be18cf50 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -4,8 +4,6 @@ import ( "fmt" "strings" - "github.com/cosmos/cosmos-sdk/testutil" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -23,7 +21,7 @@ func TxSignExec(clientCtx client.Context, from fmt.Stringer, filename string, ex args = append(args, extraArgs...) - return testutil.CallCliCmd(clientCtx, cli.GetSignCommand, args) + return client.CallCliCmd(clientCtx, cli.GetSignCommand, args) } func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { @@ -33,7 +31,7 @@ func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...str args = append(args, extraArgs...) - return testutil.CallCliCmd(clientCtx, cli.GetBroadcastCommand, args) + return client.CallCliCmd(clientCtx, cli.GetBroadcastCommand, args) } func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { @@ -44,7 +42,7 @@ func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string args = append(args, extraArgs...) - return testutil.CallCliCmd(clientCtx, cli.GetEncodeCommand, args) + return client.CallCliCmd(clientCtx, cli.GetEncodeCommand, args) } func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte, error) { @@ -54,7 +52,7 @@ func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte filename, } - return testutil.CallCliCmd(clientCtx, cli.GetValidateSignaturesCommand, args) + return client.CallCliCmd(clientCtx, cli.GetValidateSignaturesCommand, args) } func TxMultiSignExec(clientCtx client.Context, from string, filename string, extraArgs ...string) ([]byte, error) { @@ -67,7 +65,7 @@ func TxMultiSignExec(clientCtx client.Context, from string, filename string, ext args = append(args, extraArgs...) - return testutil.CallCliCmd(clientCtx, cli.GetMultiSignCommand, args) + return client.CallCliCmd(clientCtx, cli.GetMultiSignCommand, args) } func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename string, extraArgs ...string) ([]byte, error) { @@ -79,7 +77,7 @@ func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename strin args = append(args, extraArgs...) - return testutil.CallCliCmd(clientCtx, cli.GetSignBatchCommand, args) + return client.CallCliCmd(clientCtx, cli.GetSignBatchCommand, args) } func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...string) ([]byte, error) { @@ -90,7 +88,7 @@ func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...strin args = append(args, extraArgs...) - return testutil.CallCliCmd(clientCtx, cli.GetDecodeCommand, args) + return client.CallCliCmd(clientCtx, cli.GetDecodeCommand, args) } // DONTCOVER diff --git a/x/bank/client/testutil/cli_helpers.go b/x/bank/client/testutil/cli_helpers.go index 9b6076d3677e..11f1867c665a 100644 --- a/x/bank/client/testutil/cli_helpers.go +++ b/x/bank/client/testutil/cli_helpers.go @@ -3,8 +3,6 @@ package testutil import ( "fmt" - "github.com/cosmos/cosmos-sdk/testutil" - "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" @@ -19,14 +17,14 @@ func MsgSendExec(clientCtx client.Context, from, to, amount fmt.Stringer, extraA args := []string{from.String(), to.String(), amount.String()} args = append(args, extraArgs...) - return testutil.CallCliCmd(clientCtx, bankcli.NewSendTxCmd, args) + return client.CallCliCmd(clientCtx, bankcli.NewSendTxCmd, args) } func QueryBalancesExec(clientCtx client.Context, address fmt.Stringer, extraArgs ...string) ([]byte, error) { args := []string{address.String()} args = append(args, extraArgs...) - return testutil.CallCliCmd(clientCtx, bankcli.GetBalancesCmd, args) + return client.CallCliCmd(clientCtx, bankcli.GetBalancesCmd, args) } // ---------------------------------------------------------------------------- From a1997f027a3590e6228efaa9a3841d2a2ea0ded7 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Tue, 14 Jul 2020 16:27:24 +0200 Subject: [PATCH 40/46] bring back to inner functions --- client/test_helpers.go | 25 ------------------ x/auth/client/testutil/helpers.go | 38 ++++++++++++++++++++++----- x/bank/client/testutil/cli_helpers.go | 28 ++++++++++++++++++-- 3 files changed, 57 insertions(+), 34 deletions(-) diff --git a/client/test_helpers.go b/client/test_helpers.go index e8b833556bf0..4c16ce63bfbc 100644 --- a/client/test_helpers.go +++ b/client/test_helpers.go @@ -1,12 +1,8 @@ package client import ( - "bytes" - "context" "fmt" - "github.com/spf13/cobra" - sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -38,24 +34,3 @@ func (t TestAccountRetriever) GetAccountNumberSequence(_ NodeQuerier, addr sdk.A } return acc.Num, acc.Seq, nil } - -// CallCliCmd calls theCmd cobra command and returns the output in bytes. -func CallCliCmd(clientCtx Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { - buf := new(bytes.Buffer) - clientCtx = clientCtx.WithOutput(buf) - - ctx := context.Background() - ctx = context.WithValue(ctx, ClientContextKey, &clientCtx) - - cmd := theCmd() - cmd.SetErr(buf) - cmd.SetOut(buf) - - cmd.SetArgs(extraArgs) - - if err := cmd.ExecuteContext(ctx); err != nil { - return buf.Bytes(), err - } - - return buf.Bytes(), nil -} diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index d874be18cf50..ef1ea066cd1f 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -1,9 +1,13 @@ package testutil import ( + "bytes" + "context" "fmt" "strings" + "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -21,7 +25,7 @@ func TxSignExec(clientCtx client.Context, from fmt.Stringer, filename string, ex args = append(args, extraArgs...) - return client.CallCliCmd(clientCtx, cli.GetSignCommand, args) + return callCliCmd(clientCtx, cli.GetSignCommand, args) } func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { @@ -31,7 +35,7 @@ func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...str args = append(args, extraArgs...) - return client.CallCliCmd(clientCtx, cli.GetBroadcastCommand, args) + return callCliCmd(clientCtx, cli.GetBroadcastCommand, args) } func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { @@ -42,7 +46,7 @@ func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string args = append(args, extraArgs...) - return client.CallCliCmd(clientCtx, cli.GetEncodeCommand, args) + return callCliCmd(clientCtx, cli.GetEncodeCommand, args) } func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte, error) { @@ -52,7 +56,7 @@ func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte filename, } - return client.CallCliCmd(clientCtx, cli.GetValidateSignaturesCommand, args) + return callCliCmd(clientCtx, cli.GetValidateSignaturesCommand, args) } func TxMultiSignExec(clientCtx client.Context, from string, filename string, extraArgs ...string) ([]byte, error) { @@ -65,7 +69,7 @@ func TxMultiSignExec(clientCtx client.Context, from string, filename string, ext args = append(args, extraArgs...) - return client.CallCliCmd(clientCtx, cli.GetMultiSignCommand, args) + return callCliCmd(clientCtx, cli.GetMultiSignCommand, args) } func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename string, extraArgs ...string) ([]byte, error) { @@ -77,7 +81,7 @@ func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename strin args = append(args, extraArgs...) - return client.CallCliCmd(clientCtx, cli.GetSignBatchCommand, args) + return callCliCmd(clientCtx, cli.GetSignBatchCommand, args) } func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...string) ([]byte, error) { @@ -88,7 +92,27 @@ func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...strin args = append(args, extraArgs...) - return client.CallCliCmd(clientCtx, cli.GetDecodeCommand, args) + return callCliCmd(clientCtx, cli.GetDecodeCommand, args) +} + +func callCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { + buf := new(bytes.Buffer) + clientCtx = clientCtx.WithOutput(buf) + + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + + cmd := theCmd() + cmd.SetErr(buf) + cmd.SetOut(buf) + + cmd.SetArgs(extraArgs) + + if err := cmd.ExecuteContext(ctx); err != nil { + return buf.Bytes(), err + } + + return buf.Bytes(), nil } // DONTCOVER diff --git a/x/bank/client/testutil/cli_helpers.go b/x/bank/client/testutil/cli_helpers.go index 11f1867c665a..d48bfb3497be 100644 --- a/x/bank/client/testutil/cli_helpers.go +++ b/x/bank/client/testutil/cli_helpers.go @@ -1,8 +1,12 @@ package testutil import ( + "bytes" + "context" "fmt" + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" @@ -17,14 +21,34 @@ func MsgSendExec(clientCtx client.Context, from, to, amount fmt.Stringer, extraA args := []string{from.String(), to.String(), amount.String()} args = append(args, extraArgs...) - return client.CallCliCmd(clientCtx, bankcli.NewSendTxCmd, args) + return callCliCmd(clientCtx, bankcli.NewSendTxCmd, args) } func QueryBalancesExec(clientCtx client.Context, address fmt.Stringer, extraArgs ...string) ([]byte, error) { args := []string{address.String()} args = append(args, extraArgs...) - return client.CallCliCmd(clientCtx, bankcli.GetBalancesCmd, args) + return callCliCmd(clientCtx, bankcli.GetBalancesCmd, args) +} + +func callCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { + buf := new(bytes.Buffer) + clientCtx = clientCtx.WithOutput(buf) + + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + + cmd := theCmd() + cmd.SetErr(buf) + cmd.SetOut(buf) + + cmd.SetArgs(extraArgs) + + if err := cmd.ExecuteContext(ctx); err != nil { + return buf.Bytes(), err + } + + return buf.Bytes(), nil } // ---------------------------------------------------------------------------- From 913804826871914e3a5842e5ce2baa904170b30a Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Tue, 14 Jul 2020 16:33:07 +0200 Subject: [PATCH 41/46] apply mock io --- x/bank/client/testutil/cli_helpers.go | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/x/bank/client/testutil/cli_helpers.go b/x/bank/client/testutil/cli_helpers.go index d48bfb3497be..3d787a2664f3 100644 --- a/x/bank/client/testutil/cli_helpers.go +++ b/x/bank/client/testutil/cli_helpers.go @@ -1,10 +1,11 @@ package testutil import ( - "bytes" "context" "fmt" + "github.com/cosmos/cosmos-sdk/testutil" + "github.com/spf13/cobra" "github.com/stretchr/testify/require" @@ -32,23 +33,21 @@ func QueryBalancesExec(clientCtx client.Context, address fmt.Stringer, extraArgs } func callCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { - buf := new(bytes.Buffer) - clientCtx = clientCtx.WithOutput(buf) + cmd := theCmd() + + _, out := testutil.ApplyMockIO(theCmd()) + clientCtx = clientCtx.WithOutput(out) ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - cmd := theCmd() - cmd.SetErr(buf) - cmd.SetOut(buf) - cmd.SetArgs(extraArgs) if err := cmd.ExecuteContext(ctx); err != nil { - return buf.Bytes(), err + return out.Bytes(), err } - return buf.Bytes(), nil + return out.Bytes(), nil } // ---------------------------------------------------------------------------- From bae1521337fc338ba3cc352991fbc44ef8f530ae Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Tue, 14 Jul 2020 16:36:48 +0200 Subject: [PATCH 42/46] the helpers use mockio --- x/auth/client/testutil/helpers.go | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index ef1ea066cd1f..9c670b3f5e3d 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -1,11 +1,12 @@ package testutil import ( - "bytes" "context" "fmt" "strings" + "github.com/cosmos/cosmos-sdk/testutil" + "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" @@ -96,23 +97,21 @@ func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...strin } func callCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { - buf := new(bytes.Buffer) - clientCtx = clientCtx.WithOutput(buf) + cmd := theCmd() + + _, out := testutil.ApplyMockIO(theCmd()) + clientCtx = clientCtx.WithOutput(out) ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - cmd := theCmd() - cmd.SetErr(buf) - cmd.SetOut(buf) - cmd.SetArgs(extraArgs) if err := cmd.ExecuteContext(ctx); err != nil { - return buf.Bytes(), err + return out.Bytes(), err } - return buf.Bytes(), nil + return out.Bytes(), nil } // DONTCOVER From 6a35ee948b00a6e44aaf36c615e34689109070a5 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Tue, 14 Jul 2020 16:59:27 +0200 Subject: [PATCH 43/46] fix bug --- x/auth/client/testutil/helpers.go | 2 +- x/bank/client/testutil/cli_helpers.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 9c670b3f5e3d..5562265f926c 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -99,7 +99,7 @@ func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...strin func callCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { cmd := theCmd() - _, out := testutil.ApplyMockIO(theCmd()) + _, out := testutil.ApplyMockIO(cmd) clientCtx = clientCtx.WithOutput(out) ctx := context.Background() diff --git a/x/bank/client/testutil/cli_helpers.go b/x/bank/client/testutil/cli_helpers.go index 3d787a2664f3..7ac3a263f130 100644 --- a/x/bank/client/testutil/cli_helpers.go +++ b/x/bank/client/testutil/cli_helpers.go @@ -35,7 +35,7 @@ func QueryBalancesExec(clientCtx client.Context, address fmt.Stringer, extraArgs func callCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { cmd := theCmd() - _, out := testutil.ApplyMockIO(theCmd()) + _, out := testutil.ApplyMockIO(cmd) clientCtx = clientCtx.WithOutput(out) ctx := context.Background() From 45374fb2da7ec1cd6610108cf0b174f7879411ae Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Tue, 14 Jul 2020 17:00:47 +0200 Subject: [PATCH 44/46] Add Helpers. --- x/auth/client/testutil/helpers.go | 3 +-- x/bank/client/testutil/cli_helpers.go | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 5562265f926c..3641df1302da 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -98,6 +98,7 @@ func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...strin func callCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { cmd := theCmd() + cmd.SetArgs(extraArgs) _, out := testutil.ApplyMockIO(cmd) clientCtx = clientCtx.WithOutput(out) @@ -105,8 +106,6 @@ func callCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArg ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - cmd.SetArgs(extraArgs) - if err := cmd.ExecuteContext(ctx); err != nil { return out.Bytes(), err } diff --git a/x/bank/client/testutil/cli_helpers.go b/x/bank/client/testutil/cli_helpers.go index 7ac3a263f130..c6500e7668ad 100644 --- a/x/bank/client/testutil/cli_helpers.go +++ b/x/bank/client/testutil/cli_helpers.go @@ -34,6 +34,7 @@ func QueryBalancesExec(clientCtx client.Context, address fmt.Stringer, extraArgs func callCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { cmd := theCmd() + cmd.SetArgs(extraArgs) _, out := testutil.ApplyMockIO(cmd) clientCtx = clientCtx.WithOutput(out) @@ -41,8 +42,6 @@ func callCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArg ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - cmd.SetArgs(extraArgs) - if err := cmd.ExecuteContext(ctx); err != nil { return out.Bytes(), err } From dded545d2bc46c6fb3f611649d6ec24dfdd47c05 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Tue, 14 Jul 2020 18:50:37 +0200 Subject: [PATCH 45/46] return to put the function in testutil package --- testutil/cli/cmd.go | 27 +++++++++++++++++++ x/auth/client/testutil/helpers.go | 37 ++++++--------------------- x/bank/client/testutil/cli_helpers.go | 26 +++---------------- 3 files changed, 38 insertions(+), 52 deletions(-) create mode 100644 testutil/cli/cmd.go diff --git a/testutil/cli/cmd.go b/testutil/cli/cmd.go new file mode 100644 index 000000000000..02026058bf2f --- /dev/null +++ b/testutil/cli/cmd.go @@ -0,0 +1,27 @@ +package cli + +import ( + "context" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/testutil" +) + +// ExecTestCLICmd builds the client context, mocks the output and executes the command. +func ExecTestCLICmd(clientCtx client.Context, cmd *cobra.Command, extraArgs []string) ([]byte, error) { + cmd.SetArgs(extraArgs) + + _, out := testutil.ApplyMockIO(cmd) + clientCtx = clientCtx.WithOutput(out) + + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + + if err := cmd.ExecuteContext(ctx); err != nil { + return out.Bytes(), err + } + + return out.Bytes(), nil +} diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 3641df1302da..89bb260c3ee2 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -1,17 +1,13 @@ package testutil import ( - "context" "fmt" "strings" - "github.com/cosmos/cosmos-sdk/testutil" - - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" + clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/x/auth/client/cli" ) @@ -26,7 +22,7 @@ func TxSignExec(clientCtx client.Context, from fmt.Stringer, filename string, ex args = append(args, extraArgs...) - return callCliCmd(clientCtx, cli.GetSignCommand, args) + return clitestutil.ExecTestCLICmd(clientCtx, cli.GetSignCommand(), args) } func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { @@ -36,7 +32,7 @@ func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...str args = append(args, extraArgs...) - return callCliCmd(clientCtx, cli.GetBroadcastCommand, args) + return clitestutil.ExecTestCLICmd(clientCtx, cli.GetBroadcastCommand(), args) } func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { @@ -47,7 +43,7 @@ func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string args = append(args, extraArgs...) - return callCliCmd(clientCtx, cli.GetEncodeCommand, args) + return clitestutil.ExecTestCLICmd(clientCtx, cli.GetEncodeCommand(), args) } func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte, error) { @@ -57,7 +53,7 @@ func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte filename, } - return callCliCmd(clientCtx, cli.GetValidateSignaturesCommand, args) + return clitestutil.ExecTestCLICmd(clientCtx, cli.GetValidateSignaturesCommand(), args) } func TxMultiSignExec(clientCtx client.Context, from string, filename string, extraArgs ...string) ([]byte, error) { @@ -70,7 +66,7 @@ func TxMultiSignExec(clientCtx client.Context, from string, filename string, ext args = append(args, extraArgs...) - return callCliCmd(clientCtx, cli.GetMultiSignCommand, args) + return clitestutil.ExecTestCLICmd(clientCtx, cli.GetMultiSignCommand(), args) } func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename string, extraArgs ...string) ([]byte, error) { @@ -82,7 +78,7 @@ func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename strin args = append(args, extraArgs...) - return callCliCmd(clientCtx, cli.GetSignBatchCommand, args) + return clitestutil.ExecTestCLICmd(clientCtx, cli.GetSignBatchCommand(), args) } func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...string) ([]byte, error) { @@ -93,24 +89,7 @@ func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...strin args = append(args, extraArgs...) - return callCliCmd(clientCtx, cli.GetDecodeCommand, args) -} - -func callCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { - cmd := theCmd() - cmd.SetArgs(extraArgs) - - _, out := testutil.ApplyMockIO(cmd) - clientCtx = clientCtx.WithOutput(out) - - ctx := context.Background() - ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - - if err := cmd.ExecuteContext(ctx); err != nil { - return out.Bytes(), err - } - - return out.Bytes(), nil + return clitestutil.ExecTestCLICmd(clientCtx, cli.GetDecodeCommand(), args) } // DONTCOVER diff --git a/x/bank/client/testutil/cli_helpers.go b/x/bank/client/testutil/cli_helpers.go index c6500e7668ad..c5cf20d9e70d 100644 --- a/x/bank/client/testutil/cli_helpers.go +++ b/x/bank/client/testutil/cli_helpers.go @@ -1,12 +1,9 @@ package testutil import ( - "context" "fmt" - "github.com/cosmos/cosmos-sdk/testutil" - - "github.com/spf13/cobra" + clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/stretchr/testify/require" @@ -22,31 +19,14 @@ func MsgSendExec(clientCtx client.Context, from, to, amount fmt.Stringer, extraA args := []string{from.String(), to.String(), amount.String()} args = append(args, extraArgs...) - return callCliCmd(clientCtx, bankcli.NewSendTxCmd, args) + return clitestutil.ExecTestCLICmd(clientCtx, bankcli.NewSendTxCmd(), args) } func QueryBalancesExec(clientCtx client.Context, address fmt.Stringer, extraArgs ...string) ([]byte, error) { args := []string{address.String()} args = append(args, extraArgs...) - return callCliCmd(clientCtx, bankcli.GetBalancesCmd, args) -} - -func callCliCmd(clientCtx client.Context, theCmd func() *cobra.Command, extraArgs []string) ([]byte, error) { - cmd := theCmd() - cmd.SetArgs(extraArgs) - - _, out := testutil.ApplyMockIO(cmd) - clientCtx = clientCtx.WithOutput(out) - - ctx := context.Background() - ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - - if err := cmd.ExecuteContext(ctx); err != nil { - return out.Bytes(), err - } - - return out.Bytes(), nil + return clitestutil.ExecTestCLICmd(clientCtx, bankcli.GetBalancesCmd(), args) } // ---------------------------------------------------------------------------- From 861660611d8ffe5c38ea2414e5f8300336e10447 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Tue, 14 Jul 2020 19:27:25 +0200 Subject: [PATCH 46/46] return BufferWriter in ExecTestCLICmd --- testutil/cli/cmd.go | 6 +-- x/auth/client/cli/cli_test.go | 69 ++++++++++++++------------- x/auth/client/testutil/helpers.go | 16 ++++--- x/bank/client/cli/cli_test.go | 2 +- x/bank/client/testutil/cli_helpers.go | 6 ++- 5 files changed, 52 insertions(+), 47 deletions(-) diff --git a/testutil/cli/cmd.go b/testutil/cli/cmd.go index 02026058bf2f..1f09ae92966c 100644 --- a/testutil/cli/cmd.go +++ b/testutil/cli/cmd.go @@ -10,7 +10,7 @@ import ( ) // ExecTestCLICmd builds the client context, mocks the output and executes the command. -func ExecTestCLICmd(clientCtx client.Context, cmd *cobra.Command, extraArgs []string) ([]byte, error) { +func ExecTestCLICmd(clientCtx client.Context, cmd *cobra.Command, extraArgs []string) (testutil.BufferWriter, error) { cmd.SetArgs(extraArgs) _, out := testutil.ApplyMockIO(cmd) @@ -20,8 +20,8 @@ func ExecTestCLICmd(clientCtx client.Context, cmd *cobra.Command, extraArgs []st ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) if err := cmd.ExecuteContext(ctx); err != nil { - return out.Bytes(), err + return out, err } - return out.Bytes(), nil + return out, nil } diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 06e515770034..750df016df46 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -74,21 +74,21 @@ func (s *IntegrationTestSuite) TestCLIValidateSignatures() { s.Require().NoError(err) var tx types.StdTx - err = val.ClientCtx.JSONMarshaler.UnmarshalJSON(res, &tx) + err = val.ClientCtx.JSONMarshaler.UnmarshalJSON(res.Bytes(), &tx) s.Require().NoError(err) // write unsigned tx to file - unsignedTx, cleanup := testutil.WriteToNewTempFile(s.T(), string(res)) + unsignedTx, cleanup := testutil.WriteToNewTempFile(s.T(), res.String()) defer cleanup() res, err = authtest.TxSignExec(val.ClientCtx, val.Address, unsignedTx.Name()) s.Require().NoError(err) var signedTx types.StdTx - err = val.ClientCtx.JSONMarshaler.UnmarshalJSON(res, &signedTx) + err = val.ClientCtx.JSONMarshaler.UnmarshalJSON(res.Bytes(), &signedTx) s.Require().NoError(err) - signedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(res)) + signedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), res.String()) defer cleanup() res, err = authtest.TxValidateSignaturesExec(val.ClientCtx, signedTxFile.Name()) @@ -124,7 +124,7 @@ func (s *IntegrationTestSuite) TestCLISignBatch() { s.Require().NoError(err) // Write the output to disk - filename, cleanup1 := testutil.WriteToNewTempFile(s.T(), strings.Repeat(string(generatedStd), 3)) + filename, cleanup1 := testutil.WriteToNewTempFile(s.T(), strings.Repeat(generatedStd.String(), 3)) defer cleanup1() // sign-batch file - offline is set but account-number and sequence are not @@ -135,11 +135,12 @@ func (s *IntegrationTestSuite) TestCLISignBatch() { // sign-batch file res, err = authtest.TxSignBatchExec(val.ClientCtx, val.Address, filename.Name(), fmt.Sprintf("--%s=%s", flags.FlagChainID, val.ClientCtx.ChainID)) s.Require().NoError(err) - s.Require().Equal(3, len(strings.Split(strings.Trim(string(res), "\n"), "\n"))) + s.Require().Equal(3, len(strings.Split(strings.Trim(res.String(), "\n"), "\n"))) // sign-batch file res, err = authtest.TxSignBatchExec(val.ClientCtx, val.Address, filename.Name(), fmt.Sprintf("--%s=%s", flags.FlagChainID, val.ClientCtx.ChainID), "--signature-only") - s.Require().Equal(3, len(strings.Split(strings.Trim(string(res), "\n"), "\n"))) + s.Require().NoError(err) + s.Require().Equal(3, len(strings.Split(strings.Trim(res.String(), "\n"), "\n"))) // Sign batch malformed tx file. malformedFile, cleanup2 := testutil.WriteToNewTempFile(s.T(), fmt.Sprintf("%smalformed", generatedStd)) @@ -175,7 +176,7 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { ) s.Require().NoError(err) - normalGeneratedStdTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, string(normalGeneratedTx)) + normalGeneratedStdTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, normalGeneratedTx.String()) s.Require().Equal(normalGeneratedStdTx.Fee.Gas, uint64(flags.DefaultGasLimit)) s.Require().Equal(len(normalGeneratedStdTx.Msgs), 1) s.Require().Equal(0, len(normalGeneratedStdTx.GetSignatures())) @@ -196,7 +197,7 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { ) s.Require().NoError(err) - limitedGasStdTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, string(limitedGasGeneratedTx)) + limitedGasStdTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, limitedGasGeneratedTx.String()) s.Require().Equal(limitedGasStdTx.Fee.Gas, uint64(100)) s.Require().Equal(len(limitedGasStdTx.Msgs), 1) s.Require().Equal(0, len(limitedGasStdTx.GetSignatures())) @@ -217,18 +218,18 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { ) s.Require().NoError(err) - finalStdTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, string(finalGeneratedTx)) + finalStdTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, finalGeneratedTx.String()) s.Require().Equal(uint64(flags.DefaultGasLimit), finalStdTx.Fee.Gas) s.Require().Equal(len(finalStdTx.Msgs), 1) // Write the output to disk - unsignedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(finalGeneratedTx)) + unsignedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), finalGeneratedTx.String()) defer cleanup() // Test validate-signatures res, err := authtest.TxValidateSignaturesExec(val1.ClientCtx, unsignedTxFile.Name()) s.Require().EqualError(err, "signatures validation failed") - s.Require().True(strings.Contains(string(res), fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n\n", val1.Address.String()))) + s.Require().True(strings.Contains(res.String(), fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n\n", val1.Address.String()))) // Test sign @@ -245,19 +246,19 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { signedTx, err := authtest.TxSignExec(val1.ClientCtx, val1.Address, unsignedTxFile.Name()) s.Require().NoError(err) - signedFinalTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, string(signedTx)) + signedFinalTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, signedTx.String()) s.Require().Equal(len(signedFinalTx.Msgs), 1) s.Require().Equal(1, len(signedFinalTx.GetSignatures())) s.Require().Equal(val1.Address.String(), signedFinalTx.GetSigners()[0].String()) // Write the output to disk - signedTxFile, cleanup2 := testutil.WriteToNewTempFile(s.T(), string(signedTx)) + signedTxFile, cleanup2 := testutil.WriteToNewTempFile(s.T(), signedTx.String()) defer cleanup2() // Validate Signature res, err = authtest.TxValidateSignaturesExec(val1.ClientCtx, signedTxFile.Name()) s.Require().NoError(err) - s.Require().True(strings.Contains(string(res), "[OK]")) + s.Require().True(strings.Contains(res.String(), "[OK]")) // Ensure foo has right amount of funds startTokens := sdk.TokensFromConsensusPower(400) @@ -265,7 +266,7 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { s.Require().NoError(err) var coins sdk.Coins - err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp, &coins) + err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp.Bytes(), &coins) s.Require().NoError(err) s.Require().Equal(startTokens, coins.AmountOf(cli.Denom)) @@ -290,7 +291,7 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { resp, err = bankcli.QueryBalancesExec(val1.ClientCtx, account.GetAddress()) s.Require().NoError(err) - err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp, &coins) + err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp.Bytes(), &coins) s.Require().NoError(err) s.Require().Equal(sendTokens, coins.AmountOf(cli.Denom)) @@ -298,7 +299,7 @@ func (s *IntegrationTestSuite) TestCLISendGenerateSignAndBroadcast() { resp, err = bankcli.QueryBalancesExec(val1.ClientCtx, val1.Address) s.Require().NoError(err) - err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp, &coins) + err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp.Bytes(), &coins) s.Require().NoError(err) s.Require().Equal(sdk.NewInt(389999990), coins.AmountOf(cli.Denom)) } @@ -357,7 +358,7 @@ func (s *IntegrationTestSuite) TestCLIMultisignInsufficientCosigners() { s.Require().NoError(err) // Save tx to file - multiGeneratedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(multiGeneratedTx)) + multiGeneratedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), multiGeneratedTx.String()) defer cleanup() // Multisign, sign with one signature @@ -365,14 +366,14 @@ func (s *IntegrationTestSuite) TestCLIMultisignInsufficientCosigners() { account1Signature, err := authtest.TxSignExec(val1.ClientCtx, account1.GetAddress(), multiGeneratedTxFile.Name(), "--multisig", multisigInfo.GetAddress().String()) s.Require().NoError(err) - sign1File, cleanup2 := testutil.WriteToNewTempFile(s.T(), string(account1Signature)) + sign1File, cleanup2 := testutil.WriteToNewTempFile(s.T(), account1Signature.String()) defer cleanup2() multiSigWith1Signature, err := authtest.TxMultiSignExec(val1.ClientCtx, multisigInfo.GetName(), multiGeneratedTxFile.Name(), sign1File.Name()) s.Require().NoError(err) // Save tx to file - multiSigWith1SignatureFile, cleanup3 := testutil.WriteToNewTempFile(s.T(), string(multiSigWith1Signature)) + multiSigWith1SignatureFile, cleanup3 := testutil.WriteToNewTempFile(s.T(), multiSigWith1Signature.String()) defer cleanup3() exec, err := authtest.TxValidateSignaturesExec(val1.ClientCtx, multiSigWith1SignatureFile.Name()) @@ -401,20 +402,20 @@ func (s *IntegrationTestSuite) TestCLIEncode() { s.Require().NoError(err) // Save tx to file - savedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(normalGeneratedTx)) + savedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), normalGeneratedTx.String()) defer cleanup() // Enconde encodeExec, err := authtest.TxEncodeExec(val1.ClientCtx, savedTxFile.Name()) s.Require().NoError(err) - trimmedBase64 := strings.Trim(string(encodeExec), "\"\n") + trimmedBase64 := strings.Trim(encodeExec.String(), "\"\n") // Check that the transaction decodes as expected decodedTx, err := authtest.TxDecodeExec(val1.ClientCtx, trimmedBase64) s.Require().NoError(err) - theTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, string(decodedTx)) + theTx := cli.UnmarshalStdTx(s.T(), val1.ClientCtx.JSONMarshaler, decodedTx.String()) s.Require().Equal("deadbeef", theTx.Memo) } @@ -461,7 +462,7 @@ func (s *IntegrationTestSuite) TestCLIMultisignSortSignatures() { s.Require().NoError(err) var coins sdk.Coins - err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp, &coins) + err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp.Bytes(), &coins) s.Require().NoError(err) s.Require().Equal(sendTokens.Amount, coins.AmountOf(cli.Denom)) @@ -481,7 +482,7 @@ func (s *IntegrationTestSuite) TestCLIMultisignSortSignatures() { s.Require().NoError(err) // Save tx to file - multiGeneratedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(multiGeneratedTx)) + multiGeneratedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), multiGeneratedTx.String()) defer cleanup() // Sign with account1 @@ -489,21 +490,21 @@ func (s *IntegrationTestSuite) TestCLIMultisignSortSignatures() { account1Signature, err := authtest.TxSignExec(val1.ClientCtx, account1.GetAddress(), multiGeneratedTxFile.Name(), "--multisig", multisigInfo.GetAddress().String()) s.Require().NoError(err) - sign1File, cleanup2 := testutil.WriteToNewTempFile(s.T(), string(account1Signature)) + sign1File, cleanup2 := testutil.WriteToNewTempFile(s.T(), account1Signature.String()) defer cleanup2() // Sign with account1 account2Signature, err := authtest.TxSignExec(val1.ClientCtx, account2.GetAddress(), multiGeneratedTxFile.Name(), "--multisig", multisigInfo.GetAddress().String()) s.Require().NoError(err) - sign2File, cleanup3 := testutil.WriteToNewTempFile(s.T(), string(account2Signature)) + sign2File, cleanup3 := testutil.WriteToNewTempFile(s.T(), account2Signature.String()) defer cleanup3() multiSigWith2Signatures, err := authtest.TxMultiSignExec(val1.ClientCtx, multisigInfo.GetName(), multiGeneratedTxFile.Name(), sign1File.Name(), sign2File.Name()) s.Require().NoError(err) // Write the output to disk - signedTxFile, cleanup4 := testutil.WriteToNewTempFile(s.T(), string(multiSigWith2Signatures)) + signedTxFile, cleanup4 := testutil.WriteToNewTempFile(s.T(), multiSigWith2Signatures.String()) defer cleanup4() _, err = authtest.TxValidateSignaturesExec(val1.ClientCtx, signedTxFile.Name()) @@ -559,7 +560,7 @@ func (s *IntegrationTestSuite) TestCLIMultisign() { s.Require().NoError(err) var coins sdk.Coins - err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp, &coins) + err = val1.ClientCtx.JSONMarshaler.UnmarshalJSON(resp.Bytes(), &coins) s.Require().NoError(err) s.Require().Equal(sendTokens.Amount, coins.AmountOf(cli.Denom)) @@ -579,7 +580,7 @@ func (s *IntegrationTestSuite) TestCLIMultisign() { s.Require().NoError(err) // Save tx to file - multiGeneratedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), string(multiGeneratedTx)) + multiGeneratedTxFile, cleanup := testutil.WriteToNewTempFile(s.T(), multiGeneratedTx.String()) defer cleanup() // Sign with account1 @@ -587,14 +588,14 @@ func (s *IntegrationTestSuite) TestCLIMultisign() { account1Signature, err := authtest.TxSignExec(val1.ClientCtx, account1.GetAddress(), multiGeneratedTxFile.Name(), "--multisig", multisigInfo.GetAddress().String()) s.Require().NoError(err) - sign1File, cleanup2 := testutil.WriteToNewTempFile(s.T(), string(account1Signature)) + sign1File, cleanup2 := testutil.WriteToNewTempFile(s.T(), account1Signature.String()) defer cleanup2() // Sign with account1 account2Signature, err := authtest.TxSignExec(val1.ClientCtx, account2.GetAddress(), multiGeneratedTxFile.Name(), "--multisig", multisigInfo.GetAddress().String()) s.Require().NoError(err) - sign2File, cleanup3 := testutil.WriteToNewTempFile(s.T(), string(account2Signature)) + sign2File, cleanup3 := testutil.WriteToNewTempFile(s.T(), account2Signature.String()) defer cleanup3() // Does not work in offline mode. @@ -607,7 +608,7 @@ func (s *IntegrationTestSuite) TestCLIMultisign() { s.Require().NoError(err) // Write the output to disk - signedTxFile, cleanup4 := testutil.WriteToNewTempFile(s.T(), string(multiSigWith2Signatures)) + signedTxFile, cleanup4 := testutil.WriteToNewTempFile(s.T(), multiSigWith2Signatures.String()) defer cleanup4() _, err = authtest.TxValidateSignaturesExec(val1.ClientCtx, signedTxFile.Name()) diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 89bb260c3ee2..14f7d8100035 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -4,6 +4,8 @@ import ( "fmt" "strings" + "github.com/cosmos/cosmos-sdk/testutil" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -11,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/client/cli" ) -func TxSignExec(clientCtx client.Context, from fmt.Stringer, filename string, extraArgs ...string) ([]byte, error) { +func TxSignExec(clientCtx client.Context, from fmt.Stringer, filename string, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), fmt.Sprintf("--from=%s", from.String()), @@ -25,7 +27,7 @@ func TxSignExec(clientCtx client.Context, from fmt.Stringer, filename string, ex return clitestutil.ExecTestCLICmd(clientCtx, cli.GetSignCommand(), args) } -func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { +func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{ filename, } @@ -35,7 +37,7 @@ func TxBroadcastExec(clientCtx client.Context, filename string, extraArgs ...str return clitestutil.ExecTestCLICmd(clientCtx, cli.GetBroadcastCommand(), args) } -func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string) ([]byte, error) { +func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), filename, @@ -46,7 +48,7 @@ func TxEncodeExec(clientCtx client.Context, filename string, extraArgs ...string return clitestutil.ExecTestCLICmd(clientCtx, cli.GetEncodeCommand(), args) } -func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte, error) { +func TxValidateSignaturesExec(clientCtx client.Context, filename string) (testutil.BufferWriter, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), fmt.Sprintf("--%s=%s", flags.FlagChainID, clientCtx.ChainID), @@ -56,7 +58,7 @@ func TxValidateSignaturesExec(clientCtx client.Context, filename string) ([]byte return clitestutil.ExecTestCLICmd(clientCtx, cli.GetValidateSignaturesCommand(), args) } -func TxMultiSignExec(clientCtx client.Context, from string, filename string, extraArgs ...string) ([]byte, error) { +func TxMultiSignExec(clientCtx client.Context, from string, filename string, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), fmt.Sprintf("--%s=%s", flags.FlagChainID, clientCtx.ChainID), @@ -69,7 +71,7 @@ func TxMultiSignExec(clientCtx client.Context, from string, filename string, ext return clitestutil.ExecTestCLICmd(clientCtx, cli.GetMultiSignCommand(), args) } -func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename string, extraArgs ...string) ([]byte, error) { +func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename string, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), fmt.Sprintf("--from=%s", from.String()), @@ -81,7 +83,7 @@ func TxSignBatchExec(clientCtx client.Context, from fmt.Stringer, filename strin return clitestutil.ExecTestCLICmd(clientCtx, cli.GetSignBatchCommand(), args) } -func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...string) ([]byte, error) { +func TxDecodeExec(clientCtx client.Context, encodedTx string, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), encodedTx, diff --git a/x/bank/client/cli/cli_test.go b/x/bank/client/cli/cli_test.go index 2041ec2d965d..239277b76c4d 100644 --- a/x/bank/client/cli/cli_test.go +++ b/x/bank/client/cli/cli_test.go @@ -280,7 +280,7 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(bz, tc.respType), string(bz)) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(bz.Bytes(), tc.respType), bz.String()) txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, txResp.Code) diff --git a/x/bank/client/testutil/cli_helpers.go b/x/bank/client/testutil/cli_helpers.go index c5cf20d9e70d..b2fd1e22851d 100644 --- a/x/bank/client/testutil/cli_helpers.go +++ b/x/bank/client/testutil/cli_helpers.go @@ -3,6 +3,8 @@ package testutil import ( "fmt" + "github.com/cosmos/cosmos-sdk/testutil" + clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/stretchr/testify/require" @@ -15,14 +17,14 @@ import ( bankcli "github.com/cosmos/cosmos-sdk/x/bank/client/cli" ) -func MsgSendExec(clientCtx client.Context, from, to, amount fmt.Stringer, extraArgs ...string) ([]byte, error) { +func MsgSendExec(clientCtx client.Context, from, to, amount fmt.Stringer, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{from.String(), to.String(), amount.String()} args = append(args, extraArgs...) return clitestutil.ExecTestCLICmd(clientCtx, bankcli.NewSendTxCmd(), args) } -func QueryBalancesExec(clientCtx client.Context, address fmt.Stringer, extraArgs ...string) ([]byte, error) { +func QueryBalancesExec(clientCtx client.Context, address fmt.Stringer, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{address.String()} args = append(args, extraArgs...)