Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: add go linting #15

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: "CodeQL"

on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]

jobs:
analyze:
name: Analyze
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }}
permissions:
actions: read
contents: read
security-events: write

strategy:
fail-fast: false
matrix:
language: [ 'go']

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}

- name: Make all
run: make all

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"
50 changes: 50 additions & 0 deletions .github/workflows/lint-go.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
name: Go Lint

on:
push:
branches:
- master
pull_request:

permissions:
contents: read

jobs:
golangci:
name: golangci-lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: '1.21'
cache: false
- name: golangci-lint
uses: golangci/golangci-lint-action@v3
with:
version: v1.54

# Optional: working directory, useful for monorepos
# working-directory: somedir

# Optional: golangci-lint command line arguments.
#
# Note: By default, the `.golangci.yml` file should be at the root of the repository.
# The location of the configuration file can be changed by using `--config=`
args: --timeout=30m

# Optional: show only new issues if it's a pull request. The default value is `false`.
only-new-issues: ${{ github.event_name == 'pull_request' }}

# Optional: if set to true, then all caching functionality will be completely disabled,
# takes precedence over all other caching options.
skip-cache: true

# Optional: if set to true, then the action won't cache or restore ~/go/pkg.
skip-pkg-cache: true

# Optional: if set to true, then the action won't cache or restore ~/.cache/go-build.
skip-build-cache: true

# Optional: The mode to install golangci-lint. It can be 'binary' or 'goinstall'.
# install-mode: "goinstall"
19 changes: 19 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Please refer to the official golangci-lint config documentation for more details:
# https://golangci-lint.run/usage/configuration/
# https://github.com/golangci/golangci-lint/blob/master/.golangci.reference.yml

linters:
enable-all: true

linters-settings:
gci:
sections:
- standard
- default

run:
timeout: 10m
tests: false

issues:
max-issues-per-linter: 1000
23 changes: 16 additions & 7 deletions builtin/gen/bindata.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,21 +44,28 @@ import (
"time"
)

const (
maxDecompressedSize = 1 << 20 // 1MB
)

func bindataRead(data []byte, name string) ([]byte, error) {
gz, err := gzip.NewReader(bytes.NewBuffer(data))
if err != nil {
return nil, fmt.Errorf("Read %q: %v", name, err)
}

// Limit the number of bytes read from the decompressor
limitedReader := io.LimitReader(gz, maxDecompressedSize)

var buf bytes.Buffer
_, err = io.Copy(&buf, gz)
_, err = io.Copy(&buf, limitedReader)
clErr := gz.Close()

if err != nil {
return nil, fmt.Errorf("Read %q: %v", name, err)
}
if clErr != nil {
return nil, err
return nil, clErr
}

return buf.Bytes(), nil
Expand Down Expand Up @@ -794,11 +801,13 @@ var _bindata = map[string]func() (*asset, error){
// directory embedded in the file by go-bindata.
// For example if you run go-bindata on data/... and data contains the
// following hierarchy:
// data/
// foo.txt
// img/
// a.png
// b.png
//
// data/
// foo.txt
// img/
// a.png
// b.png
//
// then AssetDir("data") would return []string{"foo.txt", "img"}
// AssetDir("data/img") would return []string{"a.png", "b.png"}
// AssetDir("foo.txt") and AssetDir("notexist") would return an error
Expand Down
24 changes: 16 additions & 8 deletions cache/rnd_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,11 @@
package cache

import (
"math/rand"
"crypto/rand"
"math/big"
"sync"
"time"
)

func init() {
rand.Seed(time.Now().UnixNano())
}

// RandCache a simple cache which randomly evicts entries when
// length exceeds limit.
type RandCache struct {
Expand Down Expand Up @@ -106,7 +102,13 @@ func (rc *RandCache) Pick() *Entry {
if len(rc.s) == 0 {
return nil
}
ent := rc.s[rand.Intn(len(rc.s))]

randomIndex, err := rand.Int(rand.Reader, big.NewInt(int64(len(rc.s))))
if err != nil {
return nil
}

ent := rc.s[randomIndex.Uint64()]
cpy := ent.Entry
return &cpy
}
Expand Down Expand Up @@ -141,6 +143,12 @@ func (rc *RandCache) randDrop() {
if len(rc.s) == 0 {
return
}
ent := rc.s[rand.Intn(len(rc.s))]

randomIndex, err := rand.Int(rand.Reader, big.NewInt(int64(len(rc.s))))
if err != nil {
return
}

ent := rc.s[randomIndex.Uint64()]
rc.remove(ent.Key)
}
12 changes: 10 additions & 2 deletions cmd/thor/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,10 @@
gene := genesis.NewMainnet()
return gene, thor.GetForkConfig(gene.ID()), nil
default:
network = filepath.Clean(network)
if _, err := os.Stat(network); os.IsNotExist(err) {
return nil, thor.ForkConfig{}, errors.New(fmt.Sprintf("the specified genesis file [%v] does not exist", network))

Check warning on line 208 in cmd/thor/utils.go

View workflow job for this annotation

GitHub Actions / golangci-lint

errorf: should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...) (revive)
}
file, err := os.Open(network)
if err != nil {
return nil, thor.ForkConfig{}, errors.Wrap(err, "open genesis file")
Expand Down Expand Up @@ -444,8 +448,12 @@
}

peersCachePath := filepath.Join(instanceDir, "peers.cache")
peersCachePath = filepath.Clean(peersCachePath)
if _, err := os.Stat(peersCachePath); os.IsNotExist(err) {

Check failure on line 452 in cmd/thor/utils.go

View workflow job for this annotation

GitHub Actions / golangci-lint

only one cuddle assignment allowed before if statement (wsl)
log.Warn("failed to load peers cache", "err", err)
}

if data, err := ioutil.ReadFile(peersCachePath); err != nil {
if data, err := os.ReadFile(peersCachePath); err != nil {
if !os.IsNotExist(err) {
log.Warn("failed to load peers cache", "err", err)
}
Expand Down Expand Up @@ -518,7 +526,7 @@
handler = handleXGenesisID(handler, genesisID)
handler = handleXThorestVersion(handler)
handler = requestBodyLimit(handler)
srv := &http.Server{Handler: handler}
srv := &http.Server{Handler: handler, ReadHeaderTimeout: time.Millisecond * time.Duration(timeout)}

Check failure on line 529 in cmd/thor/utils.go

View workflow job for this annotation

GitHub Actions / golangci-lint

Addr, DisableGeneralOptionsHandler, TLSConfig, ReadTimeout, WriteTimeout, IdleTimeout, MaxHeaderBytes, TLSNextProto, ConnState, ErrorLog, BaseContext, ConnContext are missing in Server (exhaustivestruct)
var goes co.Goes
goes.Go(func() {
srv.Serve(listener)
Expand Down
20 changes: 13 additions & 7 deletions comm/peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
package comm

import (
"math/rand"
"crypto/rand"
"math/big"
mathRand "math/rand"
"sync"
"time"

Expand All @@ -24,10 +26,6 @@
maxKnownBlocks = 1024 // Maximum block IDs to keep in the known list (prevent DOS)
)

func init() {
rand.Seed(time.Now().UnixNano())
}

// Peer extends p2p.Peer with RPC integrated.
type Peer struct {
*p2p.Peer
Expand Down Expand Up @@ -84,7 +82,15 @@
// MarkTransaction marks a transaction to known.
func (p *Peer) MarkTransaction(hash thor.Bytes32) {
// that's 10~100 block intervals
expiration := mclock.AbsTime(time.Second * time.Duration(thor.BlockInterval*uint64(rand.Intn(91)+10)))
randomValue, err := rand.Int(rand.Reader, big.NewInt(91))

Check failure on line 85 in comm/peer.go

View workflow job for this annotation

GitHub Actions / golangci-lint

mnd: Magic number: 91, in <argument> detected (gomnd)
if err != nil {
log.Warn("failed to generate random value", "err", err)
return

Check failure on line 88 in comm/peer.go

View workflow job for this annotation

GitHub Actions / golangci-lint

return with no blank line before (nlreturn)
}

// Add 10 to the random value to get a number in the range [10, 100].
interval := randomValue.Int64() + 10

Check failure on line 92 in comm/peer.go

View workflow job for this annotation

GitHub Actions / golangci-lint

mnd: Magic number: 10, in <operation> detected (gomnd)
expiration := mclock.AbsTime(time.Second * time.Duration(thor.BlockInterval*uint64(interval)))

deadline := mclock.Now() + expiration
p.knownTxs.Add(hash, deadline)
Expand Down Expand Up @@ -183,7 +189,7 @@
defer ps.lock.Unlock()

ret := make(Peers, len(ps.m))
perm := rand.Perm(len(ps.m))
perm := mathRand.Perm(len(ps.m))
i := 0
for _, s := range ps.m {
// randomly
Expand Down
22 changes: 14 additions & 8 deletions p2psrv/rpc/rpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

import (
"context"
"math/rand"
"crypto/rand"
"math/big"
"sync"
"time"

Expand All @@ -17,11 +18,6 @@
"github.com/pkg/errors"
)

func init() {
// required when generate call id
rand.Seed(time.Now().UnixNano())
}

const (
rpcDefaultTimeout = time.Second * 10
)
Expand Down Expand Up @@ -154,12 +150,22 @@
return nil
}

// generateRandomID generates a cryptographically secure random uint32.
func generateRandomID() (uint32, error) {
maxInt := big.NewInt(1<<32 - 1)
randomID, err := rand.Int(rand.Reader, maxInt)
if err != nil {

Check failure on line 157 in p2psrv/rpc/rpc.go

View workflow job for this annotation

GitHub Actions / golangci-lint

only one cuddle assignment allowed before if statement (wsl)
return 0, err
}
return uint32(randomID.Int64()), nil

Check failure on line 160 in p2psrv/rpc/rpc.go

View workflow job for this annotation

GitHub Actions / golangci-lint

return statements should not be cuddled if block has more than two lines (wsl)
}

func (r *RPC) prepareCall(msgCode uint64, onResult func(*p2p.Msg) error) uint32 {
r.lock.Lock()
defer r.lock.Unlock()
for {
id := rand.Uint32()
if id == 0 {
id, err := generateRandomID()
if id == 0 || err != nil {
// 0 id is taken by Notify
continue
}
Expand Down
6 changes: 6 additions & 0 deletions txpool/blocklist.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"sync"

Expand All @@ -27,6 +28,10 @@

// Load load list from local file.
func (bl *blocklist) Load(path string) error {
path = filepath.Clean(path)
if _, err := os.Stat(path); os.IsNotExist(err) {
return fmt.Errorf("the path [%v] does not exist", path)

Check failure on line 33 in txpool/blocklist.go

View workflow job for this annotation

GitHub Actions / golangci-lint

err113: do not define dynamic errors, use wrapped static errors instead: "fmt.Errorf(\"the path [%v] does not exist\", path)" (goerr113)
}
file, err := os.Open(path)
if err != nil {
return err
Expand All @@ -47,6 +52,7 @@

// Save save list to local file.
func (bl *blocklist) Save(path string) error {
path = filepath.Clean(path)
file, err := os.Create(path)
if err != nil {
return err
Expand Down
14 changes: 11 additions & 3 deletions txpool/tx_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@

import (
"context"
"math/rand"
"crypto/rand"
"errors"
"math/big"
"os"
"sync/atomic"
"time"
Expand Down Expand Up @@ -161,7 +163,7 @@
var eTag string
fetch := func() {
if err := p.blocklist.Fetch(p.ctx, url, &eTag); err != nil {
if err == context.Canceled {
if errors.Is(err, context.Canceled) {
return
}
log.Warn("blocklist fetch failed", "error", err, "url", url)
Expand All @@ -180,8 +182,14 @@
fetch()

for {

// delay 1~2 min
delay := time.Second * time.Duration(rand.Int()%60+60)
randomNum, err := rand.Int(rand.Reader, new(big.Int).Sub(big.NewInt(121), big.NewInt(60)))

Check failure on line 187 in txpool/tx_pool.go

View workflow job for this annotation

GitHub Actions / golangci-lint

mnd: Magic number: 121, in <argument> detected (gomnd)
if err != nil {
randomNum = big.NewInt(90)

Check failure on line 189 in txpool/tx_pool.go

View workflow job for this annotation

GitHub Actions / golangci-lint

mnd: Magic number: 90, in <argument> detected (gomnd)
}

delay := time.Second * time.Duration(randomNum.Int64())
select {
case <-p.ctx.Done():
return
Expand Down
Loading
Loading