diff --git a/.golangci.yml b/.golangci.yml index 2ad6cbd3..2d230c01 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -37,7 +37,7 @@ linters: - misspell - nakedret - nilerr - # - nlreturn # Style wise I personally like this one, todo(lazar): unlax at somepoint, good practice + - nlreturn - noctx - nonamedreturns - nosprintfhostport diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b2c0b58..2b9ca81a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) ## Unreleased +### Improvements + +* [#251](https://github.com/babylonlabs-io/finality-provider/pull/251) chore: nlreturn lint + ## v0.14.2 ### Bug Fixes diff --git a/clientcontroller/babylon.go b/clientcontroller/babylon.go index 0b209ba1..ed0916e0 100644 --- a/clientcontroller/babylon.go +++ b/clientcontroller/babylon.go @@ -75,6 +75,7 @@ func NewBabylonController( func (bc *BabylonController) mustGetTxSigner() string { signer := bc.GetKeyAddress() prefix := bc.cfg.AccountPrefix + return sdk.MustBech32ifyAddressBytes(prefix, signer) } @@ -288,6 +289,7 @@ func (bc *BabylonController) QueryFinalityProviderVotingPower(fpPk *btcec.Public // therefore, it should be treated as the fp having 0 voting power if strings.Contains(err.Error(), finalitytypes.ErrVotingPowerTableNotUpdated.Error()) { bc.logger.Info("the voting power table not updated yet") + return 0, nil } @@ -338,6 +340,7 @@ func (bc *BabylonController) QueryBlocks(startHeight, endHeight uint64, limit ui if count > uint64(limit) { count = uint64(limit) } + return bc.queryLatestBlocks(sdk.Uint64ToBigEndian(startHeight), count, finalitytypes.QueriedBlockStatus_ANY, false) } @@ -367,6 +370,7 @@ func (bc *BabylonController) queryLatestBlocks(startKey []byte, count uint64, st func getContextWithCancel(timeout time.Duration) (context.Context, context.CancelFunc) { ctx, cancel := context.WithTimeout(context.Background(), timeout) + return ctx, cancel } @@ -558,6 +562,7 @@ func (bc *BabylonController) EditFinalityProvider(fpPk *btcec.PublicKey, if reqValue != "" { return reqValue } + return defaultValue } diff --git a/clientcontroller/retry_utils.go b/clientcontroller/retry_utils.go index 10813622..71e405a4 100644 --- a/clientcontroller/retry_utils.go +++ b/clientcontroller/retry_utils.go @@ -42,6 +42,7 @@ func (e ExpectedError) Error() string { if e.error == nil { return "expected error" } + return e.error.Error() } @@ -52,6 +53,7 @@ func (e ExpectedError) Unwrap() error { // Is adds support for errors.Is usage on isExpected func (ExpectedError) Is(err error) bool { _, isExpected := err.(ExpectedError) + return isExpected } diff --git a/eotsmanager/client/rpcclient.go b/eotsmanager/client/rpcclient.go index 10866cac..3d0a17f7 100644 --- a/eotsmanager/client/rpcclient.go +++ b/eotsmanager/client/rpcclient.go @@ -89,6 +89,7 @@ func (c *EOTSManagerGRpcClient) SaveEOTSKeyName(pk *btcec.PublicKey, keyName str EotsPk: pk.SerializeUncompressed(), } _, err := c.client.SaveEOTSKeyName(context.Background(), req) + return err } diff --git a/eotsmanager/cmd/eotsd/daemon/keys.go b/eotsmanager/cmd/eotsd/daemon/keys.go index c550d216..1ebb9776 100644 --- a/eotsmanager/cmd/eotsd/daemon/keys.go +++ b/eotsmanager/cmd/eotsd/daemon/keys.go @@ -82,6 +82,7 @@ func saveKeyOnPostRun(cmd *cobra.Command, commandName string) { subCmd.PostRunE = func(cmd *cobra.Command, args []string) error { keyName := args[0] _, err := saveKeyNameMapping(cmd, keyName) + return err } } @@ -246,6 +247,7 @@ func printFromKey(cmd *cobra.Command, keyName string, eotsPk *types.BIP340PubKey ctx := cmd.Context() mnemonic := ctx.Value(mnemonicCtxKey).(string) //nolint: forcetypeassert showMnemonic := ctx.Value(mnemonicShowCtxKey).(bool) + return printCreatePubKeyHex(cmd, k, eotsPk, showMnemonic, mnemonic, clientCtx.OutputFormat) } diff --git a/eotsmanager/cmd/eotsd/daemon/keysadd.go b/eotsmanager/cmd/eotsd/daemon/keysadd.go index 2b6562ea..d17d76ed 100644 --- a/eotsmanager/cmd/eotsd/daemon/keysadd.go +++ b/eotsmanager/cmd/eotsd/daemon/keysadd.go @@ -40,6 +40,7 @@ func runAddCmdPrepare(cmd *cobra.Command, args []string) error { } buf := bufio.NewReader(clientCtx.Input) + return runAddCmd(clientCtx, cmd, args, buf) } @@ -297,6 +298,7 @@ func runAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *buf // used later for printing the values if needed ctxWithValues := context.WithValue(cmd.Context(), mnemonicCtxKey, mnemonic) //nolint: revive,staticcheck cmd.SetContext(context.WithValue(ctxWithValues, mnemonicShowCtxKey, showMnemonic)) //nolint: revive,staticcheck + return nil } @@ -308,6 +310,7 @@ func validateMultisigThreshold(k, nKeys int) error { return fmt.Errorf( "threshold k of n multisignature: %d < %d", nKeys, k) } + return nil } @@ -322,5 +325,6 @@ func readMnemonicFromFile(filePath string) (string, error) { if err != nil { return "", err } + return string(bz), nil } diff --git a/eotsmanager/config/config.go b/eotsmanager/config/config.go index e5c1df4d..aebdf8c9 100644 --- a/eotsmanager/config/config.go +++ b/eotsmanager/config/config.go @@ -131,5 +131,6 @@ func DefaultConfigWithHomePath(homePath string) *Config { if err := cfg.Validate(); err != nil { panic(err) } + return cfg } diff --git a/eotsmanager/localmanager.go b/eotsmanager/localmanager.go index afe5b970..3163e138 100644 --- a/eotsmanager/localmanager.go +++ b/eotsmanager/localmanager.go @@ -170,6 +170,7 @@ func LoadBIP340PubKeyFromKeyName(kr keyring.Keyring, keyName string) (*bbntypes. return nil, err } eotsPk = bbntypes.NewBIP340PubKeyFromBTCPK(pk) + return eotsPk, nil default: return nil, fmt.Errorf("unsupported key type in keyring") @@ -286,6 +287,7 @@ func (lm *LocalEOTSManager) SignSchnorrSig(fpPk []byte, msg []byte, passphrase s func (lm *LocalEOTSManager) signSchnorrSigFromPrivKey(privKey *btcec.PrivateKey, fpPk []byte, msg []byte) (*schnorr.Signature, error) { // Update metrics lm.metrics.IncrementEotsFpTotalSchnorrSignCounter(hex.EncodeToString(fpPk)) + return schnorr.Sign(privKey, msg) } @@ -306,6 +308,7 @@ func (lm *LocalEOTSManager) SignSchnorrSigFromKeyname(keyName, passphrase string if err != nil { return nil, nil, fmt.Errorf("failed to schnorr sign: %w", err) } + return signature, eotsPk, nil } @@ -320,6 +323,7 @@ func (lm *LocalEOTSManager) getRandomnessPair(fpPk []byte, chainID []byte, heigh return nil, nil, err } privRand, pubRand := randgenerator.GenerateRandomness(record.PrivKey.Serialize(), chainID, height) + return privRand, pubRand, nil } @@ -363,6 +367,7 @@ func (lm *LocalEOTSManager) eotsPrivKeyFromKeyName(keyName string) (*btcec.Priva switch v := privKeyCached.(type) { case *secp256k1.PrivKey: privKey, _ = btcec.PrivKeyFromBytes(v.Key) + return privKey, nil default: return nil, fmt.Errorf("unsupported key type in keyring") @@ -371,6 +376,7 @@ func (lm *LocalEOTSManager) eotsPrivKeyFromKeyName(keyName string) (*btcec.Priva func (lm *LocalEOTSManager) keyExists(name string) bool { _, err := lm.kr.Key(name) + return err == nil } diff --git a/eotsmanager/service/rpcserver.go b/eotsmanager/service/rpcserver.go index a100b4d2..cd91aa01 100644 --- a/eotsmanager/service/rpcserver.go +++ b/eotsmanager/service/rpcserver.go @@ -32,6 +32,7 @@ func newRPCServer( func (r *rpcServer) RegisterWithGrpcServer(grpcServer *grpc.Server) error { // Register the main RPC server. proto.RegisterEOTSManagerServer(grpcServer, r) + return nil } diff --git a/eotsmanager/store/eotsstore.go b/eotsmanager/store/eotsstore.go index 1ced1a27..52226271 100644 --- a/eotsmanager/store/eotsstore.go +++ b/eotsmanager/store/eotsstore.go @@ -96,6 +96,7 @@ func (s *EOTSStore) GetEOTSKeyName(pk []byte) (string, error) { } keyName = string(keyNameBytes) + return nil }, func() {}) @@ -190,6 +191,7 @@ func (s *EOTSStore) GetSignRecord(eotsPk, chainID []byte, height uint64) (*Signi if errors.Is(err, ErrSignRecordNotFound) { return nil, false, nil } + return nil, false, err } diff --git a/finality-provider/cmd/fpd/daemon/commit_pr.go b/finality-provider/cmd/fpd/daemon/commit_pr.go index f39eb4f8..81d8a771 100644 --- a/finality-provider/cmd/fpd/daemon/commit_pr.go +++ b/finality-provider/cmd/fpd/daemon/commit_pr.go @@ -32,6 +32,7 @@ WARNING: this can drain the finality provider's balance if the target height is RunE: runCommandCommitPubRand, } cmd.Flags().Uint64("start-height", math.MaxUint64, "The block height to start committing pubrand from (optional)") + return cmd } @@ -99,5 +100,6 @@ func runCommandCommitPubRand(cmd *cobra.Command, args []string) error { if startHeight == math.MaxUint64 { return fp.TestCommitPubRand(targetHeight) } + return fp.TestCommitPubRandWithStartHeight(startHeight, targetHeight) } diff --git a/finality-provider/cmd/fpd/daemon/daemon_commands.go b/finality-provider/cmd/fpd/daemon/daemon_commands.go index 3eda12ca..116c2bd0 100644 --- a/finality-provider/cmd/fpd/daemon/daemon_commands.go +++ b/finality-provider/cmd/fpd/daemon/daemon_commands.go @@ -40,6 +40,7 @@ func CommandGetDaemonInfo() *cobra.Command { RunE: runCommandGetDaemonInfo, } cmd.Flags().String(fpdDaemonAddressFlag, defaultFpdDaemonAddress, "The RPC server address of fpd") + return cmd } @@ -65,6 +66,7 @@ func runCommandGetDaemonInfo(cmd *cobra.Command, _ []string) error { } printRespJSON(info) + return nil } @@ -139,6 +141,7 @@ Where finality-provider.json contains: return err } } + return nil } @@ -195,6 +198,7 @@ func runCommandCreateFP(ctx client.Context, cmd *cobra.Command, _ []string) erro } printRespJSON(res) + return nil } @@ -265,6 +269,7 @@ func getDescriptionFromFlags(f *pflag.FlagSet) (stakingtypes.Description, error) } description := stakingtypes.NewDescription(monikerStr, identityStr, websiteStr, securityContactStr, detailsStr) + return description.EnsureLength() } @@ -279,6 +284,7 @@ func CommandLsFP() *cobra.Command { RunE: runCommandLsFP, } cmd.Flags().String(fpdDaemonAddressFlag, defaultFpdDaemonAddress, "The RPC server address of fpd") + return cmd } @@ -318,6 +324,7 @@ func CommandInfoFP() *cobra.Command { RunE: runCommandInfoFP, } cmd.Flags().String(fpdDaemonAddressFlag, defaultFpdDaemonAddress, "The RPC server address of fpd") + return cmd } @@ -552,6 +559,7 @@ func printRespJSON(resp interface{}) { jsonBytes, err := json.MarshalIndent(resp, "", " ") if err != nil { fmt.Println("unable to decode response: ", err) + return } @@ -579,6 +587,7 @@ func loadKeyName(homeDir string, cmd *cobra.Command) (string, error) { if keyName == "" { return "", fmt.Errorf("the key in config is empty") } + return keyName, nil } diff --git a/finality-provider/cmd/fpd/daemon/init.go b/finality-provider/cmd/fpd/daemon/init.go index 5d7e8f95..e3bfafa6 100644 --- a/finality-provider/cmd/fpd/daemon/init.go +++ b/finality-provider/cmd/fpd/daemon/init.go @@ -24,6 +24,7 @@ func CommandInit() *cobra.Command { RunE: fpcmd.RunEWithClientCtx(runInitCmd), } cmd.Flags().Bool(forceFlag, false, "Override existing configuration") + return cmd } diff --git a/finality-provider/cmd/fpd/daemon/keys.go b/finality-provider/cmd/fpd/daemon/keys.go index 6ebad62f..68950c3c 100644 --- a/finality-provider/cmd/fpd/daemon/keys.go +++ b/finality-provider/cmd/fpd/daemon/keys.go @@ -17,5 +17,6 @@ func CommandKeys() *cobra.Command { } keyAddCmd.Long += "\nIf this key is needed to run as the default for the finality-provider daemon, remind to update the fpd.conf" + return keysCmd } diff --git a/finality-provider/cmd/fpd/daemon/start.go b/finality-provider/cmd/fpd/daemon/start.go index 271205a2..a88eb1c9 100644 --- a/finality-provider/cmd/fpd/daemon/start.go +++ b/finality-provider/cmd/fpd/daemon/start.go @@ -32,6 +32,7 @@ func CommandStart() *cobra.Command { cmd.Flags().String(fpEotsPkFlag, "", "The EOTS public key of the finality-provider to start") cmd.Flags().String(passphraseFlag, "", "The pass phrase used to decrypt the private key") cmd.Flags().String(rpcListenerFlag, "", "The address that the RPC server listens to") + return cmd } @@ -97,6 +98,7 @@ func runStartCmd(ctx client.Context, cmd *cobra.Command, _ []string) error { } fpServer := service.NewFinalityProviderServer(cfg, logger, fpApp, dbBackend, shutdownInterceptor) + return fpServer.RunUntilShutdown() } diff --git a/finality-provider/proto/finality_providers.go b/finality-provider/proto/finality_providers.go index fefa8111..172d9b1e 100644 --- a/finality-provider/proto/finality_providers.go +++ b/finality-provider/proto/finality_providers.go @@ -14,11 +14,13 @@ func (sfp *FinalityProvider) MustGetBTCPK() *btcec.PublicKey { if err != nil { panic(fmt.Errorf("failed to parse BTC PK: %w", err)) } + return btcPubKey } func (sfp *FinalityProvider) MustGetBIP340BTCPK() *bbn.BIP340PubKey { btcPK := sfp.MustGetBTCPK() + return bbn.NewBIP340PubKeyFromBTCPK(btcPK) } @@ -27,6 +29,7 @@ func NewFinalityProviderInfo(sfp *FinalityProvider) (*FinalityProviderInfo, erro if err := des.Unmarshal(sfp.Description); err != nil { return nil, err } + return &FinalityProviderInfo{ FpAddr: sfp.FpAddr, BtcPkHex: sfp.MustGetBIP340BTCPK().MarshalHex(), diff --git a/finality-provider/service/app.go b/finality-provider/service/app.go index 80e4fc11..0c92f026 100644 --- a/finality-provider/service/app.go +++ b/finality-provider/service/app.go @@ -69,6 +69,7 @@ func NewFinalityProviderAppFromConfig( } logger.Info("successfully connected to a remote EOTS manager", zap.String("address", cfg.EOTSManagerAddress)) + return NewFinalityProviderApp(cfg, cc, em, db, logger) } @@ -223,6 +224,7 @@ func (app *FinalityProviderApp) SyncAllFinalityProvidersStatus() error { zap.Uint64("power", power), ) } + continue } slashed, jailed, err := app.cc.QueryFinalityProviderSlashedOrJailed(fp.BtcPk) @@ -299,6 +301,7 @@ func (app *FinalityProviderApp) Stop() error { if err := app.fpIns.Stop(); err != nil { stopErr = fmt.Errorf("failed to close the fp instance: %w", err) + return } @@ -308,11 +311,13 @@ func (app *FinalityProviderApp) Stop() error { app.logger.Debug("Stopping EOTS manager") if err := app.eotsManager.Close(); err != nil { stopErr = fmt.Errorf("failed to close the EOTS manager: %w", err) + return } app.logger.Debug("FinalityProviderApp successfully stopped") }) + return stopErr } diff --git a/finality-provider/service/benchmark_helper.go b/finality-provider/service/benchmark_helper.go index 7174e635..b4923c6f 100644 --- a/finality-provider/service/benchmark_helper.go +++ b/finality-provider/service/benchmark_helper.go @@ -39,6 +39,7 @@ func (fp *FinalityProviderInstance) HelperCommitPubRand(tipHeight uint64) (*type zap.Uint64("block_height", tipHeight), zap.Uint64("last_committed_height", lastCommittedHeight), ) + return nil, nil, nil } diff --git a/finality-provider/service/chain_poller.go b/finality-provider/service/chain_poller.go index 1b755e7a..08d32791 100644 --- a/finality-provider/service/chain_poller.go +++ b/finality-provider/service/chain_poller.go @@ -123,6 +123,7 @@ func (cp *ChainPoller) blockWithRetry(height uint64) (*types.BlockInfo, error) { if err != nil { return err } + return nil }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { cp.logger.Debug( @@ -150,6 +151,7 @@ func (cp *ChainPoller) waitForActivation() { if cp.nextHeight < activatedHeight { cp.nextHeight = activatedHeight } + return } select { @@ -212,6 +214,7 @@ func (cp *ChainPoller) pollChain() { "the target height %d is not higher than the next height %d to retrieve", targetHeight, cp.nextHeight)} req.resp <- resp + continue } diff --git a/finality-provider/service/client/rpcclient.go b/finality-provider/service/client/rpcclient.go index 68c2a1c0..a0706cdc 100644 --- a/finality-provider/service/client/rpcclient.go +++ b/finality-provider/service/client/rpcclient.go @@ -28,6 +28,7 @@ func NewFinalityProviderServiceGRpcClient(remoteAddr string) (*FinalityProviderS if conn == nil { return nil } + return conn.Close() } diff --git a/finality-provider/service/eots_manager_adapter.go b/finality-provider/service/eots_manager_adapter.go index 29be16bf..bbc09866 100644 --- a/finality-provider/service/eots_manager_adapter.go +++ b/finality-provider/service/eots_manager_adapter.go @@ -38,6 +38,7 @@ func getHashToSignForCommitPubRand(startHeight uint64, numPubRand uint64, commit if _, err := hasher.Write(commitment); err != nil { return nil, err } + return hasher.Sum(nil), nil } diff --git a/finality-provider/service/event_loops.go b/finality-provider/service/event_loops.go index f3e8c42f..47021b11 100644 --- a/finality-provider/service/event_loops.go +++ b/finality-provider/service/event_loops.go @@ -57,24 +57,28 @@ func (app *FinalityProviderApp) monitorCriticalErr() { if err != nil { app.logger.Debug("the finality-provider instance is already shutdown", zap.String("pk", criticalErr.fpBtcPk.MarshalHex())) + continue } if errors.Is(criticalErr.err, ErrFinalityProviderSlashed) { app.setFinalityProviderSlashed(fpi) app.logger.Debug("the finality-provider has been slashed", zap.String("pk", criticalErr.fpBtcPk.MarshalHex())) + continue } if errors.Is(criticalErr.err, ErrFinalityProviderJailed) { app.setFinalityProviderJailed(fpi) app.logger.Debug("the finality-provider has been jailed", zap.String("pk", criticalErr.fpBtcPk.MarshalHex())) + continue } app.logger.Fatal(instanceTerminatingMsg, zap.String("pk", criticalErr.fpBtcPk.MarshalHex()), zap.Error(criticalErr.err)) case <-app.quit: app.logger.Info("exiting monitor critical error loop") + return } } @@ -92,12 +96,14 @@ func (app *FinalityProviderApp) registrationLoop() { popBytes, err := req.pop.Marshal() if err != nil { req.errResponse <- err + continue } desBytes, err := req.description.Marshal() if err != nil { req.errResponse <- err + continue } res, err := app.cc.RegisterFinalityProvider( @@ -114,6 +120,7 @@ func (app *FinalityProviderApp) registrationLoop() { zap.Error(err), ) req.errResponse <- err + continue } @@ -131,6 +138,7 @@ func (app *FinalityProviderApp) registrationLoop() { } case <-app.quit: app.logger.Info("exiting registration loop") + return } } @@ -146,14 +154,17 @@ func (app *FinalityProviderApp) unjailFpLoop() { isSlashed, isJailed, err := app.cc.QueryFinalityProviderSlashedOrJailed(req.btcPubKey.MustToBTCPK()) if err != nil { req.errResponse <- fmt.Errorf("failed to query jailing status of the finality provider %s: %w", pkHex, err) + continue } if isSlashed { req.errResponse <- fmt.Errorf("the finality provider %s is already slashed", pkHex) + continue } if !isJailed { req.errResponse <- fmt.Errorf("the finality provider %s is not jailed", pkHex) + continue } @@ -168,6 +179,7 @@ func (app *FinalityProviderApp) unjailFpLoop() { zap.Error(err), ) req.errResponse <- err + continue } @@ -182,6 +194,7 @@ func (app *FinalityProviderApp) unjailFpLoop() { } case <-app.quit: app.logger.Info("exiting unjailing fp loop") + return } } @@ -207,6 +220,7 @@ func (app *FinalityProviderApp) metricsUpdateLoop() { continue case <-app.quit: app.logger.Info("exiting metrics update loop") + return } } diff --git a/finality-provider/service/fp_instance.go b/finality-provider/service/fp_instance.go index 03817441..a69c60c2 100644 --- a/finality-provider/service/fp_instance.go +++ b/finality-provider/service/fp_instance.go @@ -188,6 +188,7 @@ func (fp *FinalityProviderInstance) finalitySigSubmissionLoop() { processedBlocks, err := fp.processBlocksToVote(pollerBlocks) if err != nil { fp.reportCriticalErr(err) + continue } @@ -201,6 +202,7 @@ func (fp *FinalityProviderInstance) finalitySigSubmissionLoop() { if !errors.Is(err, ErrFinalityProviderShutDown) { fp.reportCriticalErr(err) } + continue } if res == nil { @@ -219,6 +221,7 @@ func (fp *FinalityProviderInstance) finalitySigSubmissionLoop() { ) case <-fp.quit: fp.logger.Info("the finality signature submission loop is closing") + return } } @@ -240,6 +243,7 @@ func (fp *FinalityProviderInstance) processBlocksToVote(blocks []*types.BlockInf zap.Uint64("block_height", blk.Height), zap.Uint64("last_voted_height", fp.GetLastVotedHeight()), ) + continue } @@ -258,6 +262,7 @@ func (fp *FinalityProviderInstance) processBlocksToVote(blocks []*types.BlockInf // the finality provider does not have voting power // and it will never will at this block, so continue fp.metrics.IncrementFpTotalBlocksWithoutVotingPower(fp.GetBtcPkHex()) + continue } @@ -287,6 +292,7 @@ func (fp *FinalityProviderInstance) getBatchBlocksFromChan() []*types.BlockInfo } case <-fp.quit: fp.logger.Info("the get all blocks loop is closing") + return nil default: return pollerBlocks @@ -304,6 +310,7 @@ func (fp *FinalityProviderInstance) randomnessCommitmentLoop() { should, startHeight, err := fp.ShouldCommitRandomness() if err != nil { fp.reportCriticalErr(err) + continue } if !should { @@ -314,6 +321,7 @@ func (fp *FinalityProviderInstance) randomnessCommitmentLoop() { if err != nil { fp.metrics.IncrementFpTotalFailedRandomness(fp.GetBtcPkHex()) fp.reportCriticalErr(err) + continue } // txRes could be nil if no need to commit more randomness @@ -326,6 +334,7 @@ func (fp *FinalityProviderInstance) randomnessCommitmentLoop() { } case <-fp.quit: fp.logger.Info("the randomness commitment loop is closing") + return } } @@ -366,6 +375,7 @@ func (fp *FinalityProviderInstance) ShouldCommitRandomness() (bool, uint64, erro zap.Uint64("tip_height", tipHeight), zap.Uint64("last_committed_height", lastCommittedHeight), ) + return false, 0, nil } @@ -462,6 +472,7 @@ func (fp *FinalityProviderInstance) retrySubmitSigsUntilFinalized(targetBlocks [ continue case <-fp.quit: fp.logger.Debug("the finality-provider instance is closing", zap.String("pk", fp.GetBtcPkHex())) + return nil, ErrFinalityProviderShutDown } } @@ -641,6 +652,7 @@ func (fp *FinalityProviderInstance) SubmitBatchFinalitySignatures(blocks []*type if strings.Contains(err.Error(), "slashed") { return nil, ErrFinalityProviderSlashed } + return nil, err } @@ -714,6 +726,7 @@ func (fp *FinalityProviderInstance) TestSubmitFinalitySignatureAndExtractPrivKey if err != nil { return nil, nil, fmt.Errorf("failed to extract private key: %s", err.Error()) } + break } } @@ -748,6 +761,7 @@ func (fp *FinalityProviderInstance) DetermineStartHeight() (uint64, error) { fp.logger.Info("using static chain scanning mode", zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("start_height", fp.cfg.PollerConfig.StaticChainScanningStartHeight)) + return fp.cfg.PollerConfig.StaticChainScanningStartHeight, nil } @@ -824,6 +838,7 @@ func (fp *FinalityProviderInstance) lastCommittedPublicRandWithRetry(count uint6 return err } response = resp + return nil }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { fp.logger.Debug( @@ -835,6 +850,7 @@ func (fp *FinalityProviderInstance) lastCommittedPublicRandWithRetry(count uint6 })); err != nil { return nil, err } + return response, nil } @@ -850,6 +866,7 @@ func (fp *FinalityProviderInstance) latestFinalizedHeightWithRetry() (uint64, er return nil } height = blocks[0].Height + return nil }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { fp.logger.Debug( @@ -873,6 +890,7 @@ func (fp *FinalityProviderInstance) highestVotedHeightWithRetry() (uint64, error return err } height = h + return nil }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { fp.logger.Debug( @@ -896,6 +914,7 @@ func (fp *FinalityProviderInstance) getFinalityActivationHeightWithRetry() (uint return err } response = finalityActivationHeight + return nil }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { fp.logger.Debug( @@ -907,6 +926,7 @@ func (fp *FinalityProviderInstance) getFinalityActivationHeightWithRetry() (uint })); err != nil { return 0, err } + return response, nil } @@ -921,6 +941,7 @@ func (fp *FinalityProviderInstance) getLatestBlockWithRetry() (*types.BlockInfo, if err != nil { return err } + return nil }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { fp.logger.Debug( @@ -948,6 +969,7 @@ func (fp *FinalityProviderInstance) GetVotingPowerWithRetry(height uint64) (uint if err != nil { return err } + return nil }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { fp.logger.Debug( @@ -975,6 +997,7 @@ func (fp *FinalityProviderInstance) GetFinalityProviderSlashedOrJailedWithRetry( if err != nil { return err } + return nil }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { fp.logger.Debug( diff --git a/finality-provider/service/fp_store_adapter.go b/finality-provider/service/fp_store_adapter.go index da1c0190..5deeb220 100644 --- a/finality-provider/service/fp_store_adapter.go +++ b/finality-provider/service/fp_store_adapter.go @@ -30,6 +30,7 @@ func newFpState( func (fps *fpState) getStoreFinalityProvider() *store.StoredFinalityProvider { fps.mu.Lock() defer fps.mu.Unlock() + return fps.fp } @@ -37,6 +38,7 @@ func (fps *fpState) setStatus(s proto.FinalityProviderStatus) error { fps.mu.Lock() fps.fp.Status = s fps.mu.Unlock() + return fps.s.SetFpStatus(fps.fp.BtcPk, s) } @@ -44,6 +46,7 @@ func (fps *fpState) setLastVotedHeight(height uint64) error { fps.mu.Lock() fps.fp.LastVotedHeight = height fps.mu.Unlock() + return fps.s.SetFpLastVotedHeight(fps.fp.BtcPk, height) } diff --git a/finality-provider/service/rpcserver.go b/finality-provider/service/rpcserver.go index 502780f3..38e80d9b 100644 --- a/finality-provider/service/rpcserver.go +++ b/finality-provider/service/rpcserver.go @@ -70,6 +70,7 @@ func (r *rpcServer) Stop() error { func (r *rpcServer) RegisterWithGrpcServer(grpcServer *grpc.Server) error { // Register the main RPC server. proto.RegisterFinalityProvidersServer(grpcServer, r) + return nil } @@ -133,6 +134,7 @@ func (r *rpcServer) AddFinalitySignature(_ context.Context, req *proto.AddFinali select { case <-r.app.quit: r.app.logger.Info("exiting metrics update loop") + return res, nil default: fpPk, err := bbntypes.NewBIP340PubKeyFromHex(req.BtcPk) @@ -148,6 +150,7 @@ func (r *rpcServer) AddFinalitySignature(_ context.Context, req *proto.AddFinali if fpi.GetBtcPkHex() != req.BtcPk { errMsg := fmt.Sprintf("the finality provider running does not match the request, got: %s, expected: %s", req.BtcPk, fpi.GetBtcPkHex()) + return nil, errors.New(errMsg) } @@ -169,6 +172,7 @@ func (r *rpcServer) AddFinalitySignature(_ context.Context, req *proto.AddFinali localPrivKey, err := r.app.getFpPrivKey(fpPk.MustMarshal()) if err != nil { r.app.logger.Error(fmt.Sprintf("err get priv key %s", err.Error())) + return nil, err } @@ -186,9 +190,11 @@ func (r *rpcServer) AddFinalitySignature(_ context.Context, req *proto.AddFinali " extracted: %s, local: %s, local-negated: %s", res.ExtractedSkHex, localSkHex, localSkNegateHex, ) + return nil, errors.New(msg) } } + return res, nil } } diff --git a/finality-provider/store/fpstore.go b/finality-provider/store/fpstore.go index 5d558e06..ed95f1ca 100644 --- a/finality-provider/store/fpstore.go +++ b/finality-provider/store/fpstore.go @@ -37,6 +37,7 @@ func NewFinalityProviderStore(db kvdb.Backend) (*FinalityProviderStore, error) { func (s *FinalityProviderStore) initBuckets() error { return kvdb.Batch(s.db, func(tx kvdb.RwTx) error { _, err := tx.CreateTopLevelBucket(finalityProviderBucketName) + return err }) } @@ -101,6 +102,7 @@ func saveFinalityProvider( func (s *FinalityProviderStore) SetFpStatus(btcPk *btcec.PublicKey, status proto.FinalityProviderStatus) error { setFpStatus := func(fp *proto.FinalityProvider) error { fp.Status = status + return nil } @@ -156,6 +158,7 @@ func (s *FinalityProviderStore) setFinalityProviderState( stateTransitionFn func(provider *proto.FinalityProvider) error, ) error { pkBytes := schnorr.SerializePubKey(btcPk) + return kvdb.Batch(s.db, func(tx kvdb.RwTx) error { fpBucket := tx.ReadWriteBucket(finalityProviderBucketName) if fpBucket == nil { @@ -206,6 +209,7 @@ func (s *FinalityProviderStore) GetFinalityProvider(btcPk *btcec.PublicKey) (*St } storedFp = fpFromDB + return nil }, func() {}) diff --git a/finality-provider/store/fpstore_test.go b/finality-provider/store/fpstore_test.go index 3e212a47..3702bdf1 100644 --- a/finality-provider/store/fpstore_test.go +++ b/finality-provider/store/fpstore_test.go @@ -186,6 +186,7 @@ func TestUpdateFpStatusFromVotingPower(t *testing.T) { actStatus, err := fps.UpdateFpStatusFromVotingPower(tc.votingPowerOnChain, fp) if tc.expErr != nil { require.EqualError(t, err, tc.expErr.Error()) + return } require.NoError(t, err) diff --git a/finality-provider/store/pub_rand.go b/finality-provider/store/pub_rand.go index 51fa45b6..89c77a87 100644 --- a/finality-provider/store/pub_rand.go +++ b/finality-provider/store/pub_rand.go @@ -33,6 +33,7 @@ func NewPubRandProofStore(db kvdb.Backend) (*PubRandProofStore, error) { func (s *PubRandProofStore) initBuckets() error { return kvdb.Batch(s.db, func(tx kvdb.RwTx) error { _, err := tx.CreateTopLevelBucket(pubRandProofBucketName) + return err }) } @@ -197,6 +198,7 @@ func (s *PubRandProofStore) RemovePubRandProofList(chainID []byte, pk []byte, ta return err } } + return nil }, func() {}) diff --git a/keyring/keyringcontroller.go b/keyring/keyringcontroller.go index fd0bf84a..ad4c194e 100644 --- a/keyring/keyringcontroller.go +++ b/keyring/keyringcontroller.go @@ -107,6 +107,7 @@ func (kc *ChainKeyringController) CreateChainKey(passphrase, hdPath, mnemonic st switch v := privKey.(type) { case *sdksecp256k1.PrivKey: sk, pk := btcec.PrivKeyFromBytes(v.Key) + return &types.ChainKeyInfo{ Name: kc.fpName, AccAddress: accAddress, diff --git a/log/log.go b/log/log.go index d29ab499..8d0abcf8 100644 --- a/log/log.go +++ b/log/log.go @@ -76,5 +76,6 @@ func NewRootLoggerWithFile(logFile string, level string) (*zap.Logger, error) { if err != nil { return nil, err } + return logger, nil } diff --git a/metrics/config.go b/metrics/config.go index 17bde531..217b74af 100644 --- a/metrics/config.go +++ b/metrics/config.go @@ -36,6 +36,7 @@ func (cfg *Config) Address() (string, error) { if err := cfg.Validate(); err != nil { return "", err } + return fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), nil } diff --git a/metrics/fp_collectors.go b/metrics/fp_collectors.go index 11e00e89..4696e647 100644 --- a/metrics/fp_collectors.go +++ b/metrics/fp_collectors.go @@ -155,6 +155,7 @@ func NewFpMetrics() *FpMetrics { prometheus.MustRegister(fpMetricsInstance.fpTotalFailedVotes) prometheus.MustRegister(fpMetricsInstance.fpTotalFailedRandomness) }) + return fpMetricsInstance } diff --git a/testutil/datagen.go b/testutil/datagen.go index e3c0ec47..8b5971ec 100644 --- a/testutil/datagen.go +++ b/testutil/datagen.go @@ -25,16 +25,19 @@ import ( func GenRandomByteArray(r *rand.Rand, length uint64) []byte { newHeaderBytes := make([]byte, length) r.Read(newHeaderBytes) + return newHeaderBytes } func GenRandomHexStr(r *rand.Rand, length uint64) string { randBytes := GenRandomByteArray(r, length) + return hex.EncodeToString(randBytes) } func RandomDescription(r *rand.Rand) *stakingtypes.Description { des := stakingtypes.NewDescription(GenRandomHexStr(r, 10), "", "", "", "") + return &des } @@ -50,6 +53,7 @@ func AddRandomSeedsToFuzzer(f *testing.F, num uint) { func GenPublicRand(r *rand.Rand, t *testing.T) *bbn.SchnorrPubRand { _, eotsPR, err := eots.RandGen(r) require.NoError(t, err) + return bbn.NewSchnorrPubRandFromFieldVal(eotsPR) } @@ -111,6 +115,7 @@ func CreateChainKey(keyringDir, chainID, keyName, backend, passphrase, hdPath, m func GenSdkContext(r *rand.Rand, t *testing.T) client.Context { chainID := "testchain-" + GenRandomHexStr(r, 4) dir := t.TempDir() + return client.Context{}. WithChainID(chainID). WithCodec(codec.MakeCodec()). diff --git a/testutil/logger.go b/testutil/logger.go index 80aa29bd..878fc3eb 100644 --- a/testutil/logger.go +++ b/testutil/logger.go @@ -13,5 +13,6 @@ func GetTestLogger(t *testing.T) *zap.Logger { logger, err := loggerConfig.Build() require.NoError(t, err) + return logger } diff --git a/testutil/port.go b/testutil/port.go index 19ad7f76..fedeb7a8 100644 --- a/testutil/port.go +++ b/testutil/port.go @@ -36,12 +36,14 @@ func AllocateUniquePort(t *testing.T) int { if _, exists := allocatedPorts[port]; exists { // Port already allocated, try another one portMutex.Unlock() + continue } listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port)) if err != nil { portMutex.Unlock() + continue } @@ -57,5 +59,6 @@ func AllocateUniquePort(t *testing.T) int { // If no available port was found, fail the test t.Fatalf("failed to find an available port in range %d-%d", basePort, basePort+portRange) + return 0 } diff --git a/testutil/utils.go b/testutil/utils.go index 841e0c8f..89b0ffe5 100644 --- a/testutil/utils.go +++ b/testutil/utils.go @@ -15,6 +15,7 @@ const TestPubRandNum = 25 func ZeroCommissionRate() *sdkmath.LegacyDec { zeroCom := sdkmath.LegacyZeroDec() + return &zeroCom } diff --git a/types/pub_rand_commit.go b/types/pub_rand_commit.go index 3b1c63e6..1e878036 100644 --- a/types/pub_rand_commit.go +++ b/types/pub_rand_commit.go @@ -13,5 +13,6 @@ func GetPubRandCommitAndProofs(pubRandList []*btcec.FieldVal) ([]byte, []*merkle for _, pr := range pubRandList { prBytesList = append(prBytesList, bbn.NewSchnorrPubRandFromFieldVal(pr).MustMarshal()) } + return merkle.ProofsFromByteSlices(prBytesList) } diff --git a/util/path.go b/util/path.go index 95ad7e1b..e3dd8eaf 100644 --- a/util/path.go +++ b/util/path.go @@ -19,6 +19,7 @@ func FileExists(name string) bool { return false } } + return true } @@ -35,8 +36,10 @@ func MakeDirectory(dir string) error { err = fmt.Errorf(str, e.Path, link) } } + return fmt.Errorf("failed to create dir %s: %w", dir, err) } + return nil } @@ -72,7 +75,9 @@ func GetSubCommand(cmd *cobra.Command, commandName string) *cobra.Command { if !strings.EqualFold(c.Name(), commandName) { continue } + return c } + return nil } diff --git a/version/cmd.go b/version/cmd.go index cb56880f..6cf05601 100644 --- a/version/cmd.go +++ b/version/cmd.go @@ -33,5 +33,6 @@ func CommandVersion(binaryName string) *cobra.Command { cmd.Printf(sb.String()) //nolint:govet // it's not an issue }, } + return cmd } diff --git a/version/version.go b/version/version.go index 9f701f99..3aab6424 100644 --- a/version/version.go +++ b/version/version.go @@ -42,5 +42,6 @@ func Version() string { func RPC() string { commit, ts := CommitInfo() + return fmt.Sprintf("version: %s, commit: %s, timestamp: %s ", version, commit, ts) }