diff --git a/.golangci.yml b/.golangci.yml index 3dc12bb05..8000bcac6 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,27 +1,23 @@ linters-settings: govet: - check-shadowing: true + enable: + - shadow -# TODO_TECHDEBT: Enable each linter listed, 1 by 1, fixing issues as they appear. -# Don't forget to delete the `disable-all: true` line as well. linters: disable-all: true enable: -# - govet -# - revive -# - errcheck -# - unused + - errcheck + - gosimple - goimports + - govet + - ineffassign + - staticcheck + - unused issues: exclude-use-default: true max-issues-per-linter: 0 max-same-issues: 0 - # TODO_CONSIDERATION/TODO_TECHDEBT: Perhaps we should prefer enforcing the best - # practices suggested by the linters over convention or the default in generated - # code (where possible). The more exceptions we have, the bigger the gaps will be - # in our linting coverage. We could eliminate or reduce these exceptions step- - # by-step. exclude-rules: # Exclude cosmos-sdk module genesis.go files as they are generated with an # empty import block containing a comment used by ignite CLI. @@ -48,6 +44,7 @@ issues: - path: ^x/.+/codec.go$ linters: - revive + # Exclude test files from errcheck linter - path: _test\.go$ linters: - errcheck diff --git a/Makefile b/Makefile index 9e2295d54..28cb34a04 100644 --- a/Makefile +++ b/Makefile @@ -85,11 +85,10 @@ endif #################### # TODO_IMPROVE(@okdas): Add other dependencies (ignite, docker, k8s, etc) here -# TODO_BLOCKER(@okdas): bump `golangci-lint` when we upgrade golang to 1.21+ .PHONY: install_ci_deps install_ci_deps: ## Installs `mockgen` and other go tools go install "github.com/golang/mock/mockgen@v1.6.0" && mockgen --version - go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.53.3 && golangci-lint --version + go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.59.1 && golangci-lint --version go install golang.org/x/tools/cmd/goimports@latest go install github.com/mikefarah/yq/v4@latest diff --git a/Tiltfile b/Tiltfile index 5af009be2..f4f8ab790 100644 --- a/Tiltfile +++ b/Tiltfile @@ -150,20 +150,20 @@ configmap_create( secret_create_generic( "poktrolld-keys", from_file=listdir("localnet/poktrolld/keyring-test/") ) + +# Import validator keys for the poktrolld helm chart to consume +secret_create_generic( + "poktrolld-validator-keys", + from_file=[ + "localnet/poktrolld/config/node_key.json", + "localnet/poktrolld/config/priv_validator_key.json", + ], +) + # Import configuration files into Kubernetes ConfigMap configmap_create( "poktrolld-configs", from_file=listdir("localnet/poktrolld/config/"), watch=True ) -# TODO_BLOCKER(@okdas): Import validator keys when we switch to `poktrolld` helm chart -# by uncommenting the following lines: -# load("ext://secret", "secret_create_generic") -# secret_create_generic( -# "poktrolld-validator-keys", -# from_file=[ -# "localnet/poktrolld/config/node_key.json", -# "localnet/poktrolld/config/priv_validator_key.json", -# ], -# ) # Hot reload protobuf changes local_resource( diff --git a/app/app.go b/app/app.go index e86cf6fce..6f14c8bf3 100644 --- a/app/app.go +++ b/app/app.go @@ -190,7 +190,7 @@ func New( appBuilder *runtime.AppBuilder // merge the AppConfig and other configuration in one config - appConfig = depinject.Configs( + deps = depinject.Configs( AppConfig(), depinject.Supply( // Supply the application options @@ -246,7 +246,7 @@ func New( ) ) - if err := depinject.Inject(appConfig, + if err := depinject.Inject(deps, &appBuilder, &app.appCodec, &app.legacyAmino, diff --git a/app/export.go b/app/export.go index 21203b274..7b8fef07f 100644 --- a/app/export.go +++ b/app/export.go @@ -94,9 +94,9 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str } for _, delegation := range dels { - valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) - if err != nil { - panic(err) + valAddr, bech32Err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) + if bech32Err != nil { + panic(bech32Err) } delAddr := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress) @@ -116,25 +116,25 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str // reinitialize all validators err = app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - valBz, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) - if err != nil { - panic(err) + valBz, addrErr := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + if addrErr != nil { + panic(addrErr) } // donate any unwithdrawn outstanding reward fraction tokens to the community pool - scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, valBz) - if err != nil { - panic(err) + scraps, rewardsErr := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, valBz) + if rewardsErr != nil { + panic(rewardsErr) } - feePool, err := app.DistrKeeper.FeePool.Get(ctx) - if err != nil { - panic(err) + feePool, feeErr := app.DistrKeeper.FeePool.Get(ctx) + if feeErr != nil { + panic(feeErr) } feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) - if err := app.DistrKeeper.FeePool.Set(ctx, feePool); err != nil { + if err = app.DistrKeeper.FeePool.Set(ctx, feePool); err != nil { panic(err) } - if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, valBz); err != nil { + if err = app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, valBz); err != nil { panic(err) } return false @@ -142,18 +142,18 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str // reinitialize all delegations for _, del := range dels { - valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress) - if err != nil { - panic(err) + valAddr, bech32Err := sdk.ValAddressFromBech32(del.ValidatorAddress) + if bech32Err != nil { + panic(bech32Err) } delAddr := sdk.MustAccAddressFromBech32(del.DelegatorAddress) - if err := app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil { + if err = app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil { // never called as BeforeDelegationCreated always returns nil panic(fmt.Errorf("error while incrementing period: %w", err)) } - if err := app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr); err != nil { + if err = app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr); err != nil { // never called as AfterDelegationModified always returns nil panic(fmt.Errorf("error while creating a new delegation period record: %w", err)) } @@ -165,7 +165,7 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str /* Handle staking state. */ // iterate through redelegations, reset creation height - app.StakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) { + err = app.StakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) { for i := range red.Entries { red.Entries[i].CreationHeight = 0 } @@ -175,9 +175,12 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str } return false }) + if err != nil { + panic(fmt.Errorf("unable to iterate reldelegations: %w", err)) + } // iterate through unbonding delegations, reset creation height - app.StakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) { + err = app.StakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) { for i := range ubd.Entries { ubd.Entries[i].CreationHeight = 0 } @@ -187,6 +190,9 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str } return false }) + if err != nil { + panic(fmt.Errorf("unable to iterate unbonding delegations: %w", err)) + } // Iterate through validators by power descending, reset bond heights, and // update bond intra-tx counters. @@ -196,8 +202,8 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str for ; iter.Valid(); iter.Next() { addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key())) - validator, err := app.StakingKeeper.GetValidator(ctx, addr) - if err != nil { + validator, valErr := app.StakingKeeper.GetValidator(ctx, addr) + if valErr != nil { panic("expected validator, not found") } @@ -206,11 +212,13 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str validator.Jailed = true } - app.StakingKeeper.SetValidator(ctx, validator) + if err = app.StakingKeeper.SetValidator(ctx, validator); err != nil { + panic(fmt.Errorf("unable to set validator: %v: %w", validator, err)) + } counter++ } - if err := iter.Close(); err != nil { + if err = iter.Close(); err != nil { app.Logger().Error("error while closing the key-value store reverse prefix iterator: ", err) return } @@ -223,12 +231,16 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str /* Handle slashing state. */ // reset start height on signing infos - app.SlashingKeeper.IterateValidatorSigningInfos( + if err = app.SlashingKeeper.IterateValidatorSigningInfos( ctx, func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) { info.StartHeight = 0 - app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info) + if err = app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info); err != nil { + panic(fmt.Errorf("unable to set validator signing info: %w", err)) + } return false }, - ) + ); err != nil { + panic(fmt.Errorf("unable to iterate validator signing infos: %w", err)) + } } diff --git a/app/ibc.go b/app/ibc.go index 2b0bd5691..f407d1bd7 100644 --- a/app/ibc.go +++ b/app/ibc.go @@ -26,7 +26,7 @@ import ( ibctransferkeeper "github.com/cosmos/ibc-go/v8/modules/apps/transfer/keeper" ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" ibc "github.com/cosmos/ibc-go/v8/modules/core" - ibcclienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" + ibcclienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" //nolint:staticcheck // SA1019 ibcconnectiontypes "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" porttypes "github.com/cosmos/ibc-go/v8/modules/core/05-port/types" ibcexported "github.com/cosmos/ibc-go/v8/modules/core/exported" diff --git a/cmd/poktrolld/cmd/commands.go b/cmd/poktrolld/cmd/commands.go index 7eb957904..1fe0422d3 100644 --- a/cmd/poktrolld/cmd/commands.go +++ b/cmd/poktrolld/cmd/commands.go @@ -177,7 +177,7 @@ func appExport( return servertypes.ExportedApp{}, err } - if err := bApp.LoadHeight(height); err != nil { + if err = bApp.LoadHeight(height); err != nil { return servertypes.ExportedApp{}, err } } else { diff --git a/cmd/poktrolld/cmd/root.go b/cmd/poktrolld/cmd/root.go index 045e3505a..d335eecd1 100644 --- a/cmd/poktrolld/cmd/root.go +++ b/cmd/poktrolld/cmd/root.go @@ -1,6 +1,8 @@ package cmd import ( + "errors" + "log" "os" "strings" @@ -8,7 +10,7 @@ import ( clientv2keyring "cosmossdk.io/client/v2/autocli/keyring" "cosmossdk.io/core/address" "cosmossdk.io/depinject" - "cosmossdk.io/log" + cosmoslog "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/config" "github.com/cosmos/cosmos-sdk/client/flags" @@ -43,7 +45,7 @@ func NewRootCmd() *cobra.Command { if err := depinject.Inject( depinject.Configs(app.AppConfig(), depinject.Supply( - log.NewNopLogger(), + cosmoslog.NewNopLogger(), ), depinject.Provide( ProvideClientContext, @@ -62,13 +64,13 @@ func NewRootCmd() *cobra.Command { Use: app.Name + "d", Short: "Start poktroll node", SilenceErrors: true, - PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { + PersistentPreRunE: func(cmd *cobra.Command, _ []string) (err error) { // set the default command outputs cmd.SetOut(cmd.OutOrStdout()) cmd.SetErr(cmd.ErrOrStderr()) clientCtx = clientCtx.WithCmdContext(cmd.Context()) - clientCtx, err := client.ReadPersistentCommandFlags(clientCtx, cmd.Flags()) + clientCtx, err = client.ReadPersistentCommandFlags(clientCtx, cmd.Flags()) if err != nil { return err } @@ -91,11 +93,11 @@ func NewRootCmd() *cobra.Command { } clientCtx = clientCtx.WithTxConfig(txConfigWithTextual) - if err := client.SetCmdClientContextHandler(clientCtx, cmd); err != nil { + if err = client.SetCmdClientContextHandler(clientCtx, cmd); err != nil { return err } - if err := client.SetCmdClientContextHandler(clientCtx, cmd); err != nil { + if err = client.SetCmdClientContextHandler(clientCtx, cmd); err != nil { return err } @@ -115,10 +117,12 @@ func NewRootCmd() *cobra.Command { } initRootCmd(rootCmd, clientCtx.TxConfig, clientCtx.InterfaceRegistry, clientCtx.Codec, moduleBasicManager) - overwriteFlagDefaults(rootCmd, map[string]string{ + if err := overwriteFlagDefaults(rootCmd, map[string]string{ flags.FlagChainID: strings.ReplaceAll(app.Name, "-", ""), flags.FlagKeyringBackend: "test", - }) + }); err != nil { + log.Fatal(err) + } if err := autoCliOpts.EnhanceRootCommand(rootCmd); err != nil { panic(err) @@ -137,20 +141,24 @@ func NewRootCmd() *cobra.Command { return rootCmd } -func overwriteFlagDefaults(c *cobra.Command, defaults map[string]string) { - set := func(s *pflag.FlagSet, key, val string) { +func overwriteFlagDefaults(c *cobra.Command, defaults map[string]string) (err error) { + set := func(s *pflag.FlagSet, key, val string) error { if f := s.Lookup(key); f != nil { f.DefValue = val - f.Value.Set(val) + if err = f.Value.Set(val); err != nil { + return err + } } + return nil } for key, val := range defaults { - set(c.Flags(), key, val) - set(c.PersistentFlags(), key, val) + err = errors.Join(err, set(c.Flags(), key, val)) + err = errors.Join(err, set(c.PersistentFlags(), key, val)) } for _, c := range c.Commands() { - overwriteFlagDefaults(c, defaults) + err = errors.Join(err, overwriteFlagDefaults(c, defaults)) } + return err } func ProvideClientContext( diff --git a/docs/docs.go b/docs/docs.go index 1ba96c79d..6994b8c9e 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -29,7 +29,7 @@ func handler(title string) http.HandlerFunc { t, _ := httptemplate.ParseFS(template, indexFile) return func(w http.ResponseWriter, req *http.Request) { - t.Execute(w, struct { + _ = t.Execute(w, struct { Title string URL string }{ diff --git a/go.mod b/go.mod index e7c81d428..3fbc306fb 100644 --- a/go.mod +++ b/go.mod @@ -79,6 +79,8 @@ require ( gopkg.in/yaml.v2 v2.4.0 ) +require golang.org/x/text v0.16.0 + require ( buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.34.2-20240508200655-46a4cf4ba109.2 // indirect buf.build/gen/go/bufbuild/registry/connectrpc/go v1.16.2-20240710174705-f2077dee5ad4.1 // indirect @@ -277,7 +279,6 @@ require ( golang.org/x/oauth2 v0.20.0 // indirect golang.org/x/sys v0.22.0 // indirect golang.org/x/term v0.22.0 // indirect - golang.org/x/text v0.16.0 // indirect golang.org/x/time v0.5.0 // indirect google.golang.org/api v0.169.0 // indirect google.golang.org/genproto v0.0.0-20240227224415-6ceb2ff114de // indirect diff --git a/pkg/appgateserver/sdkadapter/sdk.go b/pkg/appgateserver/sdkadapter/sdk.go index e00767ed3..5bbe1d00c 100644 --- a/pkg/appgateserver/sdkadapter/sdk.go +++ b/pkg/appgateserver/sdkadapter/sdk.go @@ -33,29 +33,29 @@ func NewShannonSDK( signingKey cryptotypes.PrivKey, deps depinject.Config, ) (*ShannonSDK, error) { - sessionClient, err := query.NewSessionQuerier(deps) - if err != nil { - return nil, err + sessionClient, sessionClientErr := query.NewSessionQuerier(deps) + if sessionClientErr != nil { + return nil, sessionClientErr } - accountClient, err := query.NewAccountQuerier(deps) - if err != nil { - return nil, err + accountClient, accountClientErr := query.NewAccountQuerier(deps) + if accountClientErr != nil { + return nil, accountClientErr } - appClient, err := query.NewApplicationQuerier(deps) - if err != nil { - return nil, err + appClient, appClientErr := query.NewApplicationQuerier(deps) + if appClientErr != nil { + return nil, appClientErr } blockClient := client.BlockClient(nil) - if err := depinject.Inject(deps, &blockClient); err != nil { - return nil, err + if depsErr := depinject.Inject(deps, &blockClient); depsErr != nil { + return nil, depsErr } - signer, err := NewSigner(signingKey) - if err != nil { - return nil, err + signer, signerErr := NewSigner(signingKey) + if signerErr != nil { + return nil, signerErr } shannonSDK := &ShannonSDK{ @@ -93,7 +93,9 @@ func (shannonSDK *ShannonSDK) SendRelay( Application: application, } - shannonSDK.signer.Sign(ctx, relayRequest, appRing) + if _, err = shannonSDK.signer.Sign(ctx, relayRequest, appRing); err != nil { + return nil, err + } relayRequestBz, err := relayRequest.Marshal() if err != nil { diff --git a/pkg/appgateserver/server.go b/pkg/appgateserver/server.go index 476640821..29d3af1ee 100644 --- a/pkg/appgateserver/server.go +++ b/pkg/appgateserver/server.go @@ -136,7 +136,7 @@ func (app *appGateServer) Start(ctx context.Context) error { // Shutdown the HTTP server when the context is done. go func() { <-ctx.Done() - app.server.Shutdown(ctx) + _ = app.server.Shutdown(ctx) }() // This hooks https://github.com/slok/go-http-metrics to the appgate server HTTP server. @@ -300,13 +300,15 @@ func (app *appGateServer) ServePprof(ctx context.Context, addr string) error { // If no error, start the server in a new goroutine go func() { app.logger.Info().Str("endpoint", addr).Msg("starting a pprof endpoint") - server.ListenAndServe() + if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + app.logger.Error().Str("endpoint", addr).Msg("unable to start a pprof endpoint") + } }() go func() { <-ctx.Done() app.logger.Info().Str("endpoint", addr).Msg("stopping a pprof endpoint") - server.Shutdown(ctx) + _ = server.Shutdown(ctx) }() return nil diff --git a/pkg/client/events/query_client.go b/pkg/client/events/query_client.go index 8fe84693b..e04731f8e 100644 --- a/pkg/client/events/query_client.go +++ b/pkg/client/events/query_client.go @@ -53,7 +53,6 @@ type eventsBytesAndConn struct { // either an error or the event message bytes. eventsBytes observable.Observable[either.Bytes] conn client.Connection - isClosed bool } // Close unsubscribes all observers of eventsBytesAndConn's observable and also diff --git a/pkg/client/events/replay_client.go b/pkg/client/events/replay_client.go index 938b03bd3..ac6e9aa73 100644 --- a/pkg/client/events/replay_client.go +++ b/pkg/client/events/replay_client.go @@ -227,8 +227,6 @@ func (rClient *replayClient[T]) goPublishEvents(ctx context.Context) { if publishErr != nil { panic(fmt.Errorf("EventsReplayClient[%T].goPublishEvents should never reach this spot: %w", *new(T), publishErr)) } - - return } // retryPublishEventsFactory returns a function which is intended to be passed @@ -242,7 +240,7 @@ func (rClient *replayClient[T]) retryPublishEventsFactory(ctx context.Context) f eventsBytesObs, err := rClient.eventsClient.EventsBytes(eventsBzCtx, rClient.queryString) if err != nil { - // No need to cancel eventsBytesObs in the case of a synchronous error. + cancelEventsBzObs() errCh <- err return errCh } diff --git a/pkg/client/events/replay_client_integration_test.go b/pkg/client/events/replay_client_integration_test.go index 30fe639be..1ccca2d49 100644 --- a/pkg/client/events/replay_client_integration_test.go +++ b/pkg/client/events/replay_client_integration_test.go @@ -29,8 +29,6 @@ type tEvent struct { Message string `json:"message"` } -type messageEventReplayObs observable.ReplayObservable[messageEvent] - func (t *tEvent) EventMessage() string { return t.Message } diff --git a/pkg/client/tx/client.go b/pkg/client/tx/client.go index d12da5cf2..85c8bad5e 100644 --- a/pkg/client/tx/client.go +++ b/pkg/client/tx/client.go @@ -160,7 +160,7 @@ func NewTxClient( opt(txnClient) } - if err := txnClient.validateConfigAndSetDefaults(); err != nil { + if err = txnClient.validateConfigAndSetDefaults(); err != nil { return nil, err } @@ -256,7 +256,7 @@ func (txnClient *txClient) SignAndBroadcast( // ensure transactions is valid // NOTE: this makes the transactions valid; i.e. it is *REQUIRED* - if err := txBuilder.GetTx().ValidateBasic(); err != nil { + if err = txBuilder.GetTx().ValidateBasic(); err != nil { return either.SyncErr(err) } diff --git a/pkg/crypto/protocol/errors.go b/pkg/crypto/protocol/errors.go index da3ba4e79..68c585782 100644 --- a/pkg/crypto/protocol/errors.go +++ b/pkg/crypto/protocol/errors.go @@ -1,5 +1,5 @@ package protocol var ( - codespace = "crypto/protocol" +// codespace = "crypto/protocol" ) diff --git a/pkg/crypto/rand/float_test.go b/pkg/crypto/rand/float_test.go index de2ac0f3f..5a7763c9a 100644 --- a/pkg/crypto/rand/float_test.go +++ b/pkg/crypto/rand/float_test.go @@ -2,6 +2,7 @@ package rand_test import ( "encoding/binary" + "fmt" "sync" "sync/atomic" "testing" @@ -23,25 +24,35 @@ func TestSeededFloat32(t *testing.T) { // Sample concurrently to save time. wg := sync.WaitGroup{} + errCh := make(chan error, 1) for idx := int64(0); idx < sampleSize; idx++ { wg.Add(1) - go func() { + go func(idx int64) { idxBz := make([]byte, binary.MaxVarintLen64) binary.PutVarint(idxBz, idx) randFloat, err := poktrand.SeededFloat32(idxBz) require.NoError(t, err) if randFloat < 0 || randFloat > 1 { - t.Fatalf("secureRandFloat64() returned out of bounds value: %f", randFloat) + errCh <- fmt.Errorf("secureRandFloat64() returned out of bounds value: %f", randFloat) + wg.Done() + return } if randFloat <= probability { numTrueSamples.Add(1) } wg.Done() - }() + }(idx) } - wg.Wait() + + go func() { + wg.Wait() + close(errCh) + }() + + err := <-errCh + require.NoError(t, err) expectedNumTrueSamples := float32(sampleSize) * probability expectedNumFalseSamples := float32(sampleSize) * (1 - probability) diff --git a/pkg/crypto/rings/cache.go b/pkg/crypto/rings/cache.go index 585c0e88b..001d93f82 100644 --- a/pkg/crypto/rings/cache.go +++ b/pkg/crypto/rings/cache.go @@ -5,7 +5,7 @@ import ( "sync" "cosmossdk.io/depinject" - ring "github.com/pokt-network/ring-go" + "github.com/pokt-network/ring-go" "github.com/pokt-network/poktroll/pkg/client" "github.com/pokt-network/poktroll/pkg/crypto" @@ -48,7 +48,7 @@ func NewRingCache(deps depinject.Config) (_ crypto.RingCache, err error) { } // Supply the account and application queriers to the RingCache. - if err := depinject.Inject( + if err = depinject.Inject( deps, &rc.logger, &rc.delegationClient, diff --git a/pkg/crypto/rings/client.go b/pkg/crypto/rings/client.go index 5a8210bf0..e60da469e 100644 --- a/pkg/crypto/rings/client.go +++ b/pkg/crypto/rings/client.go @@ -9,7 +9,7 @@ import ( ring_secp256k1 "github.com/athanorlabs/go-dleq/secp256k1" ringtypes "github.com/athanorlabs/go-dleq/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - ring "github.com/pokt-network/ring-go" + "github.com/pokt-network/ring-go" "github.com/pokt-network/poktroll/pkg/client" "github.com/pokt-network/poktroll/pkg/crypto" @@ -352,8 +352,7 @@ func ringPointsContain( // avoid nested loops when checking for its existence. // Since it's not possible to use bytes slices as keys in a map, we convert // the point to a string before using it as a key. - keyFromPoint := string(publicKey.Encode()) - if _, ok := ringPoints[keyFromPoint]; !ok { + if _, ok := ringPoints[string(publicKey.Encode())]; !ok { return false } } diff --git a/pkg/deps/config/suppliers.go b/pkg/deps/config/suppliers.go index 1c4334214..b00b7f54e 100644 --- a/pkg/deps/config/suppliers.go +++ b/pkg/deps/config/suppliers.go @@ -135,7 +135,7 @@ func NewSupplyQueryClientContextFn(queryNodeGRPCURL *url.URL) SupplierFn { // This flag is read by sdkclient.GetClientQueryContext. // Cosmos-SDK is expecting a GRPC address formatted as [:], // so we only need to set the Host parameter of the URL to cosmosflags.FlagGRPC value. - if err := cmd.Flags().Set(cosmosflags.FlagGRPC, queryNodeGRPCURL.Host); err != nil { + if err = cmd.Flags().Set(cosmosflags.FlagGRPC, queryNodeGRPCURL.Host); err != nil { return nil, err } @@ -196,7 +196,7 @@ func NewSupplyTxClientContextFn( // Set --node flag to the txNodeRPCURL for the client context // This flag is read by sdkclient.GetClientTxContext. - if err := cmd.Flags().Set(cosmosflags.FlagNode, txNodeRPCURL.String()); err != nil { + if err = cmd.Flags().Set(cosmosflags.FlagNode, txNodeRPCURL.String()); err != nil { return nil, err } @@ -205,7 +205,7 @@ func NewSupplyTxClientContextFn( // for transaction signing. // Cosmos-SDK is expecting a GRPC address formatted as [:], // so we only need to set the Host parameter of the URL to cosmosflags.FlagGRPC value. - if err := cmd.Flags().Set(cosmosflags.FlagGRPC, queryNodeGRPCURL.Host); err != nil { + if err = cmd.Flags().Set(cosmosflags.FlagGRPC, queryNodeGRPCURL.Host); err != nil { return nil, err } @@ -214,7 +214,7 @@ func NewSupplyTxClientContextFn( return nil, err } - if err := cmd.Flags().Set(cosmosflags.FlagChainID, tmpChainID); err != nil { + if err = cmd.Flags().Set(cosmosflags.FlagChainID, tmpChainID); err != nil { return nil, err } diff --git a/pkg/observable/channel/observable_test.go b/pkg/observable/channel/observable_test.go index 463368959..1a04f809b 100644 --- a/pkg/observable/channel/observable_test.go +++ b/pkg/observable/channel/observable_test.go @@ -113,7 +113,7 @@ func TestChannelObservable_NotifyObservers(t *testing.T) { observers[i] = obsvbl.Subscribe(ctx) } - group, ctx := errgroup.WithContext(ctx) + group := errgroup.Group{} // ensure all observer channels are notified for obsvrIdx, obsvr := range observers { @@ -187,7 +187,7 @@ func TestChannelObservable_UnsubscribeObservers(t *testing.T) { { name: "nil context", lifecycleFn: func() observable.Observer[int] { - observer := obsvbl.Subscribe(nil) + observer := obsvbl.Subscribe(nil) //nolint:staticcheck // nil context is intentional observer.Unsubscribe() return observer }, diff --git a/pkg/observable/channel/observer_manager.go b/pkg/observable/channel/observer_manager.go index 65acca5bc..0e419120d 100644 --- a/pkg/observable/channel/observer_manager.go +++ b/pkg/observable/channel/observer_manager.go @@ -52,7 +52,7 @@ func newObserverManager[V any]() *channelObserverManager[V] { } } -func (com *channelObserverManager[V]) notifyAll(notification V) { +func (com *channelObserverManager[V]) notifyAll(notification V) { //nolint:unused // Used in the observable implementation. // Copy currentObservers to avoid holding the lock while notifying them. // New or existing Observers may (un)subscribe while this notification // is being fanned out. @@ -74,7 +74,7 @@ func (com *channelObserverManager[V]) notifyAll(notification V) { // by the channelObservable implementation as well as embedders of observerManager // (e.g. replayObservable). // It panics if toAdd is not a channelObserver. -func (com *channelObserverManager[V]) add(toAdd observable.Observer[V]) { +func (com *channelObserverManager[V]) add(toAdd observable.Observer[V]) { //nolint:unused // Used in the observable implementation. // must (write) lock observersMu so that we can safely append to the observers list com.observersMu.Lock() defer com.observersMu.Unlock() @@ -86,7 +86,7 @@ func (com *channelObserverManager[V]) add(toAdd observable.Observer[V]) { // It implements the respective member of observerManager and is used by // the channelObservable implementation as well as embedders of observerManager // (e.g. replayObservable). -func (com *channelObserverManager[V]) remove(toRemove observable.Observer[V]) { +func (com *channelObserverManager[V]) remove(toRemove observable.Observer[V]) { //nolint:unused // Used in the observable implementation. // must (write) lock to iterate over and modify the observers list com.observersMu.Lock() defer com.observersMu.Unlock() @@ -103,7 +103,7 @@ func (com *channelObserverManager[V]) remove(toRemove observable.Observer[V]) { // It implements the respective member of observerManager and is used by // the channelObservable implementation as well as embedders of observerManager // (e.g. replayObservable). -func (com *channelObserverManager[V]) removeAll() { +func (com *channelObserverManager[V]) removeAll() { //nolint:unused // Used in the observable implementation. // Copy currentObservers to avoid holding the lock while unsubscribing them. // The observers at the time of locking, prior to copying, are the canonical // set of observers which are unsubscribed. @@ -124,10 +124,10 @@ func (com *channelObserverManager[V]) removeAll() { // goUnsubscribeOnDone unsubscribes from the subscription when the context is done. // It is a blocking function and intended to be called in a goroutine. -func (com *channelObserverManager[V]) goUnsubscribeOnDone( +func (com *channelObserverManager[V]) goUnsubscribeOnDone( //nolint:unused // Used in the observable implementation. ctx context.Context, observer observable.Observer[V], -) { +) { //nolint:unused // Used in the observable implementation. <-ctx.Done() if observer.IsClosed() { return @@ -137,7 +137,7 @@ func (com *channelObserverManager[V]) goUnsubscribeOnDone( // copyObservers returns a copy of the current observers list. It is safe to // call concurrently. Notably, it is not part of the observerManager interface. -func (com *channelObserverManager[V]) copyObservers() (observers []*channelObserver[V]) { +func (com *channelObserverManager[V]) copyObservers() (observers []*channelObserver[V]) { //nolint:unused // Used in the observable implementation. defer com.observersMu.RUnlock() // This loop blocks on acquiring a read lock on observersMu. If TryRLock diff --git a/pkg/observable/channel/replay_test.go b/pkg/observable/channel/replay_test.go index 067b82c79..ad3dbca97 100644 --- a/pkg/observable/channel/replay_test.go +++ b/pkg/observable/channel/replay_test.go @@ -140,7 +140,7 @@ func TestReplayObservable(t *testing.T) { } } - require.EqualValues(t, expectedValues, actualValues) + require.EqualValues(t, expectedValues, actualValues2) } func TestReplayObservable_Last_Full_ReplayBuffer(t *testing.T) { @@ -221,13 +221,13 @@ func TestReplayObservable_Last_Blocks_And_Times_Out(t *testing.T) { // than lastN values in the replay buffer. // Add a timeout to ensure that Last doesn't block indefinitely and return // whatever values are available in the replay buffer. - ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) + ctxWithTimeout, cancel := context.WithTimeout(ctx, 100*time.Millisecond) // Last should block until lastN values have been published or the timeout // specified above is reached. // NOTE: this will produce a warning log which can safely be ignored: // > WARN: requested replay buffer size 3 is greater than replay buffer // > capacity 3; returning entire replay buffer - lastValuesCh <- replayObsvbl.Last(ctx, lastN) + lastValuesCh <- replayObsvbl.Last(ctxWithTimeout, lastN) cancel() }() return lastValuesCh diff --git a/pkg/polylog/context.go b/pkg/polylog/context.go index 0e6904b64..eb80abff3 100644 --- a/pkg/polylog/context.go +++ b/pkg/polylog/context.go @@ -2,13 +2,17 @@ package polylog import "context" -// CtxKey is the key used to store the polylog.Logger in a context.Context. This -// is **independant** of any logger-implementation-specific context key that may -// be used internal to any of the logger implementations. Polylog attempts to +// CtxKey is a type which is intended to disambiguate polylog context keys from +// other context keys which may be used in the same context.Context. +type CtxKey string + +// PolylogCtxKey is the key used to store the polylog.Logger in a context.Context. +// This is **independent** of any logger-implementation-specific context key that +// may be used internal to any of the logger implementations. Polylog attempts to // provide a ubiquitous interface for storing and retrieving loggers from the // context but also to integrate with the underlying logger implementations as // seamlessly as possible. -const CtxKey = "polylog/context" +const PolylogCtxKey CtxKey = "polylog/context" // DefaultContextLogger is the default logger implementation used when no logger // is associated with a context. It is assigned in the implementation package's @@ -31,7 +35,7 @@ var DefaultContextLogger Logger // #WithContext() method. Then this function can be used to retrieve it from that // (or a context derived from that) context, later and elsewhere. func Ctx(ctx context.Context) Logger { - logger, ok := ctx.Value(CtxKey).(Logger) + logger, ok := ctx.Value(PolylogCtxKey).(Logger) if !ok { return DefaultContextLogger } diff --git a/pkg/polylog/context_test.go b/pkg/polylog/context_test.go index d37201249..e8e0f795e 100644 --- a/pkg/polylog/context_test.go +++ b/pkg/polylog/context_test.go @@ -18,7 +18,7 @@ func TestWithContext_Ctx(t *testing.T) { ) // Ensure that no logger is associated with the context. - existingLogger, ok := ctx.Value(polylog.CtxKey).(polylog.Logger) + existingLogger, ok := ctx.Value(polylog.PolylogCtxKey).(polylog.Logger) require.False(t, ok) require.Nil(t, existingLogger) diff --git a/pkg/polylog/polyzero/logger.go b/pkg/polylog/polyzero/logger.go index 8c908fd0f..8205adc7e 100644 --- a/pkg/polylog/polyzero/logger.go +++ b/pkg/polylog/polyzero/logger.go @@ -97,7 +97,7 @@ func (ze *zerologLogger) WithLevel(level polylog.Level) polylog.Event { // // TODO_TEST/TODO_COMMUNITY: add coverage for `polyzero.Logger#WithContext()`. func (ze *zerologLogger) WithContext(ctx context.Context) context.Context { - ctx = context.WithValue(ctx, polylog.CtxKey, ze) + ctx = context.WithValue(ctx, polylog.PolylogCtxKey, ze) ctx = ze.Logger.WithContext(ctx) return ctx } diff --git a/pkg/polylog/polyzero/logger_test.go b/pkg/polylog/polyzero/logger_test.go index 61bebbba4..2f3e21c4c 100644 --- a/pkg/polylog/polyzero/logger_test.go +++ b/pkg/polylog/polyzero/logger_test.go @@ -33,12 +33,13 @@ var ( // TODO_CONSIDERATION: redesign the test helper to support regular expressions // for the output expectation. expectedTimestampDayPrecisionLayout = "2006-01-02T" - expectedTimeLayout = "2006-01-02T15:04:05-07:00" - expectedTimestampEventContains = fmt.Sprintf(`"time":"%s`, expectedTime.Format(expectedTimestampDayPrecisionLayout)) - expectedTimeEventContains = fmt.Sprintf(`"Time":"%s`, expectedTime.Format(expectedTimeLayout)) - expectedDuration = time.Millisecond + (250 * time.Nanosecond) // 1000250 - expectedDurationString = expectedDuration.String()[:len(expectedDuration.String())-2] // 1.00025 - expectedDurationEventContains = fmt.Sprintf(`"Dur":%s`, expectedDurationString) + // TODO_TECHDEBT: see TODO_TECHDEBT in #Time() test case. + // expectedTimeLayout = "2006-01-02T15:04:05-07:00" + // expectedTimeEventContains = fmt.Sprintf(`"Time":"%s`, expectedTime.Format(expectedTimeLayout)) + expectedTimestampEventContains = fmt.Sprintf(`"time":"%s`, expectedTime.Format(expectedTimestampDayPrecisionLayout)) + expectedDuration = time.Millisecond + (250 * time.Nanosecond) // 1000250 + expectedDurationString = expectedDuration.String()[:len(expectedDuration.String())-2] // 1.00025 + expectedDurationEventContains = fmt.Sprintf(`"Dur":%s`, expectedDurationString) ) func TestZerologLogger_AllLevels_AllEventTypeMethods(t *testing.T) { diff --git a/pkg/relayer/config/pocket_node_config_hydrator.go b/pkg/relayer/config/pocket_node_config_hydrator.go index 88a57fa85..79bdc6e99 100644 --- a/pkg/relayer/config/pocket_node_config_hydrator.go +++ b/pkg/relayer/config/pocket_node_config_hydrator.go @@ -28,11 +28,11 @@ func (relayMinerConfig *RelayMinerConfig) HydratePocketNodeUrls( relayMinerConfig.PocketNode.QueryNodeRPCUrl = relayMinerConfig.PocketNode.TxNodeRPCUrl } else { // If the query node rpc url is not empty, make sure it is a valid URL - queryNodeRPCUrl, err := url.Parse(yamlPocketNodeConfig.QueryNodeRPCUrl) - if err != nil { + queryNodeRPCUrl, parseErr := url.Parse(yamlPocketNodeConfig.QueryNodeRPCUrl) + if parseErr != nil { return ErrRelayMinerConfigInvalidNodeUrl.Wrapf( "invalid query node rpc url %s", - err.Error(), + parseErr.Error(), ) } relayMinerConfig.PocketNode.QueryNodeRPCUrl = queryNodeRPCUrl diff --git a/pkg/relayer/miner/gen/template.go b/pkg/relayer/miner/gen/template.go index c75e761a4..b6803a09a 100644 --- a/pkg/relayer/miner/gen/template.go +++ b/pkg/relayer/miner/gen/template.go @@ -1,3 +1,6 @@ +// NB: ensure this code is never included in any normal builds. +//go:build ignore + package main import "text/template" diff --git a/pkg/relayer/proxy/proxy_test.go b/pkg/relayer/proxy/proxy_test.go index 40a541a83..e9f8409c3 100644 --- a/pkg/relayer/proxy/proxy_test.go +++ b/pkg/relayer/proxy/proxy_test.go @@ -134,7 +134,8 @@ func init() { // RelayerProxy should start and stop without errors func TestRelayerProxy_StartAndStop(t *testing.T) { - ctx := context.TODO() + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() // Setup the RelayerProxy instrumented behavior test := testproxy.NewRelayerProxyTestBehavior(ctx, t, defaultRelayerProxyBehavior...) @@ -168,7 +169,8 @@ func TestRelayerProxy_StartAndStop(t *testing.T) { // RelayerProxy should fail to start if the signing key is not found in the keyring func TestRelayerProxy_InvalidSupplierKeyName(t *testing.T) { - ctx := context.TODO() + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() test := testproxy.NewRelayerProxyTestBehavior(ctx, t, defaultRelayerProxyBehavior...) rp, err := proxy.NewRelayerProxy( @@ -184,7 +186,8 @@ func TestRelayerProxy_InvalidSupplierKeyName(t *testing.T) { // RelayerProxy should fail to build if the signing key name is not provided func TestRelayerProxy_MissingSupplierKeyName(t *testing.T) { - ctx := context.TODO() + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() test := testproxy.NewRelayerProxyTestBehavior(ctx, t, defaultRelayerProxyBehavior...) _, err := proxy.NewRelayerProxy( @@ -197,7 +200,8 @@ func TestRelayerProxy_MissingSupplierKeyName(t *testing.T) { // RelayerProxy should fail to build if the service configs are not provided func TestRelayerProxy_EmptyServicesConfigMap(t *testing.T) { - ctx := context.TODO() + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() test := testproxy.NewRelayerProxyTestBehavior(ctx, t, defaultRelayerProxyBehavior...) @@ -212,7 +216,8 @@ func TestRelayerProxy_EmptyServicesConfigMap(t *testing.T) { // RelayerProxy should fail to start if it cannot spawn a server for the // services it advertized on-chain. func TestRelayerProxy_UnsupportedRpcType(t *testing.T) { - ctx := context.TODO() + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() unsupportedSupplierEndpoint := map[string][]*sharedtypes.SupplierEndpoint{ defaultService: { @@ -248,7 +253,8 @@ func TestRelayerProxy_UnsupportedRpcType(t *testing.T) { } func TestRelayerProxy_UnsupportedTransportType(t *testing.T) { - ctx := context.TODO() + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() badTransportSupplierEndpoints := map[string][]*sharedtypes.SupplierEndpoint{ defaultService: { @@ -302,7 +308,8 @@ func TestRelayerProxy_UnsupportedTransportType(t *testing.T) { } func TestRelayerProxy_NonConfiguredSupplierServices(t *testing.T) { - ctx := context.TODO() + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() missingServicesProxy := map[string]*config.RelayMinerServerConfig{ defaultRelayMinerServer: { @@ -519,10 +526,10 @@ func TestRelayerProxy_Relays(t *testing.T) { }, } - ctx := context.TODO() for _, test := range tests { t.Run(test.desc, func(t *testing.T) { - ctx, cancel := context.WithCancel(ctx) + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() testBehavior := testproxy.NewRelayerProxyTestBehavior(ctx, t, test.relayerProxyBehavior...) rp, err := proxy.NewRelayerProxy( diff --git a/pkg/relayer/proxy/relay_verifier.go b/pkg/relayer/proxy/relay_verifier.go index 598494021..b8d1d07dc 100644 --- a/pkg/relayer/proxy/relay_verifier.go +++ b/pkg/relayer/proxy/relay_verifier.go @@ -25,7 +25,7 @@ func (rp *relayerProxy) VerifyRelayRequest( // Verify the relayRequest metadata, signature, session header and other // basic validation. - if err := rp.ringCache.VerifyRelayRequestSignature(ctx, relayRequest); err != nil { + if err = rp.ringCache.VerifyRelayRequestSignature(ctx, relayRequest); err != nil { return err } diff --git a/pkg/relayer/proxy/server_builder.go b/pkg/relayer/proxy/server_builder.go index 45181c5ff..288c8ca48 100644 --- a/pkg/relayer/proxy/server_builder.go +++ b/pkg/relayer/proxy/server_builder.go @@ -69,9 +69,9 @@ func (rp *relayerProxy) BuildProvidedServices(ctx context.Context) error { // service's endpoint for _, service := range supplier.Services { for _, endpoint := range service.Endpoints { - endpointUrl, err := url.Parse(endpoint.Url) - if err != nil { - return err + endpointUrl, urlErr := url.Parse(endpoint.Url) + if urlErr != nil { + return urlErr } found := false // Iterate over the server configs and check if `endpointUrl` is present diff --git a/pkg/relayer/proxy/synchronous.go b/pkg/relayer/proxy/synchronous.go index 162945158..649073bdd 100644 --- a/pkg/relayer/proxy/synchronous.go +++ b/pkg/relayer/proxy/synchronous.go @@ -78,7 +78,7 @@ func NewSynchronousServer( func (sync *synchronousRPCServer) Start(ctx context.Context) error { go func() { <-ctx.Done() - sync.server.Shutdown(ctx) + _ = sync.server.Shutdown(ctx) }() // Set the HTTP handler. @@ -112,7 +112,7 @@ func (sync *synchronousRPCServer) ServeHTTP(writer http.ResponseWriter, request return } - if err := relayRequest.ValidateBasic(); err != nil { + if err = relayRequest.ValidateBasic(); err != nil { sync.replyWithError(err, relayRequest, writer) sync.logger.Warn().Err(err).Msg("failed validating relay response") return diff --git a/pkg/relayer/relayminer.go b/pkg/relayer/relayminer.go index 018d1c14c..a81e2d982 100644 --- a/pkg/relayer/relayminer.go +++ b/pkg/relayer/relayminer.go @@ -121,13 +121,15 @@ func (rel *relayMiner) ServePprof(ctx context.Context, addr string) error { // If no error, start the server in a new goroutine go func() { rel.logger.Info().Str("endpoint", addr).Msg("starting a pprof endpoint") - server.ListenAndServe() + if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + rel.logger.Error().Str("endpoint", addr).Msg("unable to start a pprof endpoint") + } }() go func() { <-ctx.Done() rel.logger.Info().Str("endpoint", addr).Msg("stopping a pprof endpoint") - server.Shutdown(ctx) + _ = server.Shutdown(ctx) }() return nil diff --git a/testutil/integration/app.go b/testutil/integration/app.go index 619a57820..05f036e69 100644 --- a/testutil/integration/app.go +++ b/testutil/integration/app.go @@ -553,8 +553,10 @@ func NewCompleteIntegrationApp(t *testing.T) *App { // This can result in the module accounts balance going negative. Giving them a baseline balance // to start with to avoid this issue. There is opportunity to improve this in the future. moduleBaseMint := types.NewCoins(sdk.NewCoin("upokt", math.NewInt(690000000000000042))) - bankKeeper.MintCoins(integrationApp.sdkCtx, suppliertypes.ModuleName, moduleBaseMint) - bankKeeper.MintCoins(integrationApp.sdkCtx, apptypes.ModuleName, moduleBaseMint) + err = bankKeeper.MintCoins(integrationApp.sdkCtx, suppliertypes.ModuleName, moduleBaseMint) + require.NoError(t, err) + err = bankKeeper.MintCoins(integrationApp.sdkCtx, apptypes.ModuleName, moduleBaseMint) + require.NoError(t, err) // Commit all the changes above by committing, finalizing and moving // to the next block. diff --git a/testutil/keeper/shared.go b/testutil/keeper/shared.go index 514025779..64b3d49f3 100644 --- a/testutil/keeper/shared.go +++ b/testutil/keeper/shared.go @@ -43,7 +43,8 @@ func SharedKeeper(t testing.TB) (keeper.Keeper, sdk.Context) { ctx := sdk.NewContext(stateStore, cmtproto.Header{}, false, log.NewNopLogger()) // Initialize params - k.SetParams(ctx, types.DefaultParams()) + err := k.SetParams(ctx, types.DefaultParams()) + require.NoError(t, err) return k, ctx } diff --git a/testutil/keeper/tokenomics.go b/testutil/keeper/tokenomics.go index 37b3ea6fb..802634be4 100644 --- a/testutil/keeper/tokenomics.go +++ b/testutil/keeper/tokenomics.go @@ -253,8 +253,10 @@ func NewTokenomicsModuleKeepers( require.NoError(t, bankKeeper.SetParams(ctx, banktypes.DefaultParams())) // Provide some initial funds to the suppliers & applications module accounts. - bankKeeper.MintCoins(ctx, suppliertypes.ModuleName, sdk.NewCoins(sdk.NewCoin("upokt", math.NewInt(1000000000000)))) - bankKeeper.MintCoins(ctx, apptypes.ModuleName, sdk.NewCoins(sdk.NewCoin("upokt", math.NewInt(1000000000000)))) + err := bankKeeper.MintCoins(ctx, suppliertypes.ModuleName, sdk.NewCoins(sdk.NewCoin("upokt", math.NewInt(1000000000000)))) + require.NoError(t, err) + err = bankKeeper.MintCoins(ctx, apptypes.ModuleName, sdk.NewCoins(sdk.NewCoin("upokt", math.NewInt(1000000000000)))) + require.NoError(t, err) // Construct a real shared keeper. sharedKeeper := sharedkeeper.NewKeeper( diff --git a/testutil/network/network.go b/testutil/network/network.go index 16ea11d22..fdfb7f8a1 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -253,7 +253,6 @@ func InitAccount(t *testing.T, net *Network, addr sdk.AccAddress) { fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(net.Config.BondDenom, math.NewInt(10))).String()), } amount := sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(200))) - addrCodec := addresscodec.NewBech32Codec(app.AccountAddressPrefix) responseRaw, err := clitestutil.MsgSendExec(ctx, val.Address, addr, amount, addrCodec, args...) require.NoError(t, err) var responseJSON map[string]interface{} diff --git a/testutil/proof/fixture_generators.go b/testutil/proof/fixture_generators.go index a4d7c24c3..96d263ce0 100644 --- a/testutil/proof/fixture_generators.go +++ b/testutil/proof/fixture_generators.go @@ -70,7 +70,7 @@ func RandSmstRootWithSum(t *testing.T, sum uint64) smt.MerkleRoot { root := [smt.SmstRootSizeBytes]byte{} // Only populate the first 32 bytes with random data, leave the last 8 bytes for the sum. - _, err := rand.Read(root[:smt.SmtRootSizeBytes]) + _, err := rand.Read(root[:smt.SmtRootSizeBytes]) //nolint:staticcheck // We need a deterministic pseudo-random source. require.NoError(t, err) binary.BigEndian.PutUint64(root[smt.SmtRootSizeBytes:], sum) diff --git a/testutil/testclient/testeventsquery/client.go b/testutil/testclient/testeventsquery/client.go index 40417e185..94649619e 100644 --- a/testutil/testclient/testeventsquery/client.go +++ b/testutil/testclient/testeventsquery/client.go @@ -44,10 +44,8 @@ func NewOneTimeEventsQuery( ) *mockclient.MockEventsQueryClient { t.Helper() ctrl := gomock.NewController(t) - cancellableCtx, _ := context.WithCancel(ctx) - eventsQueryClient := mockclient.NewMockEventsQueryClient(ctrl) - eventsQueryClient.EXPECT().EventsBytes(gomock.AssignableToTypeOf(cancellableCtx), gomock.Eq(query)). + eventsQueryClient.EXPECT().EventsBytes(gomock.Any(), gomock.Eq(query)). DoAndReturn(func( ctx context.Context, query string, diff --git a/testutil/testpolylog/event.go b/testutil/testpolylog/event.go index 82636e50c..cd44a7095 100644 --- a/testutil/testpolylog/event.go +++ b/testutil/testpolylog/event.go @@ -4,11 +4,12 @@ import ( "bytes" "fmt" "reflect" - "strings" "testing" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "golang.org/x/text/cases" + "golang.org/x/text/language" "github.com/pokt-network/poktroll/pkg/polylog" ) @@ -96,10 +97,7 @@ func RunEventMethodTests( // Title-case level string so that it can be used as the name of the // method to call on the logger using reflect and for the sub-test // descriptions. - // - // TODO_TECHDEBT: `strings.Title()` is deprecated. Follow - // migration guidance in godocs: https://pkg.go.dev/strings@go1.21.4#Title. - levelMethodName := strings.Title(level.String()) + levelMethodName := cases.Title(language.Und).String(level.String()) for _, tt := range tests { var ( diff --git a/testutil/testproxy/relayerproxy.go b/testutil/testproxy/relayerproxy.go index c9acbff1f..e3afd9179 100644 --- a/testutil/testproxy/relayerproxy.go +++ b/testutil/testproxy/relayerproxy.go @@ -5,6 +5,7 @@ import ( "context" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -151,10 +152,18 @@ func WithServicesConfigMap( server.Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { sendJSONRPCResponse(test.t, w) }) - go func() { server.ListenAndServe() }() + + go func() { + err := server.ListenAndServe() + if err != nil && !errors.Is(err, http.ErrServerClosed) { + require.NoError(test.t, err) + } + }() + go func() { <-test.ctx.Done() - server.Shutdown(test.ctx) + err := server.Shutdown(test.ctx) + require.NoError(test.t, err) }() test.proxyServersMap[serviceId] = server @@ -312,7 +321,7 @@ func GetRelayResponseError(t *testing.T, res *http.Response) (errCode int32, err require.NoError(t, err) // If the relayResponse basic validation fails then consider the payload as an error. - if err := relayResponse.ValidateBasic(); err != nil { + if err = relayResponse.ValidateBasic(); err != nil { return JSONRPCInternalErrorCode, string(relayResponse.Payload) } diff --git a/x/application/keeper/msg_server_delegate_to_gateway.go b/x/application/keeper/msg_server_delegate_to_gateway.go index 769b6b180..fd72854b5 100644 --- a/x/application/keeper/msg_server_delegate_to_gateway.go +++ b/x/application/keeper/msg_server_delegate_to_gateway.go @@ -57,7 +57,7 @@ func (k msgServer) DelegateToGateway(ctx context.Context, msg *types.MsgDelegate // Update the application with the new delegatee public key app.DelegateeGatewayAddresses = append(app.DelegateeGatewayAddresses, msg.GatewayAddress) - logger.Info(fmt.Sprintf("Successfully added delegatee public key to application")) + logger.Info("Successfully added delegatee public key to application") // Update the application store with the new delegation k.SetApplication(ctx, app) diff --git a/x/application/keeper/msg_server_delegate_to_gateway_test.go b/x/application/keeper/msg_server_delegate_to_gateway_test.go index 05a2c6271..23c4b53af 100644 --- a/x/application/keeper/msg_server_delegate_to_gateway_test.go +++ b/x/application/keeper/msg_server_delegate_to_gateway_test.go @@ -228,8 +228,8 @@ func TestMsgServer_DelegateToGateway_FailMaxReached(t *testing.T) { // Stake the application & verify that the application exists _, err := srv.StakeApplication(ctx, stakeMsg) require.NoError(t, err) - _, isAppFound := k.GetApplication(ctx, appAddr) - require.True(t, isAppFound) + _, isStakedAppFound := k.GetApplication(ctx, appAddr) + require.True(t, isStakedAppFound) // Delegate the application to the max number of gateways maxDelegatedParam := k.GetParams(ctx).MaxDelegatedGateways @@ -248,8 +248,8 @@ func TestMsgServer_DelegateToGateway_FailMaxReached(t *testing.T) { _, err = srv.DelegateToGateway(ctx, delegateMsg) require.NoError(t, err) // Check number of gateways delegated to is correct - foundApp, isAppFound := k.GetApplication(ctx, appAddr) - require.True(t, isAppFound) + foundApp, isDelegatedAppFound := k.GetApplication(ctx, appAddr) + require.True(t, isDelegatedAppFound) require.Equal(t, int(i+1), len(foundApp.DelegateeGatewayAddresses)) } @@ -280,7 +280,7 @@ func TestMsgServer_DelegateToGateway_FailMaxReached(t *testing.T) { require.ErrorIs(t, err, types.ErrAppMaxDelegatedGateways) events = sdkCtx.EventManager().Events() require.Equal(t, int(maxDelegatedParam), len(events)) - foundApp, isAppFound := k.GetApplication(ctx, appAddr) - require.True(t, isAppFound) + foundApp, isStakedAppFound := k.GetApplication(ctx, appAddr) + require.True(t, isStakedAppFound) require.Equal(t, maxDelegatedParam, uint64(len(foundApp.DelegateeGatewayAddresses))) } diff --git a/x/application/module/simulation.go b/x/application/module/simulation.go index 45d596c1d..5c0bb42d7 100644 --- a/x/application/module/simulation.go +++ b/x/application/module/simulation.go @@ -59,7 +59,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { func (am AppModule) RegisterStoreDecoder(_ simtypes.StoreDecoderRegistry) {} // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedProposalContent { +func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedProposalMsg { return nil } diff --git a/x/gateway/keeper/msg_server_unstake_gateway.go b/x/gateway/keeper/msg_server_unstake_gateway.go index fcc5e9e1d..cad367ad8 100644 --- a/x/gateway/keeper/msg_server_unstake_gateway.go +++ b/x/gateway/keeper/msg_server_unstake_gateway.go @@ -58,7 +58,11 @@ func (k msgServer) UnstakeGateway( k.RemoveGateway(ctx, gatewayAddress.String()) logger.Info(fmt.Sprintf("Successfully removed the gateway: %+v", gateway)) - ctx.EventManager().EmitTypedEvent(&types.EventGatewayUnstaked{Address: msg.Address}) + err = ctx.EventManager().EmitTypedEvent(&types.EventGatewayUnstaked{Address: msg.Address}) + if err != nil { + logger.Error(fmt.Sprintf("failed to emit event for unstaking gateway: %v", err)) + return nil, err + } isSuccessful = true return &types.MsgUnstakeGatewayResponse{}, nil diff --git a/x/gateway/module/simulation.go b/x/gateway/module/simulation.go index d87166a4c..79e8de69a 100644 --- a/x/gateway/module/simulation.go +++ b/x/gateway/module/simulation.go @@ -51,7 +51,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { func (am AppModule) RegisterStoreDecoder(_ simtypes.StoreDecoderRegistry) {} // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedProposalContent { +func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedProposalMsg { return nil } diff --git a/x/proof/keeper/msg_server_submit_proof_test.go b/x/proof/keeper/msg_server_submit_proof_test.go index e7d4a7d5c..c66c27d11 100644 --- a/x/proof/keeper/msg_server_submit_proof_test.go +++ b/x/proof/keeper/msg_server_submit_proof_test.go @@ -194,7 +194,7 @@ func TestMsgServer_SubmitProof_Success(t *testing.T) { keepers.StoreBlockHash(ctx) // Compute expected proof path. - expectedMerkleProofPath := protocol.GetPathForProof(blockHeaderHash, sessionHeader.GetSessionId()) + expectedMerkleProofPath = protocol.GetPathForProof(blockHeaderHash, sessionHeader.GetSessionId()) // Advance the block height to the test proof msg height. proofMsgHeight := test.getProofMsgHeight(&sharedParams, sessionHeader.GetSessionEndBlockHeight(), supplierAddr) @@ -475,16 +475,6 @@ func TestMsgServer_SubmitProof_Error(t *testing.T) { wrongSessionIdHeader := *validSessionHeader wrongSessionIdHeader.SessionId = "wrong session ID" - // Construct a session header with a session start height that doesn't match - // the expected session start height. - wrongSessionStartHeightHeader := *validSessionHeader - wrongSessionStartHeightHeader.SessionStartBlockHeight = 2 - - // Construct a session header with a session end height that doesn't match - // the expected session end height. - wrongSessionEndHeightHeader := *validSessionHeader - wrongSessionEndHeightHeader.SessionEndBlockHeight = 3 - // TODO_TECHDEBT: add a test case such that we can distinguish between early // & late session end block heights. @@ -701,8 +691,8 @@ func TestMsgServer_SubmitProof_Error(t *testing.T) { require.NoError(t, err) // Get the Merkle root for the session tree in order to construct a claim. - mangledRelayMerkleRootBz, err := mangledRelaySessionTree.Flush() - require.NoError(t, err) + mangledRelayMerkleRootBz, flushErr := mangledRelaySessionTree.Flush() + require.NoError(t, flushErr) // Re-set the block height to the earliest claim commit height to create a new claim. claimCtx := cosmostypes.UnwrapSDKContext(ctx) @@ -755,8 +745,8 @@ func TestMsgServer_SubmitProof_Error(t *testing.T) { ) // Get the Merkle root for the session tree in order to construct a claim. - wrongRequestSessionIdMerkleRootBz, err := wrongRequestSessionIdSessionTree.Flush() - require.NoError(t, err) + wrongRequestSessionIdMerkleRootBz, flushErr := wrongRequestSessionIdSessionTree.Flush() + require.NoError(t, flushErr) // Re-set the block height to the earliest claim commit height to create a new claim. claimCtx := cosmostypes.UnwrapSDKContext(ctx) @@ -810,8 +800,8 @@ func TestMsgServer_SubmitProof_Error(t *testing.T) { ) // Get the Merkle root for the session tree in order to construct a claim. - wrongResponseSessionIdMerkleRootBz, err := wrongResponseSessionIdSessionTree.Flush() - require.NoError(t, err) + wrongResponseSessionIdMerkleRootBz, flushErr := wrongResponseSessionIdSessionTree.Flush() + require.NoError(t, flushErr) // Re-set the block height to the earliest claim commit height to create a new claim. claimCtx := cosmostypes.UnwrapSDKContext(ctx) @@ -858,8 +848,8 @@ func TestMsgServer_SubmitProof_Error(t *testing.T) { // Ensure a valid relay response signature. testrelayer.SignRelayResponse(ctx, t, invalidRequestSignatureRelay, supplierUid, supplierAddr, keyRing) - invalidRequestSignatureRelayBz, err := invalidRequestSignatureRelay.Marshal() - require.NoError(t, err) + invalidRequestSignatureRelayBz, marshalErr := invalidRequestSignatureRelay.Marshal() + require.NoError(t, marshalErr) // Construct a session tree with 1 relay with a session header containing // a session ID that doesn't match the expected session ID. @@ -870,8 +860,8 @@ func TestMsgServer_SubmitProof_Error(t *testing.T) { require.NoError(t, err) // Get the Merkle root for the session tree in order to construct a claim. - invalidRequestSignatureMerkleRootBz, err := invalidRequestSignatureSessionTree.Flush() - require.NoError(t, err) + invalidRequestSignatureMerkleRootBz, flushErr := invalidRequestSignatureSessionTree.Flush() + require.NoError(t, flushErr) // Re-set the block height to the earliest claim commit height to create a new claim. claimCtx := cosmostypes.UnwrapSDKContext(ctx) @@ -924,8 +914,8 @@ func TestMsgServer_SubmitProof_Error(t *testing.T) { // Ensure a valid relay request signature testrelayer.SignRelayRequest(ctx, t, relay, appAddr, keyRing, ringClient) - relayBz, err := relay.Marshal() - require.NoError(t, err) + relayBz, marshalErr := relay.Marshal() + require.NoError(t, marshalErr) // Construct a session tree with 1 relay with a session header containing // a session ID that doesn't match the expected session ID. @@ -936,8 +926,8 @@ func TestMsgServer_SubmitProof_Error(t *testing.T) { require.NoError(t, err) // Get the Merkle root for the session tree in order to construct a claim. - invalidResponseSignatureMerkleRootBz, err := invalidResponseSignatureSessionTree.Flush() - require.NoError(t, err) + invalidResponseSignatureMerkleRootBz, flushErr := invalidResponseSignatureSessionTree.Flush() + require.NoError(t, flushErr) // Re-set the block height to the earliest claim commit height to create a new claim. claimCtx := cosmostypes.UnwrapSDKContext(ctx) @@ -992,8 +982,8 @@ func TestMsgServer_SubmitProof_Error(t *testing.T) { ringClient, ) - wrongPathMerkleRootBz, err := wrongPathSessionTree.Flush() - require.NoError(t, err) + wrongPathMerkleRootBz, flushErr := wrongPathSessionTree.Flush() + require.NoError(t, flushErr) // Re-set the block height to the earliest claim commit height to create a new claim. claimCtx := keepertest.SetBlockHeight(ctx, claimMsgHeight) @@ -1028,14 +1018,14 @@ func TestMsgServer_SubmitProof_Error(t *testing.T) { newProofMsg: func(t *testing.T) *prooftypes.MsgSubmitProof { // Set the minimum relay difficulty to a non-zero value such that the relays // constructed by the test helpers have a negligable chance of being valid. - err := keepers.Keeper.SetParams(ctx, prooftypes.Params{ + err = keepers.Keeper.SetParams(ctx, prooftypes.Params{ MinRelayDifficultyBits: 10, }) require.NoError(t, err) // Reset the minimum relay difficulty to zero after this test case. t.Cleanup(func() { - err := keepers.Keeper.SetParams(ctx, prooftypes.DefaultParams()) + err = keepers.Keeper.SetParams(ctx, prooftypes.DefaultParams()) require.NoError(t, err) }) @@ -1435,17 +1425,3 @@ func getClosestRelayDifficultyBits( // Count the number of leading 0s in the relay hash to determine its difficulty. return uint64(protocol.CountHashDifficultyBits(relayHash)) } - -// resetBlockHeightFn returns a function that resets the block height of the -// given context to one; the first valid session block height. -func resetBlockHeightFn(ctx *context.Context) func() { - return func() { - setBlockHeight(ctx, 1) - } -} - -// setBlockHeight sets the block height of the given context to the given height. -func setBlockHeight(ctx *context.Context, height int64) { - sdkCtx := cosmostypes.UnwrapSDKContext(*ctx) - *ctx = sdkCtx.WithBlockHeight(height) -} diff --git a/x/proof/module/helpers_test.go b/x/proof/module/helpers_test.go index d52503408..612c4df3e 100644 --- a/x/proof/module/helpers_test.go +++ b/x/proof/module/helpers_test.go @@ -4,6 +4,7 @@ import ( "strconv" "testing" + cosmosclient "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/stretchr/testify/require" @@ -36,7 +37,7 @@ func networkWithClaimObjects( numSessions int, numSuppliers int, numApps int, -) (net *network.Network, claims []types.Claim) { +) (net *network.Network, claims []types.Claim, clientCtx cosmosclient.Context) { t.Helper() // Initialize a network config. @@ -114,10 +115,8 @@ func networkWithClaimObjects( net = network.New(t, cfg) // Only the first validator's client context is populated. // (see: https://pkg.go.dev/github.com/cosmos/cosmos-sdk/testutil/network#pkg-overview) - ctx := net.Validators[0].ClientCtx - // Overwrite the client context's keyring with the in-memory one that contains - // our pre-generated accounts. - ctx = ctx.WithKeyring(kr) + clientCtx = net.Validators[0].ClientCtx + clientCtx = clientCtx.WithKeyring(kr) // Initialize all the accounts sequenceIndex := 1 @@ -132,7 +131,7 @@ func networkWithClaimObjects( // need to wait for the account to be initialized in the next block require.NoError(t, net.WaitForNextBlock()) - return net, claims + return net, claims, clientCtx } // newTestClaim returns a new claim with the given supplier address, session start height, diff --git a/x/proof/module/query_claim.go b/x/proof/module/query_claim.go index e96861133..cb2ae93f8 100644 --- a/x/proof/module/query_claim.go +++ b/x/proof/module/query_claim.go @@ -31,31 +31,31 @@ $ poktrolld q claim list-claims --session-id --node $(POCKET_NODE) $ poktrolld q claim list-claims --session-end-height --node $(POCKET_NODE) --home $(POKTROLLD_HOME) $ poktrolld q claim list-claims --supplier-address --node $(POCKET_NODE) --home $(POKTROLLD_HOME)`, Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err + RunE: func(cmd *cobra.Command, args []string) (err error) { + pageReq, pageErr := client.ReadPageRequest(cmd.Flags()) + if pageErr != nil { + return pageErr } req := &types.QueryAllClaimsRequest{ Pagination: pageReq, } - if err := updateClaimsFilter(cmd, req); err != nil { + if err = updateClaimsFilter(cmd, req); err != nil { return err } - if err := req.ValidateBasic(); err != nil { + if err = req.ValidateBasic(); err != nil { return err } - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err + clientCtx, ctxErr := client.GetClientQueryContext(cmd) + if ctxErr != nil { + return ctxErr } queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.AllClaims(cmd.Context(), req) - if err != nil { - return err + res, claimsErr := queryClient.AllClaims(cmd.Context(), req) + if claimsErr != nil { + return claimsErr } return clientCtx.PrintProto(res) }, diff --git a/x/proof/module/query_claim_test.go b/x/proof/module/query_claim_test.go index 052aa2535..b7b3167a2 100644 --- a/x/proof/module/query_claim_test.go +++ b/x/proof/module/query_claim_test.go @@ -24,9 +24,8 @@ func TestClaim_Show(t *testing.T) { numSuppliers := 3 numApps := 3 - net, claims := networkWithClaimObjects(t, numSessions, numApps, numSuppliers) + net, claims, clientCtx := networkWithClaimObjects(t, numSessions, numApps, numSuppliers) - ctx := net.Validators[0].ClientCtx commonArgs := []string{ fmt.Sprintf("--%s=json", cometcli.OutputFlag), } @@ -98,7 +97,7 @@ func TestClaim_Show(t *testing.T) { test.supplierAddr, } args = append(args, commonArgs...) - out, err := clitestutil.ExecTestCLICmd(ctx, proof.CmdShowClaim(), args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, proof.CmdShowClaim(), args) if test.expectedErr != nil { require.ErrorContains(t, err, test.expectedErr.Error()) } else { @@ -140,9 +139,8 @@ func TestClaim_List(t *testing.T) { // and management is hard (see details above). To verify if it's functioning // independently, please run: // $ make itest 2 5 ./x/proof/module -- -run TestClaim_List - net, claims := networkWithClaimObjects(t, numSessions, numSuppliers, numApps) + net, claims, clientCtx := networkWithClaimObjects(t, numSessions, numSuppliers, numApps) - ctx := net.Validators[0].ClientCtx prepareArgs := func(next []byte, offset, limit uint64, total bool) []string { args := []string{ fmt.Sprintf("--%s=json", cometcli.OutputFlag), @@ -163,7 +161,7 @@ func TestClaim_List(t *testing.T) { step := 2 for i := 0; i < totalClaims; i += step { args := prepareArgs(nil, uint64(i), uint64(step), false) - out, err := clitestutil.ExecTestCLICmd(ctx, proof.CmdListClaims(), args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, proof.CmdListClaims(), args) require.NoError(t, err) var resp types.QueryAllClaimsResponse @@ -182,7 +180,7 @@ func TestClaim_List(t *testing.T) { var next []byte for i := 0; i < totalClaims; i += step { args := prepareArgs(next, 0, uint64(step), false) - out, err := clitestutil.ExecTestCLICmd(ctx, proof.CmdListClaims(), args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, proof.CmdListClaims(), args) require.NoError(t, err) var resp types.QueryAllClaimsResponse @@ -209,7 +207,7 @@ func TestClaim_List(t *testing.T) { } } - out, err := clitestutil.ExecTestCLICmd(ctx, proof.CmdListClaims(), args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, proof.CmdListClaims(), args) require.NoError(t, err) var resp types.QueryAllClaimsResponse @@ -234,7 +232,7 @@ func TestClaim_List(t *testing.T) { } } - out, err := clitestutil.ExecTestCLICmd(ctx, proof.CmdListClaims(), args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, proof.CmdListClaims(), args) require.NoError(t, err) var resp types.QueryAllClaimsResponse @@ -259,7 +257,7 @@ func TestClaim_List(t *testing.T) { } } - out, err := clitestutil.ExecTestCLICmd(ctx, proof.CmdListClaims(), args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, proof.CmdListClaims(), args) require.NoError(t, err) var resp types.QueryAllClaimsResponse @@ -274,7 +272,7 @@ func TestClaim_List(t *testing.T) { t.Run("Total", func(t *testing.T) { args := prepareArgs(nil, 0, uint64(totalClaims), true) - out, err := clitestutil.ExecTestCLICmd(ctx, proof.CmdListClaims(), args) + out, err := clitestutil.ExecTestCLICmd(clientCtx, proof.CmdListClaims(), args) require.NoError(t, err) var resp types.QueryAllClaimsResponse diff --git a/x/proof/module/query_proof.go b/x/proof/module/query_proof.go index d3e115d15..dbc006e12 100644 --- a/x/proof/module/query_proof.go +++ b/x/proof/module/query_proof.go @@ -40,22 +40,22 @@ $ poktrolld q proof list-proofs --supplier-address --node $(P req := &types.QueryAllProofsRequest{ Pagination: pageReq, } - if err := updateProofsFilter(cmd, req); err != nil { + if err = updateProofsFilter(cmd, req); err != nil { return err } - if err := req.ValidateBasic(); err != nil { + if err = req.ValidateBasic(); err != nil { return err } - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err + clientCtx, ctxErr := client.GetClientQueryContext(cmd) + if ctxErr != nil { + return ctxErr } queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.AllProofs(cmd.Context(), req) - if err != nil { - return err + res, proofsErr := queryClient.AllProofs(cmd.Context(), req) + if proofsErr != nil { + return proofsErr } return clientCtx.PrintProto(res) @@ -88,7 +88,7 @@ $ poktrolld --home=$(POKTROLLD_HOME) q proof show-proofs