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

Add Linters #97

Merged
merged 6 commits into from
Jul 11, 2024
Merged
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
33 changes: 28 additions & 5 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,46 @@ run:

linters:
enable:
- whitespace
- gosec
- whitespace # Tool for detection of leading and trailing whitespace
- gosec # Security problems
- gci
- misspell
- misspell # Misspelled English words in comments
- gomnd
- gofmt
- goimports
- gofmt # Whether the code was gofmt-ed
- goimports # Unused imports
- revive
- wastedassign # Finds wasted assignment statements
- unconvert # Unnecessary type conversions
- prealloc # Finds slice declarations that could potentially be pre-allocated
- predeclared # Finds code that shadows one of Go's predeclared identifiers
- nolintlint # Ill-formed or insufficient nolint directives
- makezero # Finds slice declarations with non-zero initial length
- importas # Enforces consistent import aliases
- dogsled # Checks assignments with too many blank identifiers (e.g. x, , , _, := f())
- errname # Checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error
- goconst # Repeated strings that could be replaced by a constant
- forcetypeassert # Finds forced type assertions
- tparallel # Detects inappropriate usage of t.Parallel() method in your Go test codes
- thelper # Detects golang test helpers without t.Helper() call and checks the consistency of test helpers
- errcheck # Errcheck is a go lint rule for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- lll # Long lines

linters-settings:
revive:
rules:
- name: exported
arguments:
- disableStutteringCheck
goconst:
min-len: 4
min-occurrences: 3

issues:
exclude-rules:
- path: _test\.go
linters:
- gosec
- lll
include:
- EXC0012 # EXC0012 revive: Annoying issue about not having a comment. The rare codebase has such comments
- EXC0014 # EXC0014 revive: Annoying issue about not having a comment. The rare codebase has such comments
8 changes: 8 additions & 0 deletions client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import (
)

func TestClient_GetStatus(t *testing.T) {
t.Parallel()

tests := []struct {
name string
result string
Expand Down Expand Up @@ -80,6 +82,8 @@ func TestClient_GetStatus(t *testing.T) {
}

func TestClient_SignSequence(t *testing.T) {
t.Parallel()

tests := []struct {
name string
ss types.SignedSequence
Expand Down Expand Up @@ -163,6 +167,8 @@ func TestClient_SignSequence(t *testing.T) {
}

func TestClient_GetOffChainData(t *testing.T) {
t.Parallel()

tests := []struct {
name string
hash common.Hash
Expand Down Expand Up @@ -234,6 +240,8 @@ func TestClient_GetOffChainData(t *testing.T) {
}

func TestClient_ListOffChainData(t *testing.T) {
t.Parallel()

tests := []struct {
name string
hashes []common.Hash
Expand Down
7 changes: 6 additions & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,12 @@ func Load(ctx *cli.Context) (*Config, error) {

decodeHooks := []viper.DecoderConfigOption{
// this allows arrays to be decoded from env var separated by ",", example: MY_VAR="value1,value2,value3"
viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(mapstructure.TextUnmarshallerHookFunc(), mapstructure.StringToSliceHookFunc(","))),
viper.DecodeHook(
mapstructure.ComposeDecodeHookFunc(
mapstructure.TextUnmarshallerHookFunc(),
mapstructure.StringToSliceHookFunc(","),
),
),
}
err = viper.Unmarshal(&cfg, decodeHooks...)
return cfg, err
Expand Down
18 changes: 18 additions & 0 deletions db/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (
)

func Test_DB_StoreLastProcessedBlock(t *testing.T) {
t.Parallel()

testTable := []struct {
name string
task string
Expand Down Expand Up @@ -69,6 +71,8 @@ func Test_DB_StoreLastProcessedBlock(t *testing.T) {
}

func Test_DB_GetLastProcessedBlock(t *testing.T) {
t.Parallel()

testTable := []struct {
name string
task string
Expand Down Expand Up @@ -133,6 +137,8 @@ func Test_DB_GetLastProcessedBlock(t *testing.T) {
}

func Test_DB_StoreUnresolvedBatchKeys(t *testing.T) {
t.Parallel()

testTable := []struct {
name string
bk []types.BatchKey
Expand Down Expand Up @@ -212,6 +218,8 @@ func Test_DB_StoreUnresolvedBatchKeys(t *testing.T) {
}

func Test_DB_GetUnresolvedBatchKeys(t *testing.T) {
t.Parallel()

testTable := []struct {
name string
bks []types.BatchKey
Expand Down Expand Up @@ -277,6 +285,8 @@ func Test_DB_GetUnresolvedBatchKeys(t *testing.T) {
}

func Test_DB_DeleteUnresolvedBatchKeys(t *testing.T) {
t.Parallel()

testTable := []struct {
name string
bks []types.BatchKey
Expand Down Expand Up @@ -343,6 +353,8 @@ func Test_DB_DeleteUnresolvedBatchKeys(t *testing.T) {
}

func Test_DB_StoreOffChainData(t *testing.T) {
t.Parallel()

testTable := []struct {
name string
od []types.OffChainData
Expand Down Expand Up @@ -422,6 +434,8 @@ func Test_DB_StoreOffChainData(t *testing.T) {
}

func Test_DB_GetOffChainData(t *testing.T) {
t.Parallel()

testTable := []struct {
name string
od []types.OffChainData
Expand Down Expand Up @@ -505,6 +519,8 @@ func Test_DB_GetOffChainData(t *testing.T) {
}

func Test_DB_ListOffChainData(t *testing.T) {
t.Parallel()

testTable := []struct {
name string
od []types.OffChainData
Expand Down Expand Up @@ -638,6 +654,8 @@ func Test_DB_ListOffChainData(t *testing.T) {
}

func Test_DB_CountOffchainData(t *testing.T) {
t.Parallel()

testTable := []struct {
name string
od []types.OffChainData
Expand Down
6 changes: 4 additions & 2 deletions log/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ package log
// Config for log
type Config struct {
// Environment defining the log format ("production" or "development").
// In development mode enables development mode (which makes DPanicLevel logs panic), uses a console encoder, writes to standard error, and disables sampling. Stacktraces are automatically included on logs of WarnLevel and above.
// In development mode enables development mode (which makes DPanicLevel logs panic),
// uses a console encoder, writes to standard error, and disables sampling.
// Stacktraces are automatically included on logs of WarnLevel and above.
// Check [here](https://pkg.go.dev/go.uber.org/zap@v1.24.0#NewDevelopmentConfig)
Environment Environment `mapstructure:"Environment" jsonschema:"enum=production,enum=development"`
// Level of log. As lower value more logs are going to be generated
Level string `mapstructure:"Level" jsonschema:"enum=debug,enum=info,enum=warn,enum=error,enum=dpanic,enum=panic,enum=fatal"`
Level string `mapstructure:"Level" jsonschema:"enum=debug,enum=info,enum=warn,enum=error,enum=dpanic,enum=panic,enum=fatal"` //nolint:lll
// Outputs
Outputs []string `mapstructure:"Outputs"`
}
2 changes: 1 addition & 1 deletion log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func NewLogger(cfg Config) (*zap.SugaredLogger, *zap.AtomicLevel, error) {
if err != nil {
return nil, nil, err
}
defer logger.Sync() //nolint:gosec,errcheck
defer logger.Sync() //nolint:errcheck

// skip 2 callers: one for our wrapper methods and one for the package functions
withOptions := logger.WithOptions(zap.AddCallerSkip(2)) //nolint:gomnd
Expand Down
2 changes: 2 additions & 0 deletions rpc/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
)

func Test_JSONRPCCallWithContext(t *testing.T) {
t.Parallel()

tests := []struct {
name string
result string
Expand Down
4 changes: 2 additions & 2 deletions rpc/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ const (
)

var (
// invalidJSONReqErr denotes error that is returned when invalid JSON request is received
invalidJSONReqErr = errors.New("Invalid json request")
// errInvalidJSONReq denotes error that is returned when invalid JSON request is received
errInvalidJSONReq = errors.New("invalid json request")
)

// Error interface
Expand Down
15 changes: 12 additions & 3 deletions rpc/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,11 @@ func (h *Handler) Handle(req handleRequest) Response {
// check params passed by request match function params
var testStruct []interface{}
if err := json.Unmarshal(req.Params, &testStruct); err == nil && len(testStruct) > fd.numParams() {
return NewResponse(req.Request, nil, NewRPCError(InvalidParamsErrorCode, fmt.Sprintf("too many arguments, want at most %d", fd.numParams())))
return NewResponse(
req.Request,
nil,
NewRPCError(InvalidParamsErrorCode, fmt.Sprintf("too many arguments, want at most %d", fd.numParams())),
)
}

inputs := make([]interface{}, fd.numParams()-inArgsOffset)
Expand Down Expand Up @@ -161,7 +165,7 @@ func (h *Handler) HandleWs(reqBody []byte, wsConn *websocket.Conn, httpReq *http
log.Debugf("WS message received: %v", string(reqBody))
var req Request
if err := json.Unmarshal(reqBody, &req); err != nil {
return NewResponse(req, nil, NewRPCError(InvalidRequestErrorCode, invalidJSONReqErr.Error())).Bytes()
return NewResponse(req, nil, NewRPCError(InvalidRequestErrorCode, errInvalidJSONReq.Error())).Bytes()
}

handleReq := handleRequest{
Expand Down Expand Up @@ -254,7 +258,12 @@ func validateFunc(funcName string, fv reflect.Value, isMethod bool) (inNum int,
return
}
if !isRPCErrorType(ft.Out(1)) {
err = fmt.Errorf("unexpected type for the second return value of the function '%s': '%s'. Expected '%s'", funcName, ft.Out(1), rpcErrType)
err = fmt.Errorf(
"unexpected type for the second return value of the function '%s': '%s'. Expected '%s'",
funcName,
ft.Out(1),
rpcErrType,
)
return
}

Expand Down
11 changes: 7 additions & 4 deletions rpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,10 @@ func (s *Server) handle(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
w.Header().Set(
"Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization",
)

if (*req).Method == "OPTIONS" {
// TODO(pg): need to count it in the metrics?
Expand Down Expand Up @@ -156,7 +159,7 @@ func (s *Server) isSingleRequest(data []byte) (bool, Error) {
x := bytes.TrimLeft(data, " \t\r\n")

if len(x) == 0 {
return false, NewRPCError(InvalidRequestErrorCode, invalidJSONReqErr.Error())
return false, NewRPCError(InvalidRequestErrorCode, errInvalidJSONReq.Error())
}

return x[0] == '{', nil
Expand Down Expand Up @@ -213,7 +216,7 @@ func (s *Server) parseRequest(data []byte) (Request, error) {
var req Request

if err := json.Unmarshal(data, &req); err != nil {
return Request{}, NewRPCError(InvalidRequestErrorCode, invalidJSONReqErr.Error())
return Request{}, NewRPCError(InvalidRequestErrorCode, errInvalidJSONReq.Error())
}

return req, nil
Expand All @@ -223,7 +226,7 @@ func (s *Server) parseRequests(data []byte) ([]Request, error) {
var requests []Request

if err := json.Unmarshal(data, &requests); err != nil {
return nil, NewRPCError(InvalidRequestErrorCode, invalidJSONReqErr.Error())
return nil, NewRPCError(InvalidRequestErrorCode, errInvalidJSONReq.Error())
}

return requests, nil
Expand Down
2 changes: 1 addition & 1 deletion rpc/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ func Test_ServerHandleRequest(t *testing.T) {
server.handle(respRecorder, httpReq)

require.Equal(t, http.StatusInternalServerError, respRecorder.Result().StatusCode)
require.Equal(t, invalidJSONReqErr.Error(), respRecorder.Body.String())
require.Equal(t, errInvalidJSONReq.Error(), respRecorder.Body.String())
})

t.Run("GET method request", func(t *testing.T) {
Expand Down
7 changes: 6 additions & 1 deletion sequencer/call_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import (
)

func Test_GetData(t *testing.T) {
t.Parallel()

tests := []struct {
name string
batchNum uint64
Expand Down Expand Up @@ -72,7 +74,10 @@ func Test_GetData(t *testing.T) {
var params []interface{}
require.NoError(t, json.Unmarshal(res.Params, &params))
require.Equal(t, float64(tt.batchNum), params[0])
require.True(t, params[1].(bool))

boolVal, ok := params[1].(bool)
require.True(t, ok, "params[1] is not of type bool")
require.True(t, boolVal)

if tt.statusCode > 0 {
w.WriteHeader(tt.statusCode)
Expand Down
3 changes: 2 additions & 1 deletion services/datacom/datacom.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ func (d *Endpoints) SignSequence(signedSequence types.SignedSequence) (interface

// Store off-chain data by hash (hash(L2Data): L2Data)
if err = d.db.StoreOffChainData(context.Background(), signedSequence.Sequence.OffChainData()); err != nil {
return "0x0", rpc.NewRPCError(rpc.DefaultErrorCode, fmt.Errorf("failed to store offchain data. Error: %w", err).Error())
return "0x0", rpc.NewRPCError(rpc.DefaultErrorCode,
fmt.Errorf("failed to store offchain data. Error: %w", err).Error())
}

// Sign
Expand Down
2 changes: 2 additions & 0 deletions services/datacom/datacom_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ func TestDataCom_SignSequence(t *testing.T) {
require.NoError(t, err)

testFn := func(t *testing.T, cfg testConfig) {
t.Helper()

var (
signer = privateKey
signedSequence *types.SignedSequence
Expand Down
13 changes: 9 additions & 4 deletions services/status/status_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
)

func TestEndpoints_GetStatus(t *testing.T) {
t.Parallel()

tests := []struct {
name string
countOffchainData uint64
Expand Down Expand Up @@ -60,10 +62,13 @@ func TestEndpoints_GetStatus(t *testing.T) {
} else {
require.NoError(t, err)

require.NotEmpty(t, actual.(types.DACStatus).Uptime)
require.Equal(t, "v0.1.0", actual.(types.DACStatus).Version)
require.Equal(t, tt.countOffchainData, actual.(types.DACStatus).KeyCount)
require.Equal(t, tt.getLastProcessedBlock, actual.(types.DACStatus).BackfillProgress)
dacStatus, ok := actual.(types.DACStatus)
require.True(t, ok, "actual is not of type types.DACStatus")

require.NotEmpty(t, dacStatus.Uptime)
require.Equal(t, "v0.1.0", dacStatus.Version)
require.Equal(t, tt.countOffchainData, dacStatus.KeyCount)
require.Equal(t, tt.getLastProcessedBlock, dacStatus.BackfillProgress)
}
})
}
Expand Down
4 changes: 4 additions & 0 deletions services/sync/sync_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import (
)

func TestEndpoints_GetOffChainData(t *testing.T) {
t.Parallel()

tests := []struct {
name string
hash types.ArgHash
Expand Down Expand Up @@ -68,6 +70,8 @@ func TestEndpoints_GetOffChainData(t *testing.T) {
}

func TestSyncEndpoints_ListOffChainData(t *testing.T) {
t.Parallel()

tests := []struct {
name string
hashes []types.ArgHash
Expand Down
Loading
Loading