Skip to content

Commit

Permalink
Update error usage patterns to go1.13+ (#7529)
Browse files Browse the repository at this point in the history
* rely on errors.Is

* wrap errors
  • Loading branch information
farazdagi committed Oct 14, 2020
1 parent 8f04c55 commit a005c77
Show file tree
Hide file tree
Showing 25 changed files with 39 additions and 36 deletions.
4 changes: 2 additions & 2 deletions beacon-chain/core/helpers/slot_epoch.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,11 @@ func VerifySlotTime(genesisTime, slot uint64, timeTolerance time.Duration) error
func SlotToTime(genesisTimeSec, slot uint64) (time.Time, error) {
timeSinceGenesis, err := mathutil.Mul64(slot, params.BeaconConfig().SecondsPerSlot)
if err != nil {
return time.Unix(0, 0), fmt.Errorf("slot (%d) is in the far distant future: %v", slot, err)
return time.Unix(0, 0), fmt.Errorf("slot (%d) is in the far distant future: %w", slot, err)
}
sTime, err := mathutil.Add64(genesisTimeSec, timeSinceGenesis)
if err != nil {
return time.Unix(0, 0), fmt.Errorf("slot (%d) is in the far distant future: %v", slot, err)
return time.Unix(0, 0), fmt.Errorf("slot (%d) is in the far distant future: %w", slot, err)
}
return time.Unix(int64(sTime), 0), nil
}
Expand Down
2 changes: 1 addition & 1 deletion beacon-chain/core/state/transition.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ func ProcessSlots(ctx context.Context, state *stateTrie.BeaconState, slot uint64
highestSlot = cachedState.Slot()
state = cachedState
}
if err := SkipSlotCache.MarkInProgress(key); err == cache.ErrAlreadyInProgress {
if err := SkipSlotCache.MarkInProgress(key); errors.Is(err, cache.ErrAlreadyInProgress) {
cachedState, err = SkipSlotCache.Get(ctx, key)
if err != nil {
return nil, err
Expand Down
2 changes: 1 addition & 1 deletion beacon-chain/db/kv/kv.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func NewKVStore(dirPath string, stateSummaryCache *cache.StateSummaryCache) (*St
datafile := path.Join(dirPath, databaseFileName)
boltDB, err := bolt.Open(datafile, params.BeaconIoConfig().ReadWritePermissions, &bolt.Options{Timeout: 1 * time.Second, InitialMmapSize: 10e6})
if err != nil {
if err == bolt.ErrTimeout {
if errors.Is(err, bolt.ErrTimeout) {
return nil, errors.New("cannot obtain database lock, database may be in use by another process")
}
return nil, err
Expand Down
3 changes: 2 additions & 1 deletion beacon-chain/p2p/handshake.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package p2p

import (
"context"
"errors"
"fmt"
"io"
"sync"
Expand Down Expand Up @@ -110,7 +111,7 @@ func (s *Service) AddConnectionHandler(reqFunc func(ctx context.Context, id peer
}

// If peer hasn't sent a status request, we disconnect with them
if _, err := s.peers.ChainState(remotePeer); err == peerdata.ErrPeerUnknown {
if _, err := s.peers.ChainState(remotePeer); errors.Is(err, peerdata.ErrPeerUnknown) {
disconnectFromPeer()
return
}
Expand Down
2 changes: 1 addition & 1 deletion beacon-chain/rpc/beacon/validators_stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ func (is *infostream) handleConnection() error {
go func() {
for {
msg, err := is.stream.Recv()
if err == io.EOF {
if errors.Is(err, io.EOF) {
return
}
if err != nil {
Expand Down
3 changes: 2 additions & 1 deletion beacon-chain/rpc/validator/attester.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package validator

import (
"context"
"errors"
"fmt"

ptypes "github.com/gogo/protobuf/types"
Expand Down Expand Up @@ -48,7 +49,7 @@ func (vs *Server) GetAttestationData(ctx context.Context, req *ethpb.Attestation
}

if err := vs.AttestationCache.MarkInProgress(req); err != nil {
if err == cache.ErrAlreadyInProgress {
if errors.Is(err, cache.ErrAlreadyInProgress) {
res, err := vs.AttestationCache.Get(ctx, req)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not retrieve data from attestation cache: %v", err)
Expand Down
2 changes: 1 addition & 1 deletion beacon-chain/sync/initial-sync/blocks_fetcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ func (f *blocksFetcher) requestBlocks(
for i := uint64(0); ; i++ {
isFirstChunk := i == 0
blk, err := prysmsync.ReadChunkedBlock(stream, f.p2p, isFirstChunk)
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion beacon-chain/sync/initial-sync/blocks_queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ func (q *blocksQueue) loop() {
"start": fsm.start,
"error": err.Error(),
}).Debug("Can not trigger event")
if err == errNoRequiredPeers {
if errors.Is(err, errNoRequiredPeers) {
forceExit := q.exitConditions.noRequiredPeersErrRetries > noRequiredPeersErrMaxRetries
if q.mode == modeStopOnFinalizedEpoch || forceExit {
q.cancel()
Expand Down
2 changes: 1 addition & 1 deletion beacon-chain/sync/rpc_beacon_blocks_by_root.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func (s *Service) sendRecentBeaconBlocksRequest(ctx context.Context, blockRoots
for i := 0; i < len(*blockRoots); i++ {
isFirstChunk := i == 0
blk, err := ReadChunkedBlock(stream, s.p2p, isFirstChunk)
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
// Exit if peer sends more than max request blocks.
Expand Down
4 changes: 2 additions & 2 deletions beacon-chain/sync/rpc_ping.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func (s *Service) pingHandler(_ context.Context, msg interface{}, stream libp2pc
valid, err := s.validateSequenceNum(*m, stream.Conn().RemotePeer())
if err != nil {
// Descore peer for giving us a bad sequence number.
if err == errInvalidSequenceNum {
if errors.Is(err, errInvalidSequenceNum) {
s.p2p.Peers().Scorers().BadResponsesScorer().Increment(stream.Conn().RemotePeer())
s.writeErrorResponseToStream(responseCodeInvalidRequest, seqError, stream)
}
Expand Down Expand Up @@ -122,7 +122,7 @@ func (s *Service) sendPingRequest(ctx context.Context, id peer.ID) error {
valid, err := s.validateSequenceNum(*msg, stream.Conn().RemotePeer())
if err != nil {
// Descore peer for giving us a bad sequence number.
if err == errInvalidSequenceNum {
if errors.Is(err, errInvalidSequenceNum) {
s.p2p.Peers().Scorers().BadResponsesScorer().Increment(stream.Conn().RemotePeer())
}
return err
Expand Down
2 changes: 1 addition & 1 deletion beacon-chain/sync/rpc_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ func (s *Service) sendRPCStatusRequest(ctx context.Context, id peer.ID) error {
if err != nil {
s.p2p.Peers().Scorers().BadResponsesScorer().Increment(stream.Conn().RemotePeer())
// Disconnect if on a wrong fork.
if err == errWrongForkDigestVersion {
if errors.Is(err, errWrongForkDigestVersion) {
if err := s.sendGoodByeAndDisconnect(ctx, codeWrongNetwork, stream.Conn().RemotePeer()); err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion shared/aggregation/attestations/maxcover.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func MaxCoverAttestationAggregation(atts []*ethpb.Attestation) ([]*ethpb.Attesta
// Find maximum non-overlapping coverage.
maxCover, err := NewMaxCover(unaggregated)
if err != nil {
if err == aggregation.ErrBitsDifferentLen {
if errors.Is(err, aggregation.ErrBitsDifferentLen) {
return atts, nil
}
return aggregated.merge(unaggregated), err
Expand Down
2 changes: 1 addition & 1 deletion shared/prometheus/content_negotiation.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func writeResponse(w http.ResponseWriter, r *http.Request, response generatedRes
return fmt.Errorf("unexpected data: %v", response.Data)
}
if _, err := w.Write(buf.Bytes()); err != nil {
return fmt.Errorf("could not write response body: %v", err)
return fmt.Errorf("could not write response body: %w", err)
}
case contentTypeJSON:
w.Header().Set("Content-Type", contentTypeJSON)
Expand Down
4 changes: 2 additions & 2 deletions shared/promptutil/prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,12 +148,12 @@ func InputPassword(
for !hasValidPassword {
password, err = PasswordPrompt(promptText, passwordValidator)
if err != nil {
return "", fmt.Errorf("could not read password: %v", err)
return "", fmt.Errorf("could not read password: %w", err)
}
if shouldConfirmPassword {
passwordConfirmation, err := PasswordPrompt(confirmText, passwordValidator)
if err != nil {
return "", fmt.Errorf("could not read password confirmation: %v", err)
return "", fmt.Errorf("could not read password confirmation: %w", err)
}
if password != passwordConfirmation {
log.Error("Passwords do not match")
Expand Down
4 changes: 2 additions & 2 deletions slasher/beaconclient/receivers.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func (bs *Service) ReceiveBlocks(ctx context.Context) {
for {
res, err := stream.Recv()
// If the stream is closed, we stop the loop.
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
// If context is canceled we stop the loop.
Expand Down Expand Up @@ -103,7 +103,7 @@ func (bs *Service) ReceiveAttestations(ctx context.Context) {
for {
res, err := stream.Recv()
// If the stream is closed, we stop the loop.
if err == io.EOF {
if errors.Is(err, io.EOF) {
log.Info("Attestation stream closed")
break
}
Expand Down
2 changes: 1 addition & 1 deletion slasher/db/kv/kv.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func NewKVStore(dirPath string, cfg *Config) (*Store, error) {
datafile := path.Join(dirPath, databaseFileName)
boltDB, err := bolt.Open(datafile, params.BeaconIoConfig().ReadWritePermissions, &bolt.Options{Timeout: params.BeaconIoConfig().BoltTimeout})
if err != nil {
if err == bolt.ErrTimeout {
if errors.Is(err, bolt.ErrTimeout) {
return nil, errors.New("cannot obtain database lock, database may be in use by another process")
}
return nil, err
Expand Down
2 changes: 1 addition & 1 deletion tools/cluster-pk-manager/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ func (s *server) checkDepositTxs(ctx context.Context, txMap map[*keystore.Key]*t
pks := make([][]byte, 0, len(txMap))
for k, tx := range txMap {
receipt, err := s.client.TransactionReceipt(ctx, tx.Hash())
if err == ethereum.NotFound {
if errors.Is(err, ethereum.NotFound) {
// tx still not processed yet.
continue
}
Expand Down
2 changes: 1 addition & 1 deletion validator/accounts/v1/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ func Exists(keystorePath string, assertNonEmpty bool) (bool, error) {

if assertNonEmpty {
_, err = f.Readdirnames(1) // Or f.Readdir(1)
if err == io.EOF {
if errors.Is(err, io.EOF) {
return false, nil
}
}
Expand Down
2 changes: 1 addition & 1 deletion validator/accounts/v2/accounts_import.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ func ImportAccountsCli(cliCtx *cli.Context) error {
"Enter the password for your imported accounts", promptutil.NotEmpty,
)
if err != nil {
return fmt.Errorf("could not read account password: %v", err)
return fmt.Errorf("could not read account password: %w", err)
}
}
fmt.Println("Importing accounts, this may take a while...")
Expand Down
10 changes: 5 additions & 5 deletions validator/accounts/v2/wallet/wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func Exists(walletDir string) (bool, error) {
return false, errors.Wrap(err, "could not parse wallet directory")
}
isValid, err := IsValid(walletDir)
if err == ErrNoWalletFound {
if errors.Is(err, ErrNoWalletFound) {
return false, nil
} else if err != nil {
return false, errors.Wrap(err, "could not check if dir is valid")
Expand Down Expand Up @@ -169,7 +169,7 @@ func OpenWalletOrElseCli(cliCtx *cli.Context, otherwise func(cliCtx *cli.Context
return otherwise(cliCtx)
}
isValid, err := IsValid(cliCtx.String(flags.WalletDirFlag.Name))
if err == ErrNoWalletFound {
if errors.Is(err, ErrNoWalletFound) {
return otherwise(cliCtx)
}
if err != nil {
Expand Down Expand Up @@ -222,7 +222,7 @@ func OpenWallet(_ context.Context, cfg *Config) (*Wallet, error) {
}
valid, err := IsValid(cfg.WalletDir)
// ErrNoWalletFound represents both a directory that does not exist as well as an empty directory
if err == ErrNoWalletFound {
if errors.Is(err, ErrNoWalletFound) {
return nil, ErrNoWalletFound
}
if err != nil {
Expand Down Expand Up @@ -536,13 +536,13 @@ func inputPassword(
for !hasValidPassword {
walletPassword, err = promptutil.PasswordPrompt(promptText, passwordValidator)
if err != nil {
return "", fmt.Errorf("could not read account password: %v", err)
return "", fmt.Errorf("could not read account password: %w", err)
}

if confirmPassword {
passwordConfirmation, err := promptutil.PasswordPrompt(ConfirmPasswordPromptText, passwordValidator)
if err != nil {
return "", fmt.Errorf("could not read password confirmation: %v", err)
return "", fmt.Errorf("could not read password confirmation: %w", err)
}
if walletPassword != passwordConfirmation {
log.Error("Passwords do not match")
Expand Down
4 changes: 2 additions & 2 deletions validator/accounts/v2/wallet_recover.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,15 +177,15 @@ func inputMnemonic(cliCtx *cli.Context) (string, error) {
},
)
if err != nil {
return "", fmt.Errorf("could not get mnemonic language: %v", err)
return "", fmt.Errorf("could not get mnemonic language: %w", err)
}
bip39.SetWordList(allowedLanguages[selectedLanguage])
mnemonicPhrase, err := promptutil.ValidatePrompt(
os.Stdin,
"Enter the seed phrase for the wallet you would like to recover",
validateMnemonic)
if err != nil {
return "", fmt.Errorf("could not get mnemonic phrase: %v", err)
return "", fmt.Errorf("could not get mnemonic phrase: %w", err)
}
return mnemonicPhrase, nil
}
Expand Down
2 changes: 1 addition & 1 deletion validator/client/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ func (v *validator) WaitForActivation(ctx context.Context) error {
for {
res, err := stream.Recv()
// If the stream is closed, we stop the loop.
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
// If context is canceled we stop the loop.
Expand Down
4 changes: 2 additions & 2 deletions validator/db/kv/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func NewKVStore(dirPath string, pubKeys [][48]byte) (*Store, error) {
datafile := filepath.Join(dirPath, ProtectionDbFileName)
boltDB, err := bolt.Open(datafile, params.BeaconIoConfig().ReadWritePermissions, &bolt.Options{Timeout: params.BeaconIoConfig().BoltTimeout})
if err != nil {
if err == bolt.ErrTimeout {
if errors.Is(err, bolt.ErrTimeout) {
return nil, errors.New("cannot obtain database lock, database may be in use by another process")
}
return nil, err
Expand Down Expand Up @@ -105,7 +105,7 @@ func GetKVStore(directory string) (*Store, error) {
}
boltDb, err := bolt.Open(fileName, params.BeaconIoConfig().ReadWritePermissions, &bolt.Options{Timeout: params.BeaconIoConfig().BoltTimeout})
if err != nil {
if err == bolt.ErrTimeout {
if errors.Is(err, bolt.ErrTimeout) {
return nil, errors.New("cannot obtain database lock, database may be in use by another process")
}
return nil, err
Expand Down
2 changes: 1 addition & 1 deletion validator/rpc/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ func (s *Server) initializeWallet(ctx context.Context, cfg *wallet.Config) error
return wallet.ErrNoWalletFound
}
valid, err := wallet.IsValid(cfg.WalletDir)
if err == wallet.ErrNoWalletFound {
if errors.Is(err, wallet.ErrNoWalletFound) {
return wallet.ErrNoWalletFound
}
if err != nil {
Expand Down
5 changes: 3 additions & 2 deletions validator/rpc/wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"io/ioutil"
"path/filepath"
"strings"
Expand Down Expand Up @@ -183,7 +184,7 @@ func (s *Server) WalletConfig(ctx context.Context, _ *ptypes.Empty) (*pb.WalletR
return &pb.WalletResponse{}, nil
}
valid, err := wallet.IsValid(s.walletDir)
if err == wallet.ErrNoWalletFound {
if errors.Is(err, wallet.ErrNoWalletFound) {
return &pb.WalletResponse{}, nil
}
if err != nil {
Expand Down Expand Up @@ -255,7 +256,7 @@ func (s *Server) ChangePassword(ctx context.Context, req *pb.ChangePasswordReque
return nil, status.Errorf(codes.FailedPrecondition, noWalletMsg)
}
valid, err := wallet.IsValid(s.walletDir)
if err == wallet.ErrNoWalletFound {
if errors.Is(err, wallet.ErrNoWalletFound) {
return nil, status.Errorf(codes.FailedPrecondition, noWalletMsg)
}
if err != nil {
Expand Down

0 comments on commit a005c77

Please sign in to comment.