From 542e9f07cd87fbf5a3eb61f352c67a22ed662c04 Mon Sep 17 00:00:00 2001 From: Julien Robert Date: Mon, 16 May 2022 15:49:20 +0200 Subject: [PATCH 1/9] fix: make `submit-legacy-proposal` --type field not case-sensitive (#11967) --- x/gov/client/cli/tx.go | 6 +++- x/gov/simulation/decoder_test.go | 3 +- x/gov/types/v1beta1/msgs_test.go | 5 +++- x/gov/types/v1beta1/proposal.go | 12 ++++---- x/gov/types/v1beta1/proposals_test.go | 40 +++++++++++++++++++++++++-- 5 files changed, 53 insertions(+), 13 deletions(-) diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index bdf74f449306..85e821ddebee 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -180,7 +180,11 @@ $ %s tx gov submit-legacy-proposal --title="Test Proposal" --description="My awe return err } - content := v1beta1.ContentFromProposalType(proposal.Title, proposal.Description, proposal.Type) + content, ok := v1beta1.ContentFromProposalType(proposal.Title, proposal.Description, proposal.Type) + if !ok { + return fmt.Errorf("failed to create proposal content: unknown proposal type %s", proposal.Type) + } + msg, err := v1beta1.NewMsgSubmitProposal(content, amount, clientCtx.GetFromAddress()) if err != nil { return fmt.Errorf("invalid message: %w", err) diff --git a/x/gov/simulation/decoder_test.go b/x/gov/simulation/decoder_test.go index 3f0d68a38263..7d9ac2e5bc90 100644 --- a/x/gov/simulation/decoder_test.go +++ b/x/gov/simulation/decoder_test.go @@ -27,7 +27,8 @@ func TestDecodeStore(t *testing.T) { dec := simulation.NewDecodeStore(cdc) endTime := time.Now().UTC() - content := v1beta1.ContentFromProposalType("test", "test", v1beta1.ProposalTypeText) + content, ok := v1beta1.ContentFromProposalType("test", "test", v1beta1.ProposalTypeText) + require.True(t, ok) proposalA, err := v1beta1.NewProposal(content, 1, endTime, endTime.Add(24*time.Hour)) require.NoError(t, err) proposalB, err := v1beta1.NewProposal(content, 2, endTime, endTime.Add(24*time.Hour)) diff --git a/x/gov/types/v1beta1/msgs_test.go b/x/gov/types/v1beta1/msgs_test.go index 3d571a6559fc..bf6e78528c42 100644 --- a/x/gov/types/v1beta1/msgs_test.go +++ b/x/gov/types/v1beta1/msgs_test.go @@ -43,8 +43,11 @@ func TestMsgSubmitProposal(t *testing.T) { } for i, tc := range tests { + content, ok := ContentFromProposalType(tc.title, tc.description, tc.proposalType) + require.True(t, ok) + msg, err := NewMsgSubmitProposal( - ContentFromProposalType(tc.title, tc.description, tc.proposalType), + content, tc.initialDeposit, tc.proposerAddr, ) diff --git a/x/gov/types/v1beta1/proposal.go b/x/gov/types/v1beta1/proposal.go index bf735b276b29..6946a40216c4 100644 --- a/x/gov/types/v1beta1/proposal.go +++ b/x/gov/types/v1beta1/proposal.go @@ -246,14 +246,12 @@ func RegisterProposalType(ty string) { } // ContentFromProposalType returns a Content object based on the proposal type. -func ContentFromProposalType(title, desc, ty string) Content { - switch ty { - case ProposalTypeText: - return NewTextProposal(title, desc) - - default: - return nil +func ContentFromProposalType(title, desc, ty string) (Content, bool) { + if strings.EqualFold(ty, ProposalTypeText) { + return NewTextProposal(title, desc), true } + + return nil, false } // IsValidProposalType returns a boolean determining if the proposal type is diff --git a/x/gov/types/v1beta1/proposals_test.go b/x/gov/types/v1beta1/proposals_test.go index fd328b3ca471..2a29fda28753 100644 --- a/x/gov/types/v1beta1/proposals_test.go +++ b/x/gov/types/v1beta1/proposals_test.go @@ -1,16 +1,17 @@ -package v1beta1 +package v1beta1_test import ( "fmt" "testing" + "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" "github.com/stretchr/testify/require" ) func TestProposalStatus_Format(t *testing.T) { - statusDepositPeriod, _ := ProposalStatusFromString("PROPOSAL_STATUS_DEPOSIT_PERIOD") + statusDepositPeriod, _ := v1beta1.ProposalStatusFromString("PROPOSAL_STATUS_DEPOSIT_PERIOD") tests := []struct { - pt ProposalStatus + pt v1beta1.ProposalStatus sprintFArgs string expectedStringOutput string }{ @@ -22,3 +23,36 @@ func TestProposalStatus_Format(t *testing.T) { require.Equal(t, tt.expectedStringOutput, got) } } + +func TestContentFromProposalType(t *testing.T) { + tests := []struct { + proposalType string + expectedType string + }{ + { + proposalType: "TextProposal", + expectedType: "", + }, + { + proposalType: "text", + expectedType: v1beta1.ProposalTypeText, + }, + { + proposalType: "Text", + expectedType: v1beta1.ProposalTypeText, + }, + } + + for _, test := range tests { + content, ok := v1beta1.ContentFromProposalType("title", "foo", test.proposalType) + if test.expectedType == "" { + require.False(t, ok) + continue + } + + require.True(t, ok) + require.NotNil(t, content) + require.Equal(t, test.expectedType, content.ProposalType()) + } + +} From 7a915880ac9af2e1dd528df3ffeb977d5e635fa8 Mon Sep 17 00:00:00 2001 From: Julien Robert Date: Mon, 16 May 2022 18:16:08 +0200 Subject: [PATCH 2/9] test: add test on `StringifyEvents` (#11972) --- types/events.go | 2 +- types/events_test.go | 47 +++++++++++++++++++++++++++++++----------- x/bank/types/events.go | 2 +- 3 files changed, 37 insertions(+), 14 deletions(-) diff --git a/types/events.go b/types/events.go index 664a0082f8aa..dbff89ce2d02 100644 --- a/types/events.go +++ b/types/events.go @@ -211,7 +211,7 @@ func (e Events) ToABCIEvents() []abci.Event { } // Common event types and attribute keys -var ( +const ( EventTypeTx = "tx" AttributeKeyAccountSequence = "acc_seq" diff --git a/types/events_test.go b/types/events_test.go index 87622550d26a..df49138d4f09 100644 --- a/types/events_test.go +++ b/types/events_test.go @@ -103,20 +103,43 @@ func (s *eventsTestSuite) TestEventManagerTypedEvents() { } func (s *eventsTestSuite) TestStringifyEvents() { - e := sdk.Events{ - sdk.NewEvent("message", sdk.NewAttribute("sender", "foo")), - sdk.NewEvent("message", sdk.NewAttribute("module", "bank")), + cases := []struct { + name string + events sdk.Events + expTxtStr string + expJSONStr string + }{ + { + name: "default", + events: sdk.Events{ + sdk.NewEvent("message", sdk.NewAttribute(sdk.AttributeKeySender, "foo")), + sdk.NewEvent("message", sdk.NewAttribute(sdk.AttributeKeyModule, "bank")), + }, + expTxtStr: "\t\t- message\n\t\t\t- sender: foo\n\t\t\t- module: bank", + expJSONStr: "[{\"type\":\"message\",\"attributes\":[{\"key\":\"sender\",\"value\":\"foo\"},{\"key\":\"module\",\"value\":\"bank\"}]}]", + }, + { + name: "multiple events with same attributes", + events: sdk.Events{ + sdk.NewEvent( + "message", + sdk.NewAttribute(sdk.AttributeKeyModule, "staking"), + sdk.NewAttribute(sdk.AttributeKeySender, "cosmos1foo"), + ), + sdk.NewEvent("message", sdk.NewAttribute(sdk.AttributeKeySender, "foo")), + }, + expTxtStr: "\t\t- message\n\t\t\t- module: staking\n\t\t\t- sender: cosmos1foo\n\t\t\t- sender: foo", + expJSONStr: `[{"type":"message","attributes":[{"key":"module","value":"staking"},{"key":"sender","value":"cosmos1foo"},{"key":"sender","value":"foo"}]}]`, + }, } - se := sdk.StringifyEvents(e.ToABCIEvents()) - - expectedTxtStr := "\t\t- message\n\t\t\t- sender: foo\n\t\t\t- module: bank" - s.Require().Equal(expectedTxtStr, se.String()) - bz, err := json.Marshal(se) - s.Require().NoError(err) - - expectedJSONStr := "[{\"type\":\"message\",\"attributes\":[{\"key\":\"sender\",\"value\":\"foo\"},{\"key\":\"module\",\"value\":\"bank\"}]}]" - s.Require().Equal(expectedJSONStr, string(bz)) + for _, test := range cases { + se := sdk.StringifyEvents(test.events.ToABCIEvents()) + s.Require().Equal(test.expTxtStr, se.String()) + bz, err := json.Marshal(se) + s.Require().NoError(err) + s.Require().Equal(test.expJSONStr, string(bz)) + } } func (s *eventsTestSuite) TestMarkEventsToIndex() { diff --git a/x/bank/types/events.go b/x/bank/types/events.go index 9f06b85e491c..2293083e512e 100644 --- a/x/bank/types/events.go +++ b/x/bank/types/events.go @@ -9,7 +9,7 @@ const ( EventTypeTransfer = "transfer" AttributeKeyRecipient = "recipient" - AttributeKeySender = "sender" + AttributeKeySender = sdk.AttributeKeySender AttributeValueCategory = ModuleName From 86949ce4ae6470f2c9aa6d07a33ad7c64215b03b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 May 2022 12:40:00 -0400 Subject: [PATCH 3/9] build(deps): Bump google.golang.org/grpc from 1.46.0 to 1.46.2 in /api (#11974) Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.46.0 to 1.46.2. - [Release notes](https://github.com/grpc/grpc-go/releases) - [Commits](https://github.com/grpc/grpc-go/compare/v1.46.0...v1.46.2) --- updated-dependencies: - dependency-name: google.golang.org/grpc dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- api/go.mod | 2 +- api/go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/api/go.mod b/api/go.mod index f65f9a2864a4..140a0cf95713 100644 --- a/api/go.mod +++ b/api/go.mod @@ -6,7 +6,7 @@ require ( github.com/cosmos/cosmos-proto v1.0.0-alpha7 github.com/gogo/protobuf v1.3.2 google.golang.org/genproto v0.0.0-20211223182754-3ac035c7e7cb - google.golang.org/grpc v1.46.0 + google.golang.org/grpc v1.46.2 google.golang.org/protobuf v1.28.0 ) diff --git a/api/go.sum b/api/go.sum index 1a42841b90a3..7442b632d3ee 100644 --- a/api/go.sum +++ b/api/go.sum @@ -137,8 +137,8 @@ google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8 google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= -google.golang.org/grpc v1.46.0 h1:oCjezcn6g6A75TGoKYBPgKmVBLexhYLM6MebdrPApP8= -google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.46.2 h1:u+MLGgVf7vRdjEYZ8wDFhAVNmhkbJ5hmrA1LMWK1CAQ= +google.golang.org/grpc v1.46.2/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= From b0abdffc0daac6e3adbd6b912bc8d75b82f8b592 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 May 2022 18:55:05 +0200 Subject: [PATCH 4/9] build(deps): Bump google.golang.org/grpc from 1.46.0 to 1.46.2 in /orm (#11975) --- orm/go.mod | 2 +- orm/go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/orm/go.mod b/orm/go.mod index 4f2b389e20d9..c619d400c0bb 100644 --- a/orm/go.mod +++ b/orm/go.mod @@ -12,7 +12,7 @@ require ( github.com/regen-network/gocuke v0.6.2 github.com/stretchr/testify v1.7.1 github.com/tendermint/tm-db v0.6.7 - google.golang.org/grpc v1.46.0 + google.golang.org/grpc v1.46.2 google.golang.org/protobuf v1.28.0 gotest.tools/v3 v3.2.0 pgregory.net/rapid v0.4.7 diff --git a/orm/go.sum b/orm/go.sum index 794d5adefe66..0b4e8cb3e2c1 100644 --- a/orm/go.sum +++ b/orm/go.sum @@ -269,8 +269,8 @@ google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8 google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.44.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= -google.golang.org/grpc v1.46.0 h1:oCjezcn6g6A75TGoKYBPgKmVBLexhYLM6MebdrPApP8= -google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.46.2 h1:u+MLGgVf7vRdjEYZ8wDFhAVNmhkbJ5hmrA1LMWK1CAQ= +google.golang.org/grpc v1.46.2/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= From 450cd7fc8708ccb0fa21f05e251d9804a2063b79 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 17 May 2022 09:37:15 -0400 Subject: [PATCH 5/9] fix: upgrade module panic (#11969) --- CHANGELOG.md | 1 + x/upgrade/abci.go | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 625212007f1a..b565059d307e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -222,6 +222,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Bug Fixes +* [#11969](https://github.com/cosmos/cosmos-sdk/pull/11969) Fix the panic error in `x/upgrade` when `AppVersion` is not set. * (tests) [\#11940](https://github.com/cosmos/cosmos-sdk/pull/11940) Fix some client tests in the `x/gov` module * [\#11772](https://github.com/cosmos/cosmos-sdk/pull/11772) Limit types.Dec length to avoid overflow. * [\#11724](https://github.com/cosmos/cosmos-sdk/pull/11724) Fix data race issues with api.Server diff --git a/x/upgrade/abci.go b/x/upgrade/abci.go index f390a873d134..5212cd9e2ed5 100644 --- a/x/upgrade/abci.go +++ b/x/upgrade/abci.go @@ -35,7 +35,14 @@ func BeginBlocker(k keeper.Keeper, ctx sdk.Context, _ abci.RequestBeginBlock) { // 3. If the plan is ready and skip upgrade height is set for current height. if !found || !plan.ShouldExecute(ctx) || (plan.ShouldExecute(ctx) && k.IsSkipHeight(ctx.BlockHeight())) { if lastAppliedPlan != "" && !k.HasHandler(lastAppliedPlan) { - panic(fmt.Sprintf("Wrong app version %d, upgrade handler is missing for %s upgrade plan", ctx.ConsensusParams().Version.AppVersion, lastAppliedPlan)) + var appVersion uint64 + + cp := ctx.ConsensusParams() + if cp != nil && cp.Version != nil { + appVersion = cp.Version.AppVersion + } + + panic(fmt.Sprintf("Wrong app version %d, upgrade handler is missing for %s upgrade plan", appVersion, lastAppliedPlan)) } } } From 23baecf220045242d6ea779c5a3a77edde6e418a Mon Sep 17 00:00:00 2001 From: Robert Zaremba Date: Wed, 18 May 2022 13:43:52 +0200 Subject: [PATCH 6/9] feat: add Coins.Find method (#11959) Added a new helper method to find a coin in a set of `sdk.Coins` by denom. --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [x] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#pr-targeting)) - [ ] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/main/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#testing) - [ ] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable) --- CHANGELOG.md | 1 + types/coin.go | 23 ++++++++++++++++------- types/coin_test.go | 42 ++++++++++++++++++++++++++++++++++-------- 3 files changed, 51 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b565059d307e..7e162a3a105b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -86,6 +86,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (types) [\#10948](https://github.com/cosmos/cosmos-sdk/issues/10948) Add `app-db-backend` to the `app.toml` config to replace the compile-time `types.DBbackend` variable. * (authz)[\#11060](https://github.com/cosmos/cosmos-sdk/pull/11060) Support grant with no expire time. * (rosetta) [\#11590](https://github.com/cosmos/cosmos-sdk/pull/11590) Add fee suggestion for rosetta and enable offline mode. Also force set events about Fees to Success to pass reconciliation test. +* (types) [\#11959](https://github.com/cosmos/cosmos-sdk/pull/11959) Added `sdk.Coins.Find` helper method to find a coin by denom. ### API Breaking Changes diff --git a/types/coin.go b/types/coin.go index b6cf93813a8b..c5bf96aeac04 100644 --- a/types/coin.go +++ b/types/coin.go @@ -703,28 +703,37 @@ func (coins Coins) AmountOf(denom string) Int { // AmountOfNoDenomValidation returns the amount of a denom from coins // without validating the denomination. func (coins Coins) AmountOfNoDenomValidation(denom string) Int { + if ok, c := coins.Find(denom); ok { + return c.Amount + } + return ZeroInt() +} + +// Find returns true and coin if the denom exists in coins. Otherwise it returns false +// and a zero coin. Uses binary search. +// CONTRACT: coins must be valid (sorted). +func (coins Coins) Find(denom string) (bool, Coin) { switch len(coins) { case 0: - return ZeroInt() + return false, Coin{} case 1: coin := coins[0] if coin.Denom == denom { - return coin.Amount + return true, coin } - return ZeroInt() + return false, Coin{} default: - // Binary search the amount of coins remaining midIdx := len(coins) / 2 // 2:1, 3:1, 4:2 coin := coins[midIdx] switch { case denom < coin.Denom: - return coins[:midIdx].AmountOfNoDenomValidation(denom) + return coins[:midIdx].Find(denom) case denom == coin.Denom: - return coin.Amount + return true, coin default: - return coins[midIdx+1:].AmountOfNoDenomValidation(denom) + return coins[midIdx+1:].Find(denom) } } } diff --git a/types/coin_test.go b/types/coin_test.go index f405457bc8bf..7ee9c91c661e 100644 --- a/types/coin_test.go +++ b/types/coin_test.go @@ -931,7 +931,8 @@ func (s *coinTestSuite) TestSortCoins() { } } -func (s *coinTestSuite) TestAmountOf() { +func (s *coinTestSuite) TestSearch() { + require := s.Require() case0 := sdk.Coins{} case1 := sdk.Coins{ sdk.NewInt64Coin("gold", 0), @@ -949,7 +950,7 @@ func (s *coinTestSuite) TestAmountOf() { sdk.NewInt64Coin("gas", 8), } - cases := []struct { + amountOfCases := []struct { coins sdk.Coins amountOf int64 amountOfSpace int64 @@ -964,13 +965,38 @@ func (s *coinTestSuite) TestAmountOf() { {case4, 0, 0, 8, 0, 0}, } - for _, tc := range cases { - s.Require().Equal(sdk.NewInt(tc.amountOfGAS), tc.coins.AmountOf("gas")) - s.Require().Equal(sdk.NewInt(tc.amountOfMINERAL), tc.coins.AmountOf("mineral")) - s.Require().Equal(sdk.NewInt(tc.amountOfTREE), tc.coins.AmountOf("tree")) - } + s.Run("AmountOf", func() { + for i, tc := range amountOfCases { + require.Equal(sdk.NewInt(tc.amountOfGAS), tc.coins.AmountOf("gas"), i) + require.Equal(sdk.NewInt(tc.amountOfMINERAL), tc.coins.AmountOf("mineral"), i) + require.Equal(sdk.NewInt(tc.amountOfTREE), tc.coins.AmountOf("tree"), i) + } + require.Panics(func() { amountOfCases[0].coins.AmountOf("10Invalid") }) + }) - s.Require().Panics(func() { cases[0].coins.AmountOf("10Invalid") }) + zeroCoin := sdk.Coin{} + findCases := []struct { + coins sdk.Coins + denom string + expectedOk bool + expectedCoin sdk.Coin + }{ + {case0, "any", false, zeroCoin}, + {case1, "other", false, zeroCoin}, + {case1, "gold", true, case1[0]}, + {case4, "gas", true, case4[0]}, + {case2, "gas", true, case2[0]}, + {case2, "mineral", true, case2[1]}, + {case2, "tree", true, case2[2]}, + {case2, "other", false, zeroCoin}, + } + s.Run("Find", func() { + for i, tc := range findCases { + ok, c := tc.coins.Find(tc.denom) + require.Equal(tc.expectedOk, ok, i) + require.Equal(tc.expectedCoin, c, i) + } + }) } func (s *coinTestSuite) TestCoinsIsAnyGTE() { From 0fa90ad61466f3627707e3a2099b67ec9f394544 Mon Sep 17 00:00:00 2001 From: Julien Robert Date: Wed, 18 May 2022 16:08:05 +0200 Subject: [PATCH 7/9] fix: update `StartHeight` signing info in `AfterValidatorBonded` hook when validator re-bonds (#11973) --- x/slashing/keeper/hooks.go | 25 +++++++++++++----- x/slashing/keeper/keeper_test.go | 44 +++++++++++++++++--------------- x/slashing/spec/01_concepts.md | 6 ++--- x/slashing/spec/05_hooks.md | 5 ++++ 4 files changed, 50 insertions(+), 30 deletions(-) diff --git a/x/slashing/keeper/hooks.go b/x/slashing/keeper/hooks.go index 09d1afe02fac..a306f76c210d 100644 --- a/x/slashing/keeper/hooks.go +++ b/x/slashing/keeper/hooks.go @@ -11,9 +11,11 @@ import ( func (k Keeper) AfterValidatorBonded(ctx sdk.Context, address sdk.ConsAddress, _ sdk.ValAddress) error { // Update the signing info start height or create a new signing info - _, found := k.GetValidatorSigningInfo(ctx, address) - if !found { - signingInfo := types.NewValidatorSigningInfo( + signingInfo, found := k.GetValidatorSigningInfo(ctx, address) + if found { + signingInfo.StartHeight = ctx.BlockHeight() + } else { + signingInfo = types.NewValidatorSigningInfo( address, ctx.BlockHeight(), 0, @@ -21,9 +23,10 @@ func (k Keeper) AfterValidatorBonded(ctx sdk.Context, address sdk.ConsAddress, _ false, 0, ) - k.SetValidatorSigningInfo(ctx, address, signingInfo) } + k.SetValidatorSigningInfo(ctx, address, signingInfo) + return nil } @@ -74,17 +77,27 @@ func (h Hooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) er func (h Hooks) AfterValidatorBeginUnbonding(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) error { return nil } -func (h Hooks) BeforeValidatorModified(_ sdk.Context, _ sdk.ValAddress) error { return nil } + +func (h Hooks) BeforeValidatorModified(_ sdk.Context, _ sdk.ValAddress) error { + return nil +} + func (h Hooks) BeforeDelegationCreated(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) error { return nil } + func (h Hooks) BeforeDelegationSharesModified(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) error { return nil } + func (h Hooks) BeforeDelegationRemoved(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) error { return nil } + func (h Hooks) AfterDelegationModified(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) error { return nil } -func (h Hooks) BeforeValidatorSlashed(_ sdk.Context, _ sdk.ValAddress, _ sdk.Dec) error { return nil } + +func (h Hooks) BeforeValidatorSlashed(_ sdk.Context, _ sdk.ValAddress, _ sdk.Dec) error { + return nil +} diff --git a/x/slashing/keeper/keeper_test.go b/x/slashing/keeper/keeper_test.go index 7385c1f4d7e2..08502fa89c94 100644 --- a/x/slashing/keeper/keeper_test.go +++ b/x/slashing/keeper/keeper_test.go @@ -200,7 +200,9 @@ func TestValidatorDippingInAndOut(t *testing.T) { valAddr := sdk.ValAddress(addr) tstaking.CreateValidatorWithValPower(valAddr, val, power, true) - staking.EndBlocker(ctx, app.StakingKeeper) + validatorUpdates := staking.EndBlocker(ctx, app.StakingKeeper) + require.Equal(t, 2, len(validatorUpdates)) + tstaking.CheckValidator(valAddr, stakingtypes.Bonded, false) // 100 first blocks OK height := int64(0) @@ -210,22 +212,23 @@ func TestValidatorDippingInAndOut(t *testing.T) { } // kick first validator out of validator set - tstaking.CreateValidatorWithValPower(sdk.ValAddress(pks[1].Address()), pks[1], 101, true) - validatorUpdates := staking.EndBlocker(ctx, app.StakingKeeper) + tstaking.CreateValidatorWithValPower(sdk.ValAddress(pks[1].Address()), pks[1], power+1, true) + validatorUpdates = staking.EndBlocker(ctx, app.StakingKeeper) require.Equal(t, 2, len(validatorUpdates)) + tstaking.CheckValidator(sdk.ValAddress(pks[1].Address()), stakingtypes.Bonded, false) tstaking.CheckValidator(valAddr, stakingtypes.Unbonding, false) // 600 more blocks happened - height = 700 + height = height + 600 ctx = ctx.WithBlockHeight(height) // validator added back in - tstaking.DelegateWithPower(sdk.AccAddress(pks[2].Address()), sdk.ValAddress(pks[0].Address()), 50) + tstaking.DelegateWithPower(sdk.AccAddress(pks[2].Address()), valAddr, 50) validatorUpdates = staking.EndBlocker(ctx, app.StakingKeeper) require.Equal(t, 2, len(validatorUpdates)) tstaking.CheckValidator(valAddr, stakingtypes.Bonded, false) - newPower := int64(150) + newPower := power + 50 // validator misses a block app.SlashingKeeper.HandleValidatorSignature(ctx, val.Address(), newPower, false) @@ -234,9 +237,9 @@ func TestValidatorDippingInAndOut(t *testing.T) { // shouldn't be jailed/kicked yet tstaking.CheckValidator(valAddr, stakingtypes.Bonded, false) - // validator misses 500 more blocks, 501 total - latest := height - for ; height < latest+500; height++ { + // validator misses an additional 500 more blocks, after the cooling off period of SignedBlockWindow (here 1000 blocks). + latest := app.SlashingKeeper.SignedBlocksWindow(ctx) + height + for ; height < latest+app.SlashingKeeper.MinSignedPerWindow(ctx); height++ { ctx = ctx.WithBlockHeight(height) app.SlashingKeeper.HandleValidatorSignature(ctx, val.Address(), newPower, false) } @@ -248,13 +251,9 @@ func TestValidatorDippingInAndOut(t *testing.T) { // check all the signing information signInfo, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, consAddr) require.True(t, found) - require.Equal(t, int64(0), signInfo.MissedBlocksCounter) - require.Equal(t, int64(0), signInfo.IndexOffset) - // array should be cleared - for offset := int64(0); offset < app.SlashingKeeper.SignedBlocksWindow(ctx); offset++ { - missed := app.SlashingKeeper.GetValidatorMissedBlockBitArray(ctx, consAddr, offset) - require.False(t, missed) - } + require.Equal(t, int64(700), signInfo.StartHeight) + require.Equal(t, int64(499), signInfo.MissedBlocksCounter) + require.Equal(t, int64(499), signInfo.IndexOffset) // some blocks pass height = int64(5000) @@ -262,16 +261,21 @@ func TestValidatorDippingInAndOut(t *testing.T) { // validator rejoins and starts signing again app.StakingKeeper.Unjail(ctx, consAddr) + app.SlashingKeeper.HandleValidatorSignature(ctx, val.Address(), newPower, true) - height++ // validator should not be kicked since we reset counter/array when it was jailed staking.EndBlocker(ctx, app.StakingKeeper) tstaking.CheckValidator(valAddr, stakingtypes.Bonded, false) - // validator misses 501 blocks - latest = height - for ; height < latest+501; height++ { + // check start height is correctly set + signInfo, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, consAddr) + require.True(t, found) + require.Equal(t, height, signInfo.StartHeight) + + // validator misses 501 blocks after SignedBlockWindow period (1000 blocks) + latest = app.SlashingKeeper.SignedBlocksWindow(ctx) + height + for ; height < latest+app.SlashingKeeper.MinSignedPerWindow(ctx); height++ { ctx = ctx.WithBlockHeight(height) app.SlashingKeeper.HandleValidatorSignature(ctx, val.Address(), newPower, false) } diff --git a/x/slashing/spec/01_concepts.md b/x/slashing/spec/01_concepts.md index 9505706f90d3..ea7c6b319bae 100644 --- a/x/slashing/spec/01_concepts.md +++ b/x/slashing/spec/01_concepts.md @@ -43,16 +43,14 @@ _Vu_ : validator unbonded ### Single Double Sign Infraction -<-----------------> -[----------C1----D1,Vu-----] +\[----------C1----D1,Vu-----\] A single infraction is committed then later discovered, at which point the validator is unbonded and slashed at the full amount for the infraction. ### Multiple Double Sign Infractions -<---------------------------> -[----------C1--C2---C3---D1,D2,D3Vu-----] +\[----------C1--C2---C3---D1,D2,D3Vu-----\] Multiple infractions are committed and then later discovered, at which point the validator is jailed and slashed for only one infraction. Because the validator diff --git a/x/slashing/spec/05_hooks.md b/x/slashing/spec/05_hooks.md index d1234e58ee05..a839689429a8 100644 --- a/x/slashing/spec/05_hooks.md +++ b/x/slashing/spec/05_hooks.md @@ -21,6 +21,8 @@ The following hooks impact the slashing state: Upon successful first-time bonding of a new validator, we create a new `ValidatorSigningInfo` structure for the now-bonded validator, which `StartHeight` of the current block. +If the validator was out of the validator set and gets bonded again, its new bonded height is set. + ```go onValidatorBonded(address sdk.ValAddress) @@ -32,7 +34,10 @@ onValidatorBonded(address sdk.ValAddress) JailedUntil : time.Unix(0, 0), Tombstone : false, MissedBloskCounter : 0 + } else { + signingInfo.StartHeight = CurrentHeight } + setValidatorSigningInfo(signingInfo) } From b6478026c4e8c5f03c7e6c6f726a60debb9bbfac Mon Sep 17 00:00:00 2001 From: Marie Gauthier Date: Wed, 18 May 2022 16:37:01 +0200 Subject: [PATCH 8/9] chore: store audit (#11987) ## Description Ref: https://github.com/cosmos/cosmos-sdk/issues/11362 --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#pr-targeting)) - [x] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/main/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#testing) - [ ] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable) --- store/cachekv/memiterator.go | 2 +- store/cachekv/store.go | 6 ++- store/iavl/store.go | 2 +- store/streaming/constructor_test.go | 65 ++++++++++++++++++++++++++-- store/streaming/file/service.go | 4 +- store/streaming/file/service_test.go | 4 +- 6 files changed, 71 insertions(+), 12 deletions(-) diff --git a/store/cachekv/memiterator.go b/store/cachekv/memiterator.go index 04df40ff56aa..e65e8a580fce 100644 --- a/store/cachekv/memiterator.go +++ b/store/cachekv/memiterator.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/types" ) -// Iterates over iterKVCache items. +// memIterator iterates over iterKVCache items. // if key is nil, means it was deleted. // Implements Iterator. type memIterator struct { diff --git a/store/cachekv/store.go b/store/cachekv/store.go index 68fe7213dbfa..28063504b208 100644 --- a/store/cachekv/store.go +++ b/store/cachekv/store.go @@ -15,14 +15,16 @@ import ( "github.com/cosmos/cosmos-sdk/types/kv" ) -// If value is nil but deleted is false, it means the parent doesn't have the -// key. (No need to delete upon Write()) +// cValue represents a cached value. +// If dirty is true, it indicates the cached value is different from the underlying value. type cValue struct { value []byte dirty bool } // Store wraps an in-memory cache around an underlying types.KVStore. +// If a cached value is nil but deleted is defined for the corresponding key, +// it means the parent doesn't have the key. (No need to delete upon Write()) type Store struct { mtx sync.Mutex cache map[string]*cValue diff --git a/store/iavl/store.go b/store/iavl/store.go index 3b961e0ab1c3..c47e7171ad32 100644 --- a/store/iavl/store.go +++ b/store/iavl/store.go @@ -380,7 +380,7 @@ func getProofFromTree(tree *iavl.MutableTree, key []byte, exists bool) *tmcrypto //---------------------------------------- -// Implements types.Iterator. +// iavlIterator implements types.Iterator. type iavlIterator struct { *iavl.Iterator } diff --git a/store/streaming/constructor_test.go b/store/streaming/constructor_test.go index 5f9d58016f68..73d512e88ba9 100644 --- a/store/streaming/constructor_test.go +++ b/store/streaming/constructor_test.go @@ -1,13 +1,19 @@ -package streaming +package streaming_test import ( "testing" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" codecTypes "github.com/cosmos/cosmos-sdk/codec/types" + serverTypes "github.com/cosmos/cosmos-sdk/server/types" + "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/store/streaming" "github.com/cosmos/cosmos-sdk/store/streaming/file" "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/tendermint/tendermint/libs/log" + dbm "github.com/tendermint/tm-db" "github.com/stretchr/testify/require" ) @@ -24,12 +30,12 @@ var ( ) func TestStreamingServiceConstructor(t *testing.T) { - _, err := NewServiceConstructor("unexpectedName") + _, err := streaming.NewServiceConstructor("unexpectedName") require.NotNil(t, err) - constructor, err := NewServiceConstructor("file") + constructor, err := streaming.NewServiceConstructor("file") require.Nil(t, err) - var expectedType ServiceConstructor + var expectedType streaming.ServiceConstructor require.IsType(t, expectedType, constructor) serv, err := constructor(mockOptions, mockKeys, testMarshaller) @@ -41,3 +47,54 @@ func TestStreamingServiceConstructor(t *testing.T) { require.True(t, ok) } } + +func TestLoadStreamingServices(t *testing.T) { + db := dbm.NewMemDB() + encCdc := simapp.MakeTestEncodingConfig() + keys := sdk.NewKVStoreKeys("mockKey1", "mockKey2") + bApp := baseapp.NewBaseApp("appName", log.NewNopLogger(), db) + + testCases := map[string]struct { + appOpts serverTypes.AppOptions + activeStreamersLen int + }{ + "empty app options": { + appOpts: simapp.EmptyAppOptions{}, + }, + "all StoreKeys exposed": { + appOpts: streamingAppOptions{keys: []string{"*"}}, + activeStreamersLen: 1, + }, + "some StoreKey exposed": { + appOpts: streamingAppOptions{keys: []string{"mockKey1"}}, + activeStreamersLen: 1, + }, + "not exposing anything": { + appOpts: streamingAppOptions{keys: []string{"mockKey3"}}, + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + activeStreamers, _, err := streaming.LoadStreamingServices(bApp, tc.appOpts, encCdc.Codec, keys) + require.NoError(t, err) + require.Equal(t, tc.activeStreamersLen, len(activeStreamers)) + }) + } + +} + +type streamingAppOptions struct { + keys []string +} + +func (ao streamingAppOptions) Get(o string) interface{} { + switch o { + case "store.streamers": + return []string{"file"} + case "streamers.file.keys": + return ao.keys + default: + return nil + } +} diff --git a/store/streaming/file/service.go b/store/streaming/file/service.go index 02feb403e99b..16c1b5c82b35 100644 --- a/store/streaming/file/service.go +++ b/store/streaming/file/service.go @@ -39,7 +39,7 @@ type IntermediateWriter struct { outChan chan<- []byte } -// NewIntermediateWriter create an instance of an intermediateWriter that sends to the provided channel +// NewIntermediateWriter create an instance of an IntermediateWriter that sends to the provided channel func NewIntermediateWriter(outChan chan<- []byte) *IntermediateWriter { return &IntermediateWriter{ outChan: outChan, @@ -62,7 +62,7 @@ func NewStreamingService(writeDir, filePrefix string, storeKeys []types.StoreKey for _, key := range storeKeys { listeners[key] = append(listeners[key], listener) } - // check that the writeDir exists and is writeable so that we can catch the error here at initialization if it is not + // check that the writeDir exists and is writable so that we can catch the error here at initialization if it is not // we don't open a dstFile until we receive our first ABCI message if err := isDirWriteable(writeDir); err != nil { return nil, err diff --git a/store/streaming/file/service_test.go b/store/streaming/file/service_test.go index 1276b163642d..db5b2137f99b 100644 --- a/store/streaming/file/service_test.go +++ b/store/streaming/file/service_test.go @@ -372,7 +372,7 @@ func readInFile(name string) ([]byte, error) { return ioutil.ReadFile(path) } -// Returns all of the protobuf messages contained in the byte array as an array of byte arrays +// segmentBytes returns all of the protobuf messages contained in the byte array as an array of byte arrays // The messages have their length prefix removed func segmentBytes(bz []byte) ([][]byte, error) { var err error @@ -388,7 +388,7 @@ func segmentBytes(bz []byte) ([][]byte, error) { return segments, nil } -// Returns the bytes for the leading protobuf object in the byte array (removing the length prefix) and returns the remainder of the byte array +// getHeadSegment returns the bytes for the leading protobuf object in the byte array (removing the length prefix) and returns the remainder of the byte array func getHeadSegment(bz []byte) ([]byte, []byte, error) { size, prefixSize := binary.Uvarint(bz) if prefixSize < 0 { From 0b810ba08e1d1e47f76dbb8315c0f8fd3c6fd22e Mon Sep 17 00:00:00 2001 From: likhita-809 <78951027+likhita-809@users.noreply.github.com> Date: Wed, 18 May 2022 21:08:01 +0530 Subject: [PATCH 9/9] chore: store audit changes (#11989) ## Description ref: #11362 --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [ ] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] added `!` to the type prefix if API or client breaking change - [ ] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#pr-targeting)) - [ ] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/main/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#testing) - [ ] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable) --- store/firstlast.go | 4 ++-- store/tools/ics23/iavl/README.md | 2 +- store/tools/ics23/iavl/helpers/helpers.go | 4 ++-- store/tools/ics23/smt/README.md | 2 +- store/tools/ics23/smt/helpers/helpers.go | 2 +- store/tracekv/store.go | 4 ++-- store/types/store.go | 6 +++--- store/types/utils.go | 4 ++-- store/types/validity.go | 4 ++-- 9 files changed, 16 insertions(+), 16 deletions(-) diff --git a/store/firstlast.go b/store/firstlast.go index 307f932fb0c8..0ab4e319e08a 100644 --- a/store/firstlast.go +++ b/store/firstlast.go @@ -7,7 +7,7 @@ import ( sdkkv "github.com/cosmos/cosmos-sdk/types/kv" ) -// Gets the first item. +// First gets the first item. func First(st KVStore, start, end []byte) (kv sdkkv.Pair, ok bool) { iter := st.Iterator(start, end) if !iter.Valid() { @@ -18,7 +18,7 @@ func First(st KVStore, start, end []byte) (kv sdkkv.Pair, ok bool) { return sdkkv.Pair{Key: iter.Key(), Value: iter.Value()}, true } -// Gets the last item. `end` is exclusive. +// Last gets the last item. `end` is exclusive. func Last(st KVStore, start, end []byte) (kv sdkkv.Pair, ok bool) { iter := st.ReverseIterator(end, start) if !iter.Valid() { diff --git a/store/tools/ics23/iavl/README.md b/store/tools/ics23/iavl/README.md index 45f2e81a5e83..756f04871079 100644 --- a/store/tools/ics23/iavl/README.md +++ b/store/tools/ics23/iavl/README.md @@ -13,7 +13,7 @@ current value). This returns an error if the key does not exist in the tree. `func CreateNonMembershipProof(tree *iavl.MutableTree, key []byte) (*proofs.CommitmentProof, error)` produces a CommitmentProof that the given key doesn't exist in the iavl tree. -This returns an error if the key does not exist in the tree. +This returns an error if the key exists in the tree. Generalized range proofs are lower in priority, as they are just an optimization of the two basic proof types, and don't provide any additional capabilities. diff --git a/store/tools/ics23/iavl/helpers/helpers.go b/store/tools/ics23/iavl/helpers/helpers.go index c39da851c651..26f1f09dcfc9 100644 --- a/store/tools/ics23/iavl/helpers/helpers.go +++ b/store/tools/ics23/iavl/helpers/helpers.go @@ -1,7 +1,7 @@ /* Package helpers contains functions to build sample data for tests/testgen -In it's own package to avoid poluting the godoc for ics23-iavl +In it's own package to avoid polluting the godoc for ics23-iavl */ package helpers @@ -56,7 +56,7 @@ func GenerateIavlResult(size int, loc tmproofs.Where) (*IavlResult, error) { return res, nil } -// GetKey this returns a key, on Left/Right/Middle +// GetKey returns a key, on Left/Right/Middle func GetKey(allkeys [][]byte, loc tmproofs.Where) []byte { if loc == tmproofs.Left { return allkeys[0] diff --git a/store/tools/ics23/smt/README.md b/store/tools/ics23/smt/README.md index 0e65e87e2249..82c06eddcbf1 100644 --- a/store/tools/ics23/smt/README.md +++ b/store/tools/ics23/smt/README.md @@ -10,7 +10,7 @@ It exposes a two main functions : produces a CommitmentProof that the given key exists in the SMT (and contains the current value). This returns an error if the key does not exist in the tree. `func CreateNonMembershipProof(tree *smt.SparseMerkleTree, key []byte, preimages PreimageMap) (*ics23.CommitmentProof, error)` -produces a CommitmentProof that the given key doesn't exist in the SMT. This returns an error if the key does not exist in the tree. +produces a CommitmentProof that the given key doesn't exist in the SMT. This returns an error if the key exists in the tree. This relies on an auxiliary `PreimageMap` object which provides access to the preimages of all keys in the tree based on their (hashed) path ordering. diff --git a/store/tools/ics23/smt/helpers/helpers.go b/store/tools/ics23/smt/helpers/helpers.go index 1c8a1415a7c6..d444c47d61ec 100644 --- a/store/tools/ics23/smt/helpers/helpers.go +++ b/store/tools/ics23/smt/helpers/helpers.go @@ -1,7 +1,7 @@ /* Package helpers contains functions to build sample data for tests/testgen -In it's own package to avoid poluting the godoc for ics23-smt +In it's own package to avoid polluting the godoc for ics23-smt */ package helpers diff --git a/store/tracekv/store.go b/store/tracekv/store.go index a454edc7dd5f..91f3c657682c 100644 --- a/store/tracekv/store.go +++ b/store/tracekv/store.go @@ -79,13 +79,13 @@ func (tkv *Store) Has(key []byte) bool { } // Iterator implements the KVStore interface. It delegates the Iterator call -// the to the parent KVStore. +// to the parent KVStore. func (tkv *Store) Iterator(start, end []byte) types.Iterator { return tkv.iterator(start, end, true) } // ReverseIterator implements the KVStore interface. It delegates the -// ReverseIterator call the to the parent KVStore. +// ReverseIterator call to the parent KVStore. func (tkv *Store) ReverseIterator(start, end []byte) types.Iterator { return tkv.iterator(start, end, false) } diff --git a/store/types/store.go b/store/types/store.go index bb4cf2031af3..988bbf55a4f1 100644 --- a/store/types/store.go +++ b/store/types/store.go @@ -59,7 +59,7 @@ type StoreRename struct { NewKey string `json:"new_key"` } -// IsDeleted returns true if the given key should be added +// IsAdded returns true if the given key should be added func (s *StoreUpgrades) IsAdded(key string) bool { if s == nil { return false @@ -192,7 +192,7 @@ type CommitMultiStore interface { // BasicKVStore is a simple interface to get/set data type BasicKVStore interface { - // Get returns nil iff key doesn't exist. Panics on nil key. + // Get returns nil if key doesn't exist. Panics on nil key. Get(key []byte) []byte // Has checks if a key exists. Panics on nil key. @@ -338,7 +338,7 @@ type StoreKey interface { } // CapabilityKey represent the Cosmos SDK keys for object-capability -// generation in the IBC protocol as defined in https://github.com/cosmos/ics/tree/master/spec/ics-005-port-allocation#data-structures +// generation in the IBC protocol as defined in https://github.com/cosmos/ibc/tree/master/spec/core/ics-005-port-allocation#data-structures type CapabilityKey StoreKey // KVStoreKey is used for accessing substores. diff --git a/store/types/utils.go b/store/types/utils.go index 22c8ca0761f9..f0cf469871d9 100644 --- a/store/types/utils.go +++ b/store/types/utils.go @@ -6,12 +6,12 @@ import ( "github.com/cosmos/cosmos-sdk/types/kv" ) -// Iterator over all the keys with a certain prefix in ascending order +// KVStorePrefixIterator iterates over all the keys with a certain prefix in ascending order func KVStorePrefixIterator(kvs KVStore, prefix []byte) Iterator { return kvs.Iterator(prefix, PrefixEndBytes(prefix)) } -// Iterator over all the keys with a certain prefix in descending order. +// KVStoreReversePrefixIterator iterates over all the keys with a certain prefix in descending order. func KVStoreReversePrefixIterator(kvs KVStore, prefix []byte) Iterator { return kvs.ReverseIterator(prefix, PrefixEndBytes(prefix)) } diff --git a/store/types/validity.go b/store/types/validity.go index ef2387a69269..32619271b488 100644 --- a/store/types/validity.go +++ b/store/types/validity.go @@ -1,13 +1,13 @@ package types -// Check if the key is valid(key is not nil) +// AssertValidKey checks if the key is valid(key is not nil) func AssertValidKey(key []byte) { if len(key) == 0 { panic("key is nil") } } -// Check if the value is valid(value is not nil) +// AssertValidValue checks if the value is valid(value is not nil) func AssertValidValue(value []byte) { if value == nil { panic("value is nil")