Skip to content

Commit

Permalink
Adapt .golangci.yml to latest version and fix linter issues
Browse files Browse the repository at this point in the history
  • Loading branch information
muXxer committed Mar 20, 2024
1 parent 37f5cfe commit ed18f27
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 58 deletions.
83 changes: 61 additions & 22 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,104 +6,144 @@ linters-settings:
simplify: true
goimports:
local-prefixes: github.com/iotaledger
golint:
min-confidence: 0.9
gocyclo:
min-complexity: 15
govet:
check-shadowing: false
disable:
- shadow
misspell:
locale: US
staticcheck:
checks: ["all"]
nlreturn:
block-size: 3
block-size: 2
stylecheck:
initialisms: ["ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "QPS", "RAM", "RPC", "SLA", "SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "GID", "UID", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS", "SIP", "RTP", "AMQP", "DB", "TS"]
depguard:
rules:
main:
deny:
- pkg: "errors"
desc: Should be replaced with "github.com/iotaledger/hive.go/ierrors" package
- pkg: "golang.org/x/xerrors"
desc: Should be replaced with "github.com/iotaledger/hive.go/ierrors" package
- pkg: "github.com/pkg/errors"
desc: Should be replaced with "github.com/iotaledger/hive.go/ierrors" package

linters:
# Disable all linters.
disable-all: true
# Enable specific linter
enable:
- deadcode
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- typecheck
- unused
- varcheck
- asasalint
- asciicheck
- bidichk
- bodyclose
- containedctx
- contextcheck
#- containedctx
#- contextcheck # this linter is buggy and renders all nolint rules useless
- copyloopvar
#- cyclop
- decorder
#- depguard
- depguard
- dogsled
- dupl
- dupword
- durationcheck
- errchkjson
- errname
- errorlint
- execinquery
- exhaustive
#- exhaustive
#- exhaustruct
- exportloopref
#- forbidigo
- forcetypeassert
#- funlen
#- gci
- ginkgolinter
- gocheckcompilerdirectives
#- gochecknoglobals
#- gochecknoinits
#- gochecksumtype
#- gocognit
- goconst
- gocritic
#- gocyclo
- godot
- godox
#- goerr113
- goerr113
- gofmt
#- gofumpt
- goheader
- goimports
- golint
#- gomnd
- gomoddirectives
#- gomoddirectives
- gomodguard
- goprintffuncname
- gosec
- gosmopolitan
- grouper
- ifshort
- importas
- interfacer
- inamedparam
#- interfacebloat
- intrange
#- ireturn
#- lll
- loggercheck
#- maintidx
- makezero
- maligned
- mirror
- misspell
- musttag
- nakedret
#- nestif
- nilerr
- nilnil
- nlreturn
- noctx
- nolintlint
- nonamedreturns
- nosnakecase
- nosprintfhostport
- paralleltest
#- perfsprint
- prealloc
- predeclared
- promlinter
- protogetter
- reassign
- revive
- rowserrcheck
- scopelint
- sloglint
- spancheck
- sqlclosecheck
- structcheck
- stylecheck
#- tagalign
- tagliatelle
- tenv
- testableexamples
- testifylint
- testpackage
#- thelper
- thelper
- tparallel
- unconvert
- unparam
- usestdlibvars
#- varnamelen
- wastedassign
- whitespace
#- wrapcheck
#- wsl
- zerologlint

issues:
exclude-files:
- ".*_test.go$"
# Maximum issues count per one linter.
# Set to 0 to disable.
# Default: 50
Expand Down Expand Up @@ -131,4 +171,3 @@ issues:
# - "blank-imports" # revive
# - "var-naming: don't use leading k in Go names;" #revive
# - 'shadow: declaration of "err"' # govet

16 changes: 6 additions & 10 deletions components/faucet/component.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ type dependencies struct {
}

func provide(c *dig.Container) error {

// we use a restricted address for the faucet, so we don't need to filter indexer requests.
// we only allow to receive mana, the rest is blocked.
faucetAddressRestricted, faucetSigner, err := getRestrictedFaucetAddressAndSigner()
Expand Down Expand Up @@ -97,7 +96,6 @@ func provide(c *dig.Container) error {
}

if err := c.Provide(func(deps faucetDeps) (*faucet.Faucet, error) {

fetchTransactionMetadata := func(transactionID iotago.TransactionID) (*api.TransactionMetadataResponse, error) {
ctx, cancel := context.WithTimeout(Component.Daemon().ContextStopped(), 5*time.Second)
defer cancel()
Expand Down Expand Up @@ -205,7 +203,7 @@ func provide(c *dig.Container) error {
continue
}

lastAcceptedBlockSlot := iotago.SlotIndex(deps.NodeBridge.NodeStatus().LastAcceptedBlockSlot)
lastAcceptedBlockSlot := iotago.SlotIndex(deps.NodeBridge.NodeStatus().GetLastAcceptedBlockSlot())
if output.UnlockConditionSet().HasTimelockUntil(lastAcceptedBlockSlot) {
// ignore timelocked outputs for balance calculation
continue
Expand Down Expand Up @@ -240,7 +238,7 @@ func provide(c *dig.Container) error {
}

getLatestSlot := func() iotago.SlotIndex {
return iotago.SlotIndex(deps.NodeBridge.NodeStatus().LastAcceptedBlockSlot)
return iotago.SlotIndex(deps.NodeBridge.NodeStatus().GetLastAcceptedBlockSlot())
}

submitTransactionPayload := func(ctx context.Context, builder *builder.TransactionBuilder, storedManaOutputIndex int, numPoWWorkers ...int) (iotago.ApplicationPayload, iotago.BlockID, error) {
Expand Down Expand Up @@ -269,7 +267,7 @@ func provide(c *dig.Container) error {
faucetAddressRestricted,
faucetSigner,
faucet.WithLogger(Component.Logger),
faucet.WithTokenName(deps.NodeBridge.NodeConfig().BaseToken.Name),
faucet.WithTokenName(deps.NodeBridge.NodeConfig().GetBaseToken().GetName()),
faucet.WithBaseTokenAmount(iotago.BaseToken(ParamsFaucet.BaseTokenAmount)),
faucet.WithBaseTokenAmountSmall(iotago.BaseToken(ParamsFaucet.BaseTokenAmountSmall)),
faucet.WithBaseTokenAmountMaxTarget(iotago.BaseToken(ParamsFaucet.BaseTokenAmountMaxTarget)),
Expand All @@ -291,7 +289,6 @@ func provide(c *dig.Container) error {
}

func run() error {

// create a background worker that handles the accepted transactions
if err := Component.Daemon().BackgroundWorker("Faucet[ListenToAcceptedTransactions]", func(ctx context.Context) {
if err := deps.NodeBridge.ListenToAcceptedTransactions(ctx, func(tx *nodebridge.AcceptedTransaction) error {
Expand Down Expand Up @@ -349,20 +346,19 @@ func run() error {
func loadEd25519PrivateKeysFromEnvironment(name string) ([]ed25519.PrivateKey, error) {
keys, exists := os.LookupEnv(name)
if !exists {
return nil, fmt.Errorf("environment variable '%s' not set", name)
return nil, ierrors.Errorf("environment variable '%s' not set", name)
}

if len(keys) == 0 {
return nil, fmt.Errorf("environment variable '%s' not set", name)
return nil, ierrors.Errorf("environment variable '%s' not set", name)
}

privateKeysSplitted := strings.Split(keys, ",")
privateKeys := make([]ed25519.PrivateKey, len(privateKeysSplitted))
for i, key := range privateKeysSplitted {
privateKey, err := crypto.ParseEd25519PrivateKeyFromString(key)
if err != nil {
return nil, fmt.Errorf("environment variable '%s' contains an invalid private key '%s'", name, key)

return nil, ierrors.Errorf("environment variable '%s' contains an invalid private key '%s'", name, key)
}
privateKeys[i] = privateKey
}
Expand Down
1 change: 0 additions & 1 deletion components/faucet/frontend.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/labstack/echo/v4"
)

//nolint:typecheck // the linter can't find the files in the git submodule
//go:embed frontend/public
var distFiles embed.FS

Expand Down
1 change: 0 additions & 1 deletion components/faucet/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ func addFaucetOutputToQueue(c echo.Context) (*faucet.EnqueueResponse, error) {
}

func setupRoutes(e *echo.Echo) {

e.Pre(enforceMaxOneDotPerURL)

e.Group("/*").Use(frontendMiddleware())
Expand Down
18 changes: 4 additions & 14 deletions pkg/faucet/faucet.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
//nolint:nosnakecase // grpc uses underscores
package faucet

import (
Expand Down Expand Up @@ -99,7 +98,7 @@ type InfoResponse struct {
Balance iotago.BaseToken `json:"balance"`
// The name of the token of the faucet.
TokenName string `json:"tokenName"`
// The Bech32 human readable part of the the faucet.
// The Bech32 human readable part of the faucet.
Bech32HRP iotago.NetworkPrefix `json:"bech32Hrp"`
}

Expand Down Expand Up @@ -287,7 +286,6 @@ func New(
address iotago.Address,
addressSigner iotago.AddressSigner,
opts ...Option) *Faucet {

options := &Options{}
options.apply(defaultOptions...)
options.apply(opts...)
Expand Down Expand Up @@ -390,19 +388,16 @@ func (f *Faucet) Info() (*InfoResponse, error) {

// Enqueue adds a new faucet request to the queue.
func (f *Faucet) Enqueue(bech32Addr string) (*EnqueueResponse, error) {

addr, err := f.parseBech32Address(bech32Addr)
if err != nil {
return nil, err
}

if !f.isNodeHealthyFunc() {
//nolint:stylecheck,revive // this error message is shown to the user
return nil, ierrors.Wrap(echo.ErrInternalServerError, "Faucet node is not synchronized/healthy. Please try again later!")
}

if exists := f.isAlreadyinQueue(bech32Addr); exists {
//nolint:stylecheck,revive // this error message is shown to the user
return nil, ierrors.Wrap(httpserver.ErrInvalidParameter, "Address is already in the queue.")
}

Expand All @@ -412,7 +407,6 @@ func (f *Faucet) Enqueue(bech32Addr string) (*EnqueueResponse, error) {
baseTokenAmount = f.opts.baseTokenAmountSmall

if balance >= f.opts.baseTokenAmountMaxTarget {
//nolint:stylecheck,revive // this error message is shown to the user
return nil, ierrors.Wrap(httpserver.ErrInvalidParameter, "You already have enough funds on your address.")
}
}
Expand All @@ -423,7 +417,6 @@ func (f *Faucet) Enqueue(bech32Addr string) (*EnqueueResponse, error) {
defer f.Unlock()

if baseTokenAmount > f.faucetBalance {
//nolint:stylecheck,revive // this error message is shown to the user
return nil, ierrors.Wrap(echo.ErrInternalServerError, "Faucet does not have enough funds to process your request. Please try again later!")
}

Expand All @@ -445,7 +438,7 @@ func (f *Faucet) Enqueue(bech32Addr string) (*EnqueueResponse, error) {

default:
// queue is full
//nolint:stylecheck,revive // this error message is shown to the user

return nil, ierrors.Wrap(echo.ErrInternalServerError, "Faucet queue is full. Please try again later!")
}
}
Expand All @@ -465,13 +458,11 @@ func (f *Faucet) logSoftError(err error) {
func (f *Faucet) parseBech32Address(bech32Addr string) (iotago.Address, error) {
hrp, bech32Address, err := iotago.ParseBech32(bech32Addr)
if err != nil {
//nolint:stylecheck,revive // this error message is shown to the user
return nil, ierrors.Wrap(httpserver.ErrInvalidParameter, "Invalid bech32 address provided!")
}

protocolParams := f.apiProvider.CommittedAPI().ProtocolParameters()
if hrp != protocolParams.Bech32HRP() {
//nolint:stylecheck,revive // this error message is shown to the user
return nil, ierrors.Wrapf(httpserver.ErrInvalidParameter, "Invalid bech32 address provided! Address does not start with \"%s\".", protocolParams.Bech32HRP())
}

Expand Down Expand Up @@ -878,7 +869,6 @@ func (f *Faucet) collectRequestsAndSendFaucetBlock(ctx context.Context) error {

// RunFaucetLoop collects unspent outputs on the faucet address and batches the requests from the queue.
func (f *Faucet) RunFaucetLoop(ctx context.Context) error {

// set initial faucet balance
if err := f.computeAndSetInitialFaucetBalance(); err != nil {
return CriticalError(ierrors.Errorf("reading faucet address balance failed: %s, error: %w", f.address.Bech32(f.apiProvider.CommittedAPI().ProtocolParameters().Bech32HRP()), err))
Expand Down Expand Up @@ -911,7 +901,7 @@ func (f *Faucet) checkPendingTransactionState() {
f.LogDebug("entering checkPendingTransactionState...")
defer f.LogDebug("leaving checkPendingTransactionState...")

// nolint: nonamedreturns // easier to read in this case
//nolint:nonamedreturns // easier to read in this case
checkPendingTransaction := func(pendingTx *pendingTransaction) (clearPending bool, readdPending bool, logMessage string, softError error) {
if pendingTx == nil {
// no pending transaction so there is no need for additional checks
Expand Down Expand Up @@ -1008,7 +998,7 @@ func (f *Faucet) ApplyAcceptedTransaction(createdOutputs map[iotago.OutputID]str
f.LogDebug("entering ApplyAcceptedTransaction...")
defer f.LogDebug("leaving ApplyAcceptedTransaction...")

// nolint: nonamedreturns // easier to read in this case
//nolint:nonamedreturns // easier to read in this case
checkPendingTransaction := func(pendingTx *pendingTransaction) (clearPending bool, readdPending bool, logMessage string) {
if pendingTx == nil {
// no pending transaction so there is no need for additional checks
Expand Down
4 changes: 2 additions & 2 deletions pkg/faucet/test/testenv_go
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ func NewFaucetTestEnv(t *testing.T,

storeMessageFunc := func(ctx context.Context, block *iotago.Block) (iotago.BlockID, error) {
if block.ProtocolVersion != te.ProtocolParameters().Version {
return iotago.BlockID{}, fmt.Errorf("block has invalid protocol version %d instead of %d", block.ProtocolVersion, te.ProtocolParameters().Version)
return iotago.BlockID{}, ierrors.Errorf("block has invalid protocol version %d instead of %d", block.ProtocolVersion, te.ProtocolParameters().Version)
}

if len(block.Parents) == 0 {
Expand All @@ -237,7 +237,7 @@ func NewFaucetTestEnv(t *testing.T,

score := pow.Score(blk.Data())
if score < float64(MinPoWScore) {
return iotago.BlockID{}, fmt.Errorf("block has insufficient PoW score %0.2f", score)
return iotago.BlockID{}, ierrors.Errorf("block has insufficient PoW score %0.2f", score)
}

cmi := te.SyncManager().ConfirmedMilestoneIndex()
Expand Down
Loading

0 comments on commit ed18f27

Please sign in to comment.