From 0418c83816b8c4bfcac3893f68e99811f5966229 Mon Sep 17 00:00:00 2001 From: amass Date: Thu, 17 Jul 2025 20:07:50 +0300 Subject: [PATCH] bump golanglint-ci. --- .github/workflows/go.yml | 2 +- .golangci.yml | 16 +++++---- cmd/dcrtime/dcrtime.go | 44 +++++++++++------------ cmd/dcrtime_checker/dcrtime_checker.go | 6 ++-- dcrtimed/backend/filesystem/filesystem.go | 29 +++++++++------ dcrtimed/backend/filesystem/fsck.go | 12 +++---- dcrtimed/config.go | 10 +++--- dcrtimed/dcrtimed.go | 15 ++++---- dcrtimed/dcrtimewallet/log.go | 28 +++++++++++++-- goclean.sh | 2 +- merkle/merkle.go | 6 ++-- 11 files changed, 103 insertions(+), 67 deletions(-) diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index 045eec7a..83dc1356 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -18,7 +18,7 @@ jobs: - name: Check out source uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 #v3.5.3 - name: Install Linters - run: "curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.53.3" + run: "curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v2.2.2" - name: Build run: go build ./... - name: Test diff --git a/.golangci.yml b/.golangci.yml index e2755ad0..61f8f44d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,15 +1,15 @@ +version: 2 + run: - deadline: 10m + timeout: 10m linters: - disable-all: true + default: none enable: + - staticcheck - asciicheck - bidichk - bodyclose - - gofmt - - goimports - - gosimple - govet - grouper - ineffassign @@ -20,6 +20,10 @@ linters: - rowserrcheck - sqlclosecheck - tparallel - - typecheck - unconvert - unused + +formatters: + enable: + - gofmt + - goimports diff --git a/cmd/dcrtime/dcrtime.go b/cmd/dcrtime/dcrtime.go index da007e1d..7fd5f71e 100644 --- a/cmd/dcrtime/dcrtime.go +++ b/cmd/dcrtime/dcrtime.go @@ -231,7 +231,7 @@ func downloadV1(questions []string) error { for _, digest := range v.CollectionInformation.Digests { d, ok := convertDigest(digest) if !ok { - return fmt.Errorf("Invalid digest "+ + return fmt.Errorf("invalid digest "+ "server response for "+ "timestamp: %v", v.ServerTimestamp) @@ -469,7 +469,7 @@ func verifyTimestamps(vt []v2.VerifyTimestamp) error { for _, digest := range t.CollectionInformation.Digests { d, ok := convertDigest(digest) if !ok { - return fmt.Errorf("Invalid digest "+ + return fmt.Errorf("invalid digest "+ "server response for "+ "timestamp: %v", t.ServerTimestamp) @@ -568,7 +568,7 @@ func uploadV1(digests []string, exists map[string]string) error { var tsReply v1.TimestampReply decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&tsReply); err != nil { - return fmt.Errorf("Could node decode TimestampReply: %v", err) + return fmt.Errorf("could not decode TimestampReply: %v", err) } // Print human readable results. @@ -638,7 +638,7 @@ func uploadV2Batch(digests []string, exists map[string]string) error { var tsReply v2.TimestampBatchReply decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&tsReply); err != nil { - return fmt.Errorf("Could node decode TimestampReply: %v", err) + return fmt.Errorf("could not decode TimestampReply: %v", err) } // Print human readable results. @@ -704,7 +704,7 @@ func uploadV2Single(digest string, exists map[string]string) error { var tsReply v2.TimestampReply decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&tsReply); err != nil { - return fmt.Errorf("Could node decode TimestampReply: %v", err) + return fmt.Errorf("could not decode TimestampReply: %v", err) } // Print human readable results. @@ -770,10 +770,10 @@ func showWalletBalanceV1() error { if response.StatusCode != http.StatusOK { e, err := getError(response.Body) if err != nil { - return fmt.Errorf("Retrieve wallet balance failed: %v", + return fmt.Errorf("retrieve wallet balance failed: %v", response.Status) } - return fmt.Errorf("Retrieve wallet balance failed - %v: %v", + return fmt.Errorf("retrieve wallet balance failed - %v: %v", response.Status, e) } @@ -781,7 +781,7 @@ func showWalletBalanceV1() error { var balance v1.WalletBalanceReply jsonDecoder := json.NewDecoder(response.Body) if err := jsonDecoder.Decode(&balance); err != nil { - return fmt.Errorf("Could not decode WalletBalanceReply: %v", err) + return fmt.Errorf("could not decode WalletBalanceReply: %v", err) } if *verbose { @@ -832,10 +832,10 @@ func showWalletBalanceV2() error { if response.StatusCode != http.StatusOK { e, err := getError(response.Body) if err != nil { - return fmt.Errorf("Retrieve wallet balance failed: %v", + return fmt.Errorf("retrieve wallet balance failed: %v", response.Status) } - return fmt.Errorf("Retrieve wallet balance failed - %v: %v", + return fmt.Errorf("retrieve wallet balance failed - %v: %v", response.Status, e) } @@ -843,7 +843,7 @@ func showWalletBalanceV2() error { var balance v2.WalletBalanceReply jsonDecoder := json.NewDecoder(response.Body) if err := jsonDecoder.Decode(&balance); err != nil { - return fmt.Errorf("Could not decode WalletBalanceReply: %v", err) + return fmt.Errorf("could not decode WalletBalanceReply: %v", err) } if *verbose { @@ -891,10 +891,10 @@ func lastAnchorV1() error { if response.StatusCode != http.StatusOK { e, err := getError(response.Body) if err != nil { - return fmt.Errorf("Retrieve last anchor info failed: %v", + return fmt.Errorf("retrieve last anchor info failed: %v", response.Status) } - return fmt.Errorf("Retrieve last anchor info failed - %v: %v", + return fmt.Errorf("retrieve last anchor info failed - %v: %v", response.Status, e) } @@ -902,7 +902,7 @@ func lastAnchorV1() error { var anchor v1.LastAnchorReply jsonDecoder := json.NewDecoder(response.Body) if err := jsonDecoder.Decode(&anchor); err != nil { - return fmt.Errorf("Could not decode LastAnchorReply: %v", err) + return fmt.Errorf("could not decode LastAnchorReply: %v", err) } fmt.Printf( @@ -946,10 +946,10 @@ func lastAnchorV2() error { if response.StatusCode != http.StatusOK { e, err := getError(response.Body) if err != nil { - return fmt.Errorf("Retrieve last anchor info failed: %v", + return fmt.Errorf("retrieve last anchor info failed: %v", response.Status) } - return fmt.Errorf("Retrieve last anchor info failed - %v: %v", + return fmt.Errorf("retrieve last anchor info failed - %v: %v", response.Status, e) } @@ -957,7 +957,7 @@ func lastAnchorV2() error { var anchor v2.LastAnchorReply jsonDecoder := json.NewDecoder(response.Body) if err := jsonDecoder.Decode(&anchor); err != nil { - return fmt.Errorf("Could not decode LastAnchorReply: %v", err) + return fmt.Errorf("could not decode LastAnchorReply: %v", err) } fmt.Printf( @@ -1018,10 +1018,10 @@ func lastDigestsV2(n int32) error { if r.StatusCode != http.StatusOK { e, err := getError(r.Body) if err != nil { - return fmt.Errorf("Retrieve last %d digests info failed: %v", n, + return fmt.Errorf("retrieve last %d digests info failed: %v", n, r.Status) } - return fmt.Errorf("Retrieve last %d digests info failed - %v: %v", + return fmt.Errorf("retrieve last %d digests info failed - %v: %v", n, r.Status, e) } @@ -1029,7 +1029,7 @@ func lastDigestsV2(n int32) error { var ldr v2.LastDigestsReply jsonDecoder := json.NewDecoder(r.Body) if err := jsonDecoder.Decode(&ldr); err != nil { - return fmt.Errorf("Could not decode LastDigestsReply: %v", err) + return fmt.Errorf("could not decode LastDigestsReply: %v", err) } fmt.Printf( @@ -1074,7 +1074,7 @@ func loadCredentialsIfRequired() error { // Token not provided via command line. Try to load via config file. config, err := loadConfig() if err != nil { - return fmt.Errorf("Attempt to load api token "+ + return fmt.Errorf("attempt to load api token "+ "from configuration file failed: %v", err) } @@ -1134,7 +1134,7 @@ func _main() error { lastAnchorInfo = lastAnchorV2 lastDigestsInfo = lastDigestsV2 default: - return fmt.Errorf("Invalid API version %v", *apiVersion) + return fmt.Errorf("invalid API version %v", *apiVersion) } if *host == "" { diff --git a/cmd/dcrtime_checker/dcrtime_checker.go b/cmd/dcrtime_checker/dcrtime_checker.go index fce0ac78..10440990 100644 --- a/cmd/dcrtime_checker/dcrtime_checker.go +++ b/cmd/dcrtime_checker/dcrtime_checker.go @@ -29,7 +29,7 @@ func verifyV2(digest string, fProof *os.File) error { var vr v2.VerifyBatchReply decoder := json.NewDecoder(fProof) if err := decoder.Decode(&vr); err != nil { - return fmt.Errorf("Could node decode VerifyBatchReply: %v", err) + return fmt.Errorf("could not decode VerifyBatchReply: %v", err) } // Ensure file digest exists in the proof and that the saved answer was @@ -97,7 +97,7 @@ func verifyV1(digest string, fProof *os.File) error { var vr v1.VerifyReply decoder := json.NewDecoder(fProof) if err := decoder.Decode(&vr); err != nil { - return fmt.Errorf("Could node decode VerifyReply: %v", err) + return fmt.Errorf("could not decode VerifyReply: %v", err) } // Ensure file digest exists in the proof and that the saved answer was @@ -178,7 +178,7 @@ func _main() error { case v2.APIVersion: verify = verifyV2 default: - return fmt.Errorf("Invalid API version %v", *apiVersion) + return fmt.Errorf("invalid API version %v", *apiVersion) } // require -f diff --git a/dcrtimed/backend/filesystem/filesystem.go b/dcrtimed/backend/filesystem/filesystem.go index 7c3e587f..e3c4226d 100644 --- a/dcrtimed/backend/filesystem/filesystem.go +++ b/dcrtimed/backend/filesystem/filesystem.go @@ -463,14 +463,17 @@ func (fs *FileSystem) getTimestamp(timestamp int64) (backend.TimestampResult, er if fr.ChainTimestamp == 0 && !fs.testing { lfr, err := fs.lazyFlush(timestamp, fr) if err != nil { - if err == errNotEnoughConfirmation { + switch { + case errors.Is(err, errNotEnoughConfirmation): gtme.Confirmations = &lfr.Confirmations gtme.MinConfirmations = fs.confirmations - } else if err == errInvalidConfirmations { + + case errors.Is(err, errInvalidConfirmations): log.Errorf("%v: Confirmations = -1", fr.Tx.String()) return gtme, err - } else { + + default: return gtme, err } } @@ -549,23 +552,29 @@ func (fs *FileSystem) getDigest(now time.Time, current *leveldb.DB, digest [sha2 gdme.Timestamp = fr.ServerTimestamp gdme.FlushTimestamp = fr.FlushTimestamp + switch { // Override error code during testing - if fs.testing { + case fs.testing: gdme.ErrorCode = foundGlobal - } else if gdme.AnchoredTimestamp == 0 { + + case gdme.AnchoredTimestamp == 0: lfr, err := fs.lazyFlush(dbts, fr) if err != nil { - if err == errNotEnoughConfirmation { + switch { + case errors.Is(err, errNotEnoughConfirmation): gdme.Confirmations = &lfr.Confirmations gdme.MinConfirmations = fs.confirmations - } else if err == errInvalidConfirmations { + + case errors.Is(err, errInvalidConfirmations): log.Errorf("%v: Confirmations = -1", fr.Tx.String()) return gdme, err - } else { + + default: return gdme, err } } + gdme.AnchoredTimestamp = fr.ChainTimestamp } @@ -755,7 +764,7 @@ func (fs *FileSystem) GetTimestamps(timestamps []int64) ([]backend.TimestampResu // Get the last n digests in the added to the Backend func (fs *FileSystem) LastDigests(n int32) ([]backend.GetResult, error) { if n > fs.maxDigests { - return nil, fmt.Errorf("Invalid number %d of digests requested. Max is: %d", n, fs.maxDigests) + return nil, fmt.Errorf("invalid number %d of digests requested. Max is: %d", n, fs.maxDigests) } results := make([]backend.GetResult, 0) @@ -776,7 +785,7 @@ func (fs *FileSystem) LastDigests(n int32) ([]backend.GetResult, error) { break } if !files[i].IsDir() { - return nil, fmt.Errorf("Unexpected file %v", + return nil, fmt.Errorf("unexpected file %v", filepath.Join(fs.root, files[i].Name())) } diff --git a/dcrtimed/backend/filesystem/fsck.go b/dcrtimed/backend/filesystem/fsck.go index dc609e61..3ead9f36 100644 --- a/dcrtimed/backend/filesystem/fsck.go +++ b/dcrtimed/backend/filesystem/fsck.go @@ -9,6 +9,7 @@ import ( "encoding/binary" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -316,7 +317,7 @@ func (fs *FileSystem) fsckTimestamp(options *backend.FsckOptions, ts int64, empt gdbts, err := fs.db.Get(key, nil) if err != nil { - if err == leveldb.ErrNotFound { + if errors.Is(err, leveldb.ErrNotFound) { continue } return fmt.Errorf(" *** ERROR found in db: %v %v", @@ -376,7 +377,7 @@ func (fs *FileSystem) fsckTimestamps(options *backend.FsckOptions, empties map[i for _, fi := range files { if !fi.IsDir() { - return fmt.Errorf("Unexpected file %v", + return fmt.Errorf("unexpected file %v", filepath.Join(fs.root, fi.Name())) } if fi.Name() == globalDBDir { @@ -453,9 +454,8 @@ func (fs *FileSystem) fsckGlobal(options *backend.FsckOptions, empties map[int64 // At this point we treat this as fatal because there // is no need to write code for theoretical issues that // should not have happned. - return fmt.Errorf(" *** ERROR hash not found in "+ - "timestamp : %v %v\n", filepath.Join(fs.root, - ts2dirname(value)), key) + return fmt.Errorf("hash not found in timestamp : %v %v", filepath.Join( + fs.root, ts2dirname(value)), key) } // Check to see if this timestamp exists in the empties map. @@ -618,7 +618,7 @@ func (fs *FileSystem) fsckDups(options *backend.FsckOptions) error { digests := make(map[string]int64) for _, fi := range files { if !fi.IsDir() { - return fmt.Errorf("Unexpected file %v", + return fmt.Errorf("unexpected file %v", filepath.Join(fs.root, fi.Name())) } if fi.Name() == globalDBDir { diff --git a/dcrtimed/config.go b/dcrtimed/config.go index 8f2d08b2..6d3facc9 100644 --- a/dcrtimed/config.go +++ b/dcrtimed/config.go @@ -136,7 +136,7 @@ func parseAndSetDebugLevels(debugLevel string) error { if !strings.Contains(debugLevel, ",") && !strings.Contains(debugLevel, "=") { // Validate debug log level. if !validLogLevel(debugLevel) { - str := "The specified debug level [%v] is invalid" + str := "the specified debug level [%v] is invalid" return fmt.Errorf(str, debugLevel) } @@ -150,7 +150,7 @@ func parseAndSetDebugLevels(debugLevel string) error { // issues and update the log levels accordingly. for _, logLevelPair := range strings.Split(debugLevel, ",") { if !strings.Contains(logLevelPair, "=") { - str := "The specified debug level contains an invalid " + + str := "the specified debug level contains an invalid " + "subsystem/level pair [%v]" return fmt.Errorf(str, logLevelPair) } @@ -161,14 +161,14 @@ func parseAndSetDebugLevels(debugLevel string) error { // Validate subsystem. if _, exists := subsystemLoggers[subsysID]; !exists { - str := "The specified subsystem [%v] is invalid -- " + + str := "the specified subsystem [%v] is invalid -- " + "supported subsytems %v" return fmt.Errorf(str, subsysID, supportedSubsystems()) } // Validate log level. if !validLogLevel(logLevel) { - str := "The specified debug level [%v] is invalid" + str := "the specified debug level [%v] is invalid" return fmt.Errorf(str, logLevel) } @@ -239,7 +239,7 @@ func parseAndValidateAPIVersions(vs string) ([]uint, error) { // Validate out of bounds config if len(versions) == 0 || len(versions) > 2 { - return nil, fmt.Errorf("Invalid API versions config," + + return nil, fmt.Errorf("invalid API versions config," + "must have at least one and at most two") } diff --git a/dcrtimed/dcrtimed.go b/dcrtimed/dcrtimed.go index a386e3f5..9f79d544 100644 --- a/dcrtimed/dcrtimed.go +++ b/dcrtimed/dcrtimed.go @@ -12,6 +12,7 @@ import ( "crypto/x509" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -434,7 +435,7 @@ func (d *DcrtimeStore) timestampV1(w http.ResponseWriter, r *http.Request) { errorCode, err) // Tell client there is a transient error. - if err == backend.ErrTryAgainLater { + if errors.Is(err, backend.ErrTryAgainLater) { util.RespondWithError(w, http.StatusServiceUnavailable, "Server busy, please try again later.") return @@ -748,7 +749,7 @@ func (d *DcrtimeStore) timestampBatchV2(w http.ResponseWriter, r *http.Request) errorCode, err) // Tell client there is a transient error. - if err == backend.ErrTryAgainLater { + if errors.Is(err, backend.ErrTryAgainLater) { util.RespondWithError(w, http.StatusServiceUnavailable, "Server busy, please try again later.") return @@ -987,7 +988,7 @@ func (d *DcrtimeStore) timestampV2(w http.ResponseWriter, r *http.Request) { errorCode, err) // Tell client there is a transient error. - if err == backend.ErrTryAgainLater { + if errors.Is(err, backend.ErrTryAgainLater) { util.RespondWithError(w, http.StatusServiceUnavailable, "Server busy, please try again later.") return @@ -1384,11 +1385,11 @@ func getError(r io.Reader) (string, error) { } m, ok := e.(map[string]interface{}) if !ok { - return "", fmt.Errorf("Could not decode response") + return "", fmt.Errorf("could not decode response") } rError, ok := m["error"] if !ok { - return "", fmt.Errorf("No error response") + return "", fmt.Errorf("no error response") } return fmt.Sprintf("%v", rError), nil } @@ -1424,7 +1425,7 @@ func _main() error { // initializes logging and configures it accordingly. loadedCfg, _, err := loadConfig() if err != nil { - return fmt.Errorf("Could not load configuration file: %v", err) + return fmt.Errorf("could not load configuration file: %v", err) } defer func() { if logRotator != nil { @@ -1440,7 +1441,7 @@ func _main() error { } log.Infof("Version : %v", version()) log.Infof("Mode : %v", mode) - log.Infof("Network : %v", activeNetParams.Params.Name) + log.Infof("Network : %v", activeNetParams.Name) log.Infof("Home dir: %v", loadedCfg.HomeDir) // Sets subsystem loggers diff --git a/dcrtimed/dcrtimewallet/log.go b/dcrtimed/dcrtimewallet/log.go index a19b45d9..4f5c4c26 100644 --- a/dcrtimed/dcrtimewallet/log.go +++ b/dcrtimed/dcrtimewallet/log.go @@ -27,9 +27,9 @@ import ( // requests it. var log = slog.Disabled -// UseLogger sets the logger to use for the gRPC server. +// UseGrpcLogger sets the logger to use for the gRPC server. func UseGrpcLogger(l slog.Logger) { - grpclog.SetLogger(logger{l}) + grpclog.SetLoggerV2(logger{l}) log = l } @@ -64,6 +64,30 @@ func stripGrpcPrefixArgs(args ...interface{}) []interface{} { return args } +func (l logger) V(level int) bool { + return uint32(l.Level()) == uint32(level) +} + +func (l logger) Errorln(args ...interface{}) { + l.Error(stripGrpcPrefixArgs(args)...) +} + +func (l logger) Infoln(args ...interface{}) { + l.Info(stripGrpcPrefixArgs(args)...) +} + +func (l logger) Warning(args ...interface{}) { + l.Warn(stripGrpcPrefixArgs(args)...) +} + +func (l logger) Warningf(format string, args ...interface{}) { + l.Warnf(stripGrpcPrefix(format), args...) +} + +func (l logger) Warningln(args ...interface{}) { + l.Warn(stripGrpcPrefixArgs(args)...) +} + func (l logger) Fatal(args ...interface{}) { l.Critical(stripGrpcPrefixArgs(args)...) os.Exit(1) diff --git a/goclean.sh b/goclean.sh index 31d09bea..3e2d6cc2 100755 --- a/goclean.sh +++ b/goclean.sh @@ -20,7 +20,7 @@ go mod download go mod tidy UPDATED_MOD_STATUS=$(git status --porcelain go.mod go.sum) if [ "$UPDATED_MOD_STATUS" != "$MOD_STATUS" ]; then - echo "Running `go mod tidy` modified go.mod and/or go.sum" + echo "Running $(go mod tidy) modified go.mod and/or go.sum" exit 1 fi diff --git a/merkle/merkle.go b/merkle/merkle.go index 0da70b0f..4634a060 100644 --- a/merkle/merkle.go +++ b/merkle/merkle.go @@ -15,9 +15,7 @@ import ( "sort" ) -var ( - ErrEmpty = errors.New("empty merkle branch") -) +var ErrEmpty = errors.New("empty merkle branch") type sortableSlice []*[sha256.Size]byte @@ -328,7 +326,7 @@ func VerifyAuthPath(mb *Branch) (*[sha256.Size]byte, error) { } // Validate that we consumed all bits and bobs. - flagByte := int(math.Floor(float64(m.bitsUsed / 8))) + flagByte := int(m.bitsUsed / 8) if flagByte+1 < len(mb.Flags) && mb.Flags[flagByte] > 1<