golangci: enable errorlint and fix everything it found

This commit is contained in:
Roman Khimov 2022-09-02 14:29:47 +03:00
parent c703ac6805
commit 4f3ffe7290
17 changed files with 34 additions and 28 deletions

View file

@ -44,6 +44,7 @@ linters:
# - exhaustive # - exhaustive
- bodyclose - bodyclose
- contextcheck - contextcheck
- errorlint
- gofmt - gofmt
- whitespace - whitespace
- goimports - goimports

View file

@ -1,6 +1,7 @@
package main package main
import ( import (
"errors"
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
@ -110,7 +111,7 @@ func TestServerStart(t *testing.T) {
var line string var line string
require.Eventually(t, func() bool { require.Eventually(t, func() bool {
line, err = e.Out.ReadString('\n') line, err = e.Out.ReadString('\n')
if err != nil && err != io.EOF { if err != nil && !errors.Is(err, io.EOF) {
t.Fatalf("unexpected error while reading CLI output: %s", err) t.Fatalf("unexpected error while reading CLI output: %s", err)
} }
return err == nil return err == nil

View file

@ -947,7 +947,7 @@ func readWallet(ctx *cli.Context) (*wallet.Wallet, *string, error) {
if path == "-" { if path == "-" {
w := &wallet.Wallet{} w := &wallet.Wallet{}
if err := json.NewDecoder(os.Stdin).Decode(w); err != nil { if err := json.NewDecoder(os.Stdin).Decode(w); err != nil {
return nil, nil, fmt.Errorf("js %s", err) return nil, nil, fmt.Errorf("js %w", err)
} }
return w, nil, nil return w, nil, nil
} }

View file

@ -1702,7 +1702,7 @@ func (bc *Blockchain) HasTransaction(hash util.Uint256) bool {
if bc.memPool.ContainsKey(hash) { if bc.memPool.ContainsKey(hash) {
return true return true
} }
return bc.dao.HasTransaction(hash) == dao.ErrAlreadyExists return errors.Is(bc.dao.HasTransaction(hash), dao.ErrAlreadyExists)
} }
// HasBlock returns true if the blockchain contains the given // HasBlock returns true if the blockchain contains the given
@ -1761,7 +1761,7 @@ func (bc *Blockchain) HeaderHeight() uint32 {
// GetContractState returns contract by its script hash. // GetContractState returns contract by its script hash.
func (bc *Blockchain) GetContractState(hash util.Uint160) *state.Contract { func (bc *Blockchain) GetContractState(hash util.Uint160) *state.Contract {
contract, err := bc.contracts.Management.GetContract(bc.dao, hash) contract, err := bc.contracts.Management.GetContract(bc.dao, hash)
if contract == nil && err != storage.ErrKeyNotFound { if contract == nil && !errors.Is(err, storage.ErrKeyNotFound) {
bc.log.Warn("failed to get contract state", zap.Error(err)) bc.log.Warn("failed to get contract state", zap.Error(err))
} }
return contract return contract

View file

@ -176,7 +176,7 @@ func (dao *Simple) GetTokenTransferInfo(acc util.Uint160) (*state.TokenTransferI
key := dao.makeTTIKey(acc) key := dao.makeTTIKey(acc)
bs := state.NewTokenTransferInfo() bs := state.NewTokenTransferInfo()
err := dao.GetAndDecode(bs, key) err := dao.GetAndDecode(bs, key)
if err != nil && err != storage.ErrKeyNotFound { if err != nil && !errors.Is(err, storage.ErrKeyNotFound) {
return nil, err return nil, err
} }
return bs, nil return bs, nil
@ -257,7 +257,7 @@ func (dao *Simple) GetTokenTransferLog(acc util.Uint160, newestTimestamp uint64,
key := dao.getTokenTransferLogKey(acc, newestTimestamp, index, isNEP11) key := dao.getTokenTransferLogKey(acc, newestTimestamp, index, isNEP11)
value, err := dao.Store.Get(key) value, err := dao.Store.Get(key)
if err != nil { if err != nil {
if err == storage.ErrKeyNotFound { if errors.Is(err, storage.ErrKeyNotFound) {
return new(state.TokenTransferLog), nil return new(state.TokenTransferLog), nil
} }
return nil, err return nil, err
@ -306,7 +306,7 @@ func (dao *Simple) GetAppExecResults(hash util.Uint256, trig trigger.Type) ([]st
aer := new(state.AppExecResult) aer := new(state.AppExecResult)
aer.DecodeBinary(r) aer.DecodeBinary(r)
if r.Err != nil { if r.Err != nil {
if r.Err == iocore.EOF { if errors.Is(r.Err, iocore.EOF) {
break break
} }
return nil, r.Err return nil, r.Err

View file

@ -173,7 +173,7 @@ func (m *Management) getContract(ic *interop.Context, args []stackitem.Item) sta
hash := toHash160(args[0]) hash := toHash160(args[0])
ctr, err := m.GetContract(ic.DAO, hash) ctr, err := m.GetContract(ic.DAO, hash)
if err != nil { if err != nil {
if err == storage.ErrKeyNotFound { if errors.Is(err, storage.ErrKeyNotFound) {
return stackitem.Null{} return stackitem.Null{}
} }
panic(err) panic(err)

View file

@ -469,7 +469,7 @@ func (n *Notary) GetDepositFor(dao *dao.Simple, acc util.Uint160) *state.Deposit
if err == nil { if err == nil {
return deposit return deposit
} }
if err == storage.ErrKeyNotFound { if errors.Is(err, storage.ErrKeyNotFound) {
return nil return nil
} }
panic(fmt.Errorf("failed to get deposit for %s from storage: %w", acc.StringBE(), err)) panic(fmt.Errorf("failed to get deposit for %s from storage: %w", acc.StringBE(), err))

View file

@ -1,6 +1,8 @@
package storage package storage
import ( import (
"errors"
"github.com/nspcc-dev/neo-go/pkg/core/storage/dbconfig" "github.com/nspcc-dev/neo-go/pkg/core/storage/dbconfig"
"github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/filter" "github.com/syndtr/goleveldb/leveldb/filter"
@ -35,7 +37,7 @@ func NewLevelDBStore(cfg dbconfig.LevelDBOptions) (*LevelDBStore, error) {
// Get implements the Store interface. // Get implements the Store interface.
func (s *LevelDBStore) Get(key []byte) ([]byte, error) { func (s *LevelDBStore) Get(key []byte) ([]byte, error) {
value, err := s.db.Get(key, nil) value, err := s.db.Get(key, nil)
if err == leveldb.ErrNotFound { if errors.Is(err, leveldb.ErrNotFound) {
err = ErrKeyNotFound err = ErrKeyNotFound
} }
return value, err return value, err

View file

@ -1,6 +1,7 @@
package neorpc package neorpc
import ( import (
"errors"
"fmt" "fmt"
) )
@ -125,9 +126,9 @@ func (e *Error) Error() string {
// Is denotes whether the error matches the target one. // Is denotes whether the error matches the target one.
func (e *Error) Is(target error) bool { func (e *Error) Is(target error) bool {
clTarget, ok := target.(*Error) var clTarget *Error
if !ok { if errors.As(target, &clTarget) {
return false
}
return e.Code == clTarget.Code return e.Code == clTarget.Code
}
return false
} }

View file

@ -176,7 +176,7 @@ func (m *Message) decodePayload() error {
} }
r := io.NewBinReaderFromBuf(buf) r := io.NewBinReaderFromBuf(buf)
p.DecodeBinary(r) p.DecodeBinary(r)
if r.Err == nil || r.Err == payload.ErrTooManyHeaders { if r.Err == nil || errors.Is(r.Err, payload.ErrTooManyHeaders) {
m.Payload = p m.Payload = p
} }

View file

@ -417,9 +417,9 @@ func (s *Server) run() {
zap.Error(drop.reason), zap.Error(drop.reason),
zap.Int("peerCount", s.PeerCount())) zap.Int("peerCount", s.PeerCount()))
addr := drop.peer.PeerAddr().String() addr := drop.peer.PeerAddr().String()
if drop.reason == errIdenticalID { if errors.Is(drop.reason, errIdenticalID) {
s.discovery.RegisterBadAddr(addr) s.discovery.RegisterBadAddr(addr)
} else if drop.reason == errAlreadyConnected { } else if errors.Is(drop.reason, errAlreadyConnected) {
// There is a race condition when peer can be disconnected twice for the this reason // There is a race condition when peer can be disconnected twice for the this reason
// which can lead to no connections to peer at all. Here we check for such a possibility. // which can lead to no connections to peer at all. Here we check for such a possibility.
stillConnected := false stillConnected := false
@ -1380,15 +1380,15 @@ func (s *Server) iteratePeersWithSendMsg(msg *Message, send func(Peer, bool, []b
continue continue
} }
err := send(peer, blocking, pkt) err := send(peer, blocking, pkt)
switch err { if err == nil {
case nil:
if msg.Command == CMDGetAddr { if msg.Command == CMDGetAddr {
peer.AddGetAddrSent() peer.AddGetAddrSent()
} }
sentN++ sentN++
case errBusy: // Can be retried. } else if errors.Is(err, errBusy) {
// Can be retried.
continue continue
default: } else {
deadN++ deadN++
} }
finished[i] = true finished[i] = true

View file

@ -170,7 +170,7 @@ func (p *TCPPeer) handleConn() {
msg := &Message{StateRootInHeader: p.server.config.StateRootInHeader} msg := &Message{StateRootInHeader: p.server.config.StateRootInHeader}
err = msg.Decode(r) err = msg.Decode(r)
if err == payload.ErrTooManyHeaders { if errors.Is(err, payload.ErrTooManyHeaders) {
p.server.log.Warn("not all headers were processed") p.server.log.Warn("not all headers were processed")
r.Err = nil r.Err = nil
} else if err != nil { } else if err != nil {

View file

@ -2,6 +2,7 @@ package metrics
import ( import (
"context" "context"
"errors"
"net/http" "net/http"
"github.com/nspcc-dev/neo-go/pkg/config" "github.com/nspcc-dev/neo-go/pkg/config"
@ -21,7 +22,7 @@ func (ms *Service) Start() {
if ms.config.Enabled { if ms.config.Enabled {
ms.log.Info("service is running", zap.String("endpoint", ms.Addr)) ms.log.Info("service is running", zap.String("endpoint", ms.Addr))
err := ms.ListenAndServe() err := ms.ListenAndServe()
if err != nil && err != http.ErrServerClosed { if err != nil && !errors.Is(err, http.ErrServerClosed) {
ms.log.Warn("service couldn't start on configured port") ms.log.Warn("service couldn't start on configured port")
} }
} else { } else {

View file

@ -69,7 +69,7 @@ var ErrResponseTooLarge = errors.New("too big response")
func readResponse(rc gio.ReadCloser, limit int) ([]byte, error) { func readResponse(rc gio.ReadCloser, limit int) ([]byte, error) {
buf := make([]byte, limit+1) buf := make([]byte, limit+1)
n, err := gio.ReadFull(rc, buf) n, err := gio.ReadFull(rc, buf)
if err == gio.ErrUnexpectedEOF && n <= limit { if errors.Is(err, gio.ErrUnexpectedEOF) && n <= limit {
return buf[:n], nil return buf[:n], nil
} }
if err == nil || n > limit { if err == nil || n > limit {

View file

@ -340,7 +340,7 @@ func (s *Server) Start() {
} }
s.https.Addr = ln.Addr().String() s.https.Addr = ln.Addr().String()
err = s.https.ServeTLS(ln, cfg.CertFile, cfg.KeyFile) err = s.https.ServeTLS(ln, cfg.CertFile, cfg.KeyFile)
if err != http.ErrServerClosed { if !errors.Is(err, http.ErrServerClosed) {
s.log.Error("failed to start TLS RPC server", zap.Error(err)) s.log.Error("failed to start TLS RPC server", zap.Error(err))
s.errChan <- err s.errChan <- err
} }
@ -354,7 +354,7 @@ func (s *Server) Start() {
s.Addr = ln.Addr().String() // set Addr to the actual address s.Addr = ln.Addr().String() // set Addr to the actual address
go func() { go func() {
err = s.Serve(ln) err = s.Serve(ln)
if err != http.ErrServerClosed { if !errors.Is(err, http.ErrServerClosed) {
s.log.Error("failed to start RPC server", zap.Error(err)) s.log.Error("failed to start RPC server", zap.Error(err))
s.errChan <- err s.errChan <- err
} }

View file

@ -678,7 +678,7 @@ func (c *VMCLI) Run() error {
l := getReadlineInstanceFromContext(c.shell) l := getReadlineInstanceFromContext(c.shell)
for { for {
line, err := l.Readline() line, err := l.Readline()
if err == io.EOF || err == readline.ErrInterrupt { if errors.Is(err, io.EOF) || errors.Is(err, readline.ErrInterrupt) {
return nil // OK, stop execution. return nil // OK, stop execution.
} }
if err != nil { if err != nil {

View file

@ -169,7 +169,7 @@ func FromJSON(data []byte, maxCount int) (Item, error) {
d.UseNumber() d.UseNumber()
if item, err := d.decode(); err != nil { if item, err := d.decode(); err != nil {
return nil, err return nil, err
} else if _, err := d.Token(); err != gio.EOF { } else if _, err := d.Token(); !errors.Is(err, gio.EOF) {
return nil, fmt.Errorf("%w: unexpected items", ErrInvalidValue) return nil, fmt.Errorf("%w: unexpected items", ErrInvalidValue)
} else { } else {
return item, nil return item, nil