Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: enable errorlint and refactor code #14110

Merged
merged 22 commits into from
Jul 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ linters:
- dogsled
- dupl
- durationcheck
- errorlint
- exhaustive
- exhaustruct
- forbidigo
Expand Down
14 changes: 6 additions & 8 deletions api/client/beacon/checkpoint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,20 @@ import (
"net/http"
"testing"

"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/api/client"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/state"
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/blocks"
blocktest "github.com/prysmaticlabs/prysm/v5/consensus-types/blocks/testing"
"github.com/prysmaticlabs/prysm/v5/network/forks"
ethpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/testing/util"
"github.com/prysmaticlabs/prysm/v5/time/slots"

"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/encoding/ssz/detect"
"github.com/prysmaticlabs/prysm/v5/network/forks"
ethpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/runtime/version"

"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/testing/require"
"github.com/prysmaticlabs/prysm/v5/testing/util"
"github.com/prysmaticlabs/prysm/v5/time/slots"
)

type testRT struct {
Expand Down
1 change: 1 addition & 0 deletions api/client/builder/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ go_test(
"//testing/assert:go_default_library",
"//testing/require:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_pkg_errors//:go_default_library",
"@com_github_prysmaticlabs_go_bitfield//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
],
Expand Down
4 changes: 3 additions & 1 deletion api/client/builder/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"testing"

"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
fieldparams "github.com/prysmaticlabs/prysm/v5/config/fieldparams"
Expand Down Expand Up @@ -1914,7 +1915,8 @@ func TestEmptyResponseBody(t *testing.T) {
var b []byte
r := &ExecutionPayloadResponse{}
err := json.Unmarshal(b, r)
_, ok := err.(*json.SyntaxError)
var syntaxError *json.SyntaxError
ok := errors.As(err, &syntaxError)
require.Equal(t, true, ok)
})
t.Run("empty object", func(t *testing.T) {
Expand Down
4 changes: 3 additions & 1 deletion api/server/error.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package server

import (
"errors"
"fmt"
"strings"
)
Expand All @@ -15,7 +16,8 @@ type DecodeError struct {
// NewDecodeError wraps an error (either the initial decoding error or another DecodeError).
// The current field that failed decoding must be passed in.
func NewDecodeError(err error, field string) *DecodeError {
de, ok := err.(*DecodeError)
var de *DecodeError
ok := errors.As(err, &de)
if ok {
return &DecodeError{path: append([]string{field}, de.path...), err: de.err}
}
Expand Down
5 changes: 2 additions & 3 deletions api/server/structs/conversions.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/api/server"
"github.com/prysmaticlabs/prysm/v5/consensus-types/validator"
"github.com/prysmaticlabs/prysm/v5/container/slice"

fieldparams "github.com/prysmaticlabs/prysm/v5/config/fieldparams"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/consensus-types/validator"
"github.com/prysmaticlabs/prysm/v5/container/slice"
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v5/math"
enginev1 "github.com/prysmaticlabs/prysm/v5/proto/engine/v1"
Expand Down
3 changes: 1 addition & 2 deletions beacon-chain/blockchain/chain_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import (
"time"

"github.com/pkg/errors"
"go.opencensus.io/trace"

"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/helpers"
f "github.com/prysmaticlabs/prysm/v5/beacon-chain/forkchoice"
doublylinkedtree "github.com/prysmaticlabs/prysm/v5/beacon-chain/forkchoice/doubly-linked-tree"
Expand All @@ -20,6 +18,7 @@ import (
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
ethpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/time/slots"
"go.opencensus.io/trace"
)

// ChainInfoFetcher defines a common interface for methods in blockchain service which
Expand Down
15 changes: 7 additions & 8 deletions beacon-chain/blockchain/execution_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,16 +74,16 @@ func (s *Service) notifyForkchoiceUpdate(ctx context.Context, arg *fcuConfig) (*
}
payloadID, lastValidHash, err := s.cfg.ExecutionEngineCaller.ForkchoiceUpdated(ctx, fcs, arg.attributes)
if err != nil {
switch err {
case execution.ErrAcceptedSyncingPayloadStatus:
switch {
case errors.Is(err, execution.ErrAcceptedSyncingPayloadStatus):
forkchoiceUpdatedOptimisticNodeCount.Inc()
log.WithFields(logrus.Fields{
"headSlot": headBlk.Slot(),
"headPayloadBlockHash": fmt.Sprintf("%#x", bytesutil.Trunc(headPayload.BlockHash())),
"finalizedPayloadBlockHash": fmt.Sprintf("%#x", bytesutil.Trunc(finalizedHash[:])),
}).Info("Called fork choice updated with optimistic block")
return payloadID, nil
case execution.ErrInvalidPayloadStatus:
case errors.Is(err, execution.ErrInvalidPayloadStatus):
forkchoiceUpdatedInvalidNodeCount.Inc()
headRoot := arg.headRoot
if len(lastValidHash) == 0 {
Expand Down Expand Up @@ -139,7 +139,6 @@ func (s *Service) notifyForkchoiceUpdate(ctx context.Context, arg *fcuConfig) (*
"newHeadRoot": fmt.Sprintf("%#x", bytesutil.Trunc(r[:])),
}).Warn("Pruned invalid blocks")
return pid, invalidBlock{error: ErrInvalidPayload, root: arg.headRoot, invalidAncestorRoots: invalidRoots}

default:
log.WithError(err).Error(ErrUndefinedExecutionEngineError)
return nil, nil
Expand Down Expand Up @@ -231,18 +230,18 @@ func (s *Service) notifyNewPayload(ctx context.Context, preStateVersion int,
} else {
lastValidHash, err = s.cfg.ExecutionEngineCaller.NewPayload(ctx, payload, []common.Hash{}, &common.Hash{} /*empty version hashes and root before Deneb*/)
}
switch err {
case nil:
switch {
case err == nil:
newPayloadValidNodeCount.Inc()
return true, nil
case execution.ErrAcceptedSyncingPayloadStatus:
case errors.Is(err, execution.ErrAcceptedSyncingPayloadStatus):
newPayloadOptimisticNodeCount.Inc()
log.WithFields(logrus.Fields{
"slot": blk.Block().Slot(),
"payloadBlockHash": fmt.Sprintf("%#x", bytesutil.Trunc(payload.BlockHash())),
}).Info("Called new payload with optimistic block")
return false, nil
case execution.ErrInvalidPayloadStatus:
case errors.Is(err, execution.ErrInvalidPayloadStatus):
lvh := bytesutil.ToBytes32(lastValidHash)
return false, invalidBlock{
error: ErrInvalidPayload,
Expand Down
18 changes: 9 additions & 9 deletions beacon-chain/blockchain/lightclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func NewLightClientOptimisticUpdateFromBeaconState(
// assert sum(block.message.body.sync_aggregate.sync_committee_bits) >= MIN_SYNC_COMMITTEE_PARTICIPANTS
syncAggregate, err := block.Block().Body().SyncAggregate()
if err != nil {
return nil, fmt.Errorf("could not get sync aggregate %v", err)
return nil, fmt.Errorf("could not get sync aggregate %w", err)
}

if syncAggregate.SyncCommitteeBits.Count() < params.BeaconConfig().MinSyncCommitteeParticipants {
Expand All @@ -85,18 +85,18 @@ func NewLightClientOptimisticUpdateFromBeaconState(
header := state.LatestBlockHeader()
stateRoot, err := state.HashTreeRoot(ctx)
if err != nil {
return nil, fmt.Errorf("could not get state root %v", err)
return nil, fmt.Errorf("could not get state root %w", err)
}
header.StateRoot = stateRoot[:]

headerRoot, err := header.HashTreeRoot()
if err != nil {
return nil, fmt.Errorf("could not get header root %v", err)
return nil, fmt.Errorf("could not get header root %w", err)
}

blockRoot, err := block.Block().HashTreeRoot()
if err != nil {
return nil, fmt.Errorf("could not get block root %v", err)
return nil, fmt.Errorf("could not get block root %w", err)
}

if headerRoot != blockRoot {
Expand All @@ -114,14 +114,14 @@ func NewLightClientOptimisticUpdateFromBeaconState(
// attested_header.state_root = hash_tree_root(attested_state)
attestedStateRoot, err := attestedState.HashTreeRoot(ctx)
if err != nil {
return nil, fmt.Errorf("could not get attested state root %v", err)
return nil, fmt.Errorf("could not get attested state root %w", err)
}
attestedHeader.StateRoot = attestedStateRoot[:]

// assert hash_tree_root(attested_header) == block.message.parent_root
attestedHeaderRoot, err := attestedHeader.HashTreeRoot()
if err != nil {
return nil, fmt.Errorf("could not get attested header root %v", err)
return nil, fmt.Errorf("could not get attested header root %w", err)
}

if attestedHeaderRoot != block.Block().ParentRoot() {
Expand Down Expand Up @@ -175,13 +175,13 @@ func NewLightClientFinalityUpdateFromBeaconState(
if finalizedBlock.Block().Slot() != 0 {
tempFinalizedHeader, err := finalizedBlock.Header()
if err != nil {
return nil, fmt.Errorf("could not get finalized header %v", err)
return nil, fmt.Errorf("could not get finalized header %w", err)
}
finalizedHeader = migration.V1Alpha1SignedHeaderToV1(tempFinalizedHeader).GetMessage()

finalizedHeaderRoot, err := finalizedHeader.HashTreeRoot()
if err != nil {
return nil, fmt.Errorf("could not get finalized header root %v", err)
return nil, fmt.Errorf("could not get finalized header root %w", err)
}

if finalizedHeaderRoot != bytesutil.ToBytes32(attestedState.FinalizedCheckpoint().Root) {
Expand All @@ -204,7 +204,7 @@ func NewLightClientFinalityUpdateFromBeaconState(
var bErr error
finalityBranch, bErr = attestedState.FinalizedRootProof(ctx)
if bErr != nil {
return nil, fmt.Errorf("could not get finalized root proof %v", bErr)
return nil, fmt.Errorf("could not get finalized root proof %w", bErr)
}
} else {
finalizedHeader = &ethpbv1.BeaconBlockHeader{
Expand Down
5 changes: 2 additions & 3 deletions beacon-chain/blockchain/process_block.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@ import (
"time"

"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"

"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/feed"
statefeed "github.com/prysmaticlabs/prysm/v5/beacon-chain/core/feed/state"
Expand All @@ -32,6 +29,8 @@ import (
"github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1/attestation"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
"github.com/prysmaticlabs/prysm/v5/time/slots"
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"
)

// A custom slot deadline for processing state slots in our cache.
Expand Down
5 changes: 2 additions & 3 deletions beacon-chain/blockchain/process_block_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ import (

"github.com/ethereum/go-ethereum/common"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"

"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/feed"
statefeed "github.com/prysmaticlabs/prysm/v5/beacon-chain/core/feed/state"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/transition"
Expand All @@ -25,6 +22,8 @@ import (
ethpbv2 "github.com/prysmaticlabs/prysm/v5/proto/eth/v2"
ethpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/time/slots"
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"
)

// CurrentSlot returns the current slot based on time.
Expand Down
5 changes: 2 additions & 3 deletions beacon-chain/blockchain/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import (
"time"

"github.com/pkg/errors"
"go.opencensus.io/trace"

"github.com/prysmaticlabs/prysm/v5/async/event"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/blockchain/kzg"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/cache"
Expand Down Expand Up @@ -44,6 +42,7 @@ import (
ethpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
prysmTime "github.com/prysmaticlabs/prysm/v5/time"
"github.com/prysmaticlabs/prysm/v5/time/slots"
"go.opencensus.io/trace"
)

// Service represents a service that handles the internal
Expand Down Expand Up @@ -506,7 +505,7 @@ func (s *Service) saveGenesisData(ctx context.Context, genesisState state.Beacon
}
genesisBlk, err := s.cfg.BeaconDB.GenesisBlock(ctx)
if err != nil || genesisBlk == nil || genesisBlk.IsNil() {
return fmt.Errorf("could not load genesis block: %v", err)
return fmt.Errorf("could not load genesis block: %w", err)
}
genesisBlkRoot, err := genesisBlk.Block().HashTreeRoot()
if err != nil {
Expand Down
8 changes: 4 additions & 4 deletions beacon-chain/core/helpers/sync_committee.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func IsCurrentPeriodSyncCommittee(st state.BeaconState, valIdx primitives.Valida
return false, err
}
indices, err := syncCommitteeCache.CurrentPeriodIndexPosition(root, valIdx)
if err == cache.ErrNonExistingSyncCommitteeKey {
if errors.Is(err, cache.ErrNonExistingSyncCommitteeKey) {
val, err := st.ValidatorAtIndex(valIdx)
if err != nil {
return false, err
Expand Down Expand Up @@ -68,7 +68,7 @@ func IsNextPeriodSyncCommittee(
return false, err
}
indices, err := syncCommitteeCache.NextPeriodIndexPosition(root, valIdx)
if err == cache.ErrNonExistingSyncCommitteeKey {
if errors.Is(err, cache.ErrNonExistingSyncCommitteeKey) {
val, err := st.ValidatorAtIndex(valIdx)
if err != nil {
return false, err
Expand All @@ -95,7 +95,7 @@ func CurrentPeriodSyncSubcommitteeIndices(
return nil, err
}
indices, err := syncCommitteeCache.CurrentPeriodIndexPosition(root, valIdx)
if err == cache.ErrNonExistingSyncCommitteeKey {
if errors.Is(err, cache.ErrNonExistingSyncCommitteeKey) {
val, err := st.ValidatorAtIndex(valIdx)
if err != nil {
return nil, err
Expand Down Expand Up @@ -129,7 +129,7 @@ func NextPeriodSyncSubcommitteeIndices(
return nil, err
}
indices, err := syncCommitteeCache.NextPeriodIndexPosition(root, valIdx)
if err == cache.ErrNonExistingSyncCommitteeKey {
if errors.Is(err, cache.ErrNonExistingSyncCommitteeKey) {
val, err := st.ValidatorAtIndex(valIdx)
if err != nil {
return nil, err
Expand Down
11 changes: 7 additions & 4 deletions beacon-chain/execution/engine_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -647,14 +647,15 @@ func handleRPCError(err error) error {
if isTimeout(err) {
return ErrHTTPTimeout
}
e, ok := err.(gethRPC.Error)
var e gethRPC.Error
ok := errors.As(err, &e)
if !ok {
if strings.Contains(err.Error(), "401 Unauthorized") {
log.Error("HTTP authentication to your execution client is not working. Please ensure " +
"you are setting a correct value for the --jwt-secret flag in Prysm, or use an IPC connection if on " +
"the same machine. Please see our documentation for more information on authenticating connections " +
"here https://docs.prylabs.network/docs/execution-node/authentication")
return fmt.Errorf("could not authenticate connection to execution client: %v", err)
return fmt.Errorf("could not authenticate connection to execution client: %w", err)
}
return errors.Wrapf(err, "got an unexpected error in JSON-RPC response")
}
Expand Down Expand Up @@ -689,7 +690,8 @@ func handleRPCError(err error) error {
case -32000:
errServerErrorCount.Inc()
// Only -32000 status codes are data errors in the RPC specification.
errWithData, ok := err.(gethRPC.DataError)
var errWithData gethRPC.DataError
ok := errors.As(err, &errWithData)
if !ok {
return errors.Wrapf(err, "got an unexpected error in JSON-RPC response")
}
Expand All @@ -708,7 +710,8 @@ type httpTimeoutError interface {
}

func isTimeout(e error) bool {
t, ok := e.(httpTimeoutError)
var t httpTimeoutError
ok := errors.As(e, &t)
return ok && t.Timeout()
}

Expand Down
2 changes: 1 addition & 1 deletion beacon-chain/node/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -572,7 +572,7 @@ func (b *BeaconNode) startDB(cliCtx *cli.Context, depositAddress string) error {

if b.GenesisInitializer != nil {
if err := b.GenesisInitializer.Initialize(b.ctx, d); err != nil {
if err == db.ErrExistingGenesisState {
if errors.Is(err, db.ErrExistingGenesisState) {
return errors.Errorf("Genesis state flag specified but a genesis state "+
"exists already. Run again with --%s and/or ensure you are using the "+
"appropriate testnet flag to load the given genesis state.", cmd.ClearDB.Name)
Expand Down
2 changes: 1 addition & 1 deletion beacon-chain/node/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func (bc *bcnodeCollector) Collect(ch chan<- prometheus.Metric) {
func (bc *bcnodeCollector) getCurrentDbBytes() (float64, error) {
fs, err := os.Stat(bc.dbPath)
if err != nil {
return 0, fmt.Errorf("could not collect database file size for prometheus, path=%s, err=%s", bc.dbPath, err)
return 0, fmt.Errorf("could not collect database file size for prometheus, path=%s, err=%w", bc.dbPath, err)
}
return float64(fs.Size()), nil
}
Expand Down
4 changes: 0 additions & 4 deletions beacon-chain/node/registration/log.go
Original file line number Diff line number Diff line change
@@ -1,5 +1 @@
package registration

import "github.com/sirupsen/logrus"

var log = logrus.WithField("prefix", "registration")
Loading
Loading