diff --git a/.github/workflows/beekeeper.yml b/.github/workflows/beekeeper.yml index 5006a520d2c..4c69fce7a6f 100644 --- a/.github/workflows/beekeeper.yml +++ b/.github/workflows/beekeeper.yml @@ -33,18 +33,18 @@ jobs: msg: ${{ steps.commit.outputs.msg }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 if: github.event.action != 'beekeeper' with: fetch-depth: 0 - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 if: github.event.action == 'beekeeper' with: fetch-depth: 0 ref: ${{ github.event.client_payload.ref }} - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: cache: false go-version-file: go.mod diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index dea9ed5ce5e..38402e52cda 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -40,7 +40,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml index 83097774128..fb41df6f301 100644 --- a/.github/workflows/docs.yaml +++ b/.github/workflows/docs.yaml @@ -14,7 +14,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: '0' - name: Check whether docs have changed diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index b705d804914..1ec8039073f 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -21,9 +21,9 @@ jobs: os: [ubuntu-latest, macos-latest, windows-latest] steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: cache: true go-version-file: go.mod @@ -41,9 +41,9 @@ jobs: continue-on-error: ${{ github.ref == 'refs/heads/master' }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: cache: true go-version-file: go.mod @@ -55,11 +55,11 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: cache: false go-version-file: go.mod @@ -67,10 +67,10 @@ jobs: if: github.ref != 'refs/heads/master' uses: wagoid/commitlint-github-action@v5 - name: GolangCI-Lint - uses: golangci/golangci-lint-action@v6 + uses: golangci/golangci-lint-action@v8 with: skip-cache: false - version: v1.64.5 + version: v2.5.0 - name: Whitespace check run: make check-whitespace - name: go mod tidy check @@ -81,9 +81,9 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: cache: false go-version-file: go.mod @@ -109,11 +109,11 @@ jobs: if: github.ref == 'refs/heads/master' steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: cache: false go-version-file: go.mod diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 8d90e7c947d..877e4845a6a 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -12,11 +12,11 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: go-version-file: go.mod - name: Docker Hub and Quay Login diff --git a/.golangci.yml b/.golangci.yml index 4f07d6fa978..776f2575cbe 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,5 +1,4 @@ -run: - timeout: 10m +version: "2" linters: enable: - asciicheck @@ -7,19 +6,14 @@ linters: - copyloopvar - dogsled - durationcheck - - errcheck - errname - errorlint - forbidigo - gochecknoinits - goconst - - gofmt - goheader - goprintffuncname - - gosimple - - govet - importas - - ineffassign - misspell - nilerr - noctx @@ -27,49 +21,61 @@ linters: - prealloc - predeclared - promlinter - - staticcheck - thelper - - typecheck - unconvert - - unused - # - depguard disable temporary until this issue is resolved: https://github.com/golangci/golangci-lint/issues/3906 - -linters-settings: - govet: - enable-all: true - disable: - - fieldalignment ## temporally disabled - - shadow ## temporally disabled - goheader: - values: - regexp: - date: "20[1-2][0-9]" - template: |- - Copyright {{date}} The Swarm Authors. All rights reserved. - Use of this source code is governed by a BSD-style - license that can be found in the LICENSE file. - paralleltest: - # Ignore missing calls to `t.Parallel()` and only report incorrect uses of `t.Parallel()`. - ignore-missing: true -issues: - exclude-rules: - - linters: - - goheader - text: "go-ethereum Authors" ## disable check for other authors - - path: _test\.go - linters: - - goconst ## temporally disable goconst in test - - linters: - - forbidigo - path: cmd/bee/cmd - text: "use of `fmt.Print" ## allow fmt.Print in cmd directory - - linters: - - dogsled - path: pkg/api/(.+)_test\.go # temporally disable dogsled in api test files - - linters: - - dogsled - path: pkg/pushsync/(.+)_test\.go # temporally disable dogsled in pushsync test files - # temporally disable paralleltest in following packages - - linters: - - paralleltest - path: pkg/log + settings: + goheader: + values: + regexp: + date: 20[1-2][0-9] + template: |- + Copyright {{date}} The Swarm Authors. All rights reserved. + Use of this source code is governed by a BSD-style + license that can be found in the LICENSE file. + govet: + disable: + - fieldalignment + - shadow + enable-all: true + paralleltest: + ignore-missing: true + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + rules: + - linters: + - goheader + text: go-ethereum Authors + - linters: + - goconst + path: _test\.go + - linters: + - forbidigo + path: cmd/bee/cmd + text: use of `fmt.Print + - linters: + - dogsled + path: pkg/api/(.+)_test\.go + - linters: + - dogsled + path: pkg/pushsync/(.+)_test\.go + - linters: + - paralleltest + path: pkg/log + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofmt + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/Dockerfile b/Dockerfile index 0850b2ed8cf..01f7f2bad89 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.24 AS build +FROM golang:1.25 AS build WORKDIR /src # enable modules caching in separate layer diff --git a/Dockerfile.dev b/Dockerfile.dev index a417c710cbc..3cfae361aea 100644 --- a/Dockerfile.dev +++ b/Dockerfile.dev @@ -1,4 +1,4 @@ -FROM golang:1.24 AS build +FROM golang:1.25 AS build ARG REACHABILITY_OVERRIDE_PUBLIC=false ARG BATCHFACTOR_OVERRIDE_PUBLIC=5 diff --git a/Dockerfile.goreleaser b/Dockerfile.goreleaser index 2a62048228e..6772cb56963 100644 --- a/Dockerfile.goreleaser +++ b/Dockerfile.goreleaser @@ -1,4 +1,4 @@ -FROM debian:12.10-slim +FROM debian:12.12-slim ENV DEBIAN_FRONTEND=noninteractive diff --git a/Dockerfile.scratch b/Dockerfile.scratch index e11761aa326..1ecff0f7fbc 100644 --- a/Dockerfile.scratch +++ b/Dockerfile.scratch @@ -1,4 +1,4 @@ -FROM debian:12.10-slim +FROM debian:12.12-slim ENV DEBIAN_FRONTEND=noninteractive diff --git a/Makefile b/Makefile index 01568f1136b..047f5d4f8be 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ GO ?= go GOBIN ?= $$($(GO) env GOPATH)/bin GOLANGCI_LINT ?= $(GOBIN)/golangci-lint -GOLANGCI_LINT_VERSION ?= v1.64.5 +GOLANGCI_LINT_VERSION ?= v2.5.0 GOGOPROTOBUF ?= protoc-gen-gogofaster GOGOPROTOBUF_VERSION ?= v1.3.1 BEEKEEPER_INSTALL_DIR ?= $(GOBIN) diff --git a/cmd/bee/cmd/split.go b/cmd/bee/cmd/split.go index ebe798e878d..112b32ed2fa 100644 --- a/cmd/bee/cmd/split.go +++ b/cmd/bee/cmd/split.go @@ -116,13 +116,13 @@ func splitRefs(cmd *cobra.Command) { } logger.Debug("write root", "hash", rootRef) - _, err = writer.WriteString(fmt.Sprintf("%s\n", rootRef)) + _, err = fmt.Fprintf(writer, "%s\n", rootRef) if err != nil { return fmt.Errorf("write root hash: %w", err) } for _, ref := range refs { logger.Debug("write chunk", "hash", ref) - _, err = writer.WriteString(fmt.Sprintf("%s\n", ref)) + _, err = fmt.Fprintf(writer, "%s\n", ref) if err != nil { return fmt.Errorf("write chunk address: %w", err) } diff --git a/go.mod b/go.mod index dfd5fbd4a5e..eccad953b87 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,8 @@ module github.com/ethersphere/bee/v2 -go 1.24.0 +go 1.25 -toolchain go1.24.2 +toolchain go1.25.1 require ( contrib.go.opencensus.io/exporter/prometheus v0.4.2 @@ -46,7 +46,6 @@ require ( go.uber.org/atomic v1.11.0 go.uber.org/goleak v1.3.0 golang.org/x/crypto v0.36.0 - golang.org/x/net v0.38.0 golang.org/x/sync v0.12.0 golang.org/x/sys v0.31.0 golang.org/x/term v0.30.0 @@ -170,6 +169,7 @@ require ( go.uber.org/zap v1.27.0 // indirect golang.org/x/exp v0.0.0-20240213143201-ec583247a57a // indirect golang.org/x/mod v0.22.0 // indirect + golang.org/x/net v0.38.0 // indirect golang.org/x/text v0.23.0 // indirect golang.org/x/tools v0.29.0 // indirect google.golang.org/protobuf v1.36.1 // indirect diff --git a/pkg/accesscontrol/access.go b/pkg/accesscontrol/access.go index 0b7f9a094ac..71ddd3500c5 100644 --- a/pkg/accesscontrol/access.go +++ b/pkg/accesscontrol/access.go @@ -129,7 +129,7 @@ func (al *ActLogic) getAccessKey(ctx context.Context, storage kvs.KeyValueStore, // Generate lookup key and access key decryption key for a given public key. func (al *ActLogic) getKeys(publicKey *ecdsa.PublicKey) ([]byte, []byte, error) { nonces := [][]byte{zeroByteArray, oneByteArray} - keys, err := al.Session.Key(publicKey, nonces) + keys, err := al.Key(publicKey, nonces) if len(keys) != len(nonces) { return nil, nil, err } diff --git a/pkg/accesscontrol/controller.go b/pkg/accesscontrol/controller.go index 804c307ce8c..cc3c8ae6fd7 100644 --- a/pkg/accesscontrol/controller.go +++ b/pkg/accesscontrol/controller.go @@ -261,7 +261,7 @@ func (c *ControllerStruct) getGranteeList(ctx context.Context, ls file.LoadSaver } func (c *ControllerStruct) encryptRefForPublisher(publisherPubKey *ecdsa.PublicKey, ref swarm.Address) (swarm.Address, error) { - keys, err := c.access.Session.Key(publisherPubKey, [][]byte{oneByteArray}) + keys, err := c.access.Key(publisherPubKey, [][]byte{oneByteArray}) if err != nil { return swarm.ZeroAddress, err } @@ -275,7 +275,7 @@ func (c *ControllerStruct) encryptRefForPublisher(publisherPubKey *ecdsa.PublicK } func (c *ControllerStruct) decryptRefForPublisher(publisherPubKey *ecdsa.PublicKey, encryptedRef swarm.Address) (swarm.Address, error) { - keys, err := c.access.Session.Key(publisherPubKey, [][]byte{oneByteArray}) + keys, err := c.access.Key(publisherPubKey, [][]byte{oneByteArray}) if err != nil { return swarm.ZeroAddress, err } diff --git a/pkg/accesscontrol/controller_test.go b/pkg/accesscontrol/controller_test.go index 915d82d7d8b..1fa3da681ce 100644 --- a/pkg/accesscontrol/controller_test.go +++ b/pkg/accesscontrol/controller_test.go @@ -178,7 +178,7 @@ func TestController_UpdateHandler(t *testing.T) { publisher := getPrivKey(1) diffieHellman := accesscontrol.NewDefaultSession(publisher) al := accesscontrol.NewLogic(diffieHellman) - keys, err := al.Session.Key(&publisher.PublicKey, [][]byte{{1}}) + keys, err := al.Key(&publisher.PublicKey, [][]byte{{1}}) assertNoError(t, "Session key", err) refCipher := encryption.New(keys[0], 0, 0, sha3.NewLegacyKeccak256) ls := createLs() diff --git a/pkg/accesscontrol/session.go b/pkg/accesscontrol/session.go index a571337c17d..f3996264970 100644 --- a/pkg/accesscontrol/session.go +++ b/pkg/accesscontrol/session.go @@ -37,7 +37,7 @@ func (s *SessionStruct) Key(publicKey *ecdsa.PublicKey, nonces [][]byte) ([][]by if publicKey == nil { return nil, ErrInvalidPublicKey } - x, y := publicKey.Curve.ScalarMult(publicKey.X, publicKey.Y, s.key.D.Bytes()) + x, y := publicKey.ScalarMult(publicKey.X, publicKey.Y, s.key.D.Bytes()) if x == nil || y == nil { return nil, ErrSecretKeyInfinity } diff --git a/pkg/api/api_test.go b/pkg/api/api_test.go index 986bc663d3e..4dd7aa1d3f7 100644 --- a/pkg/api/api_test.go +++ b/pkg/api/api_test.go @@ -266,7 +266,7 @@ func newTestServer(t *testing.T, o testServerOptions) (*http.Client, *websocket. transport = transport.Clone() // always dial to the server address, regardless of the url host and port transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { - return net.Dial(network, ts.Listener.Addr().String()) + return (&net.Dialer{}).DialContext(ctx, network, ts.Listener.Addr().String()) } return transport.RoundTrip(r) }), diff --git a/pkg/api/chequebook.go b/pkg/api/chequebook.go index 33cd75d9767..b9a6f9b1901 100644 --- a/pkg/api/chequebook.go +++ b/pkg/api/chequebook.go @@ -118,9 +118,9 @@ func (s *Service) chequebookLastPeerHandler(w http.ResponseWriter, r *http.Reque } if err == nil { lastSentResponse = &chequebookLastChequePeerResponse{ - Beneficiary: lastSent.Cheque.Beneficiary.String(), - Chequebook: lastSent.Cheque.Chequebook.String(), - Payout: bigint.Wrap(lastSent.Cheque.CumulativePayout), + Beneficiary: lastSent.Beneficiary.String(), + Chequebook: lastSent.Chequebook.String(), + Payout: bigint.Wrap(lastSent.CumulativePayout), } } @@ -134,9 +134,9 @@ func (s *Service) chequebookLastPeerHandler(w http.ResponseWriter, r *http.Reque } if err == nil { lastReceivedResponse = &chequebookLastChequePeerResponse{ - Beneficiary: lastReceived.Cheque.Beneficiary.String(), - Chequebook: lastReceived.Cheque.Chequebook.String(), - Payout: bigint.Wrap(lastReceived.Cheque.CumulativePayout), + Beneficiary: lastReceived.Beneficiary.String(), + Chequebook: lastReceived.Chequebook.String(), + Payout: bigint.Wrap(lastReceived.CumulativePayout), } } @@ -179,9 +179,9 @@ func (s *Service) chequebookAllLastHandler(w http.ResponseWriter, _ *http.Reques lcr[i] = chequebookLastChequesPeerResponse{ Peer: i, LastSent: &chequebookLastChequePeerResponse{ - Beneficiary: j.Cheque.Beneficiary.String(), - Chequebook: j.Cheque.Chequebook.String(), - Payout: bigint.Wrap(j.Cheque.CumulativePayout), + Beneficiary: j.Beneficiary.String(), + Chequebook: j.Chequebook.String(), + Payout: bigint.Wrap(j.CumulativePayout), }, LastReceived: nil, } @@ -190,9 +190,9 @@ func (s *Service) chequebookAllLastHandler(w http.ResponseWriter, _ *http.Reques if _, ok := lcr[i]; ok { t := lcr[i] t.LastReceived = &chequebookLastChequePeerResponse{ - Beneficiary: j.Cheque.Beneficiary.String(), - Chequebook: j.Cheque.Chequebook.String(), - Payout: bigint.Wrap(j.Cheque.CumulativePayout), + Beneficiary: j.Beneficiary.String(), + Chequebook: j.Chequebook.String(), + Payout: bigint.Wrap(j.CumulativePayout), } lcr[i] = t } else { @@ -200,9 +200,9 @@ func (s *Service) chequebookAllLastHandler(w http.ResponseWriter, _ *http.Reques Peer: i, LastSent: nil, LastReceived: &chequebookLastChequePeerResponse{ - Beneficiary: j.Cheque.Beneficiary.String(), - Chequebook: j.Cheque.Chequebook.String(), - Payout: bigint.Wrap(j.Cheque.CumulativePayout), + Beneficiary: j.Beneficiary.String(), + Chequebook: j.Chequebook.String(), + Payout: bigint.Wrap(j.CumulativePayout), }, } } diff --git a/pkg/bmt/proof.go b/pkg/bmt/proof.go index 481a50d87e5..b08017b43cd 100644 --- a/pkg/bmt/proof.go +++ b/pkg/bmt/proof.go @@ -20,7 +20,7 @@ type Proof struct { // Hash overrides base hash function of Hasher to fill buffer with zeros until chunk length func (p Prover) Hash(b []byte) ([]byte, error) { for i := p.size; i < p.maxSize; i += len(zerosection) { - _, err := p.Hasher.Write(zerosection) + _, err := p.Write(zerosection) if err != nil { return nil, err } diff --git a/pkg/crypto/dh.go b/pkg/crypto/dh.go index 2d5b4e695fc..f3ea41facc4 100644 --- a/pkg/crypto/dh.go +++ b/pkg/crypto/dh.go @@ -29,7 +29,7 @@ func NewDH(key *ecdsa.PrivateKey) DH { // safety warning: this method is not meant to be exposed as it does not validate private and public keys // are on the same curve func (dh *defaultDH) SharedKey(pub *ecdsa.PublicKey, salt []byte) ([]byte, error) { - x, _ := pub.Curve.ScalarMult(pub.X, pub.Y, dh.key.D.Bytes()) + x, _ := pub.ScalarMult(pub.X, pub.Y, dh.key.D.Bytes()) if x == nil { return nil, errors.New("shared secret is point at infinity") } diff --git a/pkg/crypto/signer_test.go b/pkg/crypto/signer_test.go index b3b09ae04af..6d6690ec27e 100644 --- a/pkg/crypto/signer_test.go +++ b/pkg/crypto/signer_test.go @@ -41,7 +41,7 @@ func TestDefaultSigner(t *testing.T) { t.Fatal(err) } - if pubKey.X.Cmp(privKey.PublicKey.X) != 0 || pubKey.Y.Cmp(privKey.PublicKey.Y) != 0 { + if pubKey.X.Cmp(privKey.X) != 0 || pubKey.Y.Cmp(privKey.Y) != 0 { t.Fatalf("wanted %v but got %v", pubKey, &privKey.PublicKey) } }) @@ -54,7 +54,7 @@ func TestDefaultSigner(t *testing.T) { t.Fatal(err) } - if pubKey.X.Cmp(privKey.PublicKey.X) == 0 && pubKey.Y.Cmp(privKey.PublicKey.Y) == 0 { + if pubKey.X.Cmp(privKey.X) == 0 && pubKey.Y.Cmp(privKey.Y) == 0 { t.Fatal("expected different public key") } }) @@ -228,11 +228,11 @@ func TestRecoverEIP712(t *testing.T) { t.Fatal(err) } - if privKey.PublicKey.X.Cmp(pubKey.X) != 0 { + if privKey.X.Cmp(pubKey.X) != 0 { t.Fatalf("recovered wrong public key. wanted %x, got %x", privKey.PublicKey, pubKey) } - if privKey.PublicKey.Y.Cmp(pubKey.Y) != 0 { + if privKey.Y.Cmp(pubKey.Y) != 0 { t.Fatalf("recovered wrong public key. wanted %x, got %x", privKey.PublicKey, pubKey) } } diff --git a/pkg/feeds/getter.go b/pkg/feeds/getter.go index d0ab55da024..2bdf509e282 100644 --- a/pkg/feeds/getter.go +++ b/pkg/feeds/getter.go @@ -93,7 +93,7 @@ func FromChunk(ch swarm.Chunk) (swarm.Chunk, error) { // legacyPayload returns back the referenced chunk and datetime from the legacy feed payload func legacyPayload(wrappedChunk swarm.Chunk) (swarm.Address, error) { cacData := wrappedChunk.Data() - if !(len(cacData) == 16+swarm.HashSize || len(cacData) == 16+swarm.HashSize*2) { + if len(cacData) != 16+swarm.HashSize && len(cacData) != 16+swarm.HashSize*2 { return swarm.ZeroAddress, ErrNotLegacyPayload } diff --git a/pkg/file/buffer.go b/pkg/file/buffer.go index 976eca20fa0..aaf36f535f3 100644 --- a/pkg/file/buffer.go +++ b/pkg/file/buffer.go @@ -42,10 +42,7 @@ func (c *ChunkPipe) Read(b []byte) (int, error) { func (c *ChunkPipe) Write(b []byte) (int, error) { nw := 0 - for { - if nw >= len(b) { - break - } + for nw < len(b) { copied := copy(c.data[c.cursor:], b[nw:]) c.cursor += copied diff --git a/pkg/file/pipeline/hashtrie/hashtrie.go b/pkg/file/pipeline/hashtrie/hashtrie.go index 1aff8c0df66..9c2d17fb5fc 100644 --- a/pkg/file/pipeline/hashtrie/hashtrie.go +++ b/pkg/file/pipeline/hashtrie/hashtrie.go @@ -198,11 +198,11 @@ func (h *hashTrieWriter) wrapFullLevel(level int) error { func (h *hashTrieWriter) Sum() ([]byte, error) { for i := 1; i < maxLevel; i++ { l := h.chunkCounters[i] - switch { - case l == 0: + switch l { + case 0: // level empty, continue to the next. continue - case l == h.maxChildrenChunks: + case h.maxChildrenChunks: // this case is possible and necessary due to the carry over // in the next switch case statement. normal writes done // through writeToLevel will automatically wrap a full level. @@ -211,7 +211,7 @@ func (h *hashTrieWriter) Sum() ([]byte, error) { if err != nil { return nil, err } - case l == 1: + case 1: // this cursor assignment basically means: // take the hash|span|key from this level, and append it to // the data of the next level. you may wonder how this works: diff --git a/pkg/file/utils.go b/pkg/file/utils.go index ce1f94d372a..b0e3071f98d 100644 --- a/pkg/file/utils.go +++ b/pkg/file/utils.go @@ -66,10 +66,8 @@ func ReferenceCount(span uint64, level redundancy.Level, encrytedChunk bool) (in ) // search for branch level big enough to include span branchLevel := 1 - for { - if branchSize >= span { - break - } + for branchSize < span { + branchSize *= branching branchLevel++ } diff --git a/pkg/jsonhttp/jsonhttptest/jsonhttptest.go b/pkg/jsonhttp/jsonhttptest/jsonhttptest.go index 1c436ec9373..7902a566dc9 100644 --- a/pkg/jsonhttp/jsonhttptest/jsonhttptest.go +++ b/pkg/jsonhttp/jsonhttptest/jsonhttptest.go @@ -36,14 +36,15 @@ func Request(tb testing.TB, client *http.Client, method, url string, responseCod } } - req, err := http.NewRequest(method, url, o.requestBody) + ctx := o.ctx + if ctx == nil { + ctx = context.Background() + } + req, err := http.NewRequestWithContext(ctx, method, url, o.requestBody) if err != nil { tb.Fatal(err) } req.Header = o.requestHeaders - if o.ctx != nil { - req = req.WithContext(o.ctx) - } resp, err := client.Do(req) if err != nil { tb.Fatal(err) diff --git a/pkg/keystore/file/key.go b/pkg/keystore/file/key.go index dcbe22612f5..5844b0dd1ef 100644 --- a/pkg/keystore/file/key.go +++ b/pkg/keystore/file/key.go @@ -75,7 +75,7 @@ func encryptKey(k *ecdsa.PrivateKey, password string, edg keystore.EDG) ([]byte, return nil, err } var addr []byte - switch k.PublicKey.Curve { + switch k.Curve { case btcec.S256(): a, err := crypto.NewEthereumAddress(k.PublicKey) if err != nil { @@ -89,7 +89,7 @@ func encryptKey(k *ecdsa.PrivateKey, password string, edg keystore.EDG) ([]byte, } addr = privKey.PublicKey().Bytes() default: - return nil, fmt.Errorf("unsupported curve: %v", k.PublicKey.Curve) + return nil, fmt.Errorf("unsupported curve: %v", k.Curve) } return json.Marshal(encryptedKey{ Address: hex.EncodeToString(addr), diff --git a/pkg/manifest/mantaray/marshal.go b/pkg/manifest/mantaray/marshal.go index 0129312ff9f..f5f7edabc8f 100644 --- a/pkg/manifest/mantaray/marshal.go +++ b/pkg/manifest/mantaray/marshal.go @@ -12,6 +12,7 @@ import ( "encoding/json" "errors" "fmt" + "math" ) const ( @@ -341,7 +342,7 @@ func (f *fork) fromBytes(b []byte) error { f.prefix = b[nodeForkHeaderSize : nodeForkHeaderSize+prefixLen] f.Node = NewNodeRef(b[nodeForkPreReferenceSize:]) - f.Node.nodeType = nodeType + f.nodeType = nodeType return nil } @@ -356,7 +357,7 @@ func (f *fork) fromBytes02(b []byte, refBytesSize, metadataBytesSize int) error f.prefix = b[nodeForkHeaderSize : nodeForkHeaderSize+prefixLen] f.Node = NewNodeRef(b[nodeForkPreReferenceSize : nodeForkPreReferenceSize+refBytesSize]) - f.Node.nodeType = nodeType + f.nodeType = nodeType if metadataBytesSize > 0 { metadataBytes := b[nodeForkPreReferenceSize+refBytesSize+nodeForkMetadataBytesSize:] @@ -368,7 +369,7 @@ func (f *fork) fromBytes02(b []byte, refBytesSize, metadataBytesSize int) error return err } - f.Node.metadata = metadata + f.metadata = metadata } return nil @@ -381,7 +382,7 @@ func (f *fork) bytes() (b []byte, err error) { err = fmt.Errorf("node reference size > 256: %d", len(r)) return } - b = append(b, f.Node.nodeType, uint8(len(f.prefix))) + b = append(b, f.nodeType, uint8(len(f.prefix))) prefixBytes := make([]byte, nodePrefixMaxSize) copy(prefixBytes, f.prefix) @@ -391,13 +392,16 @@ func (f *fork) bytes() (b []byte, err error) { copy(refBytes, r) b = append(b, refBytes...) - if f.Node.IsWithMetadataType() { + if f.IsWithMetadataType() { // using JSON encoding for metadata - metadataJSONBytes, err1 := json.Marshal(f.Node.metadata) + metadataJSONBytes, err1 := json.Marshal(f.metadata) if err1 != nil { return b, err1 } + if len(metadataJSONBytes) > math.MaxInt-nodeForkMetadataBytesSize { + return nil, fmt.Errorf("metadata size overflow: %d", len(metadataJSONBytes)) + } metadataJSONBytesSizeWithSize := len(metadataJSONBytes) + nodeForkMetadataBytesSize // pad JSON bytes if necessary @@ -435,7 +439,7 @@ func (f *fork) bytes() (b []byte, err error) { var refBytes = nodeRefBytes func nodeRefBytes(f *fork) []byte { - return f.Node.ref + return f.ref } // encryptDecrypt runs a XOR encryption on the input bytes, encrypting it if it diff --git a/pkg/manifest/mantaray/node.go b/pkg/manifest/mantaray/node.go index 2e2754f200b..88d4a2cbc6a 100644 --- a/pkg/manifest/mantaray/node.go +++ b/pkg/manifest/mantaray/node.go @@ -166,7 +166,7 @@ func (n *Node) LookupNode(ctx context.Context, path []byte, l Loader) (*Node, er } c := common(f.prefix, path) if len(c) == len(f.prefix) { - return f.Node.LookupNode(ctx, path[len(c):], l) + return f.LookupNode(ctx, path[len(c):], l) } return nil, notFound(path) } @@ -259,7 +259,7 @@ func (n *Node) Add(ctx context.Context, path, entry []byte, metadata map[string] nn.SetObfuscationKey(n.obfuscationKey) } nn.refBytesSize = n.refBytesSize - f.Node.updateIsWithPathSeparator(rest) + f.updateIsWithPathSeparator(rest) nn.forks[rest[0]] = &fork{rest, f.Node} nn.makeEdge() // if common path is full path new node is value type @@ -319,7 +319,7 @@ func (n *Node) Remove(ctx context.Context, path []byte, ls LoadSaver) error { delete(n.forks, path[0]) return nil } - return f.Node.Remove(ctx, rest, ls) + return f.Remove(ctx, rest, ls) } func common(a, b []byte) (c []byte) { @@ -350,7 +350,7 @@ func (n *Node) HasPrefix(ctx context.Context, path []byte, l Loader) (bool, erro } c := common(f.prefix, path) if len(c) == len(f.prefix) { - return f.Node.HasPrefix(ctx, path[len(c):], l) + return f.HasPrefix(ctx, path[len(c):], l) } if bytes.HasPrefix(f.prefix, path) { return true, nil diff --git a/pkg/manifest/mantaray/persist.go b/pkg/manifest/mantaray/persist.go index 8ac812e50d8..259785d803c 100644 --- a/pkg/manifest/mantaray/persist.go +++ b/pkg/manifest/mantaray/persist.go @@ -71,7 +71,7 @@ func (n *Node) save(ctx context.Context, s Saver) error { eg, ectx := errgroup.WithContext(ctx) for _, f := range n.forks { eg.Go(func() error { - return f.Node.save(ectx, s) + return f.save(ectx, s) }) } if err := eg.Wait(); err != nil { diff --git a/pkg/node/devnode.go b/pkg/node/devnode.go index 9ff5363c455..acf69ce026f 100644 --- a/pkg/node/devnode.go +++ b/pkg/node/devnode.go @@ -373,7 +373,7 @@ func NewDevBee(logger log.Logger, o *DevOptions) (b *DevBee, err error) { apiService.SetP2P(p2ps) apiService.SetSwarmAddress(&swarmAddress) - apiListener, err := net.Listen("tcp", o.APIAddr) + apiListener, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", o.APIAddr) if err != nil { return nil, fmt.Errorf("api listener: %w", err) } diff --git a/pkg/node/node.go b/pkg/node/node.go index 67d185a55c5..163b599e651 100644 --- a/pkg/node/node.go +++ b/pkg/node/node.go @@ -448,7 +448,7 @@ func NewBee( runtime.SetBlockProfileRate(1) } - apiListener, err := net.Listen("tcp", o.APIAddr) + apiListener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", o.APIAddr) if err != nil { return nil, fmt.Errorf("api listener: %w", err) } diff --git a/pkg/p2p/libp2p/internal/blocklist/blocklist_test.go b/pkg/p2p/libp2p/internal/blocklist/blocklist_test.go index 74a5ba98258..da80a9ebea1 100644 --- a/pkg/p2p/libp2p/internal/blocklist/blocklist_test.go +++ b/pkg/p2p/libp2p/internal/blocklist/blocklist_test.go @@ -111,7 +111,7 @@ func TestPeers(t *testing.T) { func isIn(p swarm.Address, peers []p2p.BlockListedPeer, reason string, f bool) bool { for _, v := range peers { - if v.Address.Equal(p) && v.Reason == reason && v.Peer.FullNode == f { + if v.Address.Equal(p) && v.Reason == reason && v.FullNode == f { return true } } diff --git a/pkg/postage/postagecontract/contract_test.go b/pkg/postage/postagecontract/contract_test.go index 756bbe24a9d..80da7a8ab0d 100644 --- a/pkg/postage/postagecontract/contract_test.go +++ b/pkg/postage/postagecontract/contract_test.go @@ -76,9 +76,10 @@ func TestCreateBatch(t *testing.T) { bzzTokenAddress, transactionMock.New( transactionMock.WithSendFunc(func(ctx context.Context, request *transaction.TxRequest, boost int) (txHash common.Hash, err error) { - if *request.To == bzzTokenAddress { + switch *request.To { + case bzzTokenAddress: return txHashApprove, nil - } else if *request.To == postageStampAddress { + case postageStampAddress: if bytes.Equal(expectedCallDataForExpireLimitedBatches[:32], request.Data[:32]) { return txHashApprove, nil } @@ -90,11 +91,12 @@ func TestCreateBatch(t *testing.T) { return common.Hash{}, errors.New("sent to wrong contract") }), transactionMock.WithWaitForReceiptFunc(func(ctx context.Context, txHash common.Hash) (receipt *types.Receipt, err error) { - if txHash == txHashApprove { + switch txHash { + case txHashApprove: return &types.Receipt{ Status: 1, }, nil - } else if txHash == txHashCreate { + case txHashCreate: return &types.Receipt{ Logs: []*types.Log{ newCreateEvent(postageStampAddress, batchID), @@ -321,9 +323,10 @@ func TestTopUpBatch(t *testing.T) { bzzTokenAddress, transactionMock.New( transactionMock.WithSendFunc(func(ctx context.Context, request *transaction.TxRequest, boost int) (txHash common.Hash, err error) { - if *request.To == bzzTokenAddress { + switch *request.To { + case bzzTokenAddress: return txHashApprove, nil - } else if *request.To == postageStampAddress { + case postageStampAddress: if !bytes.Equal(expectedCallData[:64], request.Data[:64]) { return common.Hash{}, fmt.Errorf("got wrong call data. wanted %x, got %x", expectedCallData, request.Data) } @@ -332,11 +335,12 @@ func TestTopUpBatch(t *testing.T) { return common.Hash{}, errors.New("sent to wrong contract") }), transactionMock.WithWaitForReceiptFunc(func(ctx context.Context, txHash common.Hash) (receipt *types.Receipt, err error) { - if txHash == txHashApprove { + switch txHash { + case txHashApprove: return &types.Receipt{ Status: 1, }, nil - } else if txHash == txHashTopup { + case txHashTopup: return &types.Receipt{ Logs: []*types.Log{ newTopUpEvent(postageStampAddress, batch), diff --git a/pkg/settlement/swap/chequebook/factory.go b/pkg/settlement/swap/chequebook/factory.go index 53457679d2e..f548643bac1 100644 --- a/pkg/settlement/swap/chequebook/factory.go +++ b/pkg/settlement/swap/chequebook/factory.go @@ -9,13 +9,13 @@ import ( "fmt" "math/big" + "context" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/ethersphere/bee/v2/pkg/sctx" "github.com/ethersphere/bee/v2/pkg/transaction" "github.com/ethersphere/bee/v2/pkg/util/abiutil" "github.com/ethersphere/go-sw3-abi/sw3abi" - "golang.org/x/net/context" ) var ( diff --git a/pkg/shed/vector_uint64_test.go b/pkg/shed/vector_uint64_test.go index 2d602a034c0..4eeaf1cdaf3 100644 --- a/pkg/shed/vector_uint64_test.go +++ b/pkg/shed/vector_uint64_test.go @@ -56,7 +56,7 @@ func TestUint64Vector(t *testing.T) { } for _, index := range []uint64{0, 1, 2, 5, 100} { - var want uint64 = 42 + index + var want = 42 + index err = bins.Put(index, want) if err != nil { t.Fatal(err) @@ -70,7 +70,7 @@ func TestUint64Vector(t *testing.T) { } t.Run("overwrite", func(t *testing.T) { - var want uint64 = 84 + index + var want = 84 + index err = bins.Put(index, want) if err != nil { t.Fatal(err) @@ -97,7 +97,7 @@ func TestUint64Vector(t *testing.T) { for _, index := range []uint64{0, 1, 2, 3, 5, 10} { batch := new(leveldb.Batch) - var want uint64 = 43 + index + var want = 43 + index bins.PutInBatch(batch, index, want) err = db.WriteBatch(batch) if err != nil { @@ -113,7 +113,7 @@ func TestUint64Vector(t *testing.T) { t.Run("overwrite", func(t *testing.T) { batch := new(leveldb.Batch) - var want uint64 = 85 + index + var want = 85 + index bins.PutInBatch(batch, index, want) err = db.WriteBatch(batch) if err != nil { diff --git a/pkg/statestore/storeadapter/storeadapter.go b/pkg/statestore/storeadapter/storeadapter.go index 2f05f1f31c7..1deda6c6cd3 100644 --- a/pkg/statestore/storeadapter/storeadapter.go +++ b/pkg/statestore/storeadapter/storeadapter.go @@ -105,11 +105,11 @@ type rawItem struct { // Marshal implements Item interface. func (ri *rawItem) Marshal() ([]byte, error) { - if ri == nil || ri.proxyItem == nil || ri.proxyItem.obj == nil { + if ri == nil || ri.proxyItem == nil || ri.obj == nil { return nil, nil } - if buf, ok := ri.proxyItem.obj.([]byte); ok { + if buf, ok := ri.obj.([]byte); ok { return buf, nil } @@ -118,12 +118,12 @@ func (ri *rawItem) Marshal() ([]byte, error) { // Unmarshal implements Item interface. func (ri *rawItem) Unmarshal(data []byte) error { - if ri == nil || ri.proxyItem == nil || ri.proxyItem.obj == nil || len(data) == 0 { + if ri == nil || ri.proxyItem == nil || ri.obj == nil || len(data) == 0 { return nil } - if buf, ok := ri.proxyItem.obj.([]byte); ok { - ri.proxyItem.obj = append(buf[:0], data...) + if buf, ok := ri.obj.([]byte); ok { + ri.obj = append(buf[:0], data...) return nil } diff --git a/pkg/status/status_test.go b/pkg/status/status_test.go index 09213ec71d4..2b3f9383fe3 100644 --- a/pkg/status/status_test.go +++ b/pkg/status/status_test.go @@ -249,12 +249,12 @@ type statusSnapshotMock struct { *pb.Snapshot } -func (m *statusSnapshotMock) SyncRate() float64 { return m.Snapshot.PullsyncRate } +func (m *statusSnapshotMock) SyncRate() float64 { return m.PullsyncRate } func (m *statusSnapshotMock) ReserveSize() int { return int(m.Snapshot.ReserveSize) } func (m *statusSnapshotMock) StorageRadius() uint8 { return uint8(m.Snapshot.StorageRadius) } -func (m *statusSnapshotMock) Commitment() (uint64, error) { return m.Snapshot.BatchCommitment, nil } +func (m *statusSnapshotMock) Commitment() (uint64, error) { return m.BatchCommitment, nil } func (m *statusSnapshotMock) GetChainState() *postage.ChainState { - return &postage.ChainState{Block: m.Snapshot.LastSyncedBlock} + return &postage.ChainState{Block: m.LastSyncedBlock} } func (m *statusSnapshotMock) ReserveSizeWithinRadius() uint64 { return m.Snapshot.ReserveSizeWithinRadius diff --git a/pkg/storer/internal/chunkstore/chunkstore_test.go b/pkg/storer/internal/chunkstore/chunkstore_test.go index 6787cf826ab..970e92df9b8 100644 --- a/pkg/storer/internal/chunkstore/chunkstore_test.go +++ b/pkg/storer/internal/chunkstore/chunkstore_test.go @@ -109,7 +109,7 @@ type memFS struct { } func (m *memFS) Open(path string) (fs.File, error) { - return m.Fs.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o644) + return m.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o644) } func TestChunkStore(t *testing.T) { diff --git a/pkg/storer/internal/reserve/reserve_test.go b/pkg/storer/internal/reserve/reserve_test.go index 95218e992f6..6828141a73c 100644 --- a/pkg/storer/internal/reserve/reserve_test.go +++ b/pkg/storer/internal/reserve/reserve_test.go @@ -117,11 +117,12 @@ func TestReserveChunkType(t *testing.T) { Factory: func() storage.Item { return &reserve.ChunkBinItem{} }, }, func(res storage.Result) (bool, error) { item := res.Entry.(*reserve.ChunkBinItem) - if item.ChunkType == swarm.ChunkTypeContentAddressed { + switch item.ChunkType { + case swarm.ChunkTypeContentAddressed: storedChunksCA-- - } else if item.ChunkType == swarm.ChunkTypeSingleOwner { + case swarm.ChunkTypeSingleOwner: storedChunksSO-- - } else { + default: t.Fatalf("unexpected chunk type: %d", item.ChunkType) } return false, nil diff --git a/pkg/storer/storer.go b/pkg/storer/storer.go index 76b35f198ba..e3318c9b278 100644 --- a/pkg/storer/storer.go +++ b/pkg/storer/storer.go @@ -189,7 +189,7 @@ type memFS struct { } func (m *memFS) Open(path string) (fs.File, error) { - return m.Fs.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o644) + return m.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o644) } type dirFS struct { diff --git a/pkg/transaction/transaction.go b/pkg/transaction/transaction.go index da71a2150e3..2f2405dd432 100644 --- a/pkg/transaction/transaction.go +++ b/pkg/transaction/transaction.go @@ -14,6 +14,7 @@ import ( "sync" "time" + "context" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" @@ -23,7 +24,6 @@ import ( "github.com/ethersphere/bee/v2/pkg/log" "github.com/ethersphere/bee/v2/pkg/sctx" "github.com/ethersphere/bee/v2/pkg/storage" - "golang.org/x/net/context" ) // loggerName is the tree path name of the logger for this package. diff --git a/pkg/util/testutil/racedetection/off.go b/pkg/util/testutil/racedetection/off.go index d57125bfd03..cd7bfe36c55 100644 --- a/pkg/util/testutil/racedetection/off.go +++ b/pkg/util/testutil/racedetection/off.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build !race -// +build !race package racedetection diff --git a/pkg/util/testutil/racedetection/on.go b/pkg/util/testutil/racedetection/on.go index 92438ecfdc3..428ebb16800 100644 --- a/pkg/util/testutil/racedetection/on.go +++ b/pkg/util/testutil/racedetection/on.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build race -// +build race package racedetection