Skip to content

Commit

Permalink
chore(all): enable errorlint and fix all errors
Browse files Browse the repository at this point in the history
- Ignore fmt.Errorf not using wrapping with `%w`
- Use `errors.Is` instead of `==`
- Use `errors.As` instead of direct type assertions
  • Loading branch information
qdm12 committed Jan 19, 2025
1 parent 04a336a commit a27f7c2
Show file tree
Hide file tree
Showing 118 changed files with 428 additions and 316 deletions.
4 changes: 3 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ run:
linters:
disable-all: true
enable:
- errorlint
- goimports
- gosimple
- govet
Expand All @@ -32,12 +33,13 @@ linters:
# - errcheck #lot of false positives
# - contextcheck
# - errchkjson # lots of false positives
# - errorlint # this check crashes
# - exhaustive # silly check
# - makezero # false positives
# - nilerr # several intentional

linters-settings:
errorlint:
errorf: false
gofmt:
simplify: true
revive:
Expand Down
2 changes: 1 addition & 1 deletion accounts/abi/bind/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func TestWaitDeployed(t *testing.T) {

select {
case <-mined:
if err != test.wantErr {
if !errors.Is(err, test.wantErr) {
t.Errorf("test %q: error mismatch: want %q, got %q", name, test.wantErr, err)
}
if address != test.wantAddress {
Expand Down
3 changes: 2 additions & 1 deletion accounts/abi/unpack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package abi
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"math"
"math/big"
Expand Down Expand Up @@ -1105,7 +1106,7 @@ func TestPackAndUnpackIncompatibleNumber(t *testing.T) {
{Type: ty},
}
decoded, err := decodeABI.Unpack(packed)
if err != testCase.err {
if !errors.Is(err, testCase.err) {
t.Fatalf("Expected error %v, actual error %v. case %d", testCase.err, err, i)
}
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion accounts/keystore/account_cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ func TestCacheFind(t *testing.T) {
}
for i, test := range tests {
a, err := cache.find(test.Query)
if !reflect.DeepEqual(err, test.WantError) {
if !errors.Is(err, test.WantError) {
t.Errorf("test %d: error mismatch for query %v\ngot %q\nwant %q", i, test.Query, err, test.WantError)
continue
}
Expand Down
9 changes: 5 additions & 4 deletions accounts/keystore/keystore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package keystore

import (
"errors"
"math/rand"
"os"
"runtime"
Expand Down Expand Up @@ -127,7 +128,7 @@ func TestTimedUnlock(t *testing.T) {

// Signing without passphrase fails because account is locked
_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
if err != ErrLocked {
if !errors.Is(err, ErrLocked) {
t.Fatal("Signing should've failed with ErrLocked before unlocking, got ", err)
}

Expand All @@ -145,7 +146,7 @@ func TestTimedUnlock(t *testing.T) {
// Signing fails again after automatic locking
time.Sleep(250 * time.Millisecond)
_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
if err != ErrLocked {
if !errors.Is(err, ErrLocked) {
t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err)
}
}
Expand Down Expand Up @@ -185,7 +186,7 @@ func TestOverrideUnlock(t *testing.T) {
// Signing fails again after automatic locking
time.Sleep(250 * time.Millisecond)
_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
if err != ErrLocked {
if !errors.Is(err, ErrLocked) {
t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err)
}
}
Expand All @@ -206,7 +207,7 @@ func TestSignRace(t *testing.T) {
}
end := time.Now().Add(500 * time.Millisecond)
for time.Now().Before(end) {
if _, err := ks.SignHash(accounts.Account{Address: a1.Address}, testSigData); err == ErrLocked {
if _, err := ks.SignHash(accounts.Account{Address: a1.Address}, testSigData); errors.Is(err, ErrLocked) {
return
} else if err != nil {
t.Errorf("Sign error: %v", err)
Expand Down
3 changes: 2 additions & 1 deletion accounts/keystore/plain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package keystore
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"path/filepath"
"reflect"
Expand Down Expand Up @@ -90,7 +91,7 @@ func TestKeyStorePassphraseDecryptionFail(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if _, err = ks.GetKey(k1.Address, account.URL.Path, "bar"); err != ErrDecrypt {
if _, err = ks.GetKey(k1.Address, account.URL.Path, "bar"); !errors.Is(err, ErrDecrypt) {
t.Fatalf("wrong error for invalid password\ngot %q\nwant %q", err, ErrDecrypt)
}
}
Expand Down
4 changes: 2 additions & 2 deletions accounts/usbwallet/ledger.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ func (w *ledgerDriver) Open(device io.ReadWriter, passphrase string) error {
_, err := w.ledgerDerive(accounts.DefaultBaseDerivationPath)
if err != nil {
// Ethereum app is not running or in browser mode, nothing more to do, return
if err == errLedgerReplyInvalidHeader {
if errors.Is(err, errLedgerReplyInvalidHeader) {
w.browser = true
}
return nil
Expand All @@ -141,7 +141,7 @@ func (w *ledgerDriver) Close() error {
// Heartbeat implements usbwallet.driver, performing a sanity check against the
// Ledger to see if it's still online.
func (w *ledgerDriver) Heartbeat() error {
if _, err := w.ledgerVersion(); err != nil && err != errLedgerInvalidVersionReply {
if _, err := w.ledgerVersion(); err != nil && !errors.Is(err, errLedgerInvalidVersionReply) {
w.failure = err
return err
}
Expand Down
7 changes: 4 additions & 3 deletions beacon/light/committee_chain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package light

import (
"crypto/rand"
"errors"
"testing"
"time"

Expand Down Expand Up @@ -259,13 +260,13 @@ func (c *committeeChainTest) setClockPeriod(period float64) {
}

func (c *committeeChainTest) addFixedCommitteeRoot(tc *testCommitteeChain, period uint64, expErr error) {
if err := c.chain.addFixedCommitteeRoot(period, tc.periods[period].committee.Root()); err != expErr {
if err := c.chain.addFixedCommitteeRoot(period, tc.periods[period].committee.Root()); !errors.Is(err, expErr) {
c.t.Errorf("Incorrect error output from addFixedCommitteeRoot at period %d (expected %v, got %v)", period, expErr, err)
}
}

func (c *committeeChainTest) addCommittee(tc *testCommitteeChain, period uint64, expErr error) {
if err := c.chain.addCommittee(period, tc.periods[period].committee); err != expErr {
if err := c.chain.addCommittee(period, tc.periods[period].committee); !errors.Is(err, expErr) {
c.t.Errorf("Incorrect error output from addCommittee at period %d (expected %v, got %v)", period, expErr, err)
}
}
Expand All @@ -275,7 +276,7 @@ func (c *committeeChainTest) insertUpdate(tc *testCommitteeChain, period uint64,
if addCommittee {
committee = tc.periods[period+1].committee
}
if err := c.chain.InsertUpdate(tc.periods[period].update, committee); err != expErr {
if err := c.chain.InsertUpdate(tc.periods[period].update, committee); !errors.Is(err, expErr) {
c.t.Errorf("Incorrect error output from InsertUpdate at period %d (expected %v, got %v)", period, expErr, err)
}
}
Expand Down
5 changes: 3 additions & 2 deletions beacon/light/sync/update_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package sync

import (
"errors"
"sort"

"github.com/ethereum/go-ethereum/beacon/light"
Expand Down Expand Up @@ -380,12 +381,12 @@ func (s *ForwardUpdateSync) Process(requester request.Requester, events []reques
func (s *ForwardUpdateSync) processResponse(requester request.Requester, u updateResponse) (success bool) {
for i, update := range u.response.Updates {
if err := s.chain.InsertUpdate(update, u.response.Committees[i]); err != nil {
if err == light.ErrInvalidPeriod {
if errors.Is(err, light.ErrInvalidPeriod) {
// there is a gap in the update periods; stop processing without
// failing and try again next time
return
}
if err == light.ErrInvalidUpdate || err == light.ErrWrongCommitteeRoot || err == light.ErrCannotReorg {
if errors.Is(err, light.ErrInvalidUpdate) || errors.Is(err, light.ErrWrongCommitteeRoot) || errors.Is(err, light.ErrCannotReorg) {
requester.Fail(u.sid.Server, "invalid update received")
} else {
log.Error("Unexpected InsertUpdate error", "error", err)
Expand Down
4 changes: 2 additions & 2 deletions cmd/clef/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -923,13 +923,13 @@ func testExternalUI(api *core.SignerAPI) {
}
}
expectApprove := func(testcase string, err error) {
if err == nil || err == accounts.ErrUnknownAccount {
if err == nil || errors.Is(err, accounts.ErrUnknownAccount) {
return
}
addErr(fmt.Sprintf("%v: expected no error, got %v", testcase, err.Error()))
}
expectDeny := func(testcase string, err error) {
if err == nil || err != core.ErrRequestDenied {
if err == nil || !errors.Is(err, core.ErrRequestDenied) {
addErr(fmt.Sprintf("%v: expected ErrRequestDenied, got %v", testcase, err))
}
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/devp2p/internal/ethtest/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ func blocksFromFile(chainfile string, gblock *types.Block) ([]*types.Block, erro
blocks[0] = gblock
for i := 0; ; i++ {
var b types.Block
if err := stream.Decode(&b); err == io.EOF {
if err := stream.Decode(&b); errors.Is(err, io.EOF) {
break
} else if err != nil {
return nil, fmt.Errorf("at block index %d: %v", i, err)
Expand Down
3 changes: 2 additions & 1 deletion cmd/devp2p/internal/v5test/discv5tests.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package v5test

import (
"bytes"
"errors"
"net"
"slices"
"sync"
Expand Down Expand Up @@ -96,7 +97,7 @@ func (s *Suite) TestPingLargeRequestID(t *utesting.T) {
case *v5wire.Pong:
t.Errorf("PONG response with unknown request ID %x", resp.ReqID)
case *readError:
if resp.err == v5wire.ErrInvalidReqID {
if errors.Is(resp.err, v5wire.ErrInvalidReqID) {
t.Error("response with oversized request ID")
} else if !netutil.IsTimeout(resp.err) {
t.Error(resp)
Expand Down
3 changes: 2 additions & 1 deletion cmd/evm/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
Expand Down Expand Up @@ -166,7 +167,7 @@ func timedExec(bench bool, execFunc func() ([]byte, uint64, error)) ([]byte, exe
if haveGasUsed != gasUsed {
panic(fmt.Sprintf("gas differs, have %v want %v", haveGasUsed, gasUsed))
}
if haveErr != err {
if !errors.Is(haveErr, err) {
panic(fmt.Sprintf("err differs, have %v want %v", haveErr, err))
}
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/geth/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,8 @@ func loadConfig(file string, cfg *gethConfig) error {

err = tomlSettings.NewDecoder(bufio.NewReader(f)).Decode(cfg)
// Add file name to errors that have a line number.
if _, ok := err.(*toml.LineError); ok {
lineErr := new(toml.LineError)
if ok := errors.As(err, &lineErr); ok {
err = errors.New(file + ", " + err.Error())
}
return err
Expand Down
5 changes: 3 additions & 2 deletions cmd/rlpdump/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"bytes"
"container/list"
"encoding/hex"
"errors"
"flag"
"fmt"
"io"
Expand Down Expand Up @@ -106,7 +107,7 @@ func rlpToText(in *inStream, out io.Writer) error {
stream := rlp.NewStream(in, 0)
for {
if err := dump(in, stream, 0, out); err != nil {
if err != io.EOF {
if !errors.Is(err, io.EOF) {
return err
}
break
Expand Down Expand Up @@ -149,7 +150,7 @@ func dump(in *inStream, s *rlp.Stream, depth int, out io.Writer) error {
if i > 0 {
fmt.Fprint(out, ",\n")
}
if err := dump(in, s, depth+1, out); err == rlp.EOL {
if err := dump(in, s, depth+1, out); errors.Is(err, rlp.EOL) {
break
} else if err != nil {
return err
Expand Down
6 changes: 3 additions & 3 deletions cmd/utils/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ func ImportChain(chain *core.BlockChain, fn string) error {
i := 0
for ; i < importBatchSize; i++ {
var b types.Block
if err := stream.Decode(&b); err == io.EOF {
if err := stream.Decode(&b); errors.Is(err, io.EOF) {
break
} else if err != nil {
return fmt.Errorf("at block %d: %v", n, err)
Expand Down Expand Up @@ -515,7 +515,7 @@ func ImportPreimages(db ethdb.Database, fn string) error {
var blob []byte

if err := stream.Decode(&blob); err != nil {
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
return err
Expand Down Expand Up @@ -725,7 +725,7 @@ func ImportLDBData(db ethdb.Database, f string, startIndex int64, interrupt chan
key, val []byte
)
if err := stream.Decode(&op); err != nil {
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
return err
Expand Down
5 changes: 3 additions & 2 deletions common/bitutil/compress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package bitutil

import (
"bytes"
"errors"
"fmt"
"math/rand"
"testing"
Expand Down Expand Up @@ -107,7 +108,7 @@ func TestDecodingCycle(t *testing.T) {
data := hexutil.MustDecode(tt.input)

orig, err := bitsetDecodeBytes(data, tt.size)
if err != tt.fail {
if !errors.Is(err, tt.fail) {
t.Errorf("test %d: failure mismatch: have %v, want %v", i, err, tt.fail)
}
if err != nil {
Expand Down Expand Up @@ -143,7 +144,7 @@ func TestCompression(t *testing.T) {
t.Errorf("decoding mismatch for dense data: have %x, want %x, error %v", data, in, err)
}
// Check that decompressing a longer input than the target fails
if _, err := DecompressBytes([]byte{0xc0, 0x01, 0x01}, 2); err != errExceededTarget {
if _, err := DecompressBytes([]byte{0xc0, 0x01, 0x01}, 2); !errors.Is(err, errExceededTarget) {
t.Errorf("decoding error mismatch for long data: have %v, want %v", err, errExceededTarget)
}
}
Expand Down
16 changes: 10 additions & 6 deletions common/hexutil/hexutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ package hexutil

import (
"encoding/hex"
"errors"
"fmt"
"math/big"
"strconv"
Expand Down Expand Up @@ -223,18 +224,21 @@ func decodeNibble(in byte) uint64 {
}

func mapError(err error) error {
if err, ok := err.(*strconv.NumError); ok {
switch err.Err {
case strconv.ErrRange:
numErr := new(strconv.NumError)
if ok := errors.As(err, &numErr); ok {
switch {
case errors.Is(numErr.Err, strconv.ErrRange):
return ErrUint64Range
case strconv.ErrSyntax:
case errors.Is(numErr.Err, strconv.ErrSyntax):
return ErrSyntax
}
}
if _, ok := err.(hex.InvalidByteError); ok {

var invalidByteErr hex.InvalidByteError
if ok := errors.As(err, &invalidByteErr); ok {
return ErrSyntax
}
if err == hex.ErrLength {
if errors.Is(err, hex.ErrLength) {
return ErrOddLength
}
return err
Expand Down
Loading

0 comments on commit a27f7c2

Please sign in to comment.