diff --git a/.golangci.yml b/.golangci.yml index 2f82a7fc..defb9dfa 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -9,11 +9,11 @@ run: # Exit code when at least one issue was found. # Default: 1 - issues-exit-code: 1 + # issues-exit-code: 1 # Include test files or not. # Default: true - tests: true + # tests: true # List of build tags, all linters use it. # Default: []. @@ -66,62 +66,406 @@ run: # output configuration options output: - # colored-line-number|line-number|json|tab|checkstyle, default is "colored-line-number" + # Format: colored-line-number|line-number|json|colored-tab|tab|checkstyle|code-climate|junit-xml|github-actions|teamcity + # + # Multiple can be specified by separating them by comma, output can be provided + # for each of them by separating format name and path by colon symbol. + # Output path can be either `stdout`, `stderr` or path to the file to write to. + # Example: "checkstyle:report.xml,json:stdout,colored-line-number" + # + # Default: colored-line-number format: colored-line-number - # print lines of code with issue, default is true + # Print lines of code with issue. + # Default: true print-issued-lines: true - # print linter name in the end of issue text, default is true + # Print linter name in the end of issue text. + # Default: true print-linter-name: true + # Make issues output unique by line. + # Default: true + # uniq-by-line: false + + # Add a prefix to the output file references. + # Default is no prefix. + # path-prefix: "" + + # Sort results by: filepath, line and column. + # sort-results: false + +linters: + # Disable all linters. + # Default: false + disable-all: true + + # Enable specific linter + # https://golangci-lint.run/usage/linters/#enabled-by-default + enable: + # - asasalint + # - asciicheck + # - bidichk + # - bodyclose + # - containedctx + # - contextcheck + # - cyclop + # - deadcode + # - decorder + - depguard + # - dogsled + # - dupl + # - dupword + # - durationcheck + # - errcheck + # - errchkjson + # - errname + # - errorlint + # - execinquery + # - exhaustive + # - exhaustivestruct + # - exhaustruct + # - exportloopref + # - forbidigo + # - forcetypeassert + # - funlen + - gci + # - ginkgolinter + # - gocheckcompilerdirectives + # - gochecknoglobals + # - gochecknoinits + # - gocognit + # - goconst + # - gocritic + # - gocyclo + - godot + # - godox + # - goerr113 + - gofmt + - gofumpt + # - goheader + # - goimports + # - golint + # - gomnd + # - gomoddirectives + # - gomodguard + # - goprintffuncname + # - gosec + - gosimple + # - gosmopolitan + - govet + # - grouper + # - ifshort + - importas + - ineffassign + # - interfacebloat + # - interfacer + # - ireturn + # - lll + # - loggercheck + # - maintidx + # - makezero + # - maligned + # - mirror + - misspell + # - musttag + - nakedret + # - nestif + # - nilerr + # - nilnil + # - nlreturn + # - noctx + # - nolintlint + # - nonamedreturns + # - nosnakecase + # - nosprintfhostport + # - paralleltest + # - prealloc + # - predeclared + # - promlinter + # - reassign + - revive + # - rowserrcheck + # - scopelint + # - sqlclosecheck + - staticcheck + # - structcheck + # - stylecheck + # - tagalign + # - tagliatelle + # - tenv + # - testableexamples + # - testpackage + # - thelper + # - tparallel + - typecheck + # - unconvert + # - unparam + - unused + # - usestdlibvars + # - varcheck + # - varnamelen + # - wastedassign + # - whitespace + # - wrapcheck + # - wsl + # - zerologlint + + # Enable all available linters. + # Default: false + enable-all: false + + # Disable specific linter + # https://golangci-lint.run/usage/linters/#disabled-by-default + # disable: + # - asasalint + # - asciicheck + # - bidichk + # - bodyclose + # - containedctx + # - contextcheck + # - cyclop + # - deadcode + # - decorder + # - depguard + # - dogsled + # - dupl + # - dupword + # - durationcheck + # - errcheck + # - errchkjson + # - errname + # - errorlint + # - execinquery + # - exhaustive + # - exhaustivestruct + # - exhaustruct + # - exportloopref + # - forbidigo + # - forcetypeassert + # - funlen + # - gci + # - ginkgolinter + # - gocheckcompilerdirectives + # - gochecknoglobals + # - gochecknoinits + # - gocognit + # - goconst + # - gocritic + # - gocyclo + # - godot + # - godox + # - goerr113 + # - gofmt + # - gofumpt + # - goheader + # - goimports + # - golint + # - gomnd + # - gomoddirectives + # - gomodguard + # - goprintffuncname + # - gosec + # - gosimple + # - gosmopolitan + # - govet + # - grouper + # - ifshort + # - importas + # - ineffassign + # - interfacebloat + # - interfacer + # - ireturn + # - lll + # - loggercheck + # - maintidx + # - makezero + # - maligned + # - mirror + # - misspell + # - musttag + # - nakedret + # - nestif + # - nilerr + # - nilnil + # - nlreturn + # - noctx + # - nolintlint + # - nonamedreturns + # - nosnakecase + # - nosprintfhostport + # - paralleltest + # - prealloc + # - predeclared + # - promlinter + # - reassign + # - revive + # - rowserrcheck + # - scopelint + # - sqlclosecheck + # - staticcheck + # - structcheck + # - stylecheck + # - tagalign + # - tagliatelle + # - tenv + # - testableexamples + # - testpackage + # - thelper + # - tparallel + # - typecheck + # - unconvert + # - unparam + # - unused + # - usestdlibvars + # - varcheck + # - varnamelen + # - wastedassign + # - whitespace + # - wrapcheck + # - wsl + # - zerologlint + + # Enable presets. + # https://golangci-lint.run/usage/linters + # presets: + # - bugs + # - comment + # - complexity + # - error + # - format + # - import + # - metalinter + # - module + # - performance + # - sql + # - style + # - test + # - unused + + # Run only fast linters from enabled linters set (first run won't be fast) + # Default: false + fast: false + # All available settings of specific linters. linters-settings: - staticcheck: - # SAxxxx checks in https://staticcheck.io/docs/configuration/options/#checks - # Default: ["*"] - checks: ["all"] + depguard: + # Rules to apply. + # + # Variables: + # - File Variables + # you can still use and exclamation mark ! in front of a variable to say not to use it. + # Example !$test will match any file that is not a go test file. + # + # `$all` - matches all go files + # `$test` - matches all go test files + # + # - Package Variables + # + # `$gostd` - matches all of go's standard library (Pulled from `GOROOT`) + # + # Default: Only allow $gostd in all files. + rules: + # Name of a rule. + main: + # List of file globs that will match this list of settings to compare against. + # Default: $all + # files: + # - "!**/*_a _file.go" + # List of allowed packages. + # allow: + # - $gostd + # - github.com/OpenPeeDeeP + # Packages that are not allowed where the value is a suggestion. + deny: + - pkg: "io/ioutil" + desc: Use os instead + - pkg: "github.com/pkg/errors" + desc: Should be replaced by standard lib errors package + - pkg: "golang.org/x/xerrors" + desc: Should be replaced by standard lib errors package + - pkg: "golang.org/x/net/context" + desc: Should be replaced by standard lib context package + - pkg: "golang.org/x/crypto/ed25519" + desc: Should be replaced by standard lib ed25519 package - errcheck: - # Report about not checking of errors in type assertions: `a := b.(MyStruct)`. - # Such cases aren't reported by default. - # Default: false - check-type-assertions: true + gci: + # Section configuration to compare against. + # Section names are case-insensitive and may contain parameters in (). + # The default order of sections is `standard > default > custom > blank > dot`, + # If `custom-order` is `true`, it follows the order of `sections` option. + # Default: ["standard", "default"] + sections: + - standard + - default + - prefix(github.com/spacemeshos/poet) - # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`. - # Such cases aren't reported by default. - # Default: false - check-blank: true + # Skip generated files. + # Default: true + # skip-generated: false - govet: - # Report about shadowed variables. + # Enable custom order of sections. + # If `true`, make the section order the same as the order of `sections`. # Default: false - check-shadowing: false - # Disable all analyzers. + # custom-order: true + + goconst: + # Minimal length of string constant. + # Default: 3 + # min-len: 3 + + # Minimum occurrences of constant string count to trigger issue. + # Default: 3 + # min-occurrences: 3 + + # Ignore test files. # Default: false - disable-all: false - # Enable analyzers by name (in addition to default). - # Run `go tool vet help` to see all analyzers. - # Default: [] - # enable: - # Enable all analyzers. + # ignore-tests: false + + # Look for existing constants matching the values. + # Default: true + # match-constant: true + + # Search also for duplicated numbers. # Default: false - enable-all: false - # Disable analyzers by name. - # Run `go tool vet help` to see all analyzers. + # numbers: false + + # Minimum value, only works with goconst.numbers + # Default: 3 + # min: 3 + + # Maximum value, only works with goconst.numbers + # Default: 3 + # max: 3 + + # Ignore when constant is not used as function argument. + # Default: true + ignore-calls: false + + godot: + # Comments to be checked: `declarations`, `toplevel`, or `all`. + # Default: declarations + # scope: declarations + + # List of regexps for excluding particular comment lines from check. # Default: [] - # disable: + exclude: + # Exclude todo and fixme comments. + - "^FIXME:" + - "^TODO:" - revive: - # Sets the default failure confidence. - # This means that linting errors with less than 0.8 confidence will be ignored. - # Default: 0.8 - confidence: 0.8 + # Check that each sentence ends with a period. + # Default: true + # period: true + + # Check that each sentence starts with a capital letter. + # Default: false + # capital: false gofmt: # Simplify code: gofmt with `-s` option. # Default: true - simplify: true + #simplify: true # Apply the rewrite rules to the source before reformatting. # https://pkg.go.dev/cmd/gofmt @@ -132,98 +476,54 @@ linters-settings: - pattern: "a[b:len(a)]" replacement: "a[b:]" - gocyclo: - # Minimal code complexity to report. - # Default: 30 (but we recommend 10-20) - min-complexity: 10 - - goconst: - # Minimal length of string constant. - # Default: 3 - min-len: 3 + gofumpt: + # Module path which contains the source code being formatted. + # Default: "" + # module-path: github.com/org/project - # Minimum occurrences of constant string count to trigger issue. - # Default: 3 - min-occurrences: 3 + # Choose whether to use the extra rules. + # Default: false + extra-rules: true - depguard: - # Kind of list is passed in. - # Allowed values: allowlist|denylist - # Default: denylist - list-type: denylist + gosimple: + # Sxxxx checks in https://staticcheck.io/docs/configuration/options/#checks + # Default: ["*"] + checks: ["all"] - # Check the list against standard lib. + govet: + # Report about shadowed variables. # Default: false - include-go-root: true - - # A list of packages for the list type specified. - # Can accept both string prefixes and string glob patterns. + check-shadowing: false + # Disable all analyzers. + # Default: false + disable-all: false + # Enable analyzers by name (in addition to default). + # Run `go tool vet help` to see all analyzers. # Default: [] - packages: - - "io/ioutil" - - "github.com/pkg/errors" - - "golang.org/x/xerrors" - - "golang.org/x/net/context" - - "golang.org/x/crypto/ed25519" - - misspell: - # Correct spellings using locale preferences for US or UK. - # Setting locale to US will correct the British spelling of 'colour' to 'color'. - # Default is to use a neutral variety of English. - locale: US - - lll: - # Max line length, lines longer will be reported. - # '\t' is counted as 1 character by default, and can be changed with the tab-width option. - # Default: 120. - line-length: 120 - # Tab width in spaces. - # Default: 1 - tab-width: 4 - - nakedret: - # Make an issue if func has more lines of code than this setting, and it has naked returns. - # Default: 30 - max-func-lines: 30 - - prealloc: - # IMPORTANT: we don't recommend using this linter before doing performance profiling. - # For most programs usage of prealloc will be a premature optimization. - - # Report pre-allocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them. - # Default: true - simple: true - # Report pre-allocation suggestions on range loops. - # Default: true - range-loops: true - # Report pre-allocation suggestions on for loops. + # enable: + # Enable all analyzers. # Default: false - for-loops: true - - gci: - # Section configuration to compare against. - # Section names are case-insensitive and may contain parameters in (). - # The default order of sections is `standard > default > custom > blank > dot`, - # If `custom-order` is `true`, it follows the order of `sections` option. - # Default: ["standard", "default"] - sections: - - standard - - default - - prefix(github.com/spacemeshos/poet) + enable-all: false + # Disable analyzers by name. + # Run `go tool vet help` to see all analyzers. + # Default: [] + # disable: importas: # Do not allow unaliased imports of aliased packages. # Default: false - no-unaliased: false + # no-unaliased: false + # Do not allow non-required aliases. # Default: false - no-extra-aliases: false + # no-extra-aliases: false + # List of aliases # Default: [] alias: - pkg: "github.com/chaos-mesh/chaos-mesh/api/v1alpha1" alias: chaos - - pkg: "github.com/hashicorp/golang-lru" + - pkg: "github.com/hashicorp/golang-lru/v2" alias: lru - pkg: "github.com/grpc-ecosystem/go-grpc-middleware" alias: grpcmw @@ -234,7 +534,7 @@ linters-settings: - pkg: "github.com/libp2p/go-libp2p-pubsub" alias: pubsub - pkg: "github.com/libp2p/go-libp2p-pubsub/pb" - alias: pb + alias: pubsubpb - pkg: "github.com/libp2p/go-libp2p/p2p/net/mock" alias: mocknet - pkg: "github.com/libp2p/go-libp2p-testing/netutil" @@ -270,114 +570,27 @@ linters-settings: - pkg: "k8s.io/client-go/applyconfigurations/meta/v1" alias: metav1 - godot: - # Comments to be checked: `declarations`, `toplevel`, or `all`. - # Default: declarations - scope: declarations - # List of regexps for excluding particular comment lines from check. - # Default: [] - exclude: - # Exclude todo and fixme comments. - - "^FIXME:" - - "^TODO:" - # Check that each sentence ends with a period. - # Default: true - period: true - # Check that each sentence starts with a capital letter. - # Default: false - capital: false - - gofumpt: - # Choose whether to use the extra rules. - # Default: false - extra-rules: false - - gosec: - # To select a subset of rules to run. - # Available rules: https://github.com/securego/gosec#available-rules - # Default: [] - means include all rules - # includes: - # To specify a set of rules to explicitly exclude. - # Available rules: https://github.com/securego/gosec#available-rules - # Default: [] - # excludes: - # Exclude generated files - # Default: false - exclude-generated: false - # Filter out the issues with a lower severity than the given value. - # Valid options are: low, medium, high. - # Default: low - # severity: medium - # Filter out the issues with a lower confidence than the given value. - # Valid options are: low, medium, high. - # Default: low - # confidence: low - # Concurrency value. - # Default: the number of logical CPUs usable by the current process. - # concurrency: 12 - - whitespace: - # Enforces newlines (or comments) after every multi-line if statement. - # Default: false - multi-if: true - # Enforces newlines (or comments) after every multi-line function signature. - # Default: false - multi-func: true - - wrapcheck: - # An array of strings that specify substrings of signatures to ignore. - # If this set, it will override the default set of ignored signatures. - # See https://github.com/tomarrell/wrapcheck#configuration for more information. - # Default: [".Errorf(", "errors.New(", "errors.Unwrap(", ".Wrap(", ".Wrapf(", ".WithMessage(", ".WithMessagef(", ".WithStack("] - ignoreSigs: - - .Errorf( - - errors.New( - - .WithMessage( - - .WithMessagef( - - .WithStack( - -linters: - # Disable all linters. - # Default: false - disable-all: true - # Enable specific linter - # https://golangci-lint.run/usage/linters/#enabled-by-default - enable: - - gci - - importas - - govet - - godot - - gofmt - - gofumpt - - revive - - misspell - - staticcheck - - unused - - ineffassign - - typecheck - - nakedret - - depguard - - goconst - # - whitespace - # - wrapcheck - # - errcheck - - gosec - # - nakedret - # - gocyclo - # - lll - # - prealloc + misspell: + # Correct spellings using locale preferences for US or UK. + # Setting locale to US will correct the British spelling of 'colour' to 'color'. + # Default is to use a neutral variety of English. + locale: US - # Enable all available linters. - # Default: false - enable-all: false + nakedret: + # Make an issue if func has more lines of code than this setting, and it has naked returns. + # Default: 30 + max-func-lines: 30 - # Disable specific linter - # https://golangci-lint.run/usage/linters/#disabled-by-default - # disable: + revive: + # Sets the default failure confidence. + # This means that linting errors with less than 0.8 confidence will be ignored. + # Default: 0.8 + confidence: 0.8 - # Run only fast linters from enabled linters set (first run won't be fast) - # Default: false - fast: false + staticcheck: + # SAxxxx checks in https://staticcheck.io/docs/configuration/options/#checks + # Default: ["*"] + checks: ["all"] issues: # List of regexps of issue texts to exclude. @@ -388,29 +601,48 @@ issues: # # Default: https://golangci-lint.run/usage/false-positives/#default-exclusions # exclude: - + # - abcdef # Excluding configuration per-path, per-linter, per-text and per-source exclude-rules: + # Exclude some `staticcheck` messages. - linters: - staticcheck - text: SA1019 - + text: "SA1019:" # Independently of option `exclude` we use default exclude patterns, # it can be disabled by this option. # To list all excluded by default patterns execute `golangci-lint run --help`. # Default: true. exclude-use-default: false - + # If set to true exclude and exclude-rules regular expressions become case-sensitive. + # Default: false + exclude-case-sensitive: false + # The list of ids of default excludes to include or disable. + # https://golangci-lint.run/usage/false-positives/#default-exclusions + # Default: [] + # include: + # - EXC0001 + # - EXC0002 + # - EXC0003 + # - EXC0004 + # - EXC0005 + # - EXC0006 + # - EXC0007 + # - EXC0008 + # - EXC0009 + # - EXC0010 + # - EXC0011 + # - EXC0012 + # - EXC0013 + # - EXC0014 + # - EXC0015 # Maximum issues count per one linter. # Set to 0 to disable. # Default: 50 max-issues-per-linter: 0 - # Maximum count of issues with the same text. # Set to 0 to disable. # Default: 3 max-same-issues: 0 - # Show only new issues: if there are unstaged changes or untracked files, # only those changes are analyzed, else only changes in HEAD~ are analyzed. # It's a super-useful option for integration of golangci-lint into existing large codebase. @@ -418,4 +650,10 @@ issues: # much better don't allow issues in new code. # # Default: false. - new: false + # new: true + # Show only new issues created after git revision `REV`. + # new-from-rev: HEAD + # Show only new issues created in git patch with set file path. + # new-from-patch: path/to/patch/file + # Fix found issues (if it's supported by the linter). + # fix: true diff --git a/Makefile b/Makefile index 10fcac6e..16ef8692 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ VERSION ?= $(shell git describe --tags) GOLANGCI_LINT_VERSION := v1.52.0 STATICCHECK_VERSION := v0.4.3 -GOTESTSUM_VERSION := v1.9.0 +GOTESTSUM_VERSION := v1.10.0 GOSCALE_VERSION := v1.1.10 BUF_VERSION := 1.8.0 diff --git a/service/round.go b/service/round.go index 979ca4ee..70489244 100644 --- a/service/round.go +++ b/service/round.go @@ -108,7 +108,7 @@ func (r *round) submit(key, challenge []byte) error { return err } -func (r *round) execute(ctx context.Context, end time.Time, minMemoryLayer uint, fileWriterBufSize uint) error { +func (r *round) execute(ctx context.Context, end time.Time, minMemoryLayer, fileWriterBufSize uint) error { logger := logging.FromContext(ctx).With(zap.String("round", r.ID)) logger.Sugar().Infof("executing until %v...", end) diff --git a/service/service.go b/service/service.go index 9d9f09af..09bb5b74 100644 --- a/service/service.go +++ b/service/service.go @@ -366,7 +366,7 @@ func (s *Service) Started() bool { return s.started.Load() } -func (s *Service) recover(ctx context.Context) (open *round, executing *round, err error) { +func (s *Service) recover(ctx context.Context) (open, executing *round, err error) { roundsDir := filepath.Join(s.datadir, "rounds") logger := logging.FromContext(ctx).Named("recovery") logger.Info("Recovering service state", zap.String("datadir", s.datadir)) diff --git a/service/service_test.go b/service/service_test.go index 78f84d5b..753fa407 100644 --- a/service/service_test.go +++ b/service/service_test.go @@ -45,7 +45,7 @@ type challenge struct { func TestService_Recovery(t *testing.T) { req := require.New(t) tempdir := t.TempDir() - genesis := time.Now().Add(2 * time.Second) + genesis := time.Now().Add(time.Second) cfg := &service.Config{ Genesis: service.Genesis(genesis), EpochDuration: time.Second * 2, @@ -164,20 +164,34 @@ func TestService_Recovery(t *testing.T) { func TestNewService(t *testing.T) { req := require.New(t) tempdir := t.TempDir() - - cfg := service.Config{ - Genesis: service.Genesis(time.Now().Add(time.Second)), + genesis := time.Now().Add(time.Second) + cfg := &service.Config{ + Genesis: service.Genesis(genesis), EpochDuration: time.Second * 2, PhaseShift: time.Second, MaxRoundMembers: 100, } + start := make(chan struct{}) + var tick *time.Ticker + time.AfterFunc(time.Until(genesis), func() { + tick = time.NewTicker(cfg.EpochDuration) + close(start) + }) ctrl := gomock.NewController(t) powVerifier := mocks.NewMockPowVerifier(ctrl) powVerifier.EXPECT().Params().AnyTimes().Return(service.PowParams{}) powVerifier.EXPECT().SetParams(gomock.Any()).AnyTimes() - s, err := service.NewService(context.Background(), &cfg, tempdir, service.WithPowVerifier(powVerifier)) + challengesCount := 5 + challenges := make([]challenge, challengesCount) + + // Generate random challenges. + for i := 0; i < len(challenges); i++ { + challenges[i] = challenge{data: bytes.Repeat([]byte{byte(i)}, 32), nodeID: bytes.Repeat([]byte{-byte(i)}, 32)} + } + + s, err := service.NewService(context.Background(), cfg, tempdir, service.WithPowVerifier(powVerifier)) req.NoError(err) ctx, cancel := context.WithCancel(context.Background()) @@ -186,14 +200,6 @@ func TestNewService(t *testing.T) { eg.Go(func() error { return s.Run(ctx) }) req.NoError(s.Start(context.Background())) - challengesCount := 8 - challenges := make([]challenge, challengesCount) - - // Generate random challenges. - for i := 0; i < len(challenges); i++ { - challenges[i] = challenge{data: bytes.Repeat([]byte{byte(i)}, 32), nodeID: bytes.Repeat([]byte{-byte(i)}, 32)} - } - info, err := s.Info(context.Background()) require.NoError(t, err) currentRound := info.OpenRoundID @@ -212,22 +218,22 @@ func TestNewService(t *testing.T) { req.Equal(currentRound, info.OpenRoundID) // Wait for round to start execution. - req.Eventually(func() bool { - info, err := s.Info(context.Background()) - req.NoError(err) - return info.ExecutingRoundId != nil && *info.ExecutingRoundId == currentRound - }, cfg.EpochDuration*2, time.Millisecond*100) + <-start + <-tick.C + + info, err = s.Info(context.Background()) + req.NoError(err) + req.Equal(*info.ExecutingRoundId, currentRound) // Wait for end of execution. - req.Eventually(func() bool { - info, err := s.Info(context.Background()) - req.NoError(err) - prevRoundID, err := strconv.Atoi(currentRound) - req.NoError(err) - currRoundID, err := strconv.Atoi(info.OpenRoundID) - req.NoError(err) - return currRoundID >= prevRoundID+1 - }, time.Second, time.Millisecond*100) + <-tick.C + info, err = s.Info(context.Background()) + req.NoError(err) + prevRoundID, err := strconv.Atoi(currentRound) + req.NoError(err) + currRoundID, err := strconv.Atoi(info.OpenRoundID) + req.NoError(err) + req.Greater(currRoundID, prevRoundID) // Wait for proof message. proofMsg := <-s.ProofsChan()