From ca921ce550ae486ea1beb20eabf7fada213166a4 Mon Sep 17 00:00:00 2001 From: Quentin McGaw Date: Tue, 23 Nov 2021 16:46:37 +0100 Subject: [PATCH] chore(lint): check each `//nolint` and improve them (#2047) - remove unneeded `//nolint` comments - fix some of the lint-ignored errors - specify a linter that should be ignored as `//nolint:lintername` - add `nolintlint` linter to detect future unused `//nolint` comments - move exclude rules from golangci.yml to inlined `//nolint` so `nolintlint` can pick them up. --- .golangci.yml | 34 +++++++++-------------- cmd/gossamer/config.go | 2 +- cmd/gossamer/prune_test.go | 43 ++++++++++++++---------------- dot/core/messages.go | 2 +- dot/core/test_helpers.go | 2 +- dot/network/discovery_test.go | 7 +++-- dot/network/gossip.go | 2 +- dot/network/host.go | 2 +- dot/network/host_test.go | 2 +- dot/network/message.go | 2 +- dot/network/service.go | 14 +++++----- dot/network/utils.go | 2 +- dot/peerset/test_helpers.go | 2 +- dot/rpc/modules/author_test.go | 1 - dot/rpc/modules/state.go | 2 +- dot/rpc/modules/system.go | 2 +- dot/rpc/subscription/websocket.go | 7 ++--- dot/services.go | 2 +- dot/state/block.go | 2 +- dot/state/block_notify.go | 13 ++++----- dot/state/offline_pruner.go | 39 ++++++++++++++++++++++++--- dot/state/pruner/pruner.go | 5 ++-- dot/state/service_test.go | 2 +- dot/state/storage.go | 2 +- dot/state/transaction.go | 2 +- dot/sync/chain_processor.go | 2 +- dot/sync/chain_sync.go | 4 +-- dot/sync/message_test.go | 2 +- dot/sync/syncer_test.go | 2 +- dot/sync/test_helpers.go | 2 +- dot/telemetry/notify_finalized.go | 3 +-- dot/telemetry/system_interval.go | 4 +-- dot/telemetry/telemetry_test.go | 2 +- dot/types/babe.go | 4 +-- dot/types/inherents.go | 4 ++- lib/babe/babe_test.go | 4 +-- lib/babe/build.go | 6 ++--- lib/babe/build_test.go | 2 +- lib/babe/crypto.go | 22 +++++++-------- lib/babe/epoch.go | 6 ++--- lib/babe/epoch_test.go | 4 +-- lib/blocktree/blocktree.go | 6 ++--- lib/crypto/sr25519/sr25519.go | 19 ++++++++----- lib/genesis/helpers.go | 1 - lib/grandpa/errors.go | 1 - lib/grandpa/message.go | 2 +- lib/grandpa/message_handler.go | 16 ++++++----- lib/grandpa/network.go | 2 +- lib/grandpa/round_test.go | 14 +++++----- lib/grandpa/state.go | 2 +- lib/grandpa/types.go | 3 +-- lib/grandpa/vote_message.go | 2 +- lib/keystore/keystore.go | 2 +- lib/runtime/constants.go | 9 +++---- lib/runtime/life/exports.go | 9 +++---- lib/runtime/life/exports_test.go | 2 +- lib/runtime/life/resolver.go | 4 +-- lib/runtime/wasmer/exports.go | 11 ++++---- lib/runtime/wasmer/exports_test.go | 9 +++---- lib/runtime/wasmer/imports.go | 32 ++-------------------- lib/transaction/types.go | 3 --- lib/trie/database.go | 4 +-- lib/trie/database_test.go | 2 +- lib/trie/test_utils.go | 5 +++- lib/trie/trie.go | 4 +-- lib/trie/trie_test.go | 3 ++- pkg/scale/decode.go | 2 +- tests/stress/errors.go | 1 - tests/stress/grandpa_test.go | 2 +- tests/stress/helpers.go | 2 +- tests/stress/stress_test.go | 6 ++--- tests/utils/chain.go | 2 +- tests/utils/common.go | 11 +++++--- tests/utils/gossamer_utils.go | 23 +++++++++++----- tests/utils/request_utils.go | 2 +- tests/utils/rpc_methods.go | 2 +- 76 files changed, 243 insertions(+), 245 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index b28ac97af2..d5aa421ef1 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -87,6 +87,7 @@ linters: - megacheck - megacheck - misspell + - nolintlint - revive - staticcheck - unconvert @@ -125,21 +126,17 @@ issues: linters: - govet - # Exclude known linters from partially hard-vendored code, - # which is impossible to exclude via "nolint" comments. - - path: internal/hmac/ - text: "weak cryptographic primitive" + - text: "`finalized` is a misspelling of `finalised`" linters: - - gosec + - misspell - # Exclude some staticcheck messages - - linters: - - staticcheck - text: "SA9003:" + - text: "`finalize` is a misspelling of `finalise`" + linters: + - misspell - - linters: - - gosimple - text: "S1025:" + - text: "`initialize` is a misspelling of `initialise`" + linters: + - misspell - linters: - revive @@ -147,19 +144,12 @@ issues: - linters: - revive - text: "don't use ALL_CAPS in Go names;" - - - linters: - - revive + path: lib/runtime/life/ text: "don't use underscores in Go names;" - linters: - - gocyclo - text: "cyclomatic complexity 36 of func " #runtime/imports.go: registerImports - - - linters: - - gocyclo - text: "cyclomatic complexity 42 of func " # codec/decode.go: (*Decoder).DecodeTuple + - nolintlint + source: "^//nolint:revive" # Exclude lll issues for long lines with go:generate - linters: diff --git a/cmd/gossamer/config.go b/cmd/gossamer/config.go index be4f453d58..9f8864de32 100644 --- a/cmd/gossamer/config.go +++ b/cmd/gossamer/config.go @@ -26,8 +26,8 @@ import ( "github.com/urfave/cli" ) -//nolint var ( + // DefaultCfg is the default configuration for the node. DefaultCfg = dot.GssmrConfig defaultGssmrConfigPath = "./chain/gssmr/config.toml" defaultKusamaConfigPath = "./chain/kusama/config.toml" diff --git a/cmd/gossamer/prune_test.go b/cmd/gossamer/prune_test.go index 69d903005e..f04440f37d 100644 --- a/cmd/gossamer/prune_test.go +++ b/cmd/gossamer/prune_test.go @@ -12,32 +12,19 @@ import ( "github.com/stretchr/testify/require" ) -func iterateDB(db *badger.DB, cb func(*badger.Item)) { //nolint - txn := db.NewTransaction(false) - itr := txn.NewIterator(badger.DefaultIteratorOptions) - - for itr.Rewind(); itr.Valid(); itr.Next() { - cb(itr.Item()) - } -} - -func runPruneCmd(t *testing.T, configFile, prunedDBPath string) { //nolint - ctx, err := newTestContext( - "Test state trie offline pruning --prune-state", - []string{"config", "pruned-db-path", "bloom-size", "retain-blocks"}, - []interface{}{configFile, prunedDBPath, "256", int64(5)}, - ) - require.NoError(t, err) - - command := pruningCommand - err = command.Run(ctx) - require.NoError(t, err) -} - func TestPruneState(t *testing.T) { t.Skip() // this fails due to being unable to call blockState.GetHighestFinalisedHash() when initialising the blockstate // need to regenerate the test database and/or move this to the state package (which would make sense) + iterateDB := func(db *badger.DB, cb func(*badger.Item)) { + txn := db.NewTransaction(false) + itr := txn.NewIterator(badger.DefaultIteratorOptions) + + for itr.Rewind(); itr.Valid(); itr.Next() { + cb(itr.Item()) + } + } + var ( inputDBPath = "../../tests/data/db" configFile = "../../tests/data/db/config.toml" @@ -67,7 +54,17 @@ func TestPruneState(t *testing.T) { t.Log("Total keys in input DB", numStorageKeys+len(nonStorageKeys), "storage keys", numStorageKeys) t.Log("pruned DB path", prunedDBPath) - runPruneCmd(t, configFile, prunedDBPath) + // Run Prune command + ctx, err := newTestContext( + "Test state trie offline pruning --prune-state", + []string{"config", "pruned-db-path", "bloom-size", "retain-blocks"}, + []interface{}{configFile, prunedDBPath, "256", int64(5)}, + ) + require.NoError(t, err) + + command := pruningCommand + err = command.Run(ctx) + require.NoError(t, err) prunedDB, err := badger.Open(badger.DefaultOptions(prunedDBPath)) require.NoError(t, err) diff --git a/dot/core/messages.go b/dot/core/messages.go index 4418b433a5..53e9834cea 100644 --- a/dot/core/messages.go +++ b/dot/core/messages.go @@ -46,7 +46,7 @@ func (s *Service) HandleTransactionMessage(peerID peer.ID, msg *network.Transact s.storageState.Lock() defer s.storageState.Unlock() - ts, err := s.storageState.TrieState(&head.StateRoot) //nolint + ts, err := s.storageState.TrieState(&head.StateRoot) if err != nil { return err } diff --git a/dot/core/test_helpers.go b/dot/core/test_helpers.go index e7272e57d5..27ae573b82 100644 --- a/dot/core/test_helpers.go +++ b/dot/core/test_helpers.go @@ -120,7 +120,7 @@ func NewTestService(t *testing.T, cfg *Config) *Service { if cfg.CodeSubstitutes == nil { cfg.CodeSubstitutes = make(map[common.Hash]string) - genesisData, err := cfg.CodeSubstitutedState.(*state.BaseState).LoadGenesisData() //nolint + genesisData, err := cfg.CodeSubstitutedState.(*state.BaseState).LoadGenesisData() require.NoError(t, err) for k, v := range genesisData.CodeSubstitutes { diff --git a/dot/network/discovery_test.go b/dot/network/discovery_test.go index 807412df3d..023cb38b03 100644 --- a/dot/network/discovery_test.go +++ b/dot/network/discovery_test.go @@ -47,8 +47,7 @@ func newTestDiscovery(t *testing.T, num int) []*discovery { return discs } -// nolint -func connectNoSync(t *testing.T, ctx context.Context, a, b *discovery) { +func connectNoSync(ctx context.Context, t *testing.T, a, b *discovery) { t.Helper() idB := b.h.ID() @@ -82,7 +81,7 @@ func TestKadDHT(t *testing.T) { defer cancel() // connects node 0 and node 2 - connectNoSync(t, ctx, nodes[2], nodes[0]) + connectNoSync(ctx, t, nodes[2], nodes[0]) time.Sleep(startDHTTimeout + 1) @@ -91,7 +90,7 @@ func TestKadDHT(t *testing.T) { require.ErrorIs(t, err, routing.ErrNotFound) // connects node 1 and node 0 - connectNoSync(t, ctx, nodes[1], nodes[0]) + connectNoSync(ctx, t, nodes[1], nodes[0]) time.Sleep(startDHTTimeout + 1) diff --git a/dot/network/gossip.go b/dot/network/gossip.go index 2e3633c822..55da229bd3 100644 --- a/dot/network/gossip.go +++ b/dot/network/gossip.go @@ -24,7 +24,7 @@ func newGossip() *gossip { } // hasSeen broadcasts messages that have not been seen -func (g *gossip) hasSeen(msg NotificationsMessage) bool { //nolint +func (g *gossip) hasSeen(msg NotificationsMessage) bool { // check if message has not been seen if seen, ok := g.seen.Load(msg.Hash()); !ok || !seen.(bool) { // set message to has been seen diff --git a/dot/network/host.go b/dot/network/host.go index 6adba8e72b..8a6d46a252 100644 --- a/dot/network/host.go +++ b/dot/network/host.go @@ -109,7 +109,7 @@ func newHost(ctx context.Context, cfg *Config) (*host, error) { privateIPs := ma.NewFilters() for _, cidr := range privateCIDRs { - _, ipnet, err := net.ParseCIDR(cidr) //nolint + _, ipnet, err := net.ParseCIDR(cidr) if err != nil { return nil, err } diff --git a/dot/network/host_test.go b/dot/network/host_test.go index a2f45cac9f..9b7e34dea8 100644 --- a/dot/network/host_test.go +++ b/dot/network/host_test.go @@ -32,7 +32,7 @@ func TestExternalAddrs(t *testing.T) { addrInfo := node.host.addrInfo() privateIPs := ma.NewFilters() for _, cidr := range privateCIDRs { - _, ipnet, err := net.ParseCIDR(cidr) //nolint + _, ipnet, err := net.ParseCIDR(cidr) require.NoError(t, err) privateIPs.AddFilter(*ipnet, ma.ActionDeny) } diff --git a/dot/network/message.go b/dot/network/message.go index 85d72bcb74..0c0ddeb0e8 100644 --- a/dot/network/message.go +++ b/dot/network/message.go @@ -39,7 +39,7 @@ type NotificationsMessage interface { IsHandshake() bool } -// nolint +//nolint:revive const ( RequestedDataHeader = byte(1) RequestedDataBody = byte(2) diff --git a/dot/network/service.go b/dot/network/service.go index 58c0167954..d29c341127 100644 --- a/dot/network/service.go +++ b/dot/network/service.go @@ -94,7 +94,7 @@ type Service struct { // NewService creates a new network service from the configuration and message channels func NewService(cfg *Config) (*Service, error) { - ctx, cancel := context.WithCancel(context.Background()) //nolint + ctx, cancel := context.WithCancel(context.Background()) logger.Patch(log.SetLevel(cfg.LogLvl)) cfg.logger = logger @@ -103,7 +103,7 @@ func NewService(cfg *Config) (*Service, error) { err := cfg.build() if err != nil { cancel() - return nil, err //nolint + return nil, err } if cfg.MinPeers == 0 { @@ -132,8 +132,8 @@ func NewService(cfg *Config) (*Service, error) { } // pre-allocate pool of buffers used to read from streams. - // initially allocate as many buffers as liekly necessary which is the number inbound streams we will have, - // which should equal average number of peers times the number of notifications protocols, which is currently 3. + // initially allocate as many buffers as likely necessary which is the number of inbound streams we will have, + // which should equal the average number of peers times the number of notifications protocols, which is currently 3. preAllocateInPool := cfg.MinPeers * 3 poolSize := cfg.MaxPeers * 3 if cfg.noPreAllocate { // testing @@ -407,17 +407,17 @@ func (s *Service) sentBlockIntervalTelemetry() { } bestHash := best.Hash() - finalized, err := s.blockState.GetHighestFinalisedHeader() //nolint + finalised, err := s.blockState.GetHighestFinalisedHeader() if err != nil { continue } - finalizedHash := finalized.Hash() + finalizedHash := finalised.Hash() err = telemetry.GetInstance().SendMessage(telemetry.NewBlockIntervalTM( &bestHash, best.Number, &finalizedHash, - finalized.Number, + finalised.Number, big.NewInt(int64(s.transactionHandler.TransactionsCount())), big.NewInt(0), // TODO: (ed) determine where to get used_state_cache_size (#1501) )) diff --git a/dot/network/utils.go b/dot/network/utils.go index fb16633a15..c36cdbd817 100644 --- a/dot/network/utils.go +++ b/dot/network/utils.go @@ -58,7 +58,7 @@ func generateKey(seed int64, fp string) (crypto.PrivKey, error) { if seed == 0 { r = crand.Reader } else { - r = mrand.New(mrand.NewSource(seed)) //nolint + r = mrand.New(mrand.NewSource(seed)) //nolint:gosec } key, _, err := crypto.GenerateEd25519Key(r) if err != nil { diff --git a/dot/peerset/test_helpers.go b/dot/peerset/test_helpers.go index ae8b116e86..1604f7623c 100644 --- a/dot/peerset/test_helpers.go +++ b/dot/peerset/test_helpers.go @@ -49,7 +49,7 @@ func newTestPeerSet(t *testing.T, in, out uint32, bootNodes, reservedPeers []pee return handler } -func newTestPeerState(t *testing.T, maxIn, maxOut uint32) *PeersState { //nolint +func newTestPeerState(t *testing.T, maxIn, maxOut uint32) *PeersState { t.Helper() state, err := NewPeerState([]*config{ { diff --git a/dot/rpc/modules/author_test.go b/dot/rpc/modules/author_test.go index da2f8d6d37..6324b5c465 100644 --- a/dot/rpc/modules/author_test.go +++ b/dot/rpc/modules/author_test.go @@ -178,7 +178,6 @@ func TestAuthorModule_SubmitExtrinsic(t *testing.T) { var testExt = common.MustHexToBytes("0x410284ffd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d01f8efbe48487e57a22abf7e3acd491b7f3528a33a111b1298601554863d27eb129eaa4e718e1365414ff3d028b62bebc651194c6b5001e5c2839b982757e08a8c0000000600ff8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a480b00c465f14670") // invalid transaction (above tx, with last byte changed) - //nolint var testInvalidExt = []byte{1, 212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125, 142, 175, 4, 21, 22, 135, 115, 99, 38, 201, 254, 161, 126, 37, 252, 82, 135, 97, 54, 147, 201, 18, 144, 156, 178, 38, 170, 71, 148, 242, 106, 72, 69, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 216, 5, 113, 87, 87, 40, 221, 120, 247, 252, 137, 201, 74, 231, 222, 101, 85, 108, 102, 39, 31, 190, 210, 14, 215, 124, 19, 160, 180, 203, 54, 110, 167, 163, 149, 45, 12, 108, 80, 221, 65, 238, 57, 237, 199, 16, 10, 33, 185, 8, 244, 184, 243, 139, 5, 87, 252, 245, 24, 225, 37, 154, 163, 143} type fields struct { diff --git a/dot/rpc/modules/state.go b/dot/rpc/modules/state.go index b38703e6a1..1e1d4ea225 100644 --- a/dot/rpc/modules/state.go +++ b/dot/rpc/modules/state.go @@ -173,7 +173,7 @@ func (sm *StateModule) GetPairs(_ *http.Request, req *StatePairRequest, res *Sta } if req.Prefix == nil || *req.Prefix == "" || *req.Prefix == "0x" { - pairs, err := sm.storageAPI.Entries(stateRootHash) //nolint + pairs, err := sm.storageAPI.Entries(stateRootHash) if err != nil { return err } diff --git a/dot/rpc/modules/system.go b/dot/rpc/modules/system.go index 322ab2c40c..c142e5a64d 100644 --- a/dot/rpc/modules/system.go +++ b/dot/rpc/modules/system.go @@ -259,7 +259,7 @@ func (sm *SystemModule) LocalListenAddresses(r *http.Request, req *EmptyRequest, } // LocalPeerId Returns the base58-encoded PeerId fo the node. -func (sm *SystemModule) LocalPeerId(r *http.Request, req *EmptyRequest, res *string) error { //nolint +func (sm *SystemModule) LocalPeerId(r *http.Request, req *EmptyRequest, res *string) error { netstate := sm.networkAPI.NetworkState() if netstate.PeerID == "" { return errors.New("peer id cannot be empty") diff --git a/dot/rpc/subscription/websocket.go b/dot/rpc/subscription/websocket.go index 0366db417b..cb53b91438 100644 --- a/dot/rpc/subscription/websocket.go +++ b/dot/rpc/subscription/websocket.go @@ -30,9 +30,6 @@ var errCannotReadFromWebsocket = errors.New("cannot read message from websocket" var errCannotUnmarshalMessage = errors.New("cannot unmarshal webasocket message data") var logger = log.NewFromGlobal(log.AddContext("pkg", "rpc/subscription")) -// DEFAULT_BUFFER_SIZE buffer size for channels -const DEFAULT_BUFFER_SIZE = 100 - // WSConn struct to hold WebSocket Connection references type WSConn struct { UnsafeEnabled bool @@ -97,7 +94,7 @@ func (c *WSConn) HandleComm() { continue } - listener, err := setupListener(reqid, params) //nolint + listener, err := setupListener(reqid, params) if err != nil { logger.Warnf("failed to create listener (method=%s): %s", method, err) continue @@ -107,7 +104,7 @@ func (c *WSConn) HandleComm() { continue } - listener, err := c.getUnsubListener(params) //nolint + listener, err := c.getUnsubListener(params) if err != nil { logger.Warnf("failed to get unsubscriber (method=%s): %s", method, err) diff --git a/dot/services.go b/dot/services.go index 2f1ae51064..81350134d9 100644 --- a/dot/services.go +++ b/dot/services.go @@ -88,7 +88,7 @@ func createRuntime(cfg *Config, ns runtime.NodeStorage, st *state.Service, ks *k if !codeSubHash.IsEmpty() { logger.Infof("🔄 detected runtime code substitution, upgrading to block hash %s...", codeSubHash) - genData, err := st.Base.LoadGenesisData() // nolint + genData, err := st.Base.LoadGenesisData() if err != nil { return nil, err } diff --git a/dot/state/block.go b/dot/state/block.go index dc1254fb3a..fed513514a 100644 --- a/dot/state/block.go +++ b/dot/state/block.go @@ -611,7 +611,7 @@ func (bs *BlockState) HandleRuntimeChanges(newState *rtstorage.TrieState, rt run codeSubBlockHash := bs.baseState.LoadCodeSubstitutedBlockHash() if !codeSubBlockHash.Equal(common.Hash{}) { - newVersion, err := rt.CheckRuntimeVersion(code) //nolint + newVersion, err := rt.CheckRuntimeVersion(code) if err != nil { return err } diff --git a/dot/state/block_notify.go b/dot/state/block_notify.go index ebafb99f08..168bd6b2d1 100644 --- a/dot/state/block_notify.go +++ b/dot/state/block_notify.go @@ -13,26 +13,24 @@ import ( "github.com/google/uuid" ) -// DEFAULT_BUFFER_SIZE buffer size for channels -const DEFAULT_BUFFER_SIZE = 128 +const defaultBufferSize = 128 // GetImportedBlockNotifierChannel function to retrieve a imported block notifier channel func (bs *BlockState) GetImportedBlockNotifierChannel() chan *types.Block { bs.importedLock.Lock() defer bs.importedLock.Unlock() - ch := make(chan *types.Block, DEFAULT_BUFFER_SIZE) + ch := make(chan *types.Block, defaultBufferSize) bs.imported[ch] = struct{}{} return ch } -//nolint -// GetFinalisedNotifierChannel function to retrieve a finalized block notifier channel +// GetFinalisedNotifierChannel function to retrieve a finalised block notifier channel func (bs *BlockState) GetFinalisedNotifierChannel() chan *types.FinalisationInfo { bs.finalisedLock.Lock() defer bs.finalisedLock.Unlock() - ch := make(chan *types.FinalisationInfo, DEFAULT_BUFFER_SIZE) + ch := make(chan *types.FinalisationInfo, defaultBufferSize) bs.finalised[ch] = struct{}{} return ch @@ -45,8 +43,7 @@ func (bs *BlockState) FreeImportedBlockNotifierChannel(ch chan *types.Block) { delete(bs.imported, ch) } -//nolint -// FreeFinalisedNotifierChannel to free finalized notifier channel +// FreeFinalisedNotifierChannel to free finalised notifier channel func (bs *BlockState) FreeFinalisedNotifierChannel(ch chan *types.FinalisationInfo) { bs.finalisedLock.Lock() defer bs.finalisedLock.Unlock() diff --git a/dot/state/offline_pruner.go b/dot/state/offline_pruner.go index be82536460..2dce8a9de0 100644 --- a/dot/state/offline_pruner.go +++ b/dot/state/offline_pruner.go @@ -76,8 +76,19 @@ func NewOfflinePruner(inputDBPath, prunedDBPath string, bloomSize uint64, retain } // SetBloomFilter loads keys with storage prefix of last `retainBlockNum` blocks into the bloom filter -func (p *OfflinePruner) SetBloomFilter() error { - defer p.inputDB.Close() // nolint: errcheck +func (p *OfflinePruner) SetBloomFilter() (err error) { + defer func() { + closeErr := p.inputDB.Close() + switch { + case closeErr == nil: + return + case err == nil: + err = fmt.Errorf("cannot close input database: %w", closeErr) + default: + logger.Errorf("cannot close input database: %s", err) + } + }() + finalisedHash, err := p.blockState.GetHighestFinalisedHash() if err != nil { return fmt.Errorf("failed to get highest finalised hash: %w", err) @@ -135,13 +146,33 @@ func (p *OfflinePruner) Prune() error { if err != nil { return fmt.Errorf("failed to load DB %w", err) } - defer inputDB.Close() // nolint: errcheck + defer func() { + closeErr := inputDB.Close() + switch { + case closeErr == nil: + return + case err == nil: + err = fmt.Errorf("cannot close input database: %w", closeErr) + default: + logger.Errorf("cannot close input database: %s", err) + } + }() prunedDB, err := utils.LoadBadgerDB(p.prunedDBPath) if err != nil { return fmt.Errorf("failed to load DB %w", err) } - defer prunedDB.Close() // nolint: errcheck + defer func() { + closeErr := prunedDB.Close() + switch { + case closeErr == nil: + return + case err == nil: + err = fmt.Errorf("cannot close pruned database: %w", closeErr) + default: + logger.Errorf("cannot close pruned database: %s", err) + } + }() writer := prunedDB.NewStreamWriter() if err = writer.Prepare(); err != nil { diff --git a/dot/state/pruner/pruner.go b/dot/state/pruner/pruner.go index cf8420b07d..8de049ed4e 100644 --- a/dot/state/pruner/pruner.go +++ b/dot/state/pruner/pruner.go @@ -20,9 +20,10 @@ const ( pruneInterval = time.Second ) -// nolint const ( - Full = Mode("full") + // Full pruner mode. + Full = Mode("full") + // Archive pruner mode. Archive = Mode("archive") ) diff --git a/dot/state/service_test.go b/dot/state/service_test.go index 617653114e..d770f772d8 100644 --- a/dot/state/service_test.go +++ b/dot/state/service_test.go @@ -216,7 +216,7 @@ func TestService_PruneStorage(t *testing.T) { for i := 0; i < 3; i++ { block, trieState := generateBlockWithRandomTrie(t, serv, nil, int64(i+1)) digest := types.NewDigest() - prd, err := types.NewBabeSecondaryPlainPreDigest(0, uint64(i+1)).ToPreRuntimeDigest() //nolint + prd, err := types.NewBabeSecondaryPlainPreDigest(0, uint64(i+1)).ToPreRuntimeDigest() require.NoError(t, err) err = digest.Add(*prd) require.NoError(t, err) diff --git a/dot/state/storage.go b/dot/state/storage.go index 120ceef79f..b4aae4f589 100644 --- a/dot/state/storage.go +++ b/dot/state/storage.go @@ -234,7 +234,7 @@ func (s *StorageState) GetStorageByBlockHash(bhash *common.Hash, key []byte) ([] ) if bhash != nil { - header, err := s.blockState.GetHeader(*bhash) //nolint + header, err := s.blockState.GetHeader(*bhash) if err != nil { return nil, err } diff --git a/dot/state/transaction.go b/dot/state/transaction.go index e3ea772b34..2eae056f46 100644 --- a/dot/state/transaction.go +++ b/dot/state/transaction.go @@ -90,7 +90,7 @@ func (s *TransactionState) GetStatusNotifierChannel(ext types.Extrinsic) chan tr s.notifierLock.Lock() defer s.notifierLock.Unlock() - ch := make(chan transaction.Status, DEFAULT_BUFFER_SIZE) + ch := make(chan transaction.Status, defaultBufferSize) s.notifierChannels[ch] = ext.String() return ch } diff --git a/dot/sync/chain_processor.go b/dot/sync/chain_processor.go index e688cb83b3..895b2c1ff2 100644 --- a/dot/sync/chain_processor.go +++ b/dot/sync/chain_processor.go @@ -109,7 +109,7 @@ func (s *chainProcessor) processBlockData(bd *types.BlockData) error { // so when the node restarts it has blocks higher than what it thinks is the best, causing it not to sync // if we update the node to only store finalised blocks in the database, this should be fixed and the entire // code block can be removed (#1784) - block, err := s.blockState.GetBlockByHash(bd.Hash) //nolint + block, err := s.blockState.GetBlockByHash(bd.Hash) if err != nil { logger.Debugf("failed to get block header for hash %s: %s", bd.Hash, err) return err diff --git a/dot/sync/chain_sync.go b/dot/sync/chain_sync.go index 7b0741f8e6..b9c084e106 100644 --- a/dot/sync/chain_sync.go +++ b/dot/sync/chain_sync.go @@ -51,7 +51,7 @@ var pendingBlocksLimit = maxResponseSize * 32 // peerState tracks our peers's best reported blocks type peerState struct { - who peer.ID //nolint + who peer.ID hash common.Hash number *big.Int } @@ -248,7 +248,7 @@ func (cs *chainSync) setPeerHead(p peer.ID, hash common.Hash, number *big.Int) e if ps.number.Cmp(head.Number) <= 0 { // check if our block hash for that number is the same, if so, do nothing // as we already have that block - ourHash, err := cs.blockState.GetHashByNumber(ps.number) //nolint + ourHash, err := cs.blockState.GetHashByNumber(ps.number) if err != nil { return err } diff --git a/dot/sync/message_test.go b/dot/sync/message_test.go index a6b376a590..2f7b4ffc12 100644 --- a/dot/sync/message_test.go +++ b/dot/sync/message_test.go @@ -427,7 +427,7 @@ func TestService_checkOrGetDescendantHash(t *testing.T) { // expected is non-canonical block 16 for _, leaf := range leaves { - is, err := s.blockState.IsDescendantOf(ancestor, leaf) //nolint + is, err := s.blockState.IsDescendantOf(ancestor, leaf) require.NoError(t, err) if is { expected = leaf diff --git a/dot/sync/syncer_test.go b/dot/sync/syncer_test.go index 185dafbf60..d6a966c0f3 100644 --- a/dot/sync/syncer_test.go +++ b/dot/sync/syncer_test.go @@ -89,7 +89,7 @@ func newTestSyncer(t *testing.T) *Service { } // initialise runtime - genState, err := rtstorage.NewTrieState(genTrie) //nolint + genState, err := rtstorage.NewTrieState(genTrie) require.NoError(t, err) rtCfg := &wasmer.Config{} diff --git a/dot/sync/test_helpers.go b/dot/sync/test_helpers.go index b7c7b265fc..4836e3cf30 100644 --- a/dot/sync/test_helpers.go +++ b/dot/sync/test_helpers.go @@ -54,7 +54,7 @@ func BuildBlock(t *testing.T, instance runtime.Instance, parent *types.Header, e // apply each inherent extrinsic for _, inherent := range inExts { - in, err := scale.Marshal(inherent) //nolint + in, err := scale.Marshal(inherent) require.NoError(t, err) ret, err := instance.ApplyExtrinsic(in) diff --git a/dot/telemetry/notify_finalized.go b/dot/telemetry/notify_finalized.go index 24a0e18c54..8323f3280d 100644 --- a/dot/telemetry/notify_finalized.go +++ b/dot/telemetry/notify_finalized.go @@ -7,9 +7,8 @@ import ( "github.com/ChainSafe/gossamer/lib/common" ) -//nolint // notifyFinalizedTM holds `notify.finalized` telemetry message, which is -// supposed to be send when a new block gets finalized. +// supposed to be send when a new block gets finalised. type notifyFinalizedTM struct { Best common.Hash `json:"best"` // Height is same as block.Header.Number diff --git a/dot/telemetry/system_interval.go b/dot/telemetry/system_interval.go index c097cc6e50..fa6128ca35 100644 --- a/dot/telemetry/system_interval.go +++ b/dot/telemetry/system_interval.go @@ -16,8 +16,8 @@ type systemIntervalTM struct { Peers int `json:"peers,omitempty"` BestHash *common.Hash `json:"best,omitempty"` BestHeight *big.Int `json:"height,omitempty"` - FinalisedHash *common.Hash `json:"finalized_hash,omitempty"` // nolint - FinalisedHeight *big.Int `json:"finalized_height,omitempty"` // nolint + FinalisedHash *common.Hash `json:"finalized_hash,omitempty"` + FinalisedHeight *big.Int `json:"finalized_height,omitempty"` TxCount *big.Int `json:"txcount,omitempty"` UsedStateCacheSize *big.Int `json:"used_state_cache_size,omitempty"` } diff --git a/dot/telemetry/telemetry_test.go b/dot/telemetry/telemetry_test.go index 5785f80d93..b8900a9621 100644 --- a/dot/telemetry/telemetry_test.go +++ b/dot/telemetry/telemetry_test.go @@ -49,7 +49,7 @@ func TestHandler_SendMulti(t *testing.T) { []byte(`{"authority":false,"chain":"chain","genesis_hash":"0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3","implementation":"systemName","msg":"system.connected","name":"nodeName","network_id":"netID","startup_time":"startTime","ts":`), []byte(`{"best":"0x07b749b6e20fd5f1159153a2e790235018621dd06072a62bcd25e8576f6ff5e6","height":2,"msg":"block.import","origin":"NetworkInitialSync","ts":`), []byte(`{"bandwidth_download":2,"bandwidth_upload":3,"msg":"system.interval","peers":1,"ts":`), - []byte(`{"best":"0x07b749b6e20fd5f1159153a2e790235018621dd06072a62bcd25e8576f6ff5e6","finalized_hash":"0x687197c11b4cf95374159843e7f46fbcd63558db981aaef01a8bac2a44a1d6b2","finalized_height":32256,"height":32375,"msg":"system.interval","ts":`), //nolint + []byte(`{"best":"0x07b749b6e20fd5f1159153a2e790235018621dd06072a62bcd25e8576f6ff5e6","finalized_hash":"0x687197c11b4cf95374159843e7f46fbcd63558db981aaef01a8bac2a44a1d6b2","finalized_height":32256,"height":32375,"msg":"system.interval","ts":`), []byte(`{"best":"0x07b749b6e20fd5f1159153a2e790235018621dd06072a62bcd25e8576f6ff5e6","height":"32375","msg":"notify.finalized","ts":`), []byte(`{"hash":"0x5814aec3e28527f81f65841e034872f3a30337cf6c33b2d258bba6071e37e27c","msg":"prepared_block_for_proposing","number":"1","ts":`), []byte(`{"future":2,"msg":"txpool.import","ready":1,"ts":`), diff --git a/dot/types/babe.go b/dot/types/babe.go index 2751275161..dfc2217793 100644 --- a/dot/types/babe.go +++ b/dot/types/babe.go @@ -25,9 +25,9 @@ type BabeConfiguration struct { // BABEAuthorityRawToAuthority turns a slice of BABE AuthorityRaw into a slice of Authority func BABEAuthorityRawToAuthority(adr []AuthorityRaw) ([]Authority, error) { ad := make([]Authority, len(adr)) - for i, r := range adr { + for i := range adr { ad[i] = Authority{} - err := ad[i].FromRawSr25519(&r) //nolint + err := ad[i].FromRawSr25519(&adr[i]) if err != nil { return nil, err } diff --git a/dot/types/inherents.go b/dot/types/inherents.go index f059109b91..d175add39d 100644 --- a/dot/types/inherents.go +++ b/dot/types/inherents.go @@ -13,10 +13,12 @@ import ( "github.com/ChainSafe/gossamer/pkg/scale" ) -//nolint var ( + // Timstap0 is an inherent key. Timstap0 = []byte("timstap0") + // Babeslot is an inherent key. Babeslot = []byte("babeslot") + // Uncles00 is an inherent key. Uncles00 = []byte("uncles00") ) diff --git a/lib/babe/babe_test.go b/lib/babe/babe_test.go index 368f1e8682..d62397a0c4 100644 --- a/lib/babe/babe_test.go +++ b/lib/babe/babe_test.go @@ -387,12 +387,12 @@ func TestService_PauseAndResume(t *testing.T) { }() go func() { - err := bs.Resume() //nolint + err := bs.Resume() require.NoError(t, err) }() go func() { - err := bs.Resume() //nolint + err := bs.Resume() require.NoError(t, err) }() diff --git a/lib/babe/build.go b/lib/babe/build.go index bcaa5e9bff..f09a2678d7 100644 --- a/lib/babe/build.go +++ b/lib/babe/build.go @@ -41,7 +41,7 @@ func (b *Service) buildBlock(parent *types.Header, slot Slot, rt runtime.Instanc block, err := builder.buildBlock(parent, slot, rt) // is necessary to enable ethmetrics to be possible register values - ethmetrics.Enabled = true //nolint + ethmetrics.Enabled = true if err != nil { builderErrors := ethmetrics.GetOrRegisterCounter(buildBlockErrors, nil) @@ -55,7 +55,7 @@ func (b *Service) buildBlock(parent *types.Header, slot Slot, rt runtime.Instanc return block, nil } -// nolint +// BlockBuilder builds blocks. type BlockBuilder struct { keypair *sr25519.Keypair transactionState TransactionState @@ -64,7 +64,7 @@ type BlockBuilder struct { currentAuthorityIndex uint32 } -// nolint +// NewBlockBuilder creates a new block builder. func NewBlockBuilder(kp *sr25519.Keypair, ts TransactionState, bs BlockState, sp map[uint64]*VrfOutputAndProof, authidx uint32) (*BlockBuilder, error) { if ts == nil { return nil, errors.New("cannot create block builder; transaction state is nil") diff --git a/lib/babe/build_test.go b/lib/babe/build_test.go index b16773108b..f66c1a7826 100644 --- a/lib/babe/build_test.go +++ b/lib/babe/build_test.go @@ -111,7 +111,7 @@ func createTestExtrinsic(t *testing.T, rt runtime.Instance, genHash common.Hash, return types.Extrinsic(common.MustHexToBytes(extEnc)) } -func createTestBlock(t *testing.T, babeService *Service, parent *types.Header, exts [][]byte, slotNumber, epoch uint64) (*types.Block, Slot) { //nolint +func createTestBlock(t *testing.T, babeService *Service, parent *types.Header, exts [][]byte, slotNumber, epoch uint64) (*types.Block, Slot) { // create proof that we can authorize this block babeService.epochData.authorityIndex = 0 addAuthorshipProof(t, babeService, slotNumber, epoch) diff --git a/lib/babe/crypto.go b/lib/babe/crypto.go index 9f90e087e2..4bc84e2009 100644 --- a/lib/babe/crypto.go +++ b/lib/babe/crypto.go @@ -15,7 +15,7 @@ import ( ) // the code in this file is based off https://github.com/paritytech/substrate/blob/89275433863532d797318b75bb5321af098fea7c/primitives/consensus/babe/src/lib.rs#L93 -var babe_vrf_prefix = []byte("substrate-babe-vrf") +var babeVRFPrefix = []byte("substrate-babe-vrf") func makeTranscript(randomness Randomness, slot, epoch uint64) *merlin.Transcript { t := merlin.NewTranscript("BABE") //string(types.BabeEngineID[:]) @@ -62,7 +62,7 @@ func checkPrimaryThreshold(randomness Randomness, ) bool { t := makeTranscript(randomness, slot, epoch) inout := sr25519.AttachInput(output, pub, t) - res := sr25519.MakeBytes(inout, 16, babe_vrf_prefix) + res := sr25519.MakeBytes(inout, 16, babeVRFPrefix) inoutUint := common.Uint128FromLEBytes(res) @@ -86,28 +86,28 @@ func CalculateThreshold(C1, C2 uint64, numAuths int) (*common.Uint128, error) { // (1-c)^(theta) pp := 1 - c - pp_exp := math.Pow(pp, theta) + ppExp := math.Pow(pp, theta) // 1 - (1-c)^(theta) - p := 1 - pp_exp - p_rat := new(big.Rat).SetFloat64(p) + p := 1 - ppExp + pRat := new(big.Rat).SetFloat64(p) // 1 << 128 shift := new(big.Int).Lsh(big.NewInt(1), 128) - numer := new(big.Int).Mul(shift, p_rat.Num()) - denom := p_rat.Denom() + numer := new(big.Int).Mul(shift, pRat.Num()) + denom := pRat.Denom() // (1 << 128) * (1 - (1-c)^(w_k/sum(w_i))) - threshold_big := new(big.Int).Div(numer, denom) + thresholdBig := new(big.Int).Div(numer, denom) // special case where threshold is maximum - if threshold_big.Cmp(shift) == 0 { + if thresholdBig.Cmp(shift) == 0 { return common.MaxUint128, nil } - if len(threshold_big.Bytes()) > 16 { + if len(thresholdBig.Bytes()) > 16 { return nil, errors.New("threshold must be under or equal to 16 bytes") } - return common.Uint128FromBigInt(threshold_big), nil + return common.Uint128FromBigInt(thresholdBig), nil } diff --git a/lib/babe/epoch.go b/lib/babe/epoch.go index 5892b31a29..5191521145 100644 --- a/lib/babe/epoch.go +++ b/lib/babe/epoch.go @@ -23,7 +23,7 @@ func (b *Service) initiateEpoch(epoch uint64) error { return err } } else if epoch > 0 { - has, err := b.epochState.HasEpochData(epoch) //nolint + has, err := b.epochState.HasEpochData(epoch) if err != nil { return err } @@ -49,7 +49,7 @@ func (b *Service) initiateEpoch(epoch uint64) error { } if has { - cfgData, err := b.epochState.GetConfigData(epoch) //nolint + cfgData, err := b.epochState.GetConfigData(epoch) if err != nil { return err } @@ -91,7 +91,7 @@ func (b *Service) initiateEpoch(epoch uint64) error { logger.Debugf("estimated first slot as %d based on building block 1", startSlot) for i := startSlot; i < startSlot+b.epochLength; i++ { - proof, err := b.runLottery(i, epoch) //nolint + proof, err := b.runLottery(i, epoch) if err != nil { return fmt.Errorf("error running slot lottery at slot %d: error %w", i, err) } diff --git a/lib/babe/epoch_test.go b/lib/babe/epoch_test.go index 88f03460fd..39876134ee 100644 --- a/lib/babe/epoch_test.go +++ b/lib/babe/epoch_test.go @@ -75,7 +75,7 @@ func TestInitiateEpoch_Epoch1(t *testing.T) { require.GreaterOrEqual(t, len(bs.slotToProof), 1) for i, auth := range bs.epochData.authorities { - expAuth, err := expected.authorities[i].Encode() //nolint + expAuth, err := expected.authorities[i].Encode() require.NoError(t, err) res, err := auth.Encode() require.NoError(t, err) @@ -105,7 +105,7 @@ func TestInitiateEpoch_Epoch1(t *testing.T) { require.GreaterOrEqual(t, len(bs.slotToProof), 1) for i, auth := range bs.epochData.authorities { - expAuth, err := expected.authorities[i].Encode() //nolint + expAuth, err := expected.authorities[i].Encode() require.NoError(t, err) res, err := auth.Encode() require.NoError(t, err) diff --git a/lib/blocktree/blocktree.go b/lib/blocktree/blocktree.go index 9cd7ba7c43..4a15733815 100644 --- a/lib/blocktree/blocktree.go +++ b/lib/blocktree/blocktree.go @@ -218,7 +218,7 @@ func (bt *BlockTree) String() string { } // longestPath returns the path from the root to leftmost deepest leaf in BlockTree BT -func (bt *BlockTree) longestPath() []*node { //nolint +func (bt *BlockTree) longestPath() []*node { dl := bt.deepestLeaf() var path []*node for curr := dl; ; curr = curr.parent { @@ -259,8 +259,8 @@ func (bt *BlockTree) SubBlockchain(start, end Hash) ([]Hash, error) { } -// DeepestLeaf returns leftmost deepest leaf in BlockTree BT -func (bt *BlockTree) deepestLeaf() *node { //nolint +// deepestLeaf returns the leftmost deepest leaf in the block tree. +func (bt *BlockTree) deepestLeaf() *node { return bt.leaves.deepestLeaf() } diff --git a/lib/crypto/sr25519/sr25519.go b/lib/crypto/sr25519/sr25519.go index 351cf79c09..0a54c73fb4 100644 --- a/lib/crypto/sr25519/sr25519.go +++ b/lib/crypto/sr25519/sr25519.go @@ -14,14 +14,19 @@ import ( "github.com/gtank/merlin" ) -//nolint const ( - PublicKeyLength int = 32 - SeedLength int = 32 - PrivateKeyLength int = 32 - SignatureLength int = 64 - VRFOutputLength int = 32 - VRFProofLength int = 64 + // PublicKeyLength is the expected public key length for sr25519. + PublicKeyLength = 32 + // SeedLength is the expected seed length for sr25519. + SeedLength = 32 + // PrivateKeyLength is the expected private key length for sr25519. + PrivateKeyLength = 32 + // SignatureLength is the expected signature length for sr25519. + SignatureLength = 64 + // VRFOutputLength is the expected VFR output length for sr25519. + VRFOutputLength = 32 + // VRFProofLength is the expected VFR proof length for sr25519. + VRFProofLength = 64 ) // SigningContext is the context for signatures used or created with substrate diff --git a/lib/genesis/helpers.go b/lib/genesis/helpers.go index c3b7ef3fbe..2f826ecd5b 100644 --- a/lib/genesis/helpers.go +++ b/lib/genesis/helpers.go @@ -686,7 +686,6 @@ func addAuthoritiesValues(k1, k2 string, kt crypto.KeyType, value []byte, gen *G if _, err = reader.Read(buf); err == nil { var arr = [32]byte{} copy(arr[:], buf) - //nolint pa, err := bytesToAddress(kt, arr[:]) if err != nil { return err diff --git a/lib/grandpa/errors.go b/lib/grandpa/errors.go index 234f0f16f0..6c2e0d92f6 100644 --- a/lib/grandpa/errors.go +++ b/lib/grandpa/errors.go @@ -15,7 +15,6 @@ func errRoundMismatch(got, want uint64) error { return fmt.Errorf("rounds do not match: got %d, want %d", got, want) } -//nolint var ( ErrNilBlockState = errors.New("cannot have nil BlockState") ErrNilGrandpaState = errors.New("cannot have nil GrandpaState") diff --git a/lib/grandpa/message.go b/lib/grandpa/message.go index f3d204b149..e39d2ccb2f 100644 --- a/lib/grandpa/message.go +++ b/lib/grandpa/message.go @@ -14,7 +14,7 @@ import ( ) // GrandpaMessage is implemented by all GRANDPA network messages -type GrandpaMessage interface { //nolint +type GrandpaMessage interface { //nolint:revive ToConsensusMessage() (*network.ConsensusMessage, error) } diff --git a/lib/grandpa/message_handler.go b/lib/grandpa/message_handler.go index 62bd1fd2e2..b7906745e0 100644 --- a/lib/grandpa/message_handler.go +++ b/lib/grandpa/message_handler.go @@ -165,7 +165,7 @@ func (h *MessageHandler) handleCatchUpResponse(msg *CatchUpResponse) error { } // if we aren't currently expecting a catch up response, return - if !h.grandpa.paused.Load().(bool) { //nolint + if !h.grandpa.paused.Load().(bool) { logger.Debug("not currently paused, ignoring catch up response") return nil } @@ -220,7 +220,7 @@ func (h *MessageHandler) handleCatchUpResponse(msg *CatchUpResponse) error { } // verifyCatchUpResponseCompletability verifies that the pre-commit block is a descendant of, or is, the pre-voted block -func (h *MessageHandler) verifyCatchUpResponseCompletability(prevote, precommit common.Hash) error { //nolint +func (h *MessageHandler) verifyCatchUpResponseCompletability(prevote, precommit common.Hash) error { if prevote == precommit { return nil } @@ -283,8 +283,9 @@ func (h *MessageHandler) verifyPreVoteJustification(msg *CatchUpResponse) (commo // verify pre-vote justification, returning the pre-voted block if there is one votes := make(map[common.Hash]uint64) - for _, just := range msg.PreVoteJustification { - err := h.verifyJustification(&just, msg.Round, msg.SetID, prevote) //nolint + for i := range msg.PreVoteJustification { + just := &msg.PreVoteJustification[i] + err := h.verifyJustification(just, msg.Round, msg.SetID, prevote) if err != nil { continue } @@ -310,8 +311,9 @@ func (h *MessageHandler) verifyPreVoteJustification(msg *CatchUpResponse) (commo func (h *MessageHandler) verifyPreCommitJustification(msg *CatchUpResponse) error { // verify pre-commit justification count := 0 - for _, just := range msg.PreCommitJustification { - err := h.verifyJustification(&just, msg.Round, msg.SetID, precommit) //nolint + for i := range msg.PreCommitJustification { + just := &msg.PreCommitJustification[i] + err := h.verifyJustification(just, msg.Round, msg.SetID, precommit) if err != nil { continue } @@ -409,7 +411,7 @@ func (s *Service) VerifyBlockJustification(hash common.Hash, justification []byt for _, just := range fj.Commit.Precommits { // check if vote was for descendant of committed block - isDescendant, err := s.blockState.IsDescendantOf(hash, just.Vote.Hash) //nolint + isDescendant, err := s.blockState.IsDescendantOf(hash, just.Vote.Hash) if err != nil { return err } diff --git a/lib/grandpa/network.go b/lib/grandpa/network.go index 1d801169a6..a959d893a8 100644 --- a/lib/grandpa/network.go +++ b/lib/grandpa/network.go @@ -34,7 +34,7 @@ type NotificationsMessage = network.NotificationsMessage type ConsensusMessage = network.ConsensusMessage // GrandpaHandshake is exchanged by nodes that are beginning the grandpa protocol -type GrandpaHandshake struct { //nolint +type GrandpaHandshake struct { //nolint:revive Roles byte } diff --git a/lib/grandpa/round_test.go b/lib/grandpa/round_test.go index 6f4890a90e..2fd6c51959 100644 --- a/lib/grandpa/round_test.go +++ b/lib/grandpa/round_test.go @@ -120,7 +120,7 @@ func TestGrandpa_BaseCase(t *testing.T) { gs, _, _, _ = setupGrandpa(t, kr.Keys[i]) gss[i] = gs state.AddBlocksToState(t, gs.blockState.(*state.BlockState), 15, false) - pv, err := gs.determinePreVote() //nolint + pv, err := gs.determinePreVote() require.NoError(t, err) prevotes.Store(gs.publicKeyBytes(), &SignedVote{ Vote: *pv, @@ -167,7 +167,7 @@ func TestGrandpa_DifferentChains(t *testing.T) { r := rand.Intn(1) state.AddBlocksToState(t, gs.blockState.(*state.BlockState), 4+r, false) - pv, err := gs.determinePreVote() //nolint + pv, err := gs.determinePreVote() require.NoError(t, err) prevotes.Store(gs.publicKeyBytes(), &SignedVote{ Vote: *pv, @@ -219,7 +219,7 @@ func broadcastVotes(from <-chan GrandpaMessage, to []chan *networkVoteMessage, d } } -func cleanup(gs *Service, in chan *networkVoteMessage, out chan GrandpaMessage, done *bool) { //nolint +func cleanup(gs *Service, in chan *networkVoteMessage, done *bool) { *done = true close(in) gs.cancel() @@ -239,7 +239,7 @@ func TestPlayGrandpaRound_BaseCase(t *testing.T) { for i := range gss { gs, in, out, fin := setupGrandpa(t, kr.Keys[i]) - defer cleanup(gs, in, out, &done) + defer cleanup(gs, in, &done) gss[i] = gs ins[i] = in @@ -318,7 +318,7 @@ func TestPlayGrandpaRound_VaryingChain(t *testing.T) { for i := range gss { gs, in, out, fin := setupGrandpa(t, kr.Keys[i]) - defer cleanup(gs, in, out, &done) + defer cleanup(gs, in, &done) gss[i] = gs ins[i] = in @@ -413,7 +413,7 @@ func TestPlayGrandpaRound_WithEquivocation(t *testing.T) { for i := range gss { gs, in, out, fin := setupGrandpa(t, kr.Keys[i]) - defer cleanup(gs, in, out, &done) + defer cleanup(gs, in, &done) gss[i] = gs ins[i] = in @@ -510,7 +510,7 @@ func TestPlayGrandpaRound_MultipleRounds(t *testing.T) { for i := range gss { gs, in, out, fin := setupGrandpa(t, kr.Keys[i]) - defer cleanup(gs, in, out, &done) + defer cleanup(gs, in, &done) gss[i] = gs ins[i] = in diff --git a/lib/grandpa/state.go b/lib/grandpa/state.go index c762311130..e002274df0 100644 --- a/lib/grandpa/state.go +++ b/lib/grandpa/state.go @@ -41,7 +41,7 @@ type BlockState interface { } // GrandpaState is the interface required by grandpa into the grandpa state -type GrandpaState interface { //nolint +type GrandpaState interface { //nolint:revive GetCurrentSetID() (uint64, error) GetAuthorities(setID uint64) ([]types.GrandpaVoter, error) GetSetIDByBlockNumber(num *big.Int) (uint64, error) diff --git a/lib/grandpa/types.go b/lib/grandpa/types.go index 5205750d85..3a7b911f22 100644 --- a/lib/grandpa/types.go +++ b/lib/grandpa/types.go @@ -11,7 +11,7 @@ import ( "github.com/ChainSafe/gossamer/lib/crypto/ed25519" ) -//nolint +//nolint:revive type ( Voter = types.GrandpaVoter Voters = types.GrandpaVoters @@ -22,7 +22,6 @@ type ( // Subround subrounds in a grandpa round type Subround byte -//nolint var ( prevote Subround precommit Subround = 1 diff --git a/lib/grandpa/vote_message.go b/lib/grandpa/vote_message.go index d1e1b6f175..52c696fd84 100644 --- a/lib/grandpa/vote_message.go +++ b/lib/grandpa/vote_message.go @@ -131,7 +131,7 @@ func (s *Service) validateMessage(from peer.ID, m *VoteMessage) (*Vote, error) { if m.Round != s.state.round { if m.Round < s.state.round { // peer doesn't know round was finalised, send out another commit message - header, err := s.blockState.GetFinalisedHeader(m.Round, m.SetID) //nolint + header, err := s.blockState.GetFinalisedHeader(m.Round, m.SetID) if err != nil { return nil, err } diff --git a/lib/keystore/keystore.go b/lib/keystore/keystore.go index 12b90c64ac..e1e004ab09 100644 --- a/lib/keystore/keystore.go +++ b/lib/keystore/keystore.go @@ -17,7 +17,7 @@ var ( // Name represents a defined keystore name type Name string -//nolint +//nolint:revive var ( BabeName Name = "babe" GranName Name = "gran" diff --git a/lib/runtime/constants.go b/lib/runtime/constants.go index f2b7d9cb7d..af83012c30 100644 --- a/lib/runtime/constants.go +++ b/lib/runtime/constants.go @@ -9,7 +9,7 @@ import ( var runtimes = []string{HOST_API_TEST_RUNTIME, POLKADOT_RUNTIME, NODE_RUNTIME, DEV_RUNTIME} -//nolint +//nolint:revive const ( // v0.9 substrate runtime NODE_RUNTIME = "node_runtime" @@ -42,11 +42,10 @@ const ( DEV_RUNTIME_URL = "https://github.com/noot/substrate/blob/noot/v0.8-dev-runtime/target/wasm32-unknown-unknown/release/wbuild/node-runtime/node_runtime.compact.wasm?raw=true" ) -//nolint var ( // CoreVersion is the runtime API call Core_version CoreVersion = "Core_version" - // CoreInitialiseBlock is the runtime API call Core_initialize_block + // CoreInitializeBlock is the runtime API call Core_initialize_block CoreInitializeBlock = "Core_initialize_block" // CoreExecuteBlock is the runtime API call Core_execute_block CoreExecuteBlock = "Core_execute_block" @@ -66,8 +65,8 @@ var ( BlockBuilderFinalizeBlock = "BlockBuilder_finalize_block" // DecodeSessionKeys is the runtime API call SessionKeys_decode_session_keys DecodeSessionKeys = "SessionKeys_decode_session_keys" - // TransactionPaymentApiQueryInfo returns information of a given extrinsic - TransactionPaymentApiQueryInfo = "TransactionPaymentApi_query_info" + // TransactionPaymentAPIQueryInfo returns information of a given extrinsic + TransactionPaymentAPIQueryInfo = "TransactionPaymentApi_query_info" ) // GrandpaAuthoritiesKey is the location of GRANDPA authority data in the storage trie for LEGACY_NODE_RUNTIME and NODE_RUNTIME diff --git a/lib/runtime/life/exports.go b/lib/runtime/life/exports.go index 47fa1a0c52..ff04a95a7e 100644 --- a/lib/runtime/life/exports.go +++ b/lib/runtime/life/exports.go @@ -112,7 +112,6 @@ func (in *Instance) ApplyExtrinsic(data types.Extrinsic) ([]byte, error) { return in.Exec(runtime.BlockBuilderApplyExtrinsic, data) } -//nolint // FinalizeBlock calls runtime API function BlockBuilder_finalize_block func (in *Instance) FinalizeBlock() (*types.Header, error) { data, err := in.Exec(runtime.BlockBuilderFinalizeBlock, []byte{}) @@ -177,7 +176,7 @@ func (*Instance) PaymentQueryInfo([]byte) (*types.TransactionPaymentQueryInfo, e return nil, errors.New("not implemented yet") } -func (in *Instance) CheckInherents() {} //nolint -func (in *Instance) RandomSeed() {} //nolint -func (in *Instance) OffchainWorker() {} //nolint -func (in *Instance) GenerateSessionKeys() {} //nolint +func (in *Instance) CheckInherents() {} //nolint:revive +func (in *Instance) RandomSeed() {} //nolint:revive +func (in *Instance) OffchainWorker() {} //nolint:revive +func (in *Instance) GenerateSessionKeys() {} //nolint:revive diff --git a/lib/runtime/life/exports_test.go b/lib/runtime/life/exports_test.go index a2e8f8daab..d4f62e3e6f 100644 --- a/lib/runtime/life/exports_test.go +++ b/lib/runtime/life/exports_test.go @@ -152,7 +152,7 @@ func buildBlock(t *testing.T, instance runtime.Instance) *types.Block { // apply each inherent extrinsic for _, ext := range exts { - in, err := scale.Marshal(ext) //nolint + in, err := scale.Marshal(ext) require.NoError(t, err) ret, err := instance.ApplyExtrinsic(append([]byte{1}, in...)) diff --git a/lib/runtime/life/resolver.go b/lib/runtime/life/resolver.go index f85a08d2dc..ecd58fa512 100644 --- a/lib/runtime/life/resolver.go +++ b/lib/runtime/life/resolver.go @@ -26,7 +26,7 @@ import ( type Resolver struct{} // TODO: move context inside resolver (#1875) // ResolveFunc ... -func (*Resolver) ResolveFunc(module, field string) exec.FunctionImport { // nolint +func (*Resolver) ResolveFunc(module, field string) exec.FunctionImport { //nolint:gocyclo switch module { case "env": switch field { @@ -490,7 +490,7 @@ func ext_trie_blake2_256_ordered_root_version_1(vm *exec.VirtualMachine) int64 { } for i, val := range v { - key, err := scale.Marshal(big.NewInt(int64(i))) //nolint + key, err := scale.Marshal(big.NewInt(int64(i))) if err != nil { logger.Errorf("[ext_blake2_256_enumerated_trie_root]: %s", err) return 0 diff --git a/lib/runtime/wasmer/exports.go b/lib/runtime/wasmer/exports.go index 07597ea5c8..52f2c017a3 100644 --- a/lib/runtime/wasmer/exports.go +++ b/lib/runtime/wasmer/exports.go @@ -116,7 +116,6 @@ func (in *Instance) ApplyExtrinsic(data types.Extrinsic) ([]byte, error) { return in.exec(runtime.BlockBuilderApplyExtrinsic, data) } -//nolint // FinalizeBlock calls runtime API function BlockBuilder_finalize_block func (in *Instance) FinalizeBlock() (*types.Header, error) { data, err := in.exec(runtime.BlockBuilderFinalizeBlock, []byte{}) @@ -183,7 +182,7 @@ func (in *Instance) PaymentQueryInfo(ext []byte) (*types.TransactionPaymentQuery return nil, err } - resBytes, err := in.exec(runtime.TransactionPaymentApiQueryInfo, append(ext, encLen...)) + resBytes, err := in.exec(runtime.TransactionPaymentAPIQueryInfo, append(ext, encLen...)) if err != nil { return nil, err } @@ -196,7 +195,7 @@ func (in *Instance) PaymentQueryInfo(ext []byte) (*types.TransactionPaymentQuery return i, nil } -func (in *Instance) CheckInherents() {} //nolint -func (in *Instance) RandomSeed() {} //nolint -func (in *Instance) OffchainWorker() {} //nolint -func (in *Instance) GenerateSessionKeys() {} //nolint +func (in *Instance) CheckInherents() {} //nolint:revive +func (in *Instance) RandomSeed() {} //nolint:revive +func (in *Instance) OffchainWorker() {} //nolint:revive +func (in *Instance) GenerateSessionKeys() {} //nolint:revive diff --git a/lib/runtime/wasmer/exports_test.go b/lib/runtime/wasmer/exports_test.go index a396c1d424..908b22cc73 100644 --- a/lib/runtime/wasmer/exports_test.go +++ b/lib/runtime/wasmer/exports_test.go @@ -27,7 +27,7 @@ import ( "github.com/stretchr/testify/require" ) -func createTestExtrinsic(t *testing.T, rt runtime.Instance, genHash common.Hash, nonce uint64) types.Extrinsic { //nolint +func createTestExtrinsic(t *testing.T, rt runtime.Instance, genHash common.Hash, nonce uint64) types.Extrinsic { t.Helper() rawMeta, err := rt.Metadata() require.NoError(t, err) @@ -276,7 +276,7 @@ func TestInstance_Version_DevRuntime(t *testing.T) { require.Equal(t, expected.TransactionVersion(), version.TransactionVersion()) } -func balanceKey(t *testing.T, pub []byte) []byte { //nolint +func balanceKey(t *testing.T, pub []byte) []byte { h0, err := common.Twox128Hash([]byte("System")) require.NoError(t, err) h1, err := common.Twox128Hash([]byte("Account")) @@ -528,7 +528,6 @@ func buildBlockVdt(t *testing.T, instance runtime.Instance, parentHash common.Ha // apply each inherent extrinsic for _, ext := range exts { - //nolint in, err := scale.Marshal(ext) require.NoError(t, err) @@ -1098,12 +1097,12 @@ func TestInstance_PaymentQueryInfo(t *testing.T) { { // incomplete extrinsic ext: "0x4ccde39a5684e7a56da23b22d4d9fbadb023baa19c56495432884d0640000000000000000000000000000000", - err: errors.New("Failed to call the `TransactionPaymentApi_query_info` exported function."), //nolint + err: errors.New("Failed to call the `TransactionPaymentApi_query_info` exported function."), //nolint:revive }, { // incomplete extrinsic extB: nil, - err: errors.New("Failed to call the `TransactionPaymentApi_query_info` exported function."), //nolint + err: errors.New("Failed to call the `TransactionPaymentApi_query_info` exported function."), //nolint:revive }, } diff --git a/lib/runtime/wasmer/imports.go b/lib/runtime/wasmer/imports.go index 4588fe84c9..0ef5be9ccd 100644 --- a/lib/runtime/wasmer/imports.go +++ b/lib/runtime/wasmer/imports.go @@ -770,18 +770,6 @@ func ext_crypto_start_batch_verify_version_1(context unsafe.Pointer) { // beginBatchVerify(context) } -func beginBatchVerify(context unsafe.Pointer) { //nolint - instanceContext := wasm.IntoInstanceContext(context) - sigVerifier := instanceContext.Data().(*runtime.Context).SigVerifier - - if sigVerifier.IsStarted() { - logger.Error("[ext_crypto_start_batch_verify_version_1] previous batch verification is not finished") - return - } - - sigVerifier.Start() -} - //export ext_crypto_finish_batch_verify_version_1 func ext_crypto_finish_batch_verify_version_1(context unsafe.Pointer) C.int32_t { logger.Debug("[ext_crypto_finish_batch_verify_version_1] executing...") @@ -791,22 +779,6 @@ func ext_crypto_finish_batch_verify_version_1(context unsafe.Pointer) C.int32_t return 1 } -func finishBatchVerify(context unsafe.Pointer) C.int32_t { //nolint - instanceContext := wasm.IntoInstanceContext(context) - sigVerifier := instanceContext.Data().(*runtime.Context).SigVerifier - - if !sigVerifier.IsStarted() { - logger.Error("[ext_crypto_finish_batch_verify_version_1] batch verification is not started") - panic("batch verification is not started") - } - - if sigVerifier.Finish() { - return 1 - } - logger.Error("[ext_crypto_finish_batch_verify_version_1] failed to batch verify; invalid signature") - return 0 -} - //export ext_trie_blake2_256_root_version_1 func ext_trie_blake2_256_root_version_1(context unsafe.Pointer, dataSpan C.int64_t) C.int32_t { logger.Debug("[ext_trie_blake2_256_root_version_1] executing...") @@ -869,7 +841,7 @@ func ext_trie_blake2_256_ordered_root_version_1(context unsafe.Pointer, dataSpan } for i, val := range values { - key, err := scale.Marshal(big.NewInt(int64(i))) //nolint + key, err := scale.Marshal(big.NewInt(int64(i))) if err != nil { logger.Errorf("[ext_trie_blake2_256_ordered_root_version_1]: %s", err) return 0 @@ -2247,7 +2219,7 @@ func toWasmMemoryFixedSizeOptional(context wasm.InstanceContext, data []byte) (i } // ImportsNodeRuntime returns the imports for the v0.8 runtime -func ImportsNodeRuntime() (*wasm.Imports, error) { //nolint +func ImportsNodeRuntime() (*wasm.Imports, error) { //nolint:gocyclo var err error imports := wasm.NewImports() diff --git a/lib/transaction/types.go b/lib/transaction/types.go index dcb9eafd05..ab673b7cd2 100644 --- a/lib/transaction/types.go +++ b/lib/transaction/types.go @@ -49,7 +49,6 @@ func NewValidTransaction(extrinsic types.Extrinsic, validity *Validity) *ValidTr // BlockHash *common.Hash // } -//nolint // Status represents possible transaction statuses. // // The status events can be grouped based on their kinds as: @@ -87,7 +86,6 @@ const ( // has been reached, // old watchers are being removed. FinalityTimeout - //nolint // Finalized status occurs when transaction has been finalized by a finality-gadget, // e.g GRANDPA Finalized @@ -116,7 +114,6 @@ func (s Status) String() string { return "retracted" case FinalityTimeout: return "finalityTimeout" - //nolint case Finalized: return "finalized" case Usurped: diff --git a/lib/trie/database.go b/lib/trie/database.go index 1d9e3c8bf1..b6719dfd21 100644 --- a/lib/trie/database.go +++ b/lib/trie/database.go @@ -307,7 +307,7 @@ func (t *Trie) writeDirty(db chaindb.Batch, curr node) error { // always hash root even if encoding is under 32 bytes if curr == t.root { - h, err := common.Blake2bHash(enc) //nolint + h, err := common.Blake2bHash(enc) if err != nil { return err } @@ -355,7 +355,7 @@ func (t *Trie) getInsertedNodeHashes(curr node) ([]common.Hash, error) { } if curr == t.root && len(enc) < 32 { - h, err := common.Blake2bHash(enc) //nolint + h, err := common.Blake2bHash(enc) if err != nil { return nil, err } diff --git a/lib/trie/database_test.go b/lib/trie/database_test.go index 3f9f0c432c..f121573d41 100644 --- a/lib/trie/database_test.go +++ b/lib/trie/database_test.go @@ -139,7 +139,7 @@ func TestTrie_WriteDirty_Put(t *testing.T) { require.Equal(t, trie.MustHash(), res.MustHash()) for _, test := range testCase { - val, err := GetFromDB(db, trie.MustHash(), test.key) //nolint + val, err := GetFromDB(db, trie.MustHash(), test.key) require.NoError(t, err) if bytes.Equal(test.key, []byte("asdf")) { continue diff --git a/lib/trie/test_utils.go b/lib/trie/test_utils.go index 8d6cfc8e33..37a6d95c52 100644 --- a/lib/trie/test_utils.go +++ b/lib/trie/test_utils.go @@ -78,6 +78,9 @@ func generateRandomTest(t testing.TB, kv map[string][]byte, generator *prand.Ran func rand32Bytes() []byte { r := make([]byte, 32) - rand.Read(r) //nolint + _, err := rand.Read(r) + if err != nil { + panic(err) + } return r } diff --git a/lib/trie/trie.go b/lib/trie/trie.go index 0705b9ba7f..5a89c9d71a 100644 --- a/lib/trie/trie.go +++ b/lib/trie/trie.go @@ -10,7 +10,7 @@ import ( "github.com/ChainSafe/gossamer/lib/common" ) -//nolint +// EmptyHash is the empty trie hash. var EmptyHash, _ = NewEmptyTrie().Hash() // Trie is a Merkle Patricia Trie. @@ -102,7 +102,7 @@ func (t *Trie) DeepCopy() (*Trie, error) { } // RootNode returns the root of the trie -func (t *Trie) RootNode() node { //nolint +func (t *Trie) RootNode() node { return t.root } diff --git a/lib/trie/trie_test.go b/lib/trie/trie_test.go index 8945fd4b08..f6ae3ff779 100644 --- a/lib/trie/trie_test.go +++ b/lib/trie/trie_test.go @@ -51,7 +51,8 @@ func TestCommonPrefix(t *testing.T) { } } -var ( +//nolint:revive +const ( PUT = 0 DEL = 1 CLEAR_PREFIX = 2 diff --git a/pkg/scale/decode.go b/pkg/scale/decode.go index eb51e679f4..ccb3643ed2 100644 --- a/pkg/scale/decode.go +++ b/pkg/scale/decode.go @@ -614,7 +614,7 @@ func (ds *decodeState) decodeFixedWidthInt(dstv reflect.Value) (err error) { if err != nil { return } - out = uint8(b) // nolint + out = b case int16: buf := make([]byte, 2) _, err = ds.Read(buf) diff --git a/tests/stress/errors.go b/tests/stress/errors.go index 9296b93324..c0563a6fa0 100644 --- a/tests/stress/errors.go +++ b/tests/stress/errors.go @@ -7,7 +7,6 @@ import ( "errors" ) -//nolint var ( errFinalizedBlockMismatch = errors.New("node finalised head hashes don't match") errNoFinalizedBlock = errors.New("did not finalise block for round") diff --git a/tests/stress/grandpa_test.go b/tests/stress/grandpa_test.go index 9b273647c1..2e32cdd9da 100644 --- a/tests/stress/grandpa_test.go +++ b/tests/stress/grandpa_test.go @@ -121,7 +121,7 @@ func TestStress_Grandpa_CatchUp(t *testing.T) { }() time.Sleep(time.Second * 70) // let some rounds run - //nolint + node, err := utils.RunGossamer(t, numNodes-1, utils.TestDir(t, utils.KeyList[numNodes-1]), utils.GenesisSixAuths, utils.ConfigDefault, false, false) require.NoError(t, err) nodes = append(nodes, node) diff --git a/tests/stress/helpers.go b/tests/stress/helpers.go index 46150db810..c3841089ce 100644 --- a/tests/stress/helpers.go +++ b/tests/stress/helpers.go @@ -212,7 +212,7 @@ func compareFinalizedHeadsWithRetry(t *testing.T, nodes []*utils.Node, round uin return common.Hash{}, nil } -func getPendingExtrinsics(t *testing.T, node *utils.Node) []string { //nolint +func getPendingExtrinsics(t *testing.T, node *utils.Node) []string { respBody, err := utils.PostRPC(utils.AuthorPendingExtrinsics, utils.NewEndpoint(node.RPCPort), "[]") require.NoError(t, err) diff --git a/tests/stress/stress_test.go b/tests/stress/stress_test.go index 0a320ce209..48d2e68c0a 100644 --- a/tests/stress/stress_test.go +++ b/tests/stress/stress_test.go @@ -88,7 +88,6 @@ func TestSync_SingleBlockProducer(t *testing.T) { utils.Logger.Patch(log.SetLevel(log.Info)) // start block producing node first - //nolint node, err := utils.RunGossamer(t, numNodes-1, utils.TestDir(t, utils.KeyList[numNodes-1]), utils.GenesisDev, utils.ConfigNoGrandpa, false, true) require.NoError(t, err) @@ -206,7 +205,7 @@ func TestSync_Bench(t *testing.T) { require.NoError(t, err) for { - header, err := utils.GetChainHeadWithError(t, alice) //nolint + header, err := utils.GetChainHeadWithError(t, alice) if err != nil { continue } @@ -242,7 +241,7 @@ func TestSync_Bench(t *testing.T) { t.Fatal("did not sync") } - head, err := utils.GetChainHeadWithError(t, bob) //nolint + head, err := utils.GetChainHeadWithError(t, bob) if err != nil { continue } @@ -276,7 +275,6 @@ func TestSync_Restart(t *testing.T) { utils.Logger.Patch(log.SetLevel(log.Info)) // start block producing node first - //nolint node, err := utils.RunGossamer(t, numNodes-1, utils.TestDir(t, utils.KeyList[numNodes-1]), utils.GenesisDefault, utils.ConfigDefault, false, true) require.NoError(t, err) diff --git a/tests/utils/chain.go b/tests/utils/chain.go index 1c4a35e9fc..4c6e554306 100644 --- a/tests/utils/chain.go +++ b/tests/utils/chain.go @@ -16,7 +16,7 @@ import ( ) // GetHeader calls the endpoint chain_getHeader -func GetHeader(t *testing.T, node *Node, hash common.Hash) *types.Header { //nolint +func GetHeader(t *testing.T, node *Node, hash common.Hash) *types.Header { respBody, err := PostRPC(ChainGetHeader, NewEndpoint(node.RPCPort), "[\""+hash.String()+"\"]") require.NoError(t, err) diff --git a/tests/utils/common.go b/tests/utils/common.go index 8ed6e07ae0..5bd9812612 100644 --- a/tests/utils/common.go +++ b/tests/utils/common.go @@ -11,17 +11,22 @@ import ( "time" ) -//nolint var ( + // MODE is the value for the environnent variable MODE. MODE = os.Getenv("MODE") + // HOSTNAME is the value for the environnent variable HOSTNAME. HOSTNAME = os.Getenv("HOSTNAME") - PORT = os.Getenv("PORT") + // PORT is the value for the environnent variable PORT. + PORT = os.Getenv("PORT") + // LOGLEVEL is the value for the environnent variable LOGLEVEL. LOGLEVEL = os.Getenv("LOG") - NETWORK_SIZE = os.Getenv("NETWORK_SIZE") + // NETWORK_SIZE is the value for the environnent variable NETWORK_SIZE. + NETWORK_SIZE = os.Getenv("NETWORK_SIZE") //nolint:revive + // ContentTypeJSON is the JSON header application/json. ContentTypeJSON = "application/json" dialTimeout = 60 * time.Second httpClientTimeout = 120 * time.Second diff --git a/tests/utils/gossamer_utils.go b/tests/utils/gossamer_utils.go index a1beec6bbb..fbd82cdbc5 100644 --- a/tests/utils/gossamer_utils.go +++ b/tests/utils/gossamer_utils.go @@ -20,6 +20,7 @@ import ( "github.com/ChainSafe/gossamer/dot/rpc/modules" "github.com/ChainSafe/gossamer/internal/log" "github.com/ChainSafe/gossamer/lib/utils" + "github.com/stretchr/testify/assert" ) // Logger is the utils package local logger. @@ -77,7 +78,6 @@ type Node struct { // InitGossamer initialises given node number and returns node reference func InitGossamer(idx int, basePath, genesis, config string) (*Node, error) { - //nolint cmdInit := exec.Command(gossamerCMD, "init", "--config", config, "--basepath", basePath, @@ -130,7 +130,6 @@ func StartGossamer(t *testing.T, node *Node, websocket bool) error { params = append(params, "--ws", "--wsport", node.WSPort) } - //nolint node.Process = exec.Command(gossamerCMD, params...) node.Key = key @@ -151,8 +150,10 @@ func StartGossamer(t *testing.T, node *Node, websocket bool) error { t.Cleanup(func() { time.Sleep(time.Second) // wait for goroutine to finish writing - outfile.Close() //nolint - errfile.Close() //nolint + err = outfile.Close() + assert.NoError(t, err) + err = errfile.Close() + assert.NoError(t, err) }) stdoutPipe, err := node.Process.StdoutPipe() @@ -175,9 +176,19 @@ func StartGossamer(t *testing.T, node *Node, websocket bool) error { } writer := bufio.NewWriter(outfile) - go io.Copy(writer, stdoutPipe) //nolint + go func() { + _, err := io.Copy(writer, stdoutPipe) + if err != nil { + Logger.Errorf("failed copying stdout to writer: %s", err) + } + }() errWriter := bufio.NewWriter(errfile) - go io.Copy(errWriter, stderrPipe) //nolint + go func() { + _, err := io.Copy(errWriter, stderrPipe) + if err != nil { + Logger.Errorf("failed copying stderr to writer: %s", err) + } + }() var started bool for i := 0; i < maxRetries; i++ { diff --git a/tests/utils/request_utils.go b/tests/utils/request_utils.go index 309d81f1d6..2068c09d49 100644 --- a/tests/utils/request_utils.go +++ b/tests/utils/request_utils.go @@ -121,7 +121,7 @@ func DecodeWebsocket(t *testing.T, body []byte, target interface{}) error { } // DecodeRPC_NT will decode []body into target interface (NT is Not Test testing required) -func DecodeRPC_NT(body []byte, target interface{}) error { +func DecodeRPC_NT(body []byte, target interface{}) error { //nolint:revive decoder := json.NewDecoder(bytes.NewReader(body)) decoder.DisallowUnknownFields() diff --git a/tests/utils/rpc_methods.go b/tests/utils/rpc_methods.go index 06f0167668..6b5d44060d 100644 --- a/tests/utils/rpc_methods.go +++ b/tests/utils/rpc_methods.go @@ -3,7 +3,7 @@ package utils -//nolint +//nolint:revive var ( // CHAIN METHODS ChainGetBlock = "chain_getBlock"