From a940214a4923a3bf9a9161cd14bd3072299cd0c9 Mon Sep 17 00:00:00 2001 From: Alessio Treglia Date: Thu, 9 Jul 2020 14:21:20 +0200 Subject: [PATCH 1/4] testutil cleanup and reorg (#6658) Prepare migrating testing auxiliary functions from tests to testutil. Remove local duplicates on testutil.WriteToNewTempFile(). Always favor testutil.NewTestCaseDir() over ioutil.TempDir(). Add test cases for the testing auxiliary functions. --- client/keys/add_ledger_test.go | 10 ++--- client/keys/add_test.go | 6 +-- client/keys/delete_test.go | 8 ++-- client/keys/export_test.go | 8 ++-- client/keys/import_test.go | 6 +-- client/keys/list_test.go | 10 ++--- client/keys/migrate_test.go | 6 +-- client/keys/mnemonic_test.go | 4 +- client/keys/show_test.go | 10 ++--- client/tx/tx_test.go | 8 ++-- client/verifier_test.go | 6 +-- crypto/keyring/keyring_ledger_test.go | 6 +-- crypto/keyring/keyring_test.go | 52 ++++++++++++------------ crypto/keyring/legacy_test.go | 6 +-- crypto/ledger_mock.go | 6 +-- crypto/ledger_test.go | 22 +++++------ server/constructors_test.go | 6 +-- server/export_test.go | 4 +- server/init_test.go | 6 +-- tests/io.go | 35 ---------------- tests/util.go | 13 ------ testutil/ioutil.go | 46 +++++++++++++++++++++ testutil/ioutil_test.go | 55 ++++++++++++++++++++++++++ {tests => testutil}/known_values.go | 2 +- testutil/{ => network}/doc.go | 10 ++--- testutil/{ => network}/network.go | 4 +- testutil/{ => network}/network_test.go | 8 ++-- testutil/{ => network}/util.go | 2 +- version/version_test.go | 4 +- x/auth/client/cli/broadcast_test.go | 4 +- x/auth/client/cli/cli_test.go | 39 +++++++++--------- x/auth/client/cli/encode_test.go | 4 +- x/auth/client/tx_test.go | 17 ++------ x/bank/client/cli/cli_test.go | 10 ++--- x/bank/client/rest/query_test.go | 10 ++--- x/bank/client/rest/tx_test.go | 6 +-- x/crisis/client/cli/cli_test.go | 10 ++--- x/distribution/client/cli/tx_test.go | 8 ++-- x/genutil/client/cli/init_test.go | 12 +++--- x/genutil/client/cli/migrate_test.go | 4 +- x/genutil/utils_test.go | 4 +- x/gov/client/cli/parse_test.go | 15 +++---- x/params/client/cli/tx_test.go | 8 ++-- x/upgrade/types/storeloader_test.go | 4 +- 44 files changed, 281 insertions(+), 243 deletions(-) delete mode 100644 tests/io.go create mode 100644 testutil/ioutil.go create mode 100644 testutil/ioutil_test.go rename {tests => testutil}/known_values.go (90%) rename testutil/{ => network}/doc.go (89%) rename testutil/{ => network}/network.go (99%) rename testutil/{ => network}/network_test.go (82%) rename testutil/{ => network}/util.go (99%) diff --git a/client/keys/add_ledger_test.go b/client/keys/add_ledger_test.go index 3820e418d71f..fae479bfe278 100644 --- a/client/keys/add_ledger_test.go +++ b/client/keys/add_ledger_test.go @@ -13,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -37,7 +37,7 @@ func Test_runAddCmdLedgerWithCustomCoinType(t *testing.T) { cmd.Flags().AddFlagSet(Commands().PersistentFlags()) // Prepare a keybase - kbHome, kbCleanUp := tests.NewTestCaseDir(t) + kbHome, kbCleanUp := testutil.NewTestCaseDir(t) require.NotNil(t, kbHome) t.Cleanup(kbCleanUp) @@ -53,7 +53,7 @@ func Test_runAddCmdLedgerWithCustomCoinType(t *testing.T) { fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), }) - mockIn, _, _ := tests.ApplyMockIO(cmd) + mockIn, _, _ := testutil.ApplyMockIO(cmd) mockIn.Reset("test1234\ntest1234\n") require.NoError(t, cmd.Execute()) @@ -85,10 +85,10 @@ func Test_runAddCmdLedgerWithCustomCoinType(t *testing.T) { func Test_runAddCmdLedger(t *testing.T) { cmd := AddKeyCommand() cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - mockIn, _, _ := tests.ApplyMockIO(cmd) + mockIn, _, _ := testutil.ApplyMockIO(cmd) // Prepare a keybase - kbHome, kbCleanUp := tests.NewTestCaseDir(t) + kbHome, kbCleanUp := testutil.NewTestCaseDir(t) require.NotNil(t, kbHome) t.Cleanup(kbCleanUp) diff --git a/client/keys/add_test.go b/client/keys/add_test.go index 0b6af85b1d5c..1a67f79b2e9c 100644 --- a/client/keys/add_test.go +++ b/client/keys/add_test.go @@ -11,7 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -19,9 +19,9 @@ func Test_runAddCmdBasic(t *testing.T) { cmd := AddKeyCommand() cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - mockIn, _, _ := tests.ApplyMockIO(cmd) + mockIn, _, _ := testutil.ApplyMockIO(cmd) - kbHome, kbCleanUp := tests.NewTestCaseDir(t) + kbHome, kbCleanUp := testutil.NewTestCaseDir(t) require.NotNil(t, kbHome) t.Cleanup(kbCleanUp) diff --git a/client/keys/delete_test.go b/client/keys/delete_test.go index ede5e72db274..6bafefeef700 100644 --- a/client/keys/delete_test.go +++ b/client/keys/delete_test.go @@ -9,14 +9,14 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) func Test_runDeleteCmd(t *testing.T) { cmd := DeleteKeyCommand() cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - mockIn, _, _ := tests.ApplyMockIO(cmd) + mockIn, _, _ := testutil.ApplyMockIO(cmd) yesF, _ := cmd.Flags().GetBool(flagYes) forceF, _ := cmd.Flags().GetBool(flagForce) @@ -27,7 +27,7 @@ func Test_runDeleteCmd(t *testing.T) { fakeKeyName1 := "runDeleteCmd_Key1" fakeKeyName2 := "runDeleteCmd_Key2" // Now add a temporary keybase - kbHome, cleanUp := tests.NewTestCaseDir(t) + kbHome, cleanUp := testutil.NewTestCaseDir(t) t.Cleanup(cleanUp) path := sdk.GetConfig().GetFullFundraiserPath() @@ -35,7 +35,7 @@ func Test_runDeleteCmd(t *testing.T) { kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome, mockIn) require.NoError(t, err) - _, err = kb.NewAccount(fakeKeyName1, tests.TestMnemonic, "", path, hd.Secp256k1) + _, err = kb.NewAccount(fakeKeyName1, testutil.TestMnemonic, "", path, hd.Secp256k1) require.NoError(t, err) _, _, err = kb.NewMnemonic(fakeKeyName2, keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) diff --git a/client/keys/export_test.go b/client/keys/export_test.go index 937582435997..b64fb12afab4 100644 --- a/client/keys/export_test.go +++ b/client/keys/export_test.go @@ -7,20 +7,20 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" ) func Test_runExportCmd(t *testing.T) { cmd := ExportKeyCommand() cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - mockIn, _, _ := tests.ApplyMockIO(cmd) + mockIn, _, _ := testutil.ApplyMockIO(cmd) // Now add a temporary keybase - kbHome, cleanUp := tests.NewTestCaseDir(t) + kbHome, cleanUp := testutil.NewTestCaseDir(t) t.Cleanup(cleanUp) // create a key @@ -31,7 +31,7 @@ func Test_runExportCmd(t *testing.T) { }) path := sdk.GetConfig().GetFullFundraiserPath() - _, err = kb.NewAccount("keyname1", tests.TestMnemonic, "", path, hd.Secp256k1) + _, err = kb.NewAccount("keyname1", testutil.TestMnemonic, "", path, hd.Secp256k1) require.NoError(t, err) // Now enter password diff --git a/client/keys/import_test.go b/client/keys/import_test.go index 88de08be6bfb..835319bb59c9 100644 --- a/client/keys/import_test.go +++ b/client/keys/import_test.go @@ -10,17 +10,17 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) func Test_runImportCmd(t *testing.T) { cmd := ImportKeyCommand() cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - mockIn, _, _ := tests.ApplyMockIO(cmd) + mockIn, _, _ := testutil.ApplyMockIO(cmd) // Now add a temporary keybase - kbHome, cleanUp := tests.NewTestCaseDir(t) + kbHome, cleanUp := testutil.NewTestCaseDir(t) t.Cleanup(cleanUp) kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome, mockIn) diff --git a/client/keys/list_test.go b/client/keys/list_test.go index ad0bcafa9888..bcde277aa6cb 100644 --- a/client/keys/list_test.go +++ b/client/keys/list_test.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -18,18 +18,18 @@ func Test_runListCmd(t *testing.T) { cmd := ListKeysCmd() cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - kbHome1, cleanUp1 := tests.NewTestCaseDir(t) + kbHome1, cleanUp1 := testutil.NewTestCaseDir(t) t.Cleanup(cleanUp1) - kbHome2, cleanUp2 := tests.NewTestCaseDir(t) + kbHome2, cleanUp2 := testutil.NewTestCaseDir(t) t.Cleanup(cleanUp2) - mockIn, _, _ := tests.ApplyMockIO(cmd) + mockIn, _, _ := testutil.ApplyMockIO(cmd) kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome2, mockIn) require.NoError(t, err) path := "" //sdk.GetConfig().GetFullFundraiserPath() - _, err = kb.NewAccount("something", tests.TestMnemonic, "", path, hd.Secp256k1) + _, err = kb.NewAccount("something", testutil.TestMnemonic, "", path, hd.Secp256k1) require.NoError(t, err) t.Cleanup(func() { diff --git a/client/keys/migrate_test.go b/client/keys/migrate_test.go index 6f36bfc9f490..e779ffa03930 100644 --- a/client/keys/migrate_test.go +++ b/client/keys/migrate_test.go @@ -11,7 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" ) func Test_runMigrateCmd(t *testing.T) { @@ -20,7 +20,7 @@ func Test_runMigrateCmd(t *testing.T) { cmd.SetOut(ioutil.Discard) cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - kbHome, kbCleanUp := tests.NewTestCaseDir(t) + kbHome, kbCleanUp := testutil.NewTestCaseDir(t) copy.Copy("testdata", kbHome) assert.NotNil(t, kbHome) t.Cleanup(kbCleanUp) @@ -35,7 +35,7 @@ func Test_runMigrateCmd(t *testing.T) { cmd = MigrateCommand() cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - mockIn, _, _ := tests.ApplyMockIO(cmd) + mockIn, _, _ := testutil.ApplyMockIO(cmd) cmd.SetArgs([]string{ fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), diff --git a/client/keys/mnemonic_test.go b/client/keys/mnemonic_test.go index c333657f96eb..359cd8fe93c4 100644 --- a/client/keys/mnemonic_test.go +++ b/client/keys/mnemonic_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" ) func Test_RunMnemonicCmdNormal(t *testing.T) { @@ -30,7 +30,7 @@ func Test_RunMnemonicCmdUser(t *testing.T) { require.Equal(t, "EOF", err.Error()) // Try again - mockIn, _, _ := tests.ApplyMockIO(cmd) + mockIn, _, _ := testutil.ApplyMockIO(cmd) mockIn.Reset("Hi!\n") err = cmd.Execute() require.Error(t, err) diff --git a/client/keys/show_test.go b/client/keys/show_test.go index abc6d1de5b8e..024ab605de18 100644 --- a/client/keys/show_test.go +++ b/client/keys/show_test.go @@ -13,7 +13,7 @@ import ( "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" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -38,7 +38,7 @@ func Test_showKeysCmd(t *testing.T) { func Test_runShowCmd(t *testing.T) { cmd := ShowKeysCmd() cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - mockIn, _, _ := tests.ApplyMockIO(cmd) + mockIn, _, _ := testutil.ApplyMockIO(cmd) cmd.SetArgs([]string{"invalid"}) require.EqualError(t, cmd.Execute(), "invalid is not a valid name or address: decoding bech32 failed: invalid bech32 string length 7") @@ -46,7 +46,7 @@ func Test_runShowCmd(t *testing.T) { cmd.SetArgs([]string{"invalid1", "invalid2"}) require.EqualError(t, cmd.Execute(), "invalid1 is not a valid name or address: decoding bech32 failed: invalid index of 1") - kbHome, cleanUp := tests.NewTestCaseDir(t) + kbHome, cleanUp := testutil.NewTestCaseDir(t) t.Cleanup(cleanUp) fakeKeyName1 := "runShowCmd_Key1" @@ -60,11 +60,11 @@ func Test_runShowCmd(t *testing.T) { }) path := hd.NewFundraiserParams(1, sdk.CoinType, 0).String() - _, err = kb.NewAccount(fakeKeyName1, tests.TestMnemonic, "", path, hd.Secp256k1) + _, err = kb.NewAccount(fakeKeyName1, testutil.TestMnemonic, "", path, hd.Secp256k1) require.NoError(t, err) path2 := hd.NewFundraiserParams(1, sdk.CoinType, 1).String() - _, err = kb.NewAccount(fakeKeyName2, tests.TestMnemonic, "", path2, hd.Secp256k1) + _, err = kb.NewAccount(fakeKeyName2, testutil.TestMnemonic, "", path2, hd.Secp256k1) require.NoError(t, err) // Now try single key diff --git a/client/tx/tx_test.go b/client/tx/tx_test.go index dd95e2df42a4..b129e61879d4 100644 --- a/client/tx/tx_test.go +++ b/client/tx/tx_test.go @@ -4,13 +4,13 @@ import ( "errors" "testing" + "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/x/auth/signing" + "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/tests" - - "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" @@ -115,7 +115,7 @@ func TestBuildUnsignedTx(t *testing.T) { } func TestSign(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) path := hd.CreateHDPath(118, 0, 0).String() diff --git a/client/verifier_test.go b/client/verifier_test.go index 029577f48773..1088d61866d7 100644 --- a/client/verifier_test.go +++ b/client/verifier_test.go @@ -1,17 +1,17 @@ package client_test import ( - "io/ioutil" "testing" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/testutil" ) func TestCreateVerifier(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "example") - require.NoError(t, err) + tmpDir, cleanup := testutil.NewTestCaseDir(t) + t.Cleanup(cleanup) testCases := []struct { name string diff --git a/crypto/keyring/keyring_ledger_test.go b/crypto/keyring/keyring_ledger_test.go index 84ca7e5720dc..e94ba395aaaa 100644 --- a/crypto/keyring/keyring_ledger_test.go +++ b/crypto/keyring/keyring_ledger_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -52,7 +52,7 @@ func TestInMemoryCreateLedger(t *testing.T) { // TestSignVerify does some detailed checks on how we sign and validate // signatures func TestSignVerifyKeyRingWithLedger(t *testing.T) { - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) kb, err := New("keybasename", "test", dir, nil) require.NoError(t, err) @@ -89,7 +89,7 @@ func TestSignVerifyKeyRingWithLedger(t *testing.T) { } func TestAltKeyring_SaveLedgerKey(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) diff --git a/crypto/keyring/keyring_test.go b/crypto/keyring/keyring_test.go index 55646c1e3af6..1daf0164f4a8 100644 --- a/crypto/keyring/keyring_test.go +++ b/crypto/keyring/keyring_test.go @@ -15,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -30,7 +30,7 @@ func init() { } func TestNewKeyring(t *testing.T) { - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) mockIn := strings.NewReader("") t.Cleanup(cleanup) kr, err := New("cosmos", BackendFile, dir, mockIn) @@ -48,7 +48,7 @@ func TestNewKeyring(t *testing.T) { } func TestKeyManagementKeyRing(t *testing.T) { - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) kb, err := New("keybasename", "test", dir, nil) require.NoError(t, err) @@ -130,7 +130,7 @@ func TestKeyManagementKeyRing(t *testing.T) { } func TestSignVerifyKeyRing(t *testing.T) { - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) kb, err := New("keybasename", "test", dir, nil) @@ -209,7 +209,7 @@ func TestSignVerifyKeyRing(t *testing.T) { } func TestExportImportKeyRing(t *testing.T) { - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) kb, err := New("keybasename", "test", dir, nil) require.NoError(t, err) @@ -243,7 +243,7 @@ func TestExportImportKeyRing(t *testing.T) { } func TestExportImportPubKeyKeyRing(t *testing.T) { - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) kb, err := New("keybasename", "test", dir, nil) require.NoError(t, err) @@ -283,7 +283,7 @@ func TestExportImportPubKeyKeyRing(t *testing.T) { } func TestAdvancedKeyManagementKeyRing(t *testing.T) { - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) kb, err := New("keybasename", "test", dir, nil) @@ -319,7 +319,7 @@ func TestAdvancedKeyManagementKeyRing(t *testing.T) { } func TestSeedPhraseKeyRing(t *testing.T) { - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) kb, err := New("keybasename", "test", dir, nil) require.NoError(t, err) @@ -350,7 +350,7 @@ func TestSeedPhraseKeyRing(t *testing.T) { } func TestKeyringKeybaseExportImportPrivKey(t *testing.T) { - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) kb, err := New("keybasename", "test", dir, nil) require.NoError(t, err) @@ -729,7 +729,7 @@ func TestInMemorySeedPhrase(t *testing.T) { } func TestKeyChain_ShouldFailWhenAddingSameGeneratedAccount(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) kr, err := New(t.Name(), BackendTest, dir, nil) @@ -801,7 +801,7 @@ func ExampleNew() { } func TestAltKeyring_List(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -835,7 +835,7 @@ func TestAltKeyring_List(t *testing.T) { } func TestAltKeyring_NewAccount(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -864,7 +864,7 @@ func TestAltKeyring_NewAccount(t *testing.T) { } func TestAltKeyring_Get(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -880,7 +880,7 @@ func TestAltKeyring_Get(t *testing.T) { } func TestAltKeyring_KeyByAddress(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -896,7 +896,7 @@ func TestAltKeyring_KeyByAddress(t *testing.T) { } func TestAltKeyring_Delete(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -919,7 +919,7 @@ func TestAltKeyring_Delete(t *testing.T) { } func TestAltKeyring_DeleteByAddress(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -942,7 +942,7 @@ func TestAltKeyring_DeleteByAddress(t *testing.T) { } func TestAltKeyring_SavePubKey(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -968,7 +968,7 @@ func TestAltKeyring_SavePubKey(t *testing.T) { } func TestAltKeyring_SaveMultisig(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -993,7 +993,7 @@ func TestAltKeyring_SaveMultisig(t *testing.T) { } func TestAltKeyring_Sign(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -1012,7 +1012,7 @@ func TestAltKeyring_Sign(t *testing.T) { } func TestAltKeyring_SignByAddress(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -1031,7 +1031,7 @@ func TestAltKeyring_SignByAddress(t *testing.T) { } func TestAltKeyring_ImportExportPrivKey(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -1060,7 +1060,7 @@ func TestAltKeyring_ImportExportPrivKey(t *testing.T) { } func TestAltKeyring_ImportExportPrivKey_ByAddress(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -1090,7 +1090,7 @@ func TestAltKeyring_ImportExportPrivKey_ByAddress(t *testing.T) { } func TestAltKeyring_ImportExportPubKey(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -1115,7 +1115,7 @@ func TestAltKeyring_ImportExportPubKey(t *testing.T) { } func TestAltKeyring_ImportExportPubKey_ByAddress(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -1140,7 +1140,7 @@ func TestAltKeyring_ImportExportPubKey_ByAddress(t *testing.T) { } func TestAltKeyring_ConstructorSupportedAlgos(t *testing.T) { - dir, clean := tests.NewTestCaseDir(t) + dir, clean := testutil.NewTestCaseDir(t) t.Cleanup(clean) keyring, err := New(t.Name(), BackendTest, dir, nil) @@ -1155,7 +1155,7 @@ func TestAltKeyring_ConstructorSupportedAlgos(t *testing.T) { require.NoError(t, err) // but we can create a new keybase with our provided algos. - dir2, clean2 := tests.NewTestCaseDir(t) + dir2, clean2 := testutil.NewTestCaseDir(t) t.Cleanup(clean2) keyring2, err := New(t.Name(), BackendTest, dir2, nil, func(options *Options) { diff --git a/crypto/keyring/legacy_test.go b/crypto/keyring/legacy_test.go index 11ea30bf05e1..38457a32732f 100644 --- a/crypto/keyring/legacy_test.go +++ b/crypto/keyring/legacy_test.go @@ -9,11 +9,11 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" ) func TestNewLegacyKeyBase(t *testing.T) { - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) kb, err := keyring.NewLegacy("keybasename", dir) require.NoError(t, err) @@ -21,7 +21,7 @@ func TestNewLegacyKeyBase(t *testing.T) { } func TestLegacyKeybase(t *testing.T) { - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) // Backup testdata diff --git a/crypto/ledger_mock.go b/crypto/ledger_mock.go index 20a45c158bb3..2acb3c43e979 100644 --- a/crypto/ledger_mock.go +++ b/crypto/ledger_mock.go @@ -15,7 +15,7 @@ import ( bip39 "github.com/cosmos/go-bip39" "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -46,7 +46,7 @@ func (mock LedgerSECP256K1Mock) GetPublicKeySECP256K1(derivationPath []uint32) ( return nil, errors.New("Invalid derivation path") } - seed, err := bip39.NewSeedWithErrorChecking(tests.TestMnemonic, "") + seed, err := bip39.NewSeedWithErrorChecking(testutil.TestMnemonic, "") if err != nil { return nil, err } @@ -87,7 +87,7 @@ func (mock LedgerSECP256K1Mock) GetAddressPubKeySECP256K1(derivationPath []uint3 func (mock LedgerSECP256K1Mock) SignSECP256K1(derivationPath []uint32, message []byte) ([]byte, error) { path := hd.NewParams(derivationPath[0], derivationPath[1], derivationPath[2], derivationPath[3] != 0, derivationPath[4]) - seed, err := bip39.NewSeedWithErrorChecking(tests.TestMnemonic, "") + seed, err := bip39.NewSeedWithErrorChecking(testutil.TestMnemonic, "") if err != nil { return nil, err } diff --git a/crypto/ledger_test.go b/crypto/ledger_test.go index 7408543b30e4..b22db9555951 100644 --- a/crypto/ledger_test.go +++ b/crypto/ledger_test.go @@ -10,7 +10,7 @@ import ( cryptoAmino "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -30,16 +30,16 @@ func TestPublicKeyUnsafe(t *testing.T) { require.Equal(t, "eb5ae98721034fef9cd7c4c63588d3b03feb5281b9d232cba34d6f3d71aee59211ffbfe1fe87", fmt.Sprintf("%x", priv.PubKey().Bytes()), - "Is your device using test mnemonic: %s ?", tests.TestMnemonic) + "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) pubKeyAddr, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, priv.PubKey()) require.NoError(t, err) require.Equal(t, "cosmospub1addwnpepqd87l8xhcnrrtzxnkql7k55ph8fr9jarf4hn6udwukfprlalu8lgw0urza0", - pubKeyAddr, "Is your device using test mnemonic: %s ?", tests.TestMnemonic) + pubKeyAddr, "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) addr := sdk.AccAddress(priv.PubKey().Address()).String() require.Equal(t, "cosmos1w34k53py5v5xyluazqpq65agyajavep2rflq6h", - addr, "Is your device using test mnemonic: %s ?", tests.TestMnemonic) + addr, "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) } func TestPublicKeyUnsafeHDPath(t *testing.T) { @@ -78,7 +78,7 @@ func TestPublicKeyUnsafeHDPath(t *testing.T) { require.NoError(t, err) require.Equal(t, expectedAnswers[i], pubKeyAddr, - "Is your device using test mnemonic: %s ?", tests.TestMnemonic) + "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) // Store and restore serializedPk := priv.Bytes() @@ -108,15 +108,15 @@ func TestPublicKeySafe(t *testing.T) { require.Equal(t, "eb5ae98721034fef9cd7c4c63588d3b03feb5281b9d232cba34d6f3d71aee59211ffbfe1fe87", fmt.Sprintf("%x", priv.PubKey().Bytes()), - "Is your device using test mnemonic: %s ?", tests.TestMnemonic) + "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) pubKeyAddr, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, priv.PubKey()) require.NoError(t, err) require.Equal(t, "cosmospub1addwnpepqd87l8xhcnrrtzxnkql7k55ph8fr9jarf4hn6udwukfprlalu8lgw0urza0", - pubKeyAddr, "Is your device using test mnemonic: %s ?", tests.TestMnemonic) + pubKeyAddr, "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) require.Equal(t, "cosmos1w34k53py5v5xyluazqpq65agyajavep2rflq6h", - addr, "Is your device using test mnemonic: %s ?", tests.TestMnemonic) + addr, "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) addr2 := sdk.AccAddress(priv.PubKey().Address()).String() require.Equal(t, addr, addr2) @@ -167,7 +167,7 @@ func TestPublicKeyHDPath(t *testing.T) { require.Equal(t, addr2, addr) require.Equal(t, expectedAddrs[i], addr, - "Is your device using test mnemonic: %s ?", tests.TestMnemonic) + "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) // Check other methods require.NoError(t, priv.(PrivKeyLedgerSecp256k1).ValidateKey()) @@ -178,7 +178,7 @@ func TestPublicKeyHDPath(t *testing.T) { require.NoError(t, err) require.Equal(t, expectedPubKeys[i], pubKeyAddr, - "Is your device using test mnemonic: %s ?", tests.TestMnemonic) + "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) // Store and restore serializedPk := priv.Bytes() @@ -220,7 +220,7 @@ func TestSignaturesHD(t *testing.T) { require.Nil(t, err) valid := pub.VerifyBytes(msg, sig) - require.True(t, valid, "Is your device using test mnemonic: %s ?", tests.TestMnemonic) + require.True(t, valid, "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) } } diff --git a/server/constructors_test.go b/server/constructors_test.go index e11520fe5826..694f9f538492 100644 --- a/server/constructors_test.go +++ b/server/constructors_test.go @@ -6,12 +6,12 @@ import ( "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" ) func Test_openDB(t *testing.T) { t.Parallel() - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) _, err := openDB(dir) require.NoError(t, err) @@ -19,7 +19,7 @@ func Test_openDB(t *testing.T) { func Test_openTraceWriter(t *testing.T) { t.Parallel() - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) fname := filepath.Join(dir, "logfile") w, err := openTraceWriter(fname) diff --git a/server/export_test.go b/server/export_test.go index 96f14b139a7a..5e600ef1c544 100644 --- a/server/export_test.go +++ b/server/export_test.go @@ -21,13 +21,13 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/genutil" ) func TestExportCmd_ConsensusParams(t *testing.T) { - tempDir, clean := tests.NewTestCaseDir(t) + tempDir, clean := testutil.NewTestCaseDir(t) defer clean() err := createConfigFolder(tempDir) diff --git a/server/init_test.go b/server/init_test.go index c2b9b469d170..2333d6d5a0d3 100644 --- a/server/init_test.go +++ b/server/init_test.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/types" ) @@ -25,7 +25,7 @@ func TestGenerateCoinKey(t *testing.T) { func TestGenerateSaveCoinKey(t *testing.T) { t.Parallel() - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) kb, err := keyring.New(t.Name(), "test", dir, nil) @@ -47,7 +47,7 @@ func TestGenerateSaveCoinKey(t *testing.T) { func TestGenerateSaveCoinKeyOverwriteFlag(t *testing.T) { t.Parallel() - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) kb, err := keyring.New(t.Name(), "test", dir, nil) diff --git a/tests/io.go b/tests/io.go deleted file mode 100644 index a51398571926..000000000000 --- a/tests/io.go +++ /dev/null @@ -1,35 +0,0 @@ -package tests - -import ( - "bytes" - "io/ioutil" - "os" - "strings" - - "github.com/spf13/cobra" - "github.com/stretchr/testify/require" -) - -// ApplyMockIO replaces stdin/out/err with buffers that can be used during testing. -func ApplyMockIO(c *cobra.Command) (*strings.Reader, *bytes.Buffer, *bytes.Buffer) { - mockIn := strings.NewReader("") - mockOut := bytes.NewBufferString("") - mockErr := bytes.NewBufferString("") - c.SetIn(mockIn) - c.SetOut(mockOut) - c.SetErr(mockErr) - return mockIn, mockOut, mockErr -} - -// Write the given string to a new temporary file -func WriteToNewTempFile(t require.TestingT, s string) (*os.File, func()) { - fp, err := ioutil.TempFile(os.TempDir(), "cosmos_cli_test_") - require.Nil(t, err) - - _, err = fp.WriteString(s) - require.Nil(t, err) - - return fp, func() { os.Remove(fp.Name()) } -} - -// DONTCOVER diff --git a/tests/util.go b/tests/util.go index c588216e8336..129c5d12a227 100644 --- a/tests/util.go +++ b/tests/util.go @@ -2,13 +2,9 @@ package tests import ( "fmt" - "io/ioutil" "net/http" - "os" - "testing" "time" - "github.com/stretchr/testify/require" rpchttp "github.com/tendermint/tendermint/rpc/client/http" ctypes "github.com/tendermint/tendermint/rpc/core/types" @@ -115,15 +111,6 @@ func WaitForStart(url string) { panic(err) } -// NewTestCaseDir creates a new temporary directory for a test case. -// Returns the directory path and a cleanup function. -// nolint: errcheck -func NewTestCaseDir(t testing.TB) (string, func()) { - dir, err := ioutil.TempDir("", t.Name()+"_") - require.NoError(t, err) - return dir, func() { os.RemoveAll(dir) } -} - var cdc = codec.New() func init() { diff --git a/testutil/ioutil.go b/testutil/ioutil.go new file mode 100644 index 000000000000..ab0ccaec588a --- /dev/null +++ b/testutil/ioutil.go @@ -0,0 +1,46 @@ +package testutil + +import ( + "bytes" + "io/ioutil" + "os" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" +) + +// NewTestCaseDir creates a new temporary directory for a test case. +// Returns the directory path and a cleanup function. +// nolint: errcheck +func NewTestCaseDir(t testing.TB) (string, func()) { + dir, err := ioutil.TempDir("", t.Name()+"_") + require.NoError(t, err) + return dir, func() { os.RemoveAll(dir) } +} + +// ApplyMockIO replaces stdin/out/err with buffers that can be used during testing. +func ApplyMockIO(c *cobra.Command) (*strings.Reader, *bytes.Buffer, *bytes.Buffer) { + mockIn := strings.NewReader("") + mockOut := bytes.NewBufferString("") + mockErr := bytes.NewBufferString("") + c.SetIn(mockIn) + c.SetOut(mockOut) + c.SetErr(mockErr) + return mockIn, mockOut, mockErr +} + +// Write the given string to a new temporary file. +// Returns an open file and a clean up function that +// 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()+"_") + require.Nil(t, err) + + _, err = fp.WriteString(s) + require.Nil(t, err) + + return fp, func() { os.Remove(fp.Name()) } +} diff --git a/testutil/ioutil_test.go b/testutil/ioutil_test.go new file mode 100644 index 000000000000..d66f301bbb06 --- /dev/null +++ b/testutil/ioutil_test.go @@ -0,0 +1,55 @@ +package testutil_test + +import ( + "io/ioutil" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/testutil" +) + +func TestNewTestCaseDir(t *testing.T) { + dir1, cleanup1 := testutil.NewTestCaseDir(t) + dir2, cleanup2 := testutil.NewTestCaseDir(t) + + require.NotEqual(t, dir1, dir2) + require.DirExists(t, dir1) + require.DirExists(t, dir2) + + cleanup1() + + require.NoDirExists(t, dir1) + require.DirExists(t, dir2) + + cleanup2() + require.NoDirExists(t, dir2) +} + +func TestApplyMockIO(t *testing.T) { + cmd := &cobra.Command{} + + oldStdin := cmd.InOrStdin() + oldStdout := cmd.OutOrStdout() + oldStderr := cmd.ErrOrStderr() + + testutil.ApplyMockIO(cmd) + + require.NotEqual(t, cmd.InOrStdin(), oldStdin) + require.NotEqual(t, cmd.OutOrStdout(), oldStdout) + require.NotEqual(t, cmd.ErrOrStderr(), oldStderr) +} + +func TestWriteToNewTempFile(t *testing.T) { + tempfile, cleanup := testutil.WriteToNewTempFile(t, "test string") + tempfile.Close() + + bs, err := ioutil.ReadFile(tempfile.Name()) + require.NoError(t, err) + require.Equal(t, "test string", string(bs)) + + cleanup() + + require.NoFileExists(t, tempfile.Name()) +} diff --git a/tests/known_values.go b/testutil/known_values.go similarity index 90% rename from tests/known_values.go rename to testutil/known_values.go index eb2063fa1666..a87ccd2af0cc 100644 --- a/tests/known_values.go +++ b/testutil/known_values.go @@ -1,4 +1,4 @@ -package tests +package testutil const ( // Tests expect a ledger device initialized to the following mnemonic diff --git a/testutil/doc.go b/testutil/network/doc.go similarity index 89% rename from testutil/doc.go rename to testutil/network/doc.go index 3035d4e1a2d8..9e44f371ab6c 100644 --- a/testutil/doc.go +++ b/testutil/network/doc.go @@ -1,14 +1,14 @@ /* -Package testutil implements and exposes a fully operational in-process Tendermint +Package network implements and exposes a fully operational in-process Tendermint test network that consists of at least one or potentially many validators. This test network can be used primarily for integration tests or unit test suites. -The testnetwork utilizes SimApp as the ABCI application and uses all the modules +The test network utilizes SimApp as the ABCI application and uses all the modules defined in the Cosmos SDK. An in-process test network can be configured with any number of validators as well as account funds and even custom genesis state. When creating a test network, a series of Validator objects are returned. Each -Validator object has useful information such as their address and pubkey. A +Validator object has useful information such as their address and public key. A Validator will also provide its RPC, P2P, and API addresses that can be useful for integration testing. In addition, a Tendermint local RPC client is also provided which can be handy for making direct RPC calls to Tendermint. @@ -35,7 +35,7 @@ A typical testing flow might look like the following: cfg.NumValidators = 1 s.cfg = cfg - s.network = testutil.NewTestNetwork(s.T(), cfg) + s.network = testutil.New(s.T(), cfg) _, err := s.network.WaitForHeight(1) s.Require().NoError(err) @@ -62,4 +62,4 @@ A typical testing flow might look like the following: suite.Run(t, new(IntegrationTestSuite)) } */ -package testutil +package network diff --git a/testutil/network.go b/testutil/network/network.go similarity index 99% rename from testutil/network.go rename to testutil/network/network.go index d2e820257278..e029878bc921 100644 --- a/testutil/network.go +++ b/testutil/network/network.go @@ -1,4 +1,4 @@ -package testutil +package network import ( "bufio" @@ -144,7 +144,7 @@ type ( } ) -func NewTestNetwork(t *testing.T, cfg Config) *Network { +func New(t *testing.T, cfg Config) *Network { // only one caller/test can create and use a network at a time t.Log("acquiring test network lock") lock.Lock() diff --git a/testutil/network_test.go b/testutil/network/network_test.go similarity index 82% rename from testutil/network_test.go rename to testutil/network/network_test.go index 12f2338cd61c..e7b248e31a37 100644 --- a/testutil/network_test.go +++ b/testutil/network/network_test.go @@ -1,22 +1,24 @@ -package testutil +package network_test import ( "testing" "time" "github.com/stretchr/testify/suite" + + "github.com/cosmos/cosmos-sdk/testutil/network" ) type IntegrationTestSuite struct { suite.Suite - network *Network + network *network.Network } func (s *IntegrationTestSuite) SetupSuite() { s.T().Log("setting up integration test suite") - s.network = NewTestNetwork(s.T(), DefaultConfig()) + s.network = network.New(s.T(), network.DefaultConfig()) s.Require().NotNil(s.network) _, err := s.network.WaitForHeight(1) diff --git a/testutil/util.go b/testutil/network/util.go similarity index 99% rename from testutil/util.go rename to testutil/network/util.go index c981e52cfedf..9a03a94fde4e 100644 --- a/testutil/util.go +++ b/testutil/network/util.go @@ -1,4 +1,4 @@ -package testutil +package network import ( "path/filepath" diff --git a/version/version_test.go b/version/version_test.go index 12e9deb0b765..9eac0f3b53ab 100644 --- a/version/version_test.go +++ b/version/version_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/libs/cli" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" ) func TestNewInfo(t *testing.T) { @@ -40,7 +40,7 @@ go version go1.14 linux/amd64` func Test_runVersionCmd(t *testing.T) { cmd := NewVersionCommand() - _, mockOut, _ := tests.ApplyMockIO(cmd) + _, mockOut, _ := testutil.ApplyMockIO(cmd) cmd.SetArgs([]string{ fmt.Sprintf("--%s=''", cli.OutputFlag), diff --git a/x/auth/client/cli/broadcast_test.go b/x/auth/client/cli/broadcast_test.go index db8a664212c0..7ddfde4a4ae3 100644 --- a/x/auth/client/cli/broadcast_test.go +++ b/x/auth/client/cli/broadcast_test.go @@ -11,7 +11,7 @@ import ( "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/tests" + "github.com/cosmos/cosmos-sdk/testutil" ) func TestGetBroadcastCommand_OfflineFlag(t *testing.T) { @@ -31,7 +31,7 @@ func TestGetBroadcastCommand_WithoutOfflineFlag(t *testing.T) { clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) cmd := GetBroadcastCommand(clientCtx) - testDir, cleanFunc := tests.NewTestCaseDir(t) + testDir, cleanFunc := testutil.NewTestCaseDir(t) t.Cleanup(cleanFunc) // Create new file with tx diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index eb2403b4f57f..5b0ea986b55f 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -12,6 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/tests/cli" + sdktestutil "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/client/testutil" bankcli "github.com/cosmos/cosmos-sdk/x/bank/client/testutil" @@ -37,7 +38,7 @@ func TestCLIValidateSignatures(t *testing.T) { require.Empty(t, stderr) // write unsigned tx to file - unsignedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + unsignedTxFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // validate we can successfully sign @@ -51,7 +52,7 @@ func TestCLIValidateSignatures(t *testing.T) { require.Equal(t, fooAddr.String(), stdTx.GetSigners()[0].String()) // write signed tx to file - signedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + signedTxFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // validate signatures @@ -61,7 +62,7 @@ func TestCLIValidateSignatures(t *testing.T) { // modify the transaction stdTx.Memo = "MODIFIED-ORIGINAL-TX-BAD" bz := cli.MarshalStdTx(t, f.Cdc, stdTx) - modSignedTxFile, cleanup := tests.WriteToNewTempFile(t, string(bz)) + modSignedTxFile, cleanup := sdktestutil.WriteToNewTempFile(t, string(bz)) t.Cleanup(cleanup) // validate signature validation failure due to different transaction sig bytes @@ -87,7 +88,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 := sdktestutil.WriteToNewTempFile(t, strings.Repeat(generatedStdTx, 3)) t.Cleanup(cleanup1) // sign-batch file - offline is set but account-number and sequence are not @@ -107,7 +108,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 := sdktestutil.WriteToNewTempFile(t, fmt.Sprintf("%smalformed", generatedStdTx)) t.Cleanup(cleanup2) // sign-batch file @@ -165,7 +166,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 := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Test validate-signatures @@ -193,7 +194,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 := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Test validate-signatures @@ -247,7 +248,7 @@ func TestCLIMultisignInsufficientCosigners(t *testing.T) { require.True(t, success) // Write the output to disk - unsignedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + unsignedTxFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Sign with foo's key @@ -255,7 +256,7 @@ func TestCLIMultisignInsufficientCosigners(t *testing.T) { require.True(t, success) // Write the output to disk - fooSignatureFile, cleanup := tests.WriteToNewTempFile(t, stdout) + fooSignatureFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Multisign, not enough signatures @@ -263,7 +264,7 @@ func TestCLIMultisignInsufficientCosigners(t *testing.T) { require.True(t, success) // Write the output to disk - signedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + signedTxFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Validate the multisignature @@ -298,7 +299,7 @@ func TestCLIEncode(t *testing.T) { require.Empty(t, stderr) // Write it to disk - jsonTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + jsonTxFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Run the encode command @@ -336,7 +337,7 @@ func TestCLIMultisignSortSignatures(t *testing.T) { require.True(t, success) // Write the output to disk - unsignedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + unsignedTxFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Sign with foo's key @@ -344,7 +345,7 @@ func TestCLIMultisignSortSignatures(t *testing.T) { require.True(t, success) // Write the output to disk - fooSignatureFile, cleanup := tests.WriteToNewTempFile(t, stdout) + fooSignatureFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Sign with baz's key @@ -352,7 +353,7 @@ func TestCLIMultisignSortSignatures(t *testing.T) { require.True(t, success) // Write the output to disk - bazSignatureFile, cleanup := tests.WriteToNewTempFile(t, stdout) + bazSignatureFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Multisign, keys in different order @@ -361,7 +362,7 @@ func TestCLIMultisignSortSignatures(t *testing.T) { require.True(t, success) // Write the output to disk - signedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + signedTxFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Validate the multisignature @@ -402,7 +403,7 @@ func TestCLIMultisign(t *testing.T) { require.Empty(t, stderr) // Write the output to disk - unsignedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + unsignedTxFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Sign with foo's key @@ -410,7 +411,7 @@ func TestCLIMultisign(t *testing.T) { require.True(t, success) // Write the output to disk - fooSignatureFile, cleanup := tests.WriteToNewTempFile(t, stdout) + fooSignatureFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Sign with bar's key @@ -418,7 +419,7 @@ func TestCLIMultisign(t *testing.T) { require.True(t, success) // Write the output to disk - barSignatureFile, cleanup := tests.WriteToNewTempFile(t, stdout) + barSignatureFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Multisign @@ -435,7 +436,7 @@ func TestCLIMultisign(t *testing.T) { require.True(t, success) // Write the output to disk - signedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) + signedTxFile, cleanup := sdktestutil.WriteToNewTempFile(t, stdout) t.Cleanup(cleanup) // Validate the multisignature diff --git a/x/auth/client/cli/encode_test.go b/x/auth/client/cli/encode_test.go index 65c569db05fd..870b4064cb76 100644 --- a/x/auth/client/cli/encode_test.go +++ b/x/auth/client/cli/encode_test.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -35,7 +35,7 @@ func TestGetCommandEncode(t *testing.T) { JSONEncoded, err := txGen.TxJSONEncoder()(stdTx) require.NoError(t, err) - txFile, cleanup := tests.WriteToNewTempFile(t, string(JSONEncoded)) + txFile, cleanup := testutil.WriteToNewTempFile(t, string(JSONEncoded)) txFileName := txFile.Name() t.Cleanup(cleanup) diff --git a/x/auth/client/tx_test.go b/x/auth/client/tx_test.go index 0bc4f2fbb38a..e5d7fd3088d2 100644 --- a/x/auth/client/tx_test.go +++ b/x/auth/client/tx_test.go @@ -3,12 +3,11 @@ package client import ( "encoding/json" "errors" - "io/ioutil" - "os" "strings" "testing" "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" @@ -139,8 +138,8 @@ func TestReadStdTxFromFile(t *testing.T) { // Write it to the file encodedTx, err := txGen.TxJSONEncoder()(stdTx) require.NoError(t, err) - jsonTxFile := writeToNewTempFile(t, string(encodedTx)) - defer os.Remove(jsonTxFile.Name()) + jsonTxFile, cleanup := testutil.WriteToNewTempFile(t, string(encodedTx)) + t.Cleanup(cleanup) // Read it back decodedTx, err := ReadTxFromFile(clientCtx, jsonTxFile.Name()) @@ -249,16 +248,6 @@ func TestPrepareTxBuilder(t *testing.T) { require.Equal(t, accSeq, bldr.Sequence()) } -func writeToNewTempFile(t *testing.T, data string) *os.File { - fp, err := ioutil.TempFile(os.TempDir(), "client_tx_test") - require.NoError(t, err) - - _, err = fp.WriteString(data) - require.NoError(t, err) - - return fp -} - func makeCodec() *codec.Codec { var cdc = codec.New() sdk.RegisterCodec(cdc) diff --git a/x/bank/client/cli/cli_test.go b/x/bank/client/cli/cli_test.go index 74b9de358cc9..0666b3e754dc 100644 --- a/x/bank/client/cli/cli_test.go +++ b/x/bank/client/cli/cli_test.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/testutil" + "github.com/cosmos/cosmos-sdk/testutil/network" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/bank/client/cli" @@ -20,18 +20,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) diff --git a/x/bank/client/rest/query_test.go b/x/bank/client/rest/query_test.go index d9206c413023..8f9c1241b130 100644 --- a/x/bank/client/rest/query_test.go +++ b/x/bank/client/rest/query_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/suite" - "github.com/cosmos/cosmos-sdk/testutil" + "github.com/cosmos/cosmos-sdk/testutil/network" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" ) @@ -14,18 +14,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) diff --git a/x/bank/client/rest/tx_test.go b/x/bank/client/rest/tx_test.go index 17b394bec06e..d15599d63421 100644 --- a/x/bank/client/rest/tx_test.go +++ b/x/bank/client/rest/tx_test.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/testutil" + "github.com/cosmos/cosmos-sdk/testutil/network" "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/rest" @@ -41,7 +41,7 @@ func (s *IntegrationTestSuite) TestCoinSend() { }, stdTx.GetMsgs()) } -func submitSendReq(val *testutil.Validator, req bankrest.SendReq) (authtypes.StdTx, error) { +func submitSendReq(val *network.Validator, req bankrest.SendReq) (authtypes.StdTx, error) { url := fmt.Sprintf("%s/bank/accounts/%s/transfers", val.APIAddress, val.Address) bz, err := val.ClientCtx.JSONMarshaler.MarshalJSON(req) @@ -83,7 +83,7 @@ func generateSendReq(from authtypes.AccountI, amount types.Coins) bankrest.SendR } } -func getAccountInfo(val *testutil.Validator) (authtypes.AccountI, error) { +func getAccountInfo(val *network.Validator) (authtypes.AccountI, error) { url := fmt.Sprintf("%s/auth/accounts/%s", val.APIAddress, val.Address) resp, err := rest.GetRequest(url) diff --git a/x/crisis/client/cli/cli_test.go b/x/crisis/client/cli/cli_test.go index d3a7a2b9f91a..722ad65e7047 100644 --- a/x/crisis/client/cli/cli_test.go +++ b/x/crisis/client/cli/cli_test.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/testutil" + "github.com/cosmos/cosmos-sdk/testutil/network" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/crisis/client/cli" ) @@ -18,18 +18,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) diff --git a/x/distribution/client/cli/tx_test.go b/x/distribution/client/cli/tx_test.go index 7a00e9720afd..966eb73c61b8 100644 --- a/x/distribution/client/cli/tx_test.go +++ b/x/distribution/client/cli/tx_test.go @@ -1,10 +1,10 @@ package cli import ( - "io/ioutil" "testing" "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil" "github.com/stretchr/testify/require" @@ -64,9 +64,7 @@ func Test_splitAndCall_Splitting(t *testing.T) { func TestParseProposal(t *testing.T) { cdc := codec.New() - okJSON, err := ioutil.TempFile("", "proposal") - require.Nil(t, err, "unexpected error") - _, err = okJSON.WriteString(` + okJSON, cleanup := testutil.WriteToNewTempFile(t, ` { "title": "Community Pool Spend", "description": "Pay me some Atoms!", @@ -75,7 +73,7 @@ func TestParseProposal(t *testing.T) { "deposit": "1000stake" } `) - require.NoError(t, err) + t.Cleanup(cleanup) proposal, err := ParseCommunityPoolSpendProposalJSON(cdc, okJSON.Name()) require.NoError(t, err) diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index d757d4fa5222..79993c8c0638 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -21,7 +21,7 @@ import ( cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/mock" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/genutil" @@ -42,7 +42,7 @@ func createDefaultTendermintConfig(rootDir string) (*tmcfg.Config, error) { } func TestInitCmd(t *testing.T) { - home, cleanup := tests.NewTestCaseDir(t) + home, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) logger := log.NewNopLogger() @@ -63,7 +63,7 @@ func TestInitCmd(t *testing.T) { } func setupClientHome(t *testing.T) func() { - clientDir, cleanup := tests.NewTestCaseDir(t) + clientDir, cleanup := testutil.NewTestCaseDir(t) viper.Set(cli.HomeFlag, clientDir) return cleanup } @@ -71,7 +71,7 @@ func setupClientHome(t *testing.T) func() { func TestEmptyState(t *testing.T) { t.Cleanup(setupClientHome(t)) - home, cleanup := tests.NewTestCaseDir(t) + home, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) logger := log.NewNopLogger() @@ -117,7 +117,7 @@ func TestEmptyState(t *testing.T) { } func TestStartStandAlone(t *testing.T) { - home, cleanup := tests.NewTestCaseDir(t) + home, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) t.Cleanup(setupClientHome(t)) @@ -159,7 +159,7 @@ func TestStartStandAlone(t *testing.T) { } func TestInitNodeValidatorFiles(t *testing.T) { - home, cleanup := tests.NewTestCaseDir(t) + home, cleanup := testutil.NewTestCaseDir(t) cfg, err := createDefaultTendermintConfig(home) t.Cleanup(cleanup) nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(cfg) diff --git a/x/genutil/client/cli/migrate_test.go b/x/genutil/client/cli/migrate_test.go index 5602ddc88e9a..5419a35abe28 100644 --- a/x/genutil/client/cli/migrate_test.go +++ b/x/genutil/client/cli/migrate_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" ) func TestGetMigrationCallback(t *testing.T) { @@ -19,7 +19,7 @@ func TestGetMigrationCallback(t *testing.T) { } func TestMigrateGenesis(t *testing.T) { - home, cleanup := tests.NewTestCaseDir(t) + home, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) cdc := makeCodec() diff --git a/x/genutil/utils_test.go b/x/genutil/utils_test.go index 4c93fbd925a2..bf8cf9f5d0ac 100644 --- a/x/genutil/utils_test.go +++ b/x/genutil/utils_test.go @@ -6,14 +6,14 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" "github.com/stretchr/testify/require" ) func TestExportGenesisFileWithTime(t *testing.T) { t.Parallel() - dir, cleanup := tests.NewTestCaseDir(t) + dir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) fname := filepath.Join(dir, "genesis.json") diff --git a/x/gov/client/cli/parse_test.go b/x/gov/client/cli/parse_test.go index c1e3b108a348..8ac3e70e2fcf 100644 --- a/x/gov/client/cli/parse_test.go +++ b/x/gov/client/cli/parse_test.go @@ -1,18 +1,16 @@ package cli import ( - "io/ioutil" "testing" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/testutil" ) func TestParseSubmitProposalFlags(t *testing.T) { - okJSON, err := ioutil.TempFile("", "proposal") - require.Nil(t, err, "unexpected error") - _, err = okJSON.WriteString(` + okJSON, cleanup1 := testutil.WriteToNewTempFile(t, ` { "title": "Test Proposal", "description": "My awesome proposal", @@ -20,17 +18,16 @@ func TestParseSubmitProposalFlags(t *testing.T) { "deposit": "1000test" } `) - require.NoError(t, err) + t.Cleanup(cleanup1) - badJSON, err := ioutil.TempFile("", "proposal") - require.Nil(t, err, "unexpected error") - badJSON.WriteString("bad json") + badJSON, cleanup2 := testutil.WriteToNewTempFile(t, "bad json") + t.Cleanup(cleanup2) fs := NewCmdSubmitProposal(client.Context{}).Flags() // nonexistent json fs.Set(FlagProposal, "fileDoesNotExist") - _, err = parseSubmitProposalFlags(fs) + _, err := parseSubmitProposalFlags(fs) require.Error(t, err) // invalid json diff --git a/x/params/client/cli/tx_test.go b/x/params/client/cli/tx_test.go index e8973b6ea77e..9eb662bb283a 100644 --- a/x/params/client/cli/tx_test.go +++ b/x/params/client/cli/tx_test.go @@ -1,20 +1,18 @@ package cli import ( - "io/ioutil" "testing" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/x/params/client/utils" ) func TestParseProposal(t *testing.T) { cdc := codec.New() - okJSON, err := ioutil.TempFile("", "proposal") - require.Nil(t, err, "unexpected error") - _, err = okJSON.WriteString(` + okJSON, cleanup := testutil.WriteToNewTempFile(t, ` { "title": "Staking Param Change", "description": "Update max validators", @@ -28,7 +26,7 @@ func TestParseProposal(t *testing.T) { "deposit": "1000stake" } `) - require.NoError(t, err) + t.Cleanup(cleanup) proposal, err := utils.ParseParamChangeProposalJSON(cdc, okJSON.Name()) require.NoError(t, err) diff --git a/x/upgrade/types/storeloader_test.go b/x/upgrade/types/storeloader_test.go index 3280b36e4d05..a77b7593e288 100644 --- a/x/upgrade/types/storeloader_test.go +++ b/x/upgrade/types/storeloader_test.go @@ -15,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/store/rootmulti" store "github.com/cosmos/cosmos-sdk/store/types" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -66,7 +66,7 @@ func checkStore(t *testing.T, db dbm.DB, ver int64, storeKey string, k, v []byte // Test that LoadLatestVersion actually does. func TestSetLoader(t *testing.T) { // set a temporary home dir - homeDir, cleanup := tests.NewTestCaseDir(t) + homeDir, cleanup := testutil.NewTestCaseDir(t) t.Cleanup(cleanup) upgradeInfoFilePath := filepath.Join(homeDir, "upgrade-info.json") From 03fdc9d744246ab0ed47d3c8e46ad4ebcc5eb21f Mon Sep 17 00:00:00 2001 From: colin axner <25233464+colin-axner@users.noreply.github.com> Date: Thu, 9 Jul 2020 18:06:08 +0200 Subject: [PATCH 2/4] x/ibc: update error messages (#6659) * update errors in 02-client * update errors in 03-connection * update 04-channel errors + fixes to 03 changes * update ibc handler errors * tm, commitment, and verify error updates * update ics20 * remove unnecessary wrapping * fix various build issues --- x/ibc-transfer/keeper/relay.go | 2 +- x/ibc-transfer/module.go | 12 ++--- x/ibc-transfer/types/errors.go | 1 + x/ibc/02-client/handler.go | 4 +- x/ibc/02-client/keeper/client.go | 8 ++-- x/ibc/02-client/types/errors.go | 2 +- x/ibc/02-client/types/genesis.go | 6 +-- x/ibc/03-connection/handler.go | 9 ++-- x/ibc/03-connection/keeper/handshake.go | 17 +++---- x/ibc/03-connection/keeper/keeper.go | 2 +- x/ibc/03-connection/keeper/verify.go | 56 +++++++++++++++++------ x/ibc/03-connection/types/connection.go | 6 +-- x/ibc/03-connection/types/genesis.go | 2 +- x/ibc/03-connection/types/msgs.go | 10 ++-- x/ibc/04-channel/handler.go | 13 +++--- x/ibc/04-channel/keeper/handshake.go | 34 +++++++------- x/ibc/04-channel/keeper/packet.go | 20 ++++---- x/ibc/04-channel/keeper/timeout.go | 25 +++++----- x/ibc/04-channel/types/channel.go | 30 ++++-------- x/ibc/04-channel/types/genesis.go | 16 +++---- x/ibc/04-channel/types/packet.go | 20 ++------ x/ibc/07-tendermint/misbehaviour.go | 6 +-- x/ibc/07-tendermint/types/client_state.go | 12 ++--- x/ibc/07-tendermint/types/evidence.go | 2 +- x/ibc/07-tendermint/types/header.go | 2 +- x/ibc/07-tendermint/update.go | 10 ++-- x/ibc/23-commitment/types/merkle.go | 16 ++++--- x/ibc/handler.go | 18 ++++---- 28 files changed, 187 insertions(+), 174 deletions(-) diff --git a/x/ibc-transfer/keeper/relay.go b/x/ibc-transfer/keeper/relay.go index 6477d4467e10..e5b89fe59412 100644 --- a/x/ibc-transfer/keeper/relay.go +++ b/x/ibc-transfer/keeper/relay.go @@ -32,7 +32,7 @@ func (k Keeper) SendTransfer( ) error { sourceChannelEnd, found := k.channelKeeper.GetChannel(ctx, sourcePort, sourceChannel) if !found { - return sdkerrors.Wrap(channeltypes.ErrChannelNotFound, sourceChannel) + return sdkerrors.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", sourcePort, sourceChannel) } destinationPort := sourceChannelEnd.GetCounterparty().GetPortID() diff --git a/x/ibc-transfer/module.go b/x/ibc-transfer/module.go index be57f45614cb..b2a985a43a7d 100644 --- a/x/ibc-transfer/module.go +++ b/x/ibc-transfer/module.go @@ -195,12 +195,12 @@ func (am AppModule) OnChanOpenInit( } if version != types.Version { - return sdkerrors.Wrapf(porttypes.ErrInvalidPort, "invalid version: %s, expected %s", version, "ics20-1") + return sdkerrors.Wrapf(types.ErrInvalidVersion, "got: %s, expected %s", version, types.Version) } // Claim channel capability passed back by IBC module if err := am.keeper.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil { - return sdkerrors.Wrap(channeltypes.ErrChannelCapabilityNotFound, err.Error()) + return err } // TODO: escrow @@ -227,16 +227,16 @@ func (am AppModule) OnChanOpenTry( } if version != types.Version { - return sdkerrors.Wrapf(porttypes.ErrInvalidPort, "invalid version: %s, expected %s", version, "ics20-1") + return sdkerrors.Wrapf(types.ErrInvalidVersion, "got: %s, expected %s", version, types.Version) } if counterpartyVersion != types.Version { - return sdkerrors.Wrapf(porttypes.ErrInvalidPort, "invalid counterparty version: %s, expected %s", counterpartyVersion, "ics20-1") + return sdkerrors.Wrapf(types.ErrInvalidVersion, "invalid counterparty version: got: %s, expected %s", counterpartyVersion, types.Version) } // Claim channel capability passed back by IBC module if err := am.keeper.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil { - return sdkerrors.Wrap(channeltypes.ErrChannelCapabilityNotFound, err.Error()) + return err } // TODO: escrow @@ -250,7 +250,7 @@ func (am AppModule) OnChanOpenAck( counterpartyVersion string, ) error { if counterpartyVersion != types.Version { - return sdkerrors.Wrapf(porttypes.ErrInvalidPort, "invalid counterparty version: %s, expected %s", counterpartyVersion, "ics20-1") + return sdkerrors.Wrapf(types.ErrInvalidVersion, "invalid counterparty version: %s, expected %s", counterpartyVersion, types.Version) } return nil } diff --git a/x/ibc-transfer/types/errors.go b/x/ibc-transfer/types/errors.go index e46c023e4cb7..a2d391f9e745 100644 --- a/x/ibc-transfer/types/errors.go +++ b/x/ibc-transfer/types/errors.go @@ -9,4 +9,5 @@ var ( ErrInvalidPacketTimeout = sdkerrors.Register(ModuleName, 2, "invalid packet timeout") ErrOnlyOneDenomAllowed = sdkerrors.Register(ModuleName, 3, "only one denom allowed") ErrInvalidDenomForTransfer = sdkerrors.Register(ModuleName, 4, "invalid denomination for cross-chain transfer") + ErrInvalidVersion = sdkerrors.Register(ModuleName, 5, "invalid version") ) diff --git a/x/ibc/02-client/handler.go b/x/ibc/02-client/handler.go index 8e36d3c8f3ca..99e3a4daf33b 100644 --- a/x/ibc/02-client/handler.go +++ b/x/ibc/02-client/handler.go @@ -27,7 +27,7 @@ func HandleMsgCreateClient(ctx sdk.Context, k keeper.Keeper, msg exported.MsgCre case exported.Tendermint: tmMsg, ok := msg.(ibctmtypes.MsgCreateClient) if !ok { - return nil, sdkerrors.Wrap(types.ErrInvalidClientType, "Msg is not a Tendermint CreateClient msg") + return nil, sdkerrors.Wrapf(types.ErrInvalidClientType, "got %T, expected %T", msg, ibctmtypes.MsgCreateClient{}) } var err error @@ -41,7 +41,7 @@ func HandleMsgCreateClient(ctx sdk.Context, k keeper.Keeper, msg exported.MsgCre clientState = localhosttypes.NewClientState(ctx.ChainID(), ctx.BlockHeight()) consensusHeight = uint64(ctx.BlockHeight()) default: - return nil, sdkerrors.Wrap(types.ErrInvalidClientType, msg.GetClientType()) + return nil, sdkerrors.Wrapf(types.ErrInvalidClientType, "unsupported client type (%s)", msg.GetClientType()) } _, err := k.CreateClient( diff --git a/x/ibc/02-client/keeper/client.go b/x/ibc/02-client/keeper/client.go index 871d61516e00..81f0e0a45373 100644 --- a/x/ibc/02-client/keeper/client.go +++ b/x/ibc/02-client/keeper/client.go @@ -51,7 +51,7 @@ func (k Keeper) UpdateClient(ctx sdk.Context, clientID string, header exported.H // check that the header consensus matches the client one // NOTE: not checked for localhost client if header != nil && clientType != exported.Localhost && header.ClientType() != clientType { - return nil, sdkerrors.Wrapf(types.ErrInvalidConsensus, "cannot update client with ID %s", clientID) + return nil, sdkerrors.Wrapf(types.ErrInvalidHeader, "header client type (%s) does not match expected client type (%s) for client with ID %s", header.ClientType(), clientType, clientID) } clientState, found := k.GetClientState(ctx, clientID) @@ -59,7 +59,7 @@ func (k Keeper) UpdateClient(ctx sdk.Context, clientID string, header exported.H return nil, sdkerrors.Wrapf(types.ErrClientNotFound, "cannot update client with ID %s", clientID) } - // addittion to spec: prevent update if the client is frozen + // addition to spec: prevent update if the client is frozen if clientState.IsFrozen() { return nil, sdkerrors.Wrapf(types.ErrClientFrozen, "cannot update client with ID %s", clientID) } @@ -128,12 +128,12 @@ func (k Keeper) UpdateClient(ctx sdk.Context, clientID string, header exported.H func (k Keeper) CheckMisbehaviourAndUpdateState(ctx sdk.Context, misbehaviour exported.Misbehaviour) error { clientState, found := k.GetClientState(ctx, misbehaviour.GetClientID()) if !found { - return sdkerrors.Wrap(types.ErrClientNotFound, misbehaviour.GetClientID()) + return sdkerrors.Wrapf(types.ErrClientNotFound, "cannot check misbehaviour for client with ID %s", misbehaviour.GetClientID()) } consensusState, found := k.GetClientConsensusStateLTE(ctx, misbehaviour.GetClientID(), uint64(misbehaviour.GetHeight())) if !found { - return sdkerrors.Wrap(types.ErrConsensusStateNotFound, misbehaviour.GetClientID()) + return sdkerrors.Wrapf(types.ErrConsensusStateNotFound, "cannot check misbehaviour for client with ID %s", misbehaviour.GetClientID()) } var err error diff --git a/x/ibc/02-client/types/errors.go b/x/ibc/02-client/types/errors.go index 6d1f3e05a91e..4efd701212e4 100644 --- a/x/ibc/02-client/types/errors.go +++ b/x/ibc/02-client/types/errors.go @@ -14,7 +14,7 @@ var ( ErrClientTypeNotFound = sdkerrors.Register(SubModuleName, 7, "client type not found") ErrInvalidClientType = sdkerrors.Register(SubModuleName, 8, "invalid client type") ErrRootNotFound = sdkerrors.Register(SubModuleName, 9, "commitment root not found") - ErrInvalidHeader = sdkerrors.Register(SubModuleName, 10, "invalid block header") + ErrInvalidHeader = sdkerrors.Register(SubModuleName, 10, "invalid client header") ErrInvalidEvidence = sdkerrors.Register(SubModuleName, 11, "invalid light client misbehaviour evidence") ErrFailedClientConsensusStateVerification = sdkerrors.Register(SubModuleName, 12, "client consensus state verification failed") ErrFailedConnectionStateVerification = sdkerrors.Register(SubModuleName, 13, "connection state verification failed") diff --git a/x/ibc/02-client/types/genesis.go b/x/ibc/02-client/types/genesis.go index 38343a8cf6ea..74a584f10391 100644 --- a/x/ibc/02-client/types/genesis.go +++ b/x/ibc/02-client/types/genesis.go @@ -53,17 +53,17 @@ func DefaultGenesisState() GenesisState { func (gs GenesisState) Validate() error { for i, client := range gs.Clients { if err := client.Validate(); err != nil { - return fmt.Errorf("invalid client %d: %w", i, err) + return fmt.Errorf("invalid client %v index %d: %w", client, i, err) } } for i, cs := range gs.ClientsConsensus { if err := host.ClientIdentifierValidator(cs.ClientID); err != nil { - return fmt.Errorf("invalid client consensus state %d: %w", i, err) + return fmt.Errorf("invalid client consensus state identifier %s index %d: %w", cs.ClientID, i, err) } for _, consensusState := range cs.ConsensusStates { if err := consensusState.ValidateBasic(); err != nil { - return fmt.Errorf("invalid client consensus state %d: %w", i, err) + return fmt.Errorf("invalid client consensus state %v index %d: %w", consensusState, i, err) } } } diff --git a/x/ibc/03-connection/handler.go b/x/ibc/03-connection/handler.go index 86d597252077..e2d589cd913a 100644 --- a/x/ibc/03-connection/handler.go +++ b/x/ibc/03-connection/handler.go @@ -2,6 +2,7 @@ package connection import ( sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/ibc/03-connection/keeper" "github.com/cosmos/cosmos-sdk/x/ibc/03-connection/types" ) @@ -11,7 +12,7 @@ func HandleMsgConnectionOpenInit(ctx sdk.Context, k keeper.Keeper, msg *types.Ms if err := k.ConnOpenInit( ctx, msg.ConnectionID, msg.ClientID, msg.Counterparty, ); err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "connection handshake open init failed") } ctx.EventManager().EmitEvents(sdk.Events{ @@ -40,7 +41,7 @@ func HandleMsgConnectionOpenTry(ctx sdk.Context, k keeper.Keeper, msg *types.Msg msg.CounterpartyVersions, msg.ProofInit, msg.ProofConsensus, msg.ProofHeight, msg.ConsensusHeight, ); err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "connection handshake open try failed") } ctx.EventManager().EmitEvents(sdk.Events{ @@ -68,7 +69,7 @@ func HandleMsgConnectionOpenAck(ctx sdk.Context, k keeper.Keeper, msg *types.Msg ctx, msg.ConnectionID, msg.Version, msg.ProofTry, msg.ProofConsensus, msg.ProofHeight, msg.ConsensusHeight, ); err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "connection handshake open ack failed") } connectionEnd, _ := k.GetConnection(ctx, msg.ConnectionID) @@ -97,7 +98,7 @@ func HandleMsgConnectionOpenConfirm(ctx sdk.Context, k keeper.Keeper, msg *types if err := k.ConnOpenConfirm( ctx, msg.ConnectionID, msg.ProofAck, msg.ProofHeight, ); err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "connection handshake open confirm failed") } connectionEnd, _ := k.GetConnection(ctx, msg.ConnectionID) diff --git a/x/ibc/03-connection/keeper/handshake.go b/x/ibc/03-connection/keeper/handshake.go index 87806939b630..4d8bf9f31bef 100644 --- a/x/ibc/03-connection/keeper/handshake.go +++ b/x/ibc/03-connection/keeper/handshake.go @@ -22,7 +22,7 @@ func (k Keeper) ConnOpenInit( ) error { _, found := k.GetConnection(ctx, connectionID) if found { - return sdkerrors.Wrap(types.ErrConnectionExists, "cannot initialize connection") + return types.ErrConnectionExists } // connection defines chain A's ConnectionEnd @@ -30,7 +30,7 @@ func (k Keeper) ConnOpenInit( k.SetConnection(ctx, connectionID, connection) if err := k.addConnectionToClient(ctx, clientID, connectionID); err != nil { - return sdkerrors.Wrap(err, "cannot initialize connection") + return err } k.Logger(ctx).Info(fmt.Sprintf("connection %s state updated: NONE -> INIT", connectionID)) @@ -113,11 +113,11 @@ func (k Keeper) ConnOpenTry( // Set connection state to TRYOPEN and store in chainB state connection.State = types.TRYOPEN if err := k.addConnectionToClient(ctx, clientID, connectionID); err != nil { - return sdkerrors.Wrap(err, "cannot relay connection attempt") + return sdkerrors.Wrapf(err, "failed to add connection with ID %s to client with ID %s", connectionID, clientID) } k.SetConnection(ctx, connectionID, connection) - k.Logger(ctx).Info(fmt.Sprintf("connection %s state updated: NONE -> TRYOPEN ", connectionID)) + k.Logger(ctx).Info(fmt.Sprintf("connection %s state updated: %s -> TRYOPEN ", connectionID, previousConnection.State)) return nil } @@ -145,14 +145,14 @@ func (k Keeper) ConnOpenAck( // Retrieve connection connection, found := k.GetConnection(ctx, connectionID) if !found { - return sdkerrors.Wrap(types.ErrConnectionNotFound, "cannot relay ACK of open attempt") + return sdkerrors.Wrap(types.ErrConnectionNotFound, connectionID) } // Check connection on ChainA is on correct state: INIT or TRYOPEN if connection.State != types.INIT && connection.State != types.TRYOPEN { return sdkerrors.Wrapf( types.ErrInvalidConnectionState, - "connection state is not INIT (got %s)", connection.State.String(), + "connection state is not INIT or TRYOPEN (got %s)", connection.State.String(), ) } @@ -198,11 +198,12 @@ func (k Keeper) ConnOpenAck( return err } + k.Logger(ctx).Info(fmt.Sprintf("connection %s state updated: %s -> OPEN ", connectionID, connection.State)) + // Update connection state to Open connection.State = types.OPEN connection.Versions = []string{version} k.SetConnection(ctx, connectionID, connection) - k.Logger(ctx).Info(fmt.Sprintf("connection %s state updated: INIT -> OPEN ", connectionID)) return nil } @@ -219,7 +220,7 @@ func (k Keeper) ConnOpenConfirm( // Retrieve connection connection, found := k.GetConnection(ctx, connectionID) if !found { - return sdkerrors.Wrap(types.ErrConnectionNotFound, "cannot relay ACK of open attempt") + return sdkerrors.Wrap(types.ErrConnectionNotFound, connectionID) } // Check that connection state on ChainB is on state: TRYOPEN diff --git a/x/ibc/03-connection/keeper/keeper.go b/x/ibc/03-connection/keeper/keeper.go index ed0a28dccc99..a8373a97f17f 100644 --- a/x/ibc/03-connection/keeper/keeper.go +++ b/x/ibc/03-connection/keeper/keeper.go @@ -159,7 +159,7 @@ func (k Keeper) GetAllConnections(ctx sdk.Context) (connections []types.Connecti func (k Keeper) addConnectionToClient(ctx sdk.Context, clientID, connectionID string) error { _, found := k.clientKeeper.GetClientState(ctx, clientID) if !found { - return clienttypes.ErrClientNotFound + return sdkerrors.Wrap(clienttypes.ErrClientNotFound, clientID) } conns, found := k.GetClientConnectionPaths(ctx, clientID) diff --git a/x/ibc/03-connection/keeper/verify.go b/x/ibc/03-connection/keeper/verify.go index 2a578cc2ad5c..2676fec547ac 100644 --- a/x/ibc/03-connection/keeper/verify.go +++ b/x/ibc/03-connection/keeper/verify.go @@ -30,10 +30,14 @@ func (k Keeper) VerifyClientConsensusState( return sdkerrors.Wrapf(clienttypes.ErrConsensusStateNotFound, "clientID: %s with height: %d", clientID, height) } - return clientState.VerifyClientConsensusState( + if err := clientState.VerifyClientConsensusState( k.clientKeeper.ClientStore(ctx, clientID), k.cdc, k.aminoCdc, targetConsState.GetRoot(), height, connection.GetCounterparty().GetClientID(), consensusHeight, connection.GetCounterparty().GetPrefix(), proof, consensusState, - ) + ); err != nil { + return sdkerrors.Wrap(err, "failed consensus state verification") + } + + return nil } // VerifyConnectionState verifies a proof of the connection state of the @@ -62,10 +66,14 @@ func (k Keeper) VerifyConnectionState( ) } - return clientState.VerifyConnectionState( + if err := clientState.VerifyConnectionState( k.clientKeeper.ClientStore(ctx, connection.GetClientID()), k.cdc, height, connection.GetCounterparty().GetPrefix(), proof, connectionID, connectionEnd, consensusState, - ) + ); err != nil { + return sdkerrors.Wrap(err, "failed connection state verification") + } + + return nil } // VerifyChannelState verifies a proof of the channel state of the specified @@ -95,11 +103,15 @@ func (k Keeper) VerifyChannelState( ) } - return clientState.VerifyChannelState( + if err := clientState.VerifyChannelState( k.clientKeeper.ClientStore(ctx, connection.GetClientID()), k.cdc, height, connection.GetCounterparty().GetPrefix(), proof, portID, channelID, channel, consensusState, - ) + ); err != nil { + return sdkerrors.Wrap(err, "failed channel state verification") + } + + return nil } // VerifyPacketCommitment verifies a proof of an outgoing packet commitment at @@ -130,11 +142,15 @@ func (k Keeper) VerifyPacketCommitment( ) } - return clientState.VerifyPacketCommitment( + if err := clientState.VerifyPacketCommitment( k.clientKeeper.ClientStore(ctx, connection.GetClientID()), k.cdc, height, connection.GetCounterparty().GetPrefix(), proof, portID, channelID, sequence, commitmentBytes, consensusState, - ) + ); err != nil { + return sdkerrors.Wrap(err, "failed packet commitment verification") + } + + return nil } // VerifyPacketAcknowledgement verifies a proof of an incoming packet @@ -165,11 +181,15 @@ func (k Keeper) VerifyPacketAcknowledgement( ) } - return clientState.VerifyPacketAcknowledgement( + if err := clientState.VerifyPacketAcknowledgement( k.clientKeeper.ClientStore(ctx, connection.GetClientID()), k.cdc, height, connection.GetCounterparty().GetPrefix(), proof, portID, channelID, sequence, acknowledgement, consensusState, - ) + ); err != nil { + return sdkerrors.Wrap(err, "failed packet acknowledgement verification") + } + + return nil } // VerifyPacketAcknowledgementAbsence verifies a proof of the absence of an @@ -200,11 +220,15 @@ func (k Keeper) VerifyPacketAcknowledgementAbsence( ) } - return clientState.VerifyPacketAcknowledgementAbsence( + if err := clientState.VerifyPacketAcknowledgementAbsence( k.clientKeeper.ClientStore(ctx, connection.GetClientID()), k.cdc, height, connection.GetCounterparty().GetPrefix(), proof, portID, channelID, sequence, consensusState, - ) + ); err != nil { + return sdkerrors.Wrap(err, "failed packet acknowledgement absence verification") + } + + return nil } // VerifyNextSequenceRecv verifies a proof of the next sequence number to be @@ -234,9 +258,13 @@ func (k Keeper) VerifyNextSequenceRecv( ) } - return clientState.VerifyNextSequenceRecv( + if err := clientState.VerifyNextSequenceRecv( k.clientKeeper.ClientStore(ctx, connection.GetClientID()), k.cdc, height, connection.GetCounterparty().GetPrefix(), proof, portID, channelID, nextSequenceRecv, consensusState, - ) + ); err != nil { + return sdkerrors.Wrap(err, "failed next sequence receive verification") + } + + return nil } diff --git a/x/ibc/03-connection/types/connection.go b/x/ibc/03-connection/types/connection.go index 1abb34d68795..3a07f0be2c7c 100644 --- a/x/ibc/03-connection/types/connection.go +++ b/x/ibc/03-connection/types/connection.go @@ -51,13 +51,13 @@ func (c ConnectionEnd) GetVersions() []string { // counterparty's. func (c ConnectionEnd) ValidateBasic() error { if err := host.ConnectionIdentifierValidator(c.ID); err != nil { - return sdkerrors.Wrapf(err, "invalid connection ID: %s", c.ID) + return sdkerrors.Wrap(err, "invalid connection ID") } if err := host.ClientIdentifierValidator(c.ClientID); err != nil { - return sdkerrors.Wrapf(err, "invalid client ID: %s", c.ClientID) + return sdkerrors.Wrap(err, "invalid client ID") } if len(c.Versions) == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidVersion, "missing connection versions") + return sdkerrors.Wrap(sdkerrors.ErrInvalidVersion, "empty connection versions") } for _, version := range c.Versions { if err := host.ConnectionVersionValidator(version); err != nil { diff --git a/x/ibc/03-connection/types/genesis.go b/x/ibc/03-connection/types/genesis.go index 9eef1ca04bd7..31d881a62a82 100644 --- a/x/ibc/03-connection/types/genesis.go +++ b/x/ibc/03-connection/types/genesis.go @@ -43,7 +43,7 @@ func DefaultGenesisState() GenesisState { func (gs GenesisState) Validate() error { for i, conn := range gs.Connections { if err := conn.ValidateBasic(); err != nil { - return fmt.Errorf("invalid connection %d: %w", i, err) + return fmt.Errorf("invalid connection %v index %d: %w", conn, i, err) } } diff --git a/x/ibc/03-connection/types/msgs.go b/x/ibc/03-connection/types/msgs.go index 59bc9cdf52da..9b03709cb9ec 100644 --- a/x/ibc/03-connection/types/msgs.go +++ b/x/ibc/03-connection/types/msgs.go @@ -37,10 +37,10 @@ func (msg MsgConnectionOpenInit) Type() string { // ValidateBasic implements sdk.Msg func (msg MsgConnectionOpenInit) ValidateBasic() error { if err := host.ConnectionIdentifierValidator(msg.ConnectionID); err != nil { - return sdkerrors.Wrapf(err, "invalid connection ID: %s", msg.ConnectionID) + return sdkerrors.Wrap(err, "invalid connection ID") } if err := host.ClientIdentifierValidator(msg.ClientID); err != nil { - return sdkerrors.Wrapf(err, "invalid client ID: %s", msg.ClientID) + return sdkerrors.Wrap(err, "invalid client ID") } if msg.Signer.Empty() { return sdkerrors.ErrInvalidAddress @@ -94,13 +94,13 @@ func (msg MsgConnectionOpenTry) Type() string { // ValidateBasic implements sdk.Msg func (msg MsgConnectionOpenTry) ValidateBasic() error { if err := host.ConnectionIdentifierValidator(msg.ConnectionID); err != nil { - return sdkerrors.Wrapf(err, "invalid connection ID: %s", msg.ConnectionID) + return sdkerrors.Wrap(err, "invalid connection ID") } if err := host.ClientIdentifierValidator(msg.ClientID); err != nil { - return sdkerrors.Wrapf(err, "invalid client ID: %s", msg.ClientID) + return sdkerrors.Wrap(err, "invalid client ID") } if len(msg.CounterpartyVersions) == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidVersion, "missing counterparty versions") + return sdkerrors.Wrap(sdkerrors.ErrInvalidVersion, "empty counterparty versions") } for _, version := range msg.CounterpartyVersions { if err := host.ConnectionVersionValidator(version); err != nil { diff --git a/x/ibc/04-channel/handler.go b/x/ibc/04-channel/handler.go index b9f235d306ba..a21838e40171 100644 --- a/x/ibc/04-channel/handler.go +++ b/x/ibc/04-channel/handler.go @@ -4,6 +4,7 @@ import ( "strings" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/keeper" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/types" @@ -16,7 +17,7 @@ func HandleMsgChannelOpenInit(ctx sdk.Context, k keeper.Keeper, portCap *capabil portCap, msg.Channel.Counterparty, msg.Channel.Version, ) if err != nil { - return nil, nil, err + return nil, nil, sdkerrors.Wrap(err, "channel handshake open init failed") } ctx.EventManager().EmitEvents(sdk.Events{ @@ -45,7 +46,7 @@ func HandleMsgChannelOpenTry(ctx sdk.Context, k keeper.Keeper, portCap *capabili portCap, msg.Channel.Counterparty, msg.Channel.Version, msg.CounterpartyVersion, msg.ProofInit, msg.ProofHeight, ) if err != nil { - return nil, nil, err + return nil, nil, sdkerrors.Wrap(err, "channel handshake open try failed") } ctx.EventManager().EmitEvents(sdk.Events{ @@ -74,7 +75,7 @@ func HandleMsgChannelOpenAck(ctx sdk.Context, k keeper.Keeper, channelCap *capab ctx, msg.PortID, msg.ChannelID, channelCap, msg.CounterpartyVersion, msg.ProofTry, msg.ProofHeight, ) if err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "channel handshake open ack failed") } channel, _ := k.GetChannel(ctx, msg.PortID, msg.ChannelID) @@ -103,7 +104,7 @@ func HandleMsgChannelOpenAck(ctx sdk.Context, k keeper.Keeper, channelCap *capab func HandleMsgChannelOpenConfirm(ctx sdk.Context, k keeper.Keeper, channelCap *capabilitytypes.Capability, msg *types.MsgChannelOpenConfirm) (*sdk.Result, error) { err := k.ChanOpenConfirm(ctx, msg.PortID, msg.ChannelID, channelCap, msg.ProofAck, msg.ProofHeight) if err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "channel handshake open confirm failed") } channel, _ := k.GetChannel(ctx, msg.PortID, msg.ChannelID) @@ -132,7 +133,7 @@ func HandleMsgChannelOpenConfirm(ctx sdk.Context, k keeper.Keeper, channelCap *c func HandleMsgChannelCloseInit(ctx sdk.Context, k keeper.Keeper, channelCap *capabilitytypes.Capability, msg *types.MsgChannelCloseInit) (*sdk.Result, error) { err := k.ChanCloseInit(ctx, msg.PortID, msg.ChannelID, channelCap) if err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "channel handshake close init failed") } channel, _ := k.GetChannel(ctx, msg.PortID, msg.ChannelID) @@ -161,7 +162,7 @@ func HandleMsgChannelCloseInit(ctx sdk.Context, k keeper.Keeper, channelCap *cap func HandleMsgChannelCloseConfirm(ctx sdk.Context, k keeper.Keeper, channelCap *capabilitytypes.Capability, msg *types.MsgChannelCloseConfirm) (*sdk.Result, error) { err := k.ChanCloseConfirm(ctx, msg.PortID, msg.ChannelID, channelCap, msg.ProofInit, msg.ProofHeight) if err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "channel handshake close confirm failed") } channel, _ := k.GetChannel(ctx, msg.PortID, msg.ChannelID) diff --git a/x/ibc/04-channel/keeper/handshake.go b/x/ibc/04-channel/keeper/handshake.go index 4288f1bd2f81..c2960c209945 100644 --- a/x/ibc/04-channel/keeper/handshake.go +++ b/x/ibc/04-channel/keeper/handshake.go @@ -44,7 +44,7 @@ func (k Keeper) ChanOpenInit( // channel identifier and connection hop length checked on msg.ValidateBasic() _, found := k.GetChannel(ctx, portID, channelID) if found { - return nil, sdkerrors.Wrap(types.ErrChannelExists, channelID) + return nil, sdkerrors.Wrapf(types.ErrChannelExists, "port ID (%s) channel ID (%s)", portID, channelID) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, connectionHops[0]) @@ -53,10 +53,7 @@ func (k Keeper) ChanOpenInit( } if connectionEnd.GetState() == int32(connectiontypes.UNINITIALIZED) { - return nil, sdkerrors.Wrap( - connectiontypes.ErrInvalidConnectionState, - "connection state cannot be UNINITIALIZED", - ) + return nil, connectiontypes.ErrInvalidConnectionState } if len(connectionEnd.GetVersions()) != 1 { @@ -76,7 +73,7 @@ func (k Keeper) ChanOpenInit( } if !k.portKeeper.Authenticate(ctx, portCap, portID) { - return nil, sdkerrors.Wrap(porttypes.ErrInvalidPort, "caller does not own port capability") + return nil, sdkerrors.Wrapf(porttypes.ErrInvalidPort, "caller does not own port capability for port ID %s", portID) } channel := types.NewChannel(types.INIT, order, counterparty, connectionHops, version) @@ -84,7 +81,7 @@ func (k Keeper) ChanOpenInit( capKey, err := k.scopedKeeper.NewCapability(ctx, host.ChannelCapabilityPath(portID, channelID)) if err != nil { - return nil, sdkerrors.Wrap(types.ErrInvalidChannelCapability, err.Error()) + return nil, sdkerrors.Wrapf(err, "could not create channel capability for port ID %s and channel ID %s", portID, channelID) } k.SetNextSequenceSend(ctx, portID, channelID, 1) @@ -122,7 +119,7 @@ func (k Keeper) ChanOpenTry( } if !k.portKeeper.Authenticate(ctx, portCap, portID) { - return nil, sdkerrors.Wrap(porttypes.ErrInvalidPort, "caller does not own port capability") + return nil, sdkerrors.Wrapf(porttypes.ErrInvalidPort, "caller does not own port capability for port ID %s", portID) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, connectionHops[0]) @@ -182,7 +179,7 @@ func (k Keeper) ChanOpenTry( capKey, err := k.scopedKeeper.NewCapability(ctx, host.ChannelCapabilityPath(portID, channelID)) if err != nil { - return nil, sdkerrors.Wrap(types.ErrInvalidChannelCapability, err.Error()) + return nil, sdkerrors.Wrapf(err, "could not create channel capability for port ID %s and channel ID %s", portID, channelID) } k.SetNextSequenceSend(ctx, portID, channelID, 1) @@ -206,7 +203,7 @@ func (k Keeper) ChanOpenAck( ) error { channel, found := k.GetChannel(ctx, portID, channelID) if !found { - return sdkerrors.Wrap(types.ErrChannelNotFound, channelID) + return sdkerrors.Wrapf(types.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) } if !(channel.State == types.INIT || channel.State == types.TRYOPEN) { @@ -217,7 +214,7 @@ func (k Keeper) ChanOpenAck( } if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)) { - return sdkerrors.Wrap(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel") + return sdkerrors.Wrapf(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel, port ID (%s) channel ID (%s)", portID, channelID) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) @@ -253,11 +250,12 @@ func (k Keeper) ChanOpenAck( return err } + k.Logger(ctx).Info(fmt.Sprintf("channel (port-id: %s, channel-id: %s) state updated: %s -> OPEN", portID, channelID, channel.State)) + channel.State = types.OPEN channel.Version = counterpartyVersion k.SetChannel(ctx, portID, channelID, channel) - k.Logger(ctx).Info(fmt.Sprintf("channel (port-id: %s, channel-id: %s) state updated: INIT -> OPEN", portID, channelID)) return nil } @@ -273,7 +271,7 @@ func (k Keeper) ChanOpenConfirm( ) error { channel, found := k.GetChannel(ctx, portID, channelID) if !found { - return sdkerrors.Wrap(types.ErrChannelNotFound, channelID) + return sdkerrors.Wrapf(types.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) } if channel.State != types.TRYOPEN { @@ -284,7 +282,7 @@ func (k Keeper) ChanOpenConfirm( } if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)) { - return sdkerrors.Wrap(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel") + return sdkerrors.Wrapf(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel, port ID (%s) channel ID (%s)", portID, channelID) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) @@ -340,12 +338,12 @@ func (k Keeper) ChanCloseInit( chanCap *capabilitytypes.Capability, ) error { if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)) { - return sdkerrors.Wrap(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel") + return sdkerrors.Wrapf(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel, port ID (%s) channel ID (%s)", portID, channelID) } channel, found := k.GetChannel(ctx, portID, channelID) if !found { - return sdkerrors.Wrap(types.ErrChannelNotFound, channelID) + return sdkerrors.Wrapf(types.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) } if channel.State == types.CLOSED { @@ -383,12 +381,12 @@ func (k Keeper) ChanCloseConfirm( proofHeight uint64, ) error { if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)) { - return sdkerrors.Wrap(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel") + return sdkerrors.Wrap(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel, port ID (%s) channel ID (%s)") } channel, found := k.GetChannel(ctx, portID, channelID) if !found { - return sdkerrors.Wrap(types.ErrChannelNotFound, channelID) + return sdkerrors.Wrapf(types.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) } if channel.State == types.CLOSED { diff --git a/x/ibc/04-channel/keeper/packet.go b/x/ibc/04-channel/keeper/packet.go index 338911eccd0b..49fce70c4c5f 100644 --- a/x/ibc/04-channel/keeper/packet.go +++ b/x/ibc/04-channel/keeper/packet.go @@ -24,7 +24,7 @@ func (k Keeper) SendPacket( packet exported.PacketI, ) error { if err := packet.ValidateBasic(); err != nil { - return err + return sdkerrors.Wrap(err, "packet failed basic validation") } channel, found := k.GetChannel(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) @@ -40,7 +40,7 @@ func (k Keeper) SendPacket( } if !k.scopedKeeper.AuthenticateCapability(ctx, channelCap, host.ChannelCapabilityPath(packet.GetSourcePort(), packet.GetSourceChannel())) { - return sdkerrors.Wrap(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel") + return sdkerrors.Wrapf(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel, port ID (%s) channel ID (%s)", packet.GetSourcePort(), packet.GetSourceChannel()) } if packet.GetDestPort() != channel.Counterparty.PortID { @@ -267,9 +267,9 @@ func (k Keeper) PacketExecuted( capName := host.ChannelCapabilityPath(packet.GetDestPort(), packet.GetDestChannel()) if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, capName) { - return sdkerrors.Wrap( + return sdkerrors.Wrapf( types.ErrInvalidChannelCapability, - "channel capability failed authentication", + "channel capability failed authentication for capability name %s", capName, ) } @@ -336,7 +336,7 @@ func (k Keeper) AcknowledgePacket( if !found { return sdkerrors.Wrapf( types.ErrChannelNotFound, - packet.GetSourcePort(), packet.GetSourceChannel(), + "port ID (%s) channel ID (%s)", packet.GetSourcePort(), packet.GetSourceChannel(), ) } @@ -381,14 +381,14 @@ func (k Keeper) AcknowledgePacket( // verify we sent the packet and haven't cleared it out yet if !bytes.Equal(commitment, types.CommitPacket(packet)) { - return sdkerrors.Wrap(types.ErrInvalidPacket, "packet hasn't been sent") + return sdkerrors.Wrapf(types.ErrInvalidPacket, "commitment bytes are not equal: got (%v), expected (%v)", types.CommitPacket(packet), commitment) } if err := k.connectionKeeper.VerifyPacketAcknowledgement( ctx, connectionEnd, proofHeight, proof, packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence(), acknowledgement, ); err != nil { - return sdkerrors.Wrap(err, "invalid acknowledgement on counterparty chain") + return sdkerrors.Wrap(err, "packet acknowledgement verification failed") } // assert packets acknowledged in order @@ -426,15 +426,15 @@ func (k Keeper) AcknowledgementExecuted( if !found { return sdkerrors.Wrapf( types.ErrChannelNotFound, - packet.GetSourcePort(), packet.GetSourceChannel(), + "port ID (%s) channel ID (%s)", packet.GetSourcePort(), packet.GetSourceChannel(), ) } capName := host.ChannelCapabilityPath(packet.GetSourcePort(), packet.GetSourceChannel()) if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, capName) { - return sdkerrors.Wrap( + return sdkerrors.Wrapf( types.ErrInvalidChannelCapability, - "channel capability failed authentication", + "channel capability failed authentication for capability name %s", capName, ) } diff --git a/x/ibc/04-channel/keeper/timeout.go b/x/ibc/04-channel/keeper/timeout.go index ac40c66cdefd..917e1f9d2464 100644 --- a/x/ibc/04-channel/keeper/timeout.go +++ b/x/ibc/04-channel/keeper/timeout.go @@ -30,7 +30,7 @@ func (k Keeper) TimeoutPacket( if !found { return sdkerrors.Wrapf( types.ErrChannelNotFound, - packet.GetSourcePort(), packet.GetSourceChannel(), + "port ID (%s) channel ID (%s)", packet.GetSourcePort(), packet.GetSourceChannel(), ) } @@ -81,14 +81,17 @@ func (k Keeper) TimeoutPacket( // verify we sent the packet and haven't cleared it out yet if !bytes.Equal(commitment, types.CommitPacket(packet)) { - return sdkerrors.Wrap(types.ErrInvalidPacket, "packet hasn't been sent") + return sdkerrors.Wrapf(types.ErrInvalidPacket, "packet commitment bytes are not equal: got (%v), expected (%v)", commitment, types.CommitPacket(packet)) } switch channel.Ordering { case types.ORDERED: // check that packet has not been received if nextSequenceRecv > packet.GetSequence() { - return sdkerrors.Wrap(types.ErrInvalidPacket, "packet already received") + return sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet already received, next sequence receive > packet sequence (%d > %d)", nextSequenceRecv, packet.GetSequence(), + ) } // check that the recv sequence is as claimed @@ -124,14 +127,14 @@ func (k Keeper) TimeoutExecuted( ) error { channel, found := k.GetChannel(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) if !found { - return sdkerrors.Wrapf(types.ErrChannelNotFound, packet.GetSourcePort(), packet.GetSourceChannel()) + return sdkerrors.Wrapf(types.ErrChannelNotFound, "port ID (%s) channel ID (%s)", packet.GetSourcePort(), packet.GetSourceChannel()) } capName := host.ChannelCapabilityPath(packet.GetSourcePort(), packet.GetSourceChannel()) if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, capName) { - return sdkerrors.Wrap( + return sdkerrors.Wrapf( types.ErrChannelCapabilityNotFound, - "caller does not own capability for channel", + "caller does not own capability for channel with capability name %s", capName, ) } @@ -175,14 +178,14 @@ func (k Keeper) TimeoutOnClose( ) error { channel, found := k.GetChannel(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) if !found { - return sdkerrors.Wrapf(types.ErrChannelNotFound, packet.GetSourcePort(), packet.GetSourceChannel()) + return sdkerrors.Wrapf(types.ErrChannelNotFound, "port ID (%s) channel ID (%s)", packet.GetSourcePort(), packet.GetSourceChannel()) } capName := host.ChannelCapabilityPath(packet.GetSourcePort(), packet.GetSourceChannel()) if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, capName) { - return sdkerrors.Wrap( + return sdkerrors.Wrapf( types.ErrInvalidChannelCapability, - "channel capability failed authentication", + "channel capability failed authentication with capability name %s", capName, ) } @@ -209,7 +212,7 @@ func (k Keeper) TimeoutOnClose( // verify we sent the packet and haven't cleared it out yet if !bytes.Equal(commitment, types.CommitPacket(packet)) { - return sdkerrors.Wrap(types.ErrInvalidPacket, "packet hasn't been sent") + return sdkerrors.Wrapf(types.ErrInvalidPacket, "packet commitment bytes are not equal: got (%v), expected (%v)", commitment, types.CommitPacket(packet)) } counterpartyHops, found := k.CounterpartyHops(ctx, channel) @@ -237,7 +240,7 @@ func (k Keeper) TimeoutOnClose( case types.ORDERED: // check that packet has not been received if nextSequenceRecv > packet.GetSequence() { - return sdkerrors.Wrap(types.ErrInvalidPacket, "packet already received") + return sdkerrors.Wrapf(types.ErrInvalidPacket, "packet already received, next sequence receive > packet sequence (%d > %d", nextSequenceRecv, packet.GetSequence()) } // check that the recv sequence is as claimed diff --git a/x/ibc/04-channel/types/channel.go b/x/ibc/04-channel/types/channel.go index a0eae4365870..dd414b8fb12f 100644 --- a/x/ibc/04-channel/types/channel.go +++ b/x/ibc/04-channel/types/channel.go @@ -58,28 +58,22 @@ func (ch Channel) GetVersion() string { // ValidateBasic performs a basic validation of the channel fields func (ch Channel) ValidateBasic() error { if ch.State.String() == "" { - return sdkerrors.Wrap(ErrInvalidChannel, ErrInvalidChannelState.Error()) + return ErrInvalidChannelState } if !(ch.Ordering == ORDERED || ch.Ordering == UNORDERED) { return sdkerrors.Wrap(ErrInvalidChannelOrdering, ch.Ordering.String()) } if len(ch.ConnectionHops) != 1 { return sdkerrors.Wrap( - ErrInvalidChannel, - sdkerrors.Wrap(ErrTooManyConnectionHops, "IBC v1.0 only supports one connection hop").Error(), + ErrTooManyConnectionHops, + "current IBC version only supports one connection hop", ) } if err := host.ConnectionIdentifierValidator(ch.ConnectionHops[0]); err != nil { - return sdkerrors.Wrap( - ErrInvalidChannel, - sdkerrors.Wrap(err, "invalid connection hop ID").Error(), - ) + return sdkerrors.Wrap(err, "invalid connection hop ID") } if strings.TrimSpace(ch.Version) == "" { - return sdkerrors.Wrap( - ErrInvalidChannel, - sdkerrors.Wrap(sdkerrors.ErrInvalidVersion, "channel version can't be blank").Error(), - ) + return sdkerrors.Wrap(sdkerrors.ErrInvalidVersion, "channel version can't be blank") } return ch.Counterparty.ValidateBasic() } @@ -105,16 +99,10 @@ func (c Counterparty) GetChannelID() string { // ValidateBasic performs a basic validation check of the identifiers func (c Counterparty) ValidateBasic() error { if err := host.PortIdentifierValidator(c.PortID); err != nil { - return sdkerrors.Wrap( - ErrInvalidCounterparty, - sdkerrors.Wrap(err, "invalid counterparty connection ID").Error(), - ) + return sdkerrors.Wrap(err, "invalid counterparty port ID") } if err := host.ChannelIdentifierValidator(c.ChannelID); err != nil { - return sdkerrors.Wrap( - ErrInvalidCounterparty, - sdkerrors.Wrap(err, "invalid counterparty client ID").Error(), - ) + return sdkerrors.Wrap(err, "invalid counterparty channel ID") } return nil } @@ -135,10 +123,10 @@ func NewIdentifiedChannel(portID, channelID string, ch Channel) IdentifiedChanne // ValidateBasic performs a basic validation of the identifiers and channel fields. func (ic IdentifiedChannel) ValidateBasic() error { if err := host.ChannelIdentifierValidator(ic.ChannelID); err != nil { - return sdkerrors.Wrap(ErrInvalidChannel, err.Error()) + return sdkerrors.Wrap(err, "invalid channel ID") } if err := host.PortIdentifierValidator(ic.PortID); err != nil { - return sdkerrors.Wrap(ErrInvalidChannel, err.Error()) + return sdkerrors.Wrap(err, "invalid port ID") } channel := NewChannel(ic.State, ic.Ordering, ic.Counterparty, ic.ConnectionHops, ic.Version) return channel.ValidateBasic() diff --git a/x/ibc/04-channel/types/genesis.go b/x/ibc/04-channel/types/genesis.go index 762b17f55308..8e678d12823b 100644 --- a/x/ibc/04-channel/types/genesis.go +++ b/x/ibc/04-channel/types/genesis.go @@ -91,37 +91,37 @@ func DefaultGenesisState() GenesisState { func (gs GenesisState) Validate() error { for i, channel := range gs.Channels { if err := channel.ValidateBasic(); err != nil { - return fmt.Errorf("invalid channel %d: %w", i, err) + return fmt.Errorf("invalid channel %v channel index %d: %w", channel, i, err) } } for i, ack := range gs.Acknowledgements { if err := ack.Validate(); err != nil { - return fmt.Errorf("invalid acknowledgement %d: %w", i, err) + return fmt.Errorf("invalid acknowledgement %v ack index %d: %w", ack, i, err) } } for i, commitment := range gs.Commitments { if err := commitment.Validate(); err != nil { - return fmt.Errorf("invalid commitment %d: %w", i, err) + return fmt.Errorf("invalid commitment %v index %d: %w", commitment, i, err) } } for i, ss := range gs.SendSequences { if err := ss.Validate(); err != nil { - return fmt.Errorf("invalid send sequence %d: %w", i, err) + return fmt.Errorf("invalid send sequence %v index %d: %w", ss, i, err) } } for i, rs := range gs.RecvSequences { if err := rs.Validate(); err != nil { - return fmt.Errorf("invalid receive sequence %d: %w", i, err) + return fmt.Errorf("invalid receive sequence %v index %d: %w", rs, i, err) } } for i, as := range gs.AckSequences { if err := as.Validate(); err != nil { - return fmt.Errorf("invalid acknowledgement sequence %d: %w", i, err) + return fmt.Errorf("invalid acknowledgement sequence %v index %d: %w", as, i, err) } } @@ -130,10 +130,10 @@ func (gs GenesisState) Validate() error { func validateGenFields(portID, channelID string, sequence uint64) error { if err := host.PortIdentifierValidator(portID); err != nil { - return err + return fmt.Errorf("invalid port ID: %w", err) } if err := host.ChannelIdentifierValidator(channelID); err != nil { - return err + return fmt.Errorf("invalid channel ID: %w", err) } if sequence == 0 { return errors.New("sequence cannot be 0") diff --git a/x/ibc/04-channel/types/packet.go b/x/ibc/04-channel/types/packet.go index bb6c37b52ef2..d54a9193bc6d 100644 --- a/x/ibc/04-channel/types/packet.go +++ b/x/ibc/04-channel/types/packet.go @@ -72,28 +72,16 @@ func (p Packet) GetTimeoutTimestamp() uint64 { return p.TimeoutTimestamp } // ValidateBasic implements PacketI interface func (p Packet) ValidateBasic() error { if err := host.PortIdentifierValidator(p.SourcePort); err != nil { - return sdkerrors.Wrapf( - ErrInvalidPacket, - sdkerrors.Wrapf(err, "invalid source port ID: %s", p.SourcePort).Error(), - ) + return sdkerrors.Wrap(err, "invalid source port ID") } if err := host.PortIdentifierValidator(p.DestinationPort); err != nil { - return sdkerrors.Wrapf( - ErrInvalidPacket, - sdkerrors.Wrapf(err, "invalid destination port ID: %s", p.DestinationPort).Error(), - ) + return sdkerrors.Wrap(err, "invalid destination port ID") } if err := host.ChannelIdentifierValidator(p.SourceChannel); err != nil { - return sdkerrors.Wrapf( - ErrInvalidPacket, - sdkerrors.Wrapf(err, "invalid source channel ID: %s", p.SourceChannel).Error(), - ) + return sdkerrors.Wrap(err, "invalid source channel ID") } if err := host.ChannelIdentifierValidator(p.DestinationChannel); err != nil { - return sdkerrors.Wrapf( - ErrInvalidPacket, - sdkerrors.Wrapf(err, "invalid destination channel ID: %s", p.DestinationChannel).Error(), - ) + return sdkerrors.Wrap(err, "invalid destination channel ID") } if p.Sequence == 0 { return sdkerrors.Wrap(ErrInvalidPacket, "packet sequence cannot be 0") diff --git a/x/ibc/07-tendermint/misbehaviour.go b/x/ibc/07-tendermint/misbehaviour.go index 69d323b82db0..3a502a306d90 100644 --- a/x/ibc/07-tendermint/misbehaviour.go +++ b/x/ibc/07-tendermint/misbehaviour.go @@ -28,7 +28,7 @@ func CheckMisbehaviourAndUpdateState( // cast the interface to specific types before checking for misbehaviour tmClientState, ok := clientState.(types.ClientState) if !ok { - return nil, sdkerrors.Wrap(clienttypes.ErrInvalidClientType, "client state type is not Tendermint") + return nil, sdkerrors.Wrapf(clienttypes.ErrInvalidClientType, "expected type %T, got %T", types.ClientState{}, clientState) } // If client is already frozen at earlier height than evidence, return with error @@ -39,12 +39,12 @@ func CheckMisbehaviourAndUpdateState( tmConsensusState, ok := consensusState.(types.ConsensusState) if !ok { - return nil, sdkerrors.Wrap(clienttypes.ErrInvalidClientType, "consensus state is not Tendermint") + return nil, sdkerrors.Wrapf(clienttypes.ErrInvalidClientType, "expected type %T, got %T", consensusState, types.ConsensusState{}) } tmEvidence, ok := misbehaviour.(types.Evidence) if !ok { - return nil, sdkerrors.Wrap(clienttypes.ErrInvalidClientType, "evidence type is not Tendermint") + return nil, sdkerrors.Wrapf(clienttypes.ErrInvalidClientType, "expected type %T, got %T", misbehaviour, types.Evidence{}) } if err := checkMisbehaviour( diff --git a/x/ibc/07-tendermint/types/client_state.go b/x/ibc/07-tendermint/types/client_state.go index f7157636b0be..9b2450ef18ff 100644 --- a/x/ibc/07-tendermint/types/client_state.go +++ b/x/ibc/07-tendermint/types/client_state.go @@ -196,7 +196,7 @@ func (cs ClientState) VerifyClientConsensusState( } if err := merkleProof.VerifyMembership(cs.ProofSpecs, provingRoot, path, bz); err != nil { - return sdkerrors.Wrap(clienttypes.ErrFailedClientConsensusStateVerification, err.Error()) + return err } return nil @@ -235,7 +235,7 @@ func (cs ClientState) VerifyConnectionState( } if err := merkleProof.VerifyMembership(cs.ProofSpecs, consensusState.GetRoot(), path, bz); err != nil { - return sdkerrors.Wrap(clienttypes.ErrFailedConnectionStateVerification, err.Error()) + return err } return nil @@ -275,7 +275,7 @@ func (cs ClientState) VerifyChannelState( } if err := merkleProof.VerifyMembership(cs.ProofSpecs, consensusState.GetRoot(), path, bz); err != nil { - return sdkerrors.Wrap(clienttypes.ErrFailedChannelStateVerification, err.Error()) + return err } return nil @@ -337,7 +337,7 @@ func (cs ClientState) VerifyPacketAcknowledgement( } if err := merkleProof.VerifyMembership(cs.ProofSpecs, consensusState.GetRoot(), path, channeltypes.CommitAcknowledgement(acknowledgement)); err != nil { - return sdkerrors.Wrap(clienttypes.ErrFailedPacketAckVerification, err.Error()) + return err } return nil @@ -368,7 +368,7 @@ func (cs ClientState) VerifyPacketAcknowledgementAbsence( } if err := merkleProof.VerifyNonMembership(cs.ProofSpecs, consensusState.GetRoot(), path); err != nil { - return sdkerrors.Wrap(clienttypes.ErrFailedPacketAckAbsenceVerification, err.Error()) + return err } return nil @@ -400,7 +400,7 @@ func (cs ClientState) VerifyNextSequenceRecv( bz := sdk.Uint64ToBigEndian(nextSequenceRecv) if err := merkleProof.VerifyMembership(cs.ProofSpecs, consensusState.GetRoot(), path, bz); err != nil { - return sdkerrors.Wrap(clienttypes.ErrFailedNextSeqRecvVerification, err.Error()) + return err } return nil diff --git a/x/ibc/07-tendermint/types/evidence.go b/x/ibc/07-tendermint/types/evidence.go index d63a4966584d..9e8a4a470d8e 100644 --- a/x/ibc/07-tendermint/types/evidence.go +++ b/x/ibc/07-tendermint/types/evidence.go @@ -85,7 +85,7 @@ func (ev Evidence) GetTime() time.Time { // ValidateBasic implements Evidence interface func (ev Evidence) ValidateBasic() error { if err := host.ClientIdentifierValidator(ev.ClientID); err != nil { - return sdkerrors.Wrap(clienttypes.ErrInvalidEvidence, err.Error()) + return sdkerrors.Wrap(err, "evidence client ID is invalid") } // ValidateBasic on both validators diff --git a/x/ibc/07-tendermint/types/header.go b/x/ibc/07-tendermint/types/header.go index 4a88eee16b4f..d82df6c3ce07 100644 --- a/x/ibc/07-tendermint/types/header.go +++ b/x/ibc/07-tendermint/types/header.go @@ -46,7 +46,7 @@ func (h Header) GetHeight() uint64 { // and checks that validatorsets are not nil func (h Header) ValidateBasic(chainID string) error { if err := h.SignedHeader.ValidateBasic(chainID); err != nil { - return sdkerrors.Wrap(clienttypes.ErrInvalidHeader, err.Error()) + return sdkerrors.Wrap(err, "header failed basic validation") } if h.ValidatorSet == nil { return sdkerrors.Wrap(clienttypes.ErrInvalidHeader, "validator set is nil") diff --git a/x/ibc/07-tendermint/update.go b/x/ibc/07-tendermint/update.go index f8895d8f3035..728fe1eaa8fe 100644 --- a/x/ibc/07-tendermint/update.go +++ b/x/ibc/07-tendermint/update.go @@ -27,15 +27,15 @@ func CheckValidityAndUpdateState( ) (clientexported.ClientState, clientexported.ConsensusState, error) { tmClientState, ok := clientState.(types.ClientState) if !ok { - return nil, nil, sdkerrors.Wrap( - clienttypes.ErrInvalidClientType, "light client is not from Tendermint", + return nil, nil, sdkerrors.Wrapf( + clienttypes.ErrInvalidClientType, "expected type %T, got %T", types.ClientState{}, clientState, ) } tmHeader, ok := header.(types.Header) if !ok { - return nil, nil, sdkerrors.Wrap( - clienttypes.ErrInvalidHeader, "header is not from Tendermint", + return nil, nil, sdkerrors.Wrapf( + clienttypes.ErrInvalidHeader, "expected type %T, got %T", types.Header{}, header, ) } @@ -94,7 +94,7 @@ func checkValidity( clientState.TrustingPeriod, currentTimestamp, clientState.MaxClockDrift, clientState.TrustLevel, ) if err != nil { - return sdkerrors.Wrap(clienttypes.ErrInvalidHeader, err.Error()) + return sdkerrors.Wrap(err, "failed to verify header") } return nil } diff --git a/x/ibc/23-commitment/types/merkle.go b/x/ibc/23-commitment/types/merkle.go index e16568bbc0db..e8c7a44228f6 100644 --- a/x/ibc/23-commitment/types/merkle.go +++ b/x/ibc/23-commitment/types/merkle.go @@ -230,7 +230,7 @@ func (proof MerkleProof) BatchVerifyMembership(specs []*ics23.ProofSpec, root ex // of all subroots up to final root subroot, err := proofs[0].Calculate() if err != nil { - sdkerrors.Wrapf(ErrInvalidProof, "could not calculate root for proof index 0. %v", err) + return sdkerrors.Wrapf(ErrInvalidProof, "could not calculate root for proof index 0: %v", err) } if ok := ics23.BatchVerifyMembership(specs[0], subroot, proofs[0], items); !ok { return sdkerrors.Wrapf(ErrInvalidProof, "could not verify batch items") @@ -281,7 +281,7 @@ func (proof MerkleProof) BatchVerifyNonMembership(specs []*ics23.ProofSpec, root // of all subroots up to final root subroot, err := proofs[0].Calculate() if err != nil { - sdkerrors.Wrapf(ErrInvalidProof, "could not calculate root for proof index 0. %v", err) + return sdkerrors.Wrapf(ErrInvalidProof, "could not calculate root for proof index 0: %v", err) } if ok := ics23.BatchVerifyNonMembership(specs[0], subroot, proofs[0], items); !ok { return sdkerrors.Wrapf(ErrInvalidProof, "could not verify batch items") @@ -336,8 +336,8 @@ func verifyChainedMembershipProof(root []byte, specs []*ics23.ProofSpec, proofs // from the proofs and specs which are lowest to highest key := keys.GetKey(-1 * (i + 1)) if ok := ics23.VerifyMembership(specs[i], subroot, proofs[i], key, value); !ok { - return sdkerrors.Wrapf(ErrInvalidProof, "chained membership proof failed to verify membership of value: %X in subroot %X at index %d", - value, subroot, i) + return sdkerrors.Wrapf(ErrInvalidProof, "chained membership proof failed to verify membership of value: %X in subroot %X at index %d for proof %v", + value, subroot, i, proofs[i]) } // Set value to subroot so that we verify next proof in chain commits to this subroot value = subroot @@ -379,8 +379,12 @@ func (proof MerkleProof) ValidateBasic() error { // validateVerificationArgs verifies the proof arguments are valid func (proof MerkleProof) validateVerificationArgs(specs []*ics23.ProofSpec, root exported.Root) error { - if proof.Empty() || root == nil || root.Empty() { - return sdkerrors.Wrap(ErrInvalidMerkleProof, "empty params or proof") + if proof.Empty() { + return sdkerrors.Wrap(ErrInvalidMerkleProof, "proof cannot be empty") + } + + if root == nil || root.Empty() { + return sdkerrors.Wrap(ErrInvalidMerkleProof, "root cannot be empty") } if len(specs) != len(proof.Proof.Ops) { diff --git a/x/ibc/handler.go b/x/ibc/handler.go index becb45419da6..47343a1f1399 100644 --- a/x/ibc/handler.go +++ b/x/ibc/handler.go @@ -58,7 +58,7 @@ func NewHandler(k keeper.Keeper) sdk.Handler { } err = cbs.OnChanOpenInit(ctx, msg.Channel.Ordering, msg.Channel.ConnectionHops, msg.PortID, msg.ChannelID, cap, msg.Channel.Counterparty, msg.Channel.Version) if err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "channel open init callback failed") } return res, nil @@ -80,7 +80,7 @@ func NewHandler(k keeper.Keeper) sdk.Handler { } err = cbs.OnChanOpenTry(ctx, msg.Channel.Ordering, msg.Channel.ConnectionHops, msg.PortID, msg.ChannelID, cap, msg.Channel.Counterparty, msg.Channel.Version, msg.CounterpartyVersion) if err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "channel open try callback failed") } return res, nil @@ -99,7 +99,7 @@ func NewHandler(k keeper.Keeper) sdk.Handler { err = cbs.OnChanOpenAck(ctx, msg.PortID, msg.ChannelID, msg.CounterpartyVersion) if err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "channel open ack callback failed") } return channel.HandleMsgChannelOpenAck(ctx, k.ChannelKeeper, cap, msg) @@ -117,7 +117,7 @@ func NewHandler(k keeper.Keeper) sdk.Handler { err = cbs.OnChanOpenConfirm(ctx, msg.PortID, msg.ChannelID) if err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "channel open confirm callback failed") } return channel.HandleMsgChannelOpenConfirm(ctx, k.ChannelKeeper, cap, msg) @@ -135,7 +135,7 @@ func NewHandler(k keeper.Keeper) sdk.Handler { err = cbs.OnChanCloseInit(ctx, msg.PortID, msg.ChannelID) if err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "channel close init callback failed") } return channel.HandleMsgChannelCloseInit(ctx, k.ChannelKeeper, cap, msg) @@ -153,7 +153,7 @@ func NewHandler(k keeper.Keeper) sdk.Handler { err = cbs.OnChanCloseConfirm(ctx, msg.PortID, msg.ChannelID) if err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "channel close confirm callback failed") } return channel.HandleMsgChannelCloseConfirm(ctx, k.ChannelKeeper, cap, msg) @@ -174,7 +174,7 @@ func NewHandler(k keeper.Keeper) sdk.Handler { // Perform application logic callback res, ack, err := cbs.OnRecvPacket(ctx, msg.Packet) if err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "receive packet callback failed") } // Set packet acknowledgement @@ -200,7 +200,7 @@ func NewHandler(k keeper.Keeper) sdk.Handler { // Perform application logic callback res, err := cbs.OnAcknowledgementPacket(ctx, msg.Packet, msg.Acknowledgement) if err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "acknowledge packet callback failed") } // Delete packet commitment @@ -226,7 +226,7 @@ func NewHandler(k keeper.Keeper) sdk.Handler { // Perform application logic callback res, err := cbs.OnTimeoutPacket(ctx, msg.Packet) if err != nil { - return nil, err + return nil, sdkerrors.Wrap(err, "timeout packet callback failed") } // Delete packet commitment From 2da1a63288e327e416cc658fcb410ee4f487f6c7 Mon Sep 17 00:00:00 2001 From: Emmanuel T Odeke Date: Thu, 9 Jul 2020 11:28:27 -0700 Subject: [PATCH 3/4] Merge PR #6667: codec: remove unused, untested and expensive MarshalIndentFromJSON --- codec/json.go | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/codec/json.go b/codec/json.go index c1449cc739ed..61099a7145f9 100644 --- a/codec/json.go +++ b/codec/json.go @@ -2,7 +2,6 @@ package codec import ( "bytes" - "encoding/json" "github.com/cosmos/cosmos-sdk/codec/types" @@ -10,19 +9,6 @@ import ( "github.com/gogo/protobuf/proto" ) -// MarshalIndentFromJSON returns indented JSON-encoded bytes from already encoded -// JSON bytes. The output encoding will adhere to the original input's encoding -// (e.g. Proto3). -func MarshalIndentFromJSON(bz []byte) ([]byte, error) { - var generic interface{} - - if err := json.Unmarshal(bz, &generic); err != nil { - return nil, err - } - - return json.MarshalIndent(generic, "", " ") -} - // ProtoMarshalJSON provides an auxiliary function to return Proto3 JSON encoded // bytes of a message. func ProtoMarshalJSON(msg proto.Message) ([]byte, error) { From d269eaf74c48fcd4d39d728b14965fa003f40d68 Mon Sep 17 00:00:00 2001 From: Al Date: Thu, 9 Jul 2020 15:14:18 -0400 Subject: [PATCH 4/4] Document types/context.go code (#6654) * document context.go code * update CHANGELOG.md unreleased * creates -> returns * Update CHANGELOG.md Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Apply suggestions from code review Co-authored-by: Alessio Treglia * Update types/context.go Co-authored-by: Alexander Bezobchuk Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Co-authored-by: Alessio Treglia Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com> --- types/context.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/types/context.go b/types/context.go index ff559d43cde3..0cc01091c1f2 100644 --- a/types/context.go +++ b/types/context.go @@ -83,16 +83,19 @@ func NewContext(ms MultiStore, header abci.Header, isCheckTx bool, logger log.Lo } } +// WithContext returns a Context with an updated context.Context. func (c Context) WithContext(ctx context.Context) Context { c.ctx = ctx return c } +// WithMultiStore returns a Context with an updated MultiStore. func (c Context) WithMultiStore(ms MultiStore) Context { c.ms = ms return c } +// WithBlockHeader returns a Context with an updated tendermint block header in UTC time. func (c Context) WithBlockHeader(header abci.Header) Context { // https://github.com/gogo/protobuf/issues/519 header.Time = header.Time.UTC() @@ -100,6 +103,7 @@ func (c Context) WithBlockHeader(header abci.Header) Context { return c } +// WithBlockTime returns a Context with an updated tendermint block header time in UTC time func (c Context) WithBlockTime(newTime time.Time) Context { newHeader := c.BlockHeader() // https://github.com/gogo/protobuf/issues/519 @@ -107,48 +111,57 @@ func (c Context) WithBlockTime(newTime time.Time) Context { return c.WithBlockHeader(newHeader) } +// WithProposer returns a Context with an updated proposer consensus address. func (c Context) WithProposer(addr ConsAddress) Context { newHeader := c.BlockHeader() newHeader.ProposerAddress = addr.Bytes() return c.WithBlockHeader(newHeader) } +// WithBlockHeight returns a Context with an updated block height. func (c Context) WithBlockHeight(height int64) Context { newHeader := c.BlockHeader() newHeader.Height = height return c.WithBlockHeader(newHeader) } +// WithChainID returns a Context with an updated chain identifier. func (c Context) WithChainID(chainID string) Context { c.chainID = chainID return c } +// WithTxBytes returns a Context with an updated txBytes. func (c Context) WithTxBytes(txBytes []byte) Context { c.txBytes = txBytes return c } +// WithLogger returns a Context with an updated logger. func (c Context) WithLogger(logger log.Logger) Context { c.logger = logger return c } +// WithVoteInfos returns a Context with an updated consensus VoteInfo. func (c Context) WithVoteInfos(voteInfo []abci.VoteInfo) Context { c.voteInfo = voteInfo return c } +// WithGasMeter returns a Context with an updated transaction GasMeter. func (c Context) WithGasMeter(meter GasMeter) Context { c.gasMeter = meter return c } +// WithBlockGasMeter returns a Context with an updated block GasMeter func (c Context) WithBlockGasMeter(meter GasMeter) Context { c.blockGasMeter = meter return c } +// WithIsCheckTx enables or disables CheckTx value for verifying transactions and returns an updated Context func (c Context) WithIsCheckTx(isCheckTx bool) Context { c.checkTx = isCheckTx return c @@ -164,16 +177,19 @@ func (c Context) WithIsReCheckTx(isRecheckTx bool) Context { return c } +// WithMinGasPrices returns a Context with an updated minimum gas price value func (c Context) WithMinGasPrices(gasPrices DecCoins) Context { c.minGasPrice = gasPrices return c } +// WithConsensusParams returns a Context with an updated consensus params func (c Context) WithConsensusParams(params *abci.ConsensusParams) Context { c.consParams = params return c } +// WithEventManager returns a Context with an updated event manager func (c Context) WithEventManager(em *EventManager) Context { c.eventManager = em return c