diff --git a/CHANGELOG.md b/CHANGELOG.md index b2e409e937..9b9ac55cf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * Add the Quarantine module back in [#1926](https://github.com/provenance-io/provenance/pull/1926). * Bump wasmd to `v0.50.0` [#1760](https://github.com/provenance-io/provenance/issues/1760). * Update stargate queries for Attribute, Exchange, Marker, IBCRateLimit, Metadata, Msgfees, and Oracle modules [#1760](https://github.com/provenance-io/provenance/issues/1760). +* Update stargate queries for Quarantine and Sanction modules [#2016](https://github.com/provenance-io/provenance/pull/2016). ### Improvements @@ -99,6 +100,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * `name` add `UpdateParams` endpoint and cli [#2004](https://github.com/provenance-io/provenance/pull/2004). * Update the exchange `commitment-settlement-fee-calc` cli query to utilize the keyring [#2001](https://github.com/provenance-io/provenance/pull/2001). * Implement the ProposalMsgs module interface for the internal/provwasm, ibcratelimit, oracle, and sanction modules [#1993](https://github.com/provenance-io/provenance/pull/1993.) +* Breakdown internal/helpers into multiple internal packages [#2019](https://github.com/provenance-io/provenance/pull/2019). ### Client Breaking @@ -136,6 +138,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ - Bump `docker/setup-qemu-action` from 2 to 3 ([#1983](https://github.com/provenance-io/provenance/pull/1983)) - Update `github.com/cosmos/ibc-go/v8` to our forked tag v8.2.1-pio-1 ([#1998](https://github.com/provenance-io/provenance/pull/1998)) - Bump `github.com/rs/zerolog` from 1.32.0 to 1.33.0 ([#1994](https://github.com/provenance-io/provenance/pull/1994)) +- Bump `github.com/spf13/viper` from 1.18.2 to 1.19.0 ([#2020](https://github.com/provenance-io/provenance/pull/2020)) --- diff --git a/app/export.go b/app/export.go index 39005d2d44..026565f3e6 100644 --- a/app/export.go +++ b/app/export.go @@ -17,7 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/provenance-io/provenance/internal/helpers" + internalsdk "github.com/provenance-io/provenance/internal/sdk" markertypes "github.com/provenance-io/provenance/x/marker/types" ) @@ -100,7 +100,7 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str // withdraw all validator commission ierr := app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, helpers.MustGetOperatorAddr(val)) + _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, internalsdk.MustGetOperatorAddr(val)) return false }) if ierr != nil { @@ -136,7 +136,7 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str // reinitialize all validators ierr = app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { // donate any unwithdrawn outstanding reward fraction tokens to the community pool - scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, helpers.MustGetOperatorAddr(val)) + scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, internalsdk.MustGetOperatorAddr(val)) if err != nil { panic(err) } @@ -150,7 +150,7 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str panic(err) } - if err = app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, helpers.MustGetOperatorAddr(val)); err != nil { + if err = app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, internalsdk.MustGetOperatorAddr(val)); err != nil { panic(err) } return false diff --git a/app/upgrades_test.go b/app/upgrades_test.go index 2f366ffd08..251b4995ae 100644 --- a/app/upgrades_test.go +++ b/app/upgrades_test.go @@ -21,7 +21,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank/testutil" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/provenance-io/provenance/internal/helpers" + internalsdk "github.com/provenance-io/provenance/internal/sdk" ) type UpgradeTestSuite struct { @@ -265,7 +265,7 @@ func (s *UpgradeTestSuite) DelegateToValidator(valAddress sdk.ValAddress, delega } func (s *UpgradeTestSuite) GetOperatorAddr(val stakingtypes.ValidatorI) sdk.ValAddress { - addr, err := helpers.GetOperatorAddr(val) + addr, err := internalsdk.GetOperatorAddr(val) s.Require().NoError(err, "GetOperatorAddr(%q)", val.GetOperator()) return addr } diff --git a/go.mod b/go.mod index 39fa4c47c9..7dfea51821 100644 --- a/go.mod +++ b/go.mod @@ -37,7 +37,7 @@ require ( github.com/spf13/cast v1.6.0 github.com/spf13/cobra v1.8.0 github.com/spf13/pflag v1.0.5 - github.com/spf13/viper v1.18.2 + github.com/spf13/viper v1.19.0 github.com/stretchr/testify v1.9.0 golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 golang.org/x/text v0.15.0 @@ -116,7 +116,7 @@ require ( github.com/google/orderedcode v0.0.1 // indirect github.com/google/s2a-go v0.1.7 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect - github.com/googleapis/gax-go/v2 v2.12.2 // indirect + github.com/googleapis/gax-go/v2 v2.12.3 // indirect github.com/gorilla/handlers v1.5.2 // indirect github.com/gorilla/websocket v1.5.1 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect @@ -156,7 +156,7 @@ require ( github.com/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a // indirect github.com/oklog/run v1.1.0 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect - github.com/pelletier/go-toml/v2 v2.1.0 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/petermattis/goid v0.0.0-20230904192822-1876fd5063bc // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect @@ -195,7 +195,7 @@ require ( golang.org/x/sys v0.19.0 // indirect golang.org/x/term v0.19.0 // indirect golang.org/x/time v0.5.0 // indirect - google.golang.org/api v0.169.0 // indirect + google.golang.org/api v0.171.0 // indirect google.golang.org/appengine v1.6.8 // indirect google.golang.org/genproto v0.0.0-20240227224415-6ceb2ff114de // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20240401170217-c3f982113cda // indirect diff --git a/go.sum b/go.sum index 5b36bdf1d0..e106744a80 100644 --- a/go.sum +++ b/go.sum @@ -610,8 +610,8 @@ github.com/googleapis/gax-go/v2 v2.3.0/go.mod h1:b8LNqSzNabLiUpXKkY7HAR5jr6bIT99 github.com/googleapis/gax-go/v2 v2.4.0/go.mod h1:XOTVJ59hdnfJLIP/dh8n5CGryZR2LxK9wbMD5+iXC6c= github.com/googleapis/gax-go/v2 v2.5.1/go.mod h1:h6B0KMMFNtI2ddbGJn3T3ZbwkeT6yqEF02fYlzkUCyo= github.com/googleapis/gax-go/v2 v2.6.0/go.mod h1:1mjbznJAPHFpesgE5ucqfYEscaz5kMdcIDwU/6+DDoY= -github.com/googleapis/gax-go/v2 v2.12.2 h1:mhN09QQW1jEWeMF74zGR81R30z4VJzjZsfkUhuHF+DA= -github.com/googleapis/gax-go/v2 v2.12.2/go.mod h1:61M8vcyyXR2kqKFxKrfA22jaA8JGF7Dc8App1U3H6jc= +github.com/googleapis/gax-go/v2 v2.12.3 h1:5/zPPDvw8Q1SuXjrqrZslrqT7dL/uJT2CQii/cLCKqA= +github.com/googleapis/gax-go/v2 v2.12.3/go.mod h1:AKloxT6GtNbaLm8QTNSidHUVsHYcBHwWRvkNFJUQcS4= github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+cLsWGBF62rFAi7WjWO4= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= @@ -854,8 +854,8 @@ github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144T github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= -github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4= -github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= +github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o= github.com/petermattis/goid v0.0.0-20230904192822-1876fd5063bc h1:8bQZVK1X6BJR/6nYUPxQEP+ReTsceJTKizeuwjWOPUA= @@ -976,8 +976,8 @@ github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIn github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= -github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ= -github.com/spf13/viper v1.18.2/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMVB+yk= +github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= +github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg= github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI= @@ -1496,8 +1496,8 @@ google.golang.org/api v0.96.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ google.golang.org/api v0.97.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ13s= google.golang.org/api v0.98.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ13s= google.golang.org/api v0.100.0/go.mod h1:ZE3Z2+ZOr87Rx7dqFsdRQkRBk36kDtp/h+QpHbB7a70= -google.golang.org/api v0.169.0 h1:QwWPy71FgMWqJN/l6jVlFHUa29a7dcUy02I8o799nPY= -google.golang.org/api v0.169.0/go.mod h1:gpNOiMA2tZ4mf5R9Iwf4rK/Dcz0fbdIgWYWVoxmsyLg= +google.golang.org/api v0.171.0 h1:w174hnBPqut76FzW5Qaupt7zY8Kql6fiVjgys4f58sU= +google.golang.org/api v0.171.0/go.mod h1:Hnq5AHm4OTMt2BUVjael2CWZFD6vksJdWCWiUAmjC9o= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= diff --git a/internal/helpers/maps.go b/internal/collections/maps.go similarity index 96% rename from internal/helpers/maps.go rename to internal/collections/maps.go index 3912b6b091..979e80bdcc 100644 --- a/internal/helpers/maps.go +++ b/internal/collections/maps.go @@ -1,4 +1,4 @@ -package helpers +package collections // This file houses functions that are in "golang.org/x/exp/maps" but not "maps", but that we want to use. // If any show up in "maps", delete them from here and switch uses to the official ones. diff --git a/internal/handlers/msg_service_router.go b/internal/handlers/msg_service_router.go index aa1f400f4a..758ea3cecd 100644 --- a/internal/handlers/msg_service_router.go +++ b/internal/handlers/msg_service_router.go @@ -18,8 +18,8 @@ import ( "github.com/cosmos/gogoproto/proto" "github.com/provenance-io/provenance/internal/antewrapper" - "github.com/provenance-io/provenance/internal/helpers" "github.com/provenance-io/provenance/internal/protocompat" + internalsdk "github.com/provenance-io/provenance/internal/sdk" msgfeeskeeper "github.com/provenance-io/provenance/x/msgfees/keeper" ) @@ -169,7 +169,7 @@ func (msr *PioMsgServiceRouter) registerMsgServiceHandler(sd *grpc.ServiceDesc, return handler(goCtx, req) } - if err = helpers.ValidateBasic(req); err != nil { + if err = internalsdk.ValidateBasic(req); err != nil { return nil, err } diff --git a/internal/provwasm/message_encoders.go b/internal/provwasm/message_encoders.go index 7c8e3dc355..47000d9723 100644 --- a/internal/provwasm/message_encoders.go +++ b/internal/provwasm/message_encoders.go @@ -12,7 +12,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/provenance-io/provenance/internal/helpers" + internalsdk "github.com/provenance-io/provenance/internal/sdk" ) // Encoder describes behavior for provenance smart contract message encoding. @@ -65,7 +65,7 @@ func customEncoders(registry *EncoderRegistry, logger log.Logger) wasmkeeper.Cus return nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } for _, msg := range msgs { - if err := helpers.ValidateBasic(msg); err != nil { + if err := internalsdk.ValidateBasic(msg); err != nil { logger.Error("message validation failed", "err", err) return nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } diff --git a/internal/provwasm/stargate_whitelist.go b/internal/provwasm/stargate_whitelist.go index 0f77489027..4ba0321b7d 100644 --- a/internal/provwasm/stargate_whitelist.go +++ b/internal/provwasm/stargate_whitelist.go @@ -24,6 +24,8 @@ import ( msgfeestypes "github.com/provenance-io/provenance/x/msgfees/types" nametypes "github.com/provenance-io/provenance/x/name/types" oracletypes "github.com/provenance-io/provenance/x/oracle/types" + "github.com/provenance-io/provenance/x/quarantine" + "github.com/provenance-io/provenance/x/sanction" triggertypes "github.com/provenance-io/provenance/x/trigger/types" ) @@ -65,6 +67,17 @@ func init() { setWhitelistedQuery("/cosmos.gov.v1beta1.Query/Params", &govtypes.QueryParamsResponse{}) setWhitelistedQuery("/cosmos.gov.v1beta1.Query/Vote", &govtypes.QueryVoteResponse{}) + // quarantine + setWhitelistedQuery("/cosmos.quarantine.v1beta1.Query/IsQuarantined", &quarantine.QueryIsQuarantinedResponse{}) + setWhitelistedQuery("/cosmos.quarantine.v1beta1.Query/QuarantinedFunds", &quarantine.QueryQuarantinedFundsResponse{}) + setWhitelistedQuery("/cosmos.quarantine.v1beta1.Query/AutoResponses", &quarantine.QueryAutoResponsesResponse{}) + + // sanction + setWhitelistedQuery("/cosmos.sanction.v1beta1.Query/IsSanctioned", &sanction.QueryIsSanctionedResponse{}) + setWhitelistedQuery("/cosmos.sanction.v1beta1.Query/SanctionedAddresses", &sanction.QuerySanctionedAddressesResponse{}) + setWhitelistedQuery("/cosmos.sanction.v1beta1.Query/TemporaryEntries", &sanction.QueryTemporaryEntriesResponse{}) + setWhitelistedQuery("/cosmos.sanction.v1beta1.Query/Params", &sanction.QueryParamsResponse{}) + // slashing setWhitelistedQuery("/cosmos.slashing.v1beta1.Query/Params", &slashingtypes.QueryParamsResponse{}) setWhitelistedQuery("/cosmos.slashing.v1beta1.Query/SigningInfo", &slashingtypes.QuerySigningInfoResponse{}) diff --git a/internal/rand/account.go b/internal/rand/account.go new file mode 100644 index 0000000000..e5781076d0 --- /dev/null +++ b/internal/rand/account.go @@ -0,0 +1,12 @@ +package rand + +import ( + "math/rand" + + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" +) + +// SelectAccounts selects count accounts from the ones provided. +func SelectAccounts(r *rand.Rand, accs []simtypes.Account, count int) ([]simtypes.Account, error) { + return SelectEntries(r, accs, count, "accounts") +} diff --git a/internal/rand/int.go b/internal/rand/int.go new file mode 100644 index 0000000000..79cc69ad51 --- /dev/null +++ b/internal/rand/int.go @@ -0,0 +1,8 @@ +package rand + +import "math/rand" + +// IntBetween generates a random number between min and max inclusive. +func IntBetween(r *rand.Rand, min, max int) int { + return r.Intn(max-min+1) + min +} diff --git a/internal/rand/int_test.go b/internal/rand/int_test.go new file mode 100644 index 0000000000..690ff1b868 --- /dev/null +++ b/internal/rand/int_test.go @@ -0,0 +1,94 @@ +package rand + +import ( + "fmt" + "math/rand" + "slices" + "testing" + + internalcollections "github.com/provenance-io/provenance/internal/collections" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestIntBetween(t *testing.T) { + tests := []struct { + min int + max int + expPanic bool + }{ + {min: 0, max: 0}, + {min: 0, max: 10}, + {min: 1, max: 1}, + {min: -1, max: -1}, + {min: 1, max: 0, expPanic: true}, + {min: 0, max: -1, expPanic: true}, + {min: 1, max: -1, expPanic: true}, + {min: 10, max: -20, expPanic: true}, + {min: 10, max: -11, expPanic: true}, + {min: 10, max: -10, expPanic: true}, + {min: 10, max: -9, expPanic: true}, + {min: 10, max: 9, expPanic: true}, + {min: 10, max: 10}, + {min: 10, max: 11}, + {min: 10, max: 20}, + {min: -10, max: -11, expPanic: true}, + {min: -10, max: -10}, + {min: -10, max: -9}, + {min: -10, max: 9}, + {min: -10, max: 10}, + {min: -10, max: 11}, + {min: -20, max: -1}, + {min: -20, max: 0}, + {min: -20, max: 1}, + {min: 1001, max: 1100}, + {min: -1778, max: -1670}, + } + + for _, tc := range tests { + name := fmt.Sprintf("RandIntBetween(%d, %d)", tc.min, tc.max) + if tc.expPanic { + name += " panics" + } + + t.Run(name, func(t *testing.T) { + r := rand.New(rand.NewSource(1)) + // Check for panic for the first try. + seen := make(map[int]bool) + testFunc := func() { + val := IntBetween(r, tc.min, tc.max) + seen[val] = true + } + if tc.expPanic { + require.PanicsWithValue(t, "invalid argument to Intn", testFunc) + return + } + require.NotPanics(t, testFunc) + + count := tc.max - tc.min + 1 + expected := make([]int, 0, count) + for i := tc.min; i <= tc.max; i++ { + expected = append(expected, i) + } + + // Run it a bunch of times, trying to get it to return all possible values. + // I chose count*100 to essentially give each value 100 chances to be chosen, but be + // low enough to still finish pretty quickly if one or more values never gets returned. + for i := 0; i < count*100 && len(seen) < count; i++ { + testFunc() + } + // Make sure both the min and max were returned at some point. + assert.True(t, seen[tc.min], "minimum value %d in seen map", tc.min) + assert.True(t, seen[tc.max], "maximum value %d in seen map", tc.max) + + seenVals := internalcollections.Keys(seen) + slices.Sort(seenVals) + // Make sure the smallest and largest are as expected. + assert.Equal(t, tc.min, seenVals[0], "smallest number generated") + assert.Equal(t, tc.max, seenVals[len(seenVals)-1], "largest number generated") + // Make sure all values were generated. This check technically covers the previous ones, + // but I've got them split out like this for friendlier test failure messages. + assert.Equal(t, expected, seenVals, "values generated") + }) + } +} diff --git a/internal/helpers/rand.go b/internal/rand/slices.go similarity index 50% rename from internal/helpers/rand.go rename to internal/rand/slices.go index 4b02030477..0de960b9e6 100644 --- a/internal/helpers/rand.go +++ b/internal/rand/slices.go @@ -1,20 +1,13 @@ -package helpers +package rand import ( "fmt" "math/rand" - - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" ) -// RandIntBetween generates a random number between min and max inclusive. -func RandIntBetween(r *rand.Rand, min, max int) int { - return r.Intn(max-min+1) + min -} - -// SelectRandomEntries selects count entries from the ones provided. +// SelectEntries selects count entries from the ones provided. // The entriesType string is used in the error message to describe the entries slice. -func SelectRandomEntries[E any](r *rand.Rand, entries []E, count int, entriesType string) ([]E, error) { +func SelectEntries[E any](r *rand.Rand, entries []E, count int, entriesType string) ([]E, error) { if count == 0 { return nil, nil } @@ -36,8 +29,3 @@ func SelectRandomEntries[E any](r *rand.Rand, entries []E, count int, entriesTyp }) return randomized[:count], nil } - -// SelectRandomAccounts selects count accounts from the ones provided. -func SelectRandomAccounts(r *rand.Rand, accs []simtypes.Account, count int) ([]simtypes.Account, error) { - return SelectRandomEntries(r, accs, count, "accounts") -} diff --git a/internal/helpers/rand_test.go b/internal/rand/slices_test.go similarity index 62% rename from internal/helpers/rand_test.go rename to internal/rand/slices_test.go index fd619caba5..288269f6d0 100644 --- a/internal/helpers/rand_test.go +++ b/internal/rand/slices_test.go @@ -1,9 +1,8 @@ -package helpers +package rand import ( "fmt" "math/rand" - "slices" "testing" "github.com/stretchr/testify/assert" @@ -12,89 +11,7 @@ import ( "github.com/provenance-io/provenance/testutil/assertions" ) -func TestRandIntBetween(t *testing.T) { - tests := []struct { - min int - max int - expPanic bool - }{ - {min: 0, max: 0}, - {min: 0, max: 10}, - {min: 1, max: 1}, - {min: -1, max: -1}, - {min: 1, max: 0, expPanic: true}, - {min: 0, max: -1, expPanic: true}, - {min: 1, max: -1, expPanic: true}, - {min: 10, max: -20, expPanic: true}, - {min: 10, max: -11, expPanic: true}, - {min: 10, max: -10, expPanic: true}, - {min: 10, max: -9, expPanic: true}, - {min: 10, max: 9, expPanic: true}, - {min: 10, max: 10}, - {min: 10, max: 11}, - {min: 10, max: 20}, - {min: -10, max: -11, expPanic: true}, - {min: -10, max: -10}, - {min: -10, max: -9}, - {min: -10, max: 9}, - {min: -10, max: 10}, - {min: -10, max: 11}, - {min: -20, max: -1}, - {min: -20, max: 0}, - {min: -20, max: 1}, - {min: 1001, max: 1100}, - {min: -1778, max: -1670}, - } - - for _, tc := range tests { - name := fmt.Sprintf("RandIntBetween(%d, %d)", tc.min, tc.max) - if tc.expPanic { - name += " panics" - } - - t.Run(name, func(t *testing.T) { - r := rand.New(rand.NewSource(1)) - // Check for panic for the first try. - seen := make(map[int]bool) - testFunc := func() { - val := RandIntBetween(r, tc.min, tc.max) - seen[val] = true - } - if tc.expPanic { - require.PanicsWithValue(t, "invalid argument to Intn", testFunc) - return - } - require.NotPanics(t, testFunc) - - count := tc.max - tc.min + 1 - expected := make([]int, 0, count) - for i := tc.min; i <= tc.max; i++ { - expected = append(expected, i) - } - - // Run it a bunch of times, trying to get it to return all possible values. - // I chose count*100 to essentially give each value 100 chances to be chosen, but be - // low enough to still finish pretty quickly if one or more values never gets returned. - for i := 0; i < count*100 && len(seen) < count; i++ { - testFunc() - } - // Make sure both the min and max were returned at some point. - assert.True(t, seen[tc.min], "minimum value %d in seen map", tc.min) - assert.True(t, seen[tc.max], "maximum value %d in seen map", tc.max) - - seenVals := Keys(seen) - slices.Sort(seenVals) - // Make sure the smallest and largest are as expected. - assert.Equal(t, tc.min, seenVals[0], "smallest number generated") - assert.Equal(t, tc.max, seenVals[len(seenVals)-1], "largest number generated") - // Make sure all values were generated. This check technically covers the previous ones, - // but I've got them split out like this for friendlier test failure messages. - assert.Equal(t, expected, seenVals, "values generated") - }) - } -} - -func TestSelectRandomEntries(t *testing.T) { +func TestSelectEntries(t *testing.T) { entries := make([]string, 3) for i := range entries { entries[i] = fmt.Sprintf("entry_%02d", i) @@ -273,7 +190,7 @@ func TestSelectRandomEntries(t *testing.T) { var actual []string var err error testFunc := func() { - actual, err = SelectRandomEntries(r, tc.entries, tc.count, tc.entriesType) + actual, err = SelectEntries(r, tc.entries, tc.count, tc.entriesType) } require.NotPanics(t, testFunc, "SelectRandomEntries") assertions.AssertErrorValue(t, err, tc.expErr, "SelectRandomEntries error") diff --git a/internal/helpers/sdk.go b/internal/sdk/validator.go similarity index 98% rename from internal/helpers/sdk.go rename to internal/sdk/validator.go index c6c3e61980..b394546f3a 100644 --- a/internal/helpers/sdk.go +++ b/internal/sdk/validator.go @@ -1,4 +1,4 @@ -package helpers +package sdk import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/exchange/client/cli/tx_test.go b/x/exchange/client/cli/tx_test.go index 7105e20ec1..d9dfb23180 100644 --- a/x/exchange/client/cli/tx_test.go +++ b/x/exchange/client/cli/tx_test.go @@ -12,7 +12,7 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/provenance-io/provenance/internal/helpers" + internalcollections "github.com/provenance-io/provenance/internal/collections" "github.com/provenance-io/provenance/x/exchange" "github.com/provenance-io/provenance/x/exchange/client/cli" ) @@ -1010,7 +1010,7 @@ func (s *CmdTestSuite) TestCmdTxMarketManagePermissions() { } } - addrOrder := helpers.Keys(expPerms) + addrOrder := internalcollections.Keys(expPerms) sort.Slice(addrOrder, func(i, j int) bool { return bytes.Compare(s.accountAddrs[addrOrder[i]], s.accountAddrs[addrOrder[j]]) < 0 }) @@ -1042,7 +1042,7 @@ func (s *CmdTestSuite) TestCmdTxMarketManagePermissions() { 3: {exchange.Permission_cancel, exchange.Permission_attributes}, } - addrOrder := helpers.Keys(expPerms) + addrOrder := internalcollections.Keys(expPerms) sort.Slice(addrOrder, func(i, j int) bool { return bytes.Compare(s.accountAddrs[addrOrder[i]], s.accountAddrs[addrOrder[j]]) < 0 }) diff --git a/x/exchange/market_test.go b/x/exchange/market_test.go index 82240b93a7..9250ee1126 100644 --- a/x/exchange/market_test.go +++ b/x/exchange/market_test.go @@ -13,7 +13,7 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/provenance-io/provenance/internal/helpers" + internalcollections "github.com/provenance-io/provenance/internal/collections" "github.com/provenance-io/provenance/testutil/assertions" ) @@ -3153,7 +3153,7 @@ func TestPermission_Validate(t *testing.T) { } t.Run("all values have a test case", func(t *testing.T) { - allVals := helpers.Keys(Permission_name) + allVals := internalcollections.Keys(Permission_name) sort.Slice(allVals, func(i, j int) bool { return allVals[i] < allVals[j] }) @@ -3330,7 +3330,7 @@ func TestParsePermission(t *testing.T) { } t.Run("all values have a test case", func(t *testing.T) { - allVals := helpers.Keys(Permission_name) + allVals := internalcollections.Keys(Permission_name) sort.Slice(allVals, func(i, j int) bool { return allVals[i] < allVals[j] }) diff --git a/x/exchange/msgs_test.go b/x/exchange/msgs_test.go index 55cd29f434..45866ab416 100644 --- a/x/exchange/msgs_test.go +++ b/x/exchange/msgs_test.go @@ -16,8 +16,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/provenance-io/provenance/app" - "github.com/provenance-io/provenance/internal/helpers" "github.com/provenance-io/provenance/internal/pioconfig" + internalsdk "github.com/provenance-io/provenance/internal/sdk" "github.com/provenance-io/provenance/testutil" "github.com/provenance-io/provenance/testutil/assertions" @@ -218,7 +218,7 @@ func testValidateBasic(t *testing.T, msg sdk.Msg, expErr []string) { t.Helper() var err error testFunc := func() { - err = helpers.ValidateBasic(msg) + err = internalsdk.ValidateBasic(msg) } require.NotPanics(t, testFunc, "%T.ValidateBasic()", msg) diff --git a/x/hold/keeper/keeper_test.go b/x/hold/keeper/keeper_test.go index cb18fd1e9f..c722ca4266 100644 --- a/x/hold/keeper/keeper_test.go +++ b/x/hold/keeper/keeper_test.go @@ -19,7 +19,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank/testutil" "github.com/provenance-io/provenance/app" - "github.com/provenance-io/provenance/internal/helpers" + internalcollections "github.com/provenance-io/provenance/internal/collections" "github.com/provenance-io/provenance/testutil/assertions" "github.com/provenance-io/provenance/x/hold" "github.com/provenance-io/provenance/x/hold/keeper" @@ -1529,7 +1529,7 @@ func (s *TestSuite) TestVestingAndHoldOverTime() { } // Put all the step values in order. - steps := helpers.Keys(stepsMap) + steps := internalcollections.Keys(stepsMap) sort.Slice(steps, func(i, j int) bool { return steps[i] < steps[j] }) diff --git a/x/ibcratelimit/simulation/genesis.go b/x/ibcratelimit/simulation/genesis.go index aebc9f4e25..57b56a314c 100644 --- a/x/ibcratelimit/simulation/genesis.go +++ b/x/ibcratelimit/simulation/genesis.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/provenance-io/provenance/internal/helpers" + internalrand "github.com/provenance-io/provenance/internal/rand" "github.com/provenance-io/provenance/x/ibcratelimit" ) @@ -19,7 +19,7 @@ const ( // ContractFn randomized contract address func ContractFn(r *rand.Rand, accs []simtypes.Account) string { - randomAccount, _ := helpers.SelectRandomAccounts(r, accs, 1) + randomAccount, _ := internalrand.SelectAccounts(r, accs, 1) if r.Intn(2) > 0 || len(randomAccount) == 0 { return "" } diff --git a/x/name/simulation/operations.go b/x/name/simulation/operations.go index 6dbcd82281..1ea0fe3c07 100644 --- a/x/name/simulation/operations.go +++ b/x/name/simulation/operations.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" simappparams "github.com/provenance-io/provenance/app/params" - "github.com/provenance-io/provenance/internal/helpers" + internalrand "github.com/provenance-io/provenance/internal/rand" "github.com/provenance-io/provenance/x/name/keeper" "github.com/provenance-io/provenance/x/name/types" ) @@ -67,7 +67,7 @@ func SimulateMsgBindName(simState module.SimulationState, k keeper.Keeper, ak au return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgBindNameRequest{}), "no name records available to create under"), nil, nil } - nameLen := helpers.RandIntBetween(r, int(params.GetMinSegmentLength()), int(params.GetMaxSegmentLength())) + nameLen := internalrand.IntBetween(r, int(params.GetMinSegmentLength()), int(params.GetMaxSegmentLength())) newRecordName := simtypes.RandStringOfLength(r, nameLen) newRecordOwner := parentOwner if !parentRecord.Restricted { diff --git a/x/oracle/simulation/genesis.go b/x/oracle/simulation/genesis.go index 1c90f83e6d..2e63088a90 100644 --- a/x/oracle/simulation/genesis.go +++ b/x/oracle/simulation/genesis.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/provenance-io/provenance/internal/helpers" + internalrand "github.com/provenance-io/provenance/internal/rand" "github.com/provenance-io/provenance/x/oracle/types" ) @@ -22,13 +22,13 @@ func PortFn(r *rand.Rand) string { if r.Intn(2) > 0 { return "oracle" } - length := uint64(helpers.RandIntBetween(r, 6, 10)) + length := uint64(internalrand.IntBetween(r, 6, 10)) return strings.ToLower(simtypes.RandStringOfLength(r, int(length))) } // OracleFn randomized oracle address func OracleFn(r *rand.Rand, accs []simtypes.Account) string { - randomAccount, _ := helpers.SelectRandomAccounts(r, accs, 1) + randomAccount, _ := internalrand.SelectAccounts(r, accs, 1) if r.Intn(2) > 0 || len(randomAccount) == 0 { return "" } diff --git a/x/oracle/simulation/operations.go b/x/oracle/simulation/operations.go index ef6ad7692b..f2bc09fa68 100644 --- a/x/oracle/simulation/operations.go +++ b/x/oracle/simulation/operations.go @@ -18,8 +18,8 @@ import ( channelkeeper "github.com/cosmos/ibc-go/v8/modules/core/04-channel/keeper" simappparams "github.com/provenance-io/provenance/app/params" - "github.com/provenance-io/provenance/internal/helpers" "github.com/provenance-io/provenance/internal/pioconfig" + internalrand "github.com/provenance-io/provenance/internal/rand" "github.com/provenance-io/provenance/x/oracle/keeper" "github.com/provenance-io/provenance/x/oracle/types" ) @@ -71,7 +71,7 @@ func SimulateMsgSendQueryOracle(simState module.SimulationState, _ keeper.Keeper return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - raccs, err := helpers.SelectRandomAccounts(r, accs, 1) + raccs, err := internalrand.SelectAccounts(r, accs, 1) if err != nil { return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgSendQueryOracleRequest{}), err.Error()), nil, nil @@ -155,7 +155,7 @@ func randomChannel(r *rand.Rand, ctx sdk.Context, ck channelkeeper.Keeper) (stri } func randomQuery(r *rand.Rand) []byte { - queryType := helpers.RandIntBetween(r, 0, 3) + queryType := internalrand.IntBetween(r, 0, 3) var query string switch queryType { case 0: diff --git a/x/trigger/simulation/genesis.go b/x/trigger/simulation/genesis.go index 779c57cb17..6c83b5a55b 100644 --- a/x/trigger/simulation/genesis.go +++ b/x/trigger/simulation/genesis.go @@ -13,8 +13,8 @@ import ( sdktx "github.com/cosmos/cosmos-sdk/types/tx" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/provenance-io/provenance/internal/helpers" "github.com/provenance-io/provenance/internal/pioconfig" + internalrand "github.com/provenance-io/provenance/internal/rand" "github.com/provenance-io/provenance/x/trigger/types" ) @@ -31,12 +31,12 @@ const ( // TriggerIDStartFn randomized starting trigger id func TriggerIDStartFn(r *rand.Rand) uint64 { // max 5 ids for the triggers max 5 ids for the queue = min of 10 here. - return uint64(helpers.RandIntBetween(r, 10, 10000000000)) + return uint64(internalrand.IntBetween(r, 10, 10000000000)) } // QueueStartFn randomized Queue Start Index func QueueStartFn(r *rand.Rand) uint64 { - return uint64(helpers.RandIntBetween(r, 1, 10000000000)) + return uint64(internalrand.IntBetween(r, 1, 10000000000)) } // NewRandomEvent returns a random event @@ -44,16 +44,16 @@ func NewRandomEvent(r *rand.Rand, now time.Time) types.TriggerEventI { if r.Intn(2) > 0 { minimumTime := int(time.Second * 10) maximumTime := int(time.Minute * 5) - randTime := now.Add(time.Duration(helpers.RandIntBetween(r, minimumTime, maximumTime))) + randTime := now.Add(time.Duration(internalrand.IntBetween(r, minimumTime, maximumTime))) return &types.BlockTimeEvent{Time: randTime.UTC()} } - height := uint64(helpers.RandIntBetween(r, 10, 150)) + height := uint64(internalrand.IntBetween(r, 10, 150)) return &types.BlockHeightEvent{BlockHeight: height} } // NewRandomAction returns a random action func NewRandomAction(r *rand.Rand, from string, to string) sdk.Msg { - amount := int64(helpers.RandIntBetween(r, 100, 1000)) + amount := int64(internalrand.IntBetween(r, 100, 1000)) return &banktypes.MsgSend{ FromAddress: from, ToAddress: to, @@ -63,7 +63,7 @@ func NewRandomAction(r *rand.Rand, from string, to string) sdk.Msg { // NewRandomTrigger returns a random trigger func NewRandomTrigger(r *rand.Rand, simState *module.SimulationState, accs []simtypes.Account, id types.TriggerID) types.Trigger { - raccs, err := helpers.SelectRandomAccounts(r, accs, 2) + raccs, err := internalrand.SelectAccounts(r, accs, 2) if err != nil { panic(fmt.Errorf("NewRandomTrigger failed: %w", err)) } diff --git a/x/trigger/simulation/operations.go b/x/trigger/simulation/operations.go index 07299f946a..3209528577 100644 --- a/x/trigger/simulation/operations.go +++ b/x/trigger/simulation/operations.go @@ -16,8 +16,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" simappparams "github.com/provenance-io/provenance/app/params" - "github.com/provenance-io/provenance/internal/helpers" "github.com/provenance-io/provenance/internal/pioconfig" + internalrand "github.com/provenance-io/provenance/internal/rand" "github.com/provenance-io/provenance/x/trigger/keeper" "github.com/provenance-io/provenance/x/trigger/types" ) @@ -56,7 +56,7 @@ func SimulateMsgCreateTrigger(simState module.SimulationState, _ keeper.Keeper, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { now := ctx.BlockTime() - raccs, err := helpers.SelectRandomAccounts(r, accs, 2) + raccs, err := internalrand.SelectAccounts(r, accs, 2) if err != nil { return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgCreateTriggerRequest{}), err.Error()), nil, nil } diff --git a/x/trigger/types/genesis.go b/x/trigger/types/genesis.go index ce27dc3a63..17cc789b05 100644 --- a/x/trigger/types/genesis.go +++ b/x/trigger/types/genesis.go @@ -6,7 +6,7 @@ import ( types "github.com/cosmos/cosmos-sdk/codec/types" sdktx "github.com/cosmos/cosmos-sdk/types/tx" - "github.com/provenance-io/provenance/internal/helpers" + internalsdk "github.com/provenance-io/provenance/internal/sdk" ) var _ types.UnpackInterfacesMessage = (*GenesisState)(nil) @@ -60,7 +60,7 @@ func (gs GenesisState) Validate() error { } for idx, msg := range msgs { - if err = helpers.ValidateBasic(msg); err != nil { + if err = internalsdk.ValidateBasic(msg); err != nil { return fmt.Errorf("trigger id: %d, msg: %d, err: %w", trigger.GetId(), idx, err) } } diff --git a/x/trigger/types/msgs.go b/x/trigger/types/msgs.go index 3011335056..c554dc34b4 100644 --- a/x/trigger/types/msgs.go +++ b/x/trigger/types/msgs.go @@ -12,7 +12,7 @@ import ( sdktx "github.com/cosmos/cosmos-sdk/types/tx" simappparams "github.com/provenance-io/provenance/app/params" - "github.com/provenance-io/provenance/internal/helpers" + internalsdk "github.com/provenance-io/provenance/internal/sdk" ) // AllRequestMsgs defines all the Msg*Request messages. @@ -81,7 +81,7 @@ func (msg MsgCreateTriggerRequest) ValidateBasic() error { sigCtx := simappparams.AppEncodingConfig.InterfaceRegistry.SigningContext() for idx, action := range actions { - if err = helpers.ValidateBasic(action); err != nil { + if err = internalsdk.ValidateBasic(action); err != nil { return fmt.Errorf("action: %d: %w", idx, err) } if err = hasSigners(sigCtx, authorities, action); err != nil {