From 2eff00475ac1234ac1701f596808f93b3bf0bd46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ecl=C3=A9sio=20Junior?= Date: Tue, 10 Dec 2024 16:12:59 -0400 Subject: [PATCH] chore(ci): add rules to `.golintci.yaml` (#4397) --- .golangci.yml | 18 +++++++++++++++ Makefile | 2 +- devnet/bob.Dockerfile | 2 +- devnet/substrate_alice.Dockerfile | 2 +- devnet/substrate_bob.Dockerfile | 2 +- dot/network/block_announce.go | 2 +- dot/network/host.go | 4 ++-- dot/network/messages/block.go | 2 +- dot/network/ratelimiters/sliding_window.go | 2 +- dot/network/utils.go | 12 +++++----- dot/peerset/peerset.go | 16 ++++++------- dot/rpc/modules/grandpa.go | 10 ++++----- dot/rpc/modules/system.go | 6 ++--- dot/state/block.go | 6 ++--- dot/state/epoch.go | 4 ++-- dot/state/grandpa.go | 2 +- dot/state/inmemory_storage.go | 2 +- dot/state/test_helpers.go | 2 +- dot/state/transaction.go | 2 +- dot/sync/fullsync.go | 8 +++---- dot/test_utils.go | 2 +- internal/database/pebble.go | 2 +- lib/babe/babe.go | 8 +++---- lib/babe/build.go | 2 +- lib/babe/secondary.go | 2 +- lib/babe/slot.go | 2 +- lib/babe/verify.go | 2 +- lib/blocktree/blocktree.go | 4 ++-- lib/genesis/helpers.go | 8 +++---- lib/grandpa/grandpa.go | 18 +++++++-------- lib/grandpa/message.go | 2 +- lib/grandpa/message_handler.go | 8 +++---- lib/grandpa/neighbor_tracker.go | 2 +- lib/grandpa/types.go | 4 ++-- lib/runtime/allocator/freeing_bump.go | 4 ++-- lib/runtime/storage/storagediff.go | 6 ++--- lib/runtime/storage/trie.go | 2 +- lib/runtime/test_helpers.go | 2 +- lib/runtime/wazero/imports.go | 26 +++++++++++----------- lib/runtime/wazero/instance.go | 8 +++---- lib/utils/lru-cache/lru_cache.go | 2 +- lib/utils/utils.go | 4 ++-- pkg/finality-grandpa/bitfield.go | 2 +- pkg/scale/decode.go | 6 ++--- pkg/scale/encode.go | 24 ++++++++++---------- pkg/trie/node/children.go | 2 +- pkg/trie/node/node.go | 10 ++++----- pkg/trie/triedb/cache.go | 2 +- pkg/trie/triedb/iterator.go | 2 +- pkg/trie/triedb/nibbles/leftnibbles.go | 2 +- pkg/trie/triedb/nibbles/nibbles.go | 10 ++++----- pkg/trie/triedb/nibbles/nibbleslice.go | 6 ++--- pkg/trie/triedb/node.go | 2 +- scripts/p2p/common_p2p.go | 4 ++-- scripts/retrieve_block/retrieve_block.go | 8 +++---- tests/rpc/rpc_03-chain_test.go | 6 ++--- tests/utils/gossamer_utils.go | 2 +- tests/utils/node/node.go | 6 ++--- tests/utils/rpc/chain.go | 2 +- tests/utils/rpc/dev.go | 2 +- 60 files changed, 171 insertions(+), 153 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index e0a2706c61..f35d374d43 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -15,6 +15,16 @@ linters-settings: severity: warning confidence: 0.8 + gosec: + excludes: + - G115 + - G301 + - G306 + + gosimple: + excludes: + - S1009 + lll: # max line length, lines longer will be reported. Default is 120. # '\t' is counted as 1 character by default, and can be changed with the tab-width option @@ -95,6 +105,14 @@ issues: linters: - govet + - text: 'printf: non-constant format*' + linters: + - govet + + - text: 'return both a `nil` error and an invalid value*' + linters: + - nilnil + - linters: - revive text: "package comment should be of the form" diff --git a/Makefile b/Makefile index 4b24ceeff2..46a10a96e4 100644 --- a/Makefile +++ b/Makefile @@ -20,7 +20,7 @@ help: Makefile .PHONY: lint lint: - go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.61 + go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.62 golangci-lint run clean: diff --git a/devnet/bob.Dockerfile b/devnet/bob.Dockerfile index 5b4dff4c27..b8babd3f7b 100644 --- a/devnet/bob.Dockerfile +++ b/devnet/bob.Dockerfile @@ -1,7 +1,7 @@ # Copyright 2021 ChainSafe Systems (ON) # SPDX-License-Identifier: LGPL-3.0-only -FROM golang:1.20 +FROM golang:1.23 ARG DD_API_KEY=somekey ARG CHAIN=westend-local diff --git a/devnet/substrate_alice.Dockerfile b/devnet/substrate_alice.Dockerfile index c85c007dcd..82dec1a033 100644 --- a/devnet/substrate_alice.Dockerfile +++ b/devnet/substrate_alice.Dockerfile @@ -3,7 +3,7 @@ ARG POLKADOT_VERSION=v0.9.37 -FROM golang:1.20 as openmetrics +FROM golang:1.23 as openmetrics ARG METRICS_NAMESPACE=substrate.local.devnet WORKDIR /devnet diff --git a/devnet/substrate_bob.Dockerfile b/devnet/substrate_bob.Dockerfile index 8d4e680c69..2b966f11d5 100644 --- a/devnet/substrate_bob.Dockerfile +++ b/devnet/substrate_bob.Dockerfile @@ -3,7 +3,7 @@ ARG POLKADOT_VERSION=v0.9.37 -FROM golang:1.20 as openmetrics +FROM golang:1.23 as openmetrics ARG METRICS_NAMESPACE=substrate.local.devnet diff --git a/dot/network/block_announce.go b/dot/network/block_announce.go index 03da62da12..a526b2f7f5 100644 --- a/dot/network/block_announce.go +++ b/dot/network/block_announce.go @@ -145,7 +145,7 @@ func (s *Service) getBlockAnnounceHandshake() (Handshake, error) { return &BlockAnnounceHandshake{ Roles: s.cfg.Roles, - BestBlockNumber: uint32(latestBlock.Number), //nolint:gosec + BestBlockNumber: uint32(latestBlock.Number), BestBlockHash: latestBlock.Hash(), GenesisHash: s.blockState.GenesisHash(), }, nil diff --git a/dot/network/host.go b/dot/network/host.go index 4e0f2282d9..5ff2769bff 100644 --- a/dot/network/host.go +++ b/dot/network/host.go @@ -158,9 +158,9 @@ func newHost(ctx context.Context, cfg *Config) (*host, error) { // This needs to be explicitly mentioned // maxInPeers is later used in peerstate only and defines available Incoming connection slots - uint32(cfg.MaxPeers-cfg.MinPeers), //nolint:gosec + uint32(cfg.MaxPeers-cfg.MinPeers), // maxOutPeers is later used in peerstate only and defines available Outgoing connection slots - uint32(cfg.MaxPeers/2), //nolint:gosec + uint32(cfg.MaxPeers/2), reservedOnly, peerSetSlotAllocTime, ) diff --git a/dot/network/messages/block.go b/dot/network/messages/block.go index fdd1cb17aa..b65a593594 100644 --- a/dot/network/messages/block.go +++ b/dot/network/messages/block.go @@ -108,7 +108,7 @@ func (x *FromBlock) Encode() (FromBlockType, []byte) { if rawValue > uint(math.MaxUint32) { rawValue = math.MaxUint32 } - binary.LittleEndian.PutUint32(encoded, uint32(rawValue)) //nolint:gosec + binary.LittleEndian.PutUint32(encoded, uint32(rawValue)) return FromBlockNumber, encoded case common.Hash: return FromBlockHash, rawValue.ToBytes() diff --git a/dot/network/ratelimiters/sliding_window.go b/dot/network/ratelimiters/sliding_window.go index 16ecdc9e13..24ee655f4f 100644 --- a/dot/network/ratelimiters/sliding_window.go +++ b/dot/network/ratelimiters/sliding_window.go @@ -52,7 +52,7 @@ func (rl *SlidingWindowRateLimiter) IsLimitExceeded(id common.Hash) bool { recentRequests := rl.recentRequests(id) rl.limits.Put(id, recentRequests) - return uint32(len(recentRequests)) > rl.maxReqs //nolint:gosec + return uint32(len(recentRequests)) > rl.maxReqs } func (rl *SlidingWindowRateLimiter) recentRequests(id common.Hash) []time.Time { diff --git a/dot/network/utils.go b/dot/network/utils.go index 631705fab0..ed503f3503 100644 --- a/dot/network/utils.go +++ b/dot/network/utils.go @@ -88,7 +88,7 @@ func generateKey(seed int64, fp string) (crypto.PrivKey, error) { func loadKey(fp string) (crypto.PrivKey, error) { pth := path.Join(filepath.Clean(fp), DefaultKeyFile) if _, err := os.Stat(pth); os.IsNotExist(err) { - return nil, nil //nolint:nilnil + return nil, nil } keyData, err := os.ReadFile(filepath.Clean(pth)) if err != nil { @@ -106,7 +106,7 @@ func loadKey(fp string) (crypto.PrivKey, error) { func makeDir(fp string) error { _, e := os.Stat(fp) if os.IsNotExist(e) { - e = os.Mkdir(fp, os.ModePerm) //nolint:gosec + e = os.Mkdir(fp, os.ModePerm) if e != nil { return e } @@ -136,7 +136,7 @@ func saveKey(priv crypto.PrivKey, fp string) (err error) { func Uint64ToLEB128(in uint64) []byte { var out []byte for { - b := uint8(in & 0x7f) //nolint:gosec + b := uint8(in & 0x7f) in >>= 7 if in != 0 { b |= 0x80 @@ -200,7 +200,7 @@ func readStream(stream libp2pnetwork.Stream, bufPointer *[]byte, maxSize uint64) buf := *bufPointer if length > uint64(len(buf)) { logger.Warnf("received message with size %d greater than allocated message buffer size %d", length, len(buf)) - extraBytes := int(length) - len(buf) //nolint:gosec + extraBytes := int(length) - len(buf) *bufPointer = append(buf, make([]byte, extraBytes)...) buf = *bufPointer } @@ -210,7 +210,7 @@ func readStream(stream libp2pnetwork.Stream, bufPointer *[]byte, maxSize uint64) return 0, fmt.Errorf("%w: max %d, got %d", ErrGreaterThanMaxSize, maxSize, length) } - for tot < int(length) { //nolint:gosec + for tot < int(length) { n, err := stream.Read(buf[tot:]) if err != nil { return n + tot, err @@ -219,7 +219,7 @@ func readStream(stream libp2pnetwork.Stream, bufPointer *[]byte, maxSize uint64) tot += n } - if tot != int(length) { //nolint:gosec + if tot != int(length) { return tot, fmt.Errorf("%w: expected %d bytes, received %d bytes", ErrFailedToReadEntireMessage, length, tot) } diff --git a/dot/peerset/peerset.go b/dot/peerset/peerset.go index daca1f9a75..2397206c96 100644 --- a/dot/peerset/peerset.go +++ b/dot/peerset/peerset.go @@ -359,7 +359,7 @@ func (ps *PeerSet) reportPeer(change ReputationChange, peers ...peer.ID) error { ps.resultMsgCh <- Message{ Status: Drop, - setID: uint64(i), //nolint:gosec + setID: uint64(i), PeerID: pid, } @@ -406,7 +406,7 @@ func (ps *PeerSet) allocSlots(setIdx int) error { ps.resultMsgCh <- Message{ Status: Connect, - setID: uint64(setIdx), //nolint:gosec + setID: uint64(setIdx), PeerID: reservePeer, } } @@ -444,7 +444,7 @@ func (ps *PeerSet) allocSlots(setIdx int) error { ps.resultMsgCh <- Message{ Status: Connect, - setID: uint64(setIdx), //nolint:gosec + setID: uint64(setIdx), PeerID: peerID, } @@ -507,7 +507,7 @@ func (ps *PeerSet) removeReservedPeers(setID int, peers ...peer.ID) error { ps.resultMsgCh <- Message{ Status: Drop, - setID: uint64(setID), //nolint:gosec + setID: uint64(setID), PeerID: peerID, } } @@ -577,7 +577,7 @@ func (ps *PeerSet) removePeer(setID int, peers ...peer.ID) error { if status := ps.peerState.peerStatus(setID, pid); status == connectedPeer { ps.resultMsgCh <- Message{ Status: Drop, - setID: uint64(setID), //nolint:gosec + setID: uint64(setID), PeerID: pid, } @@ -614,7 +614,7 @@ func (ps *PeerSet) incoming(setID int, peers ...peer.ID) error { if !has { ps.resultMsgCh <- Message{ Status: Reject, - setID: uint64(setID), //nolint:gosec + setID: uint64(setID), PeerID: pid, } continue @@ -643,7 +643,7 @@ func (ps *PeerSet) incoming(setID int, peers ...peer.ID) error { state.RUnlock() message := Message{ - setID: uint64(setID), //nolint:gosec + setID: uint64(setID), PeerID: pid, } @@ -707,7 +707,7 @@ func (ps *PeerSet) disconnect(setIdx int, reason DropReason, peers ...peer.ID) e ps.resultMsgCh <- Message{ Status: Drop, - setID: uint64(setIdx), //nolint:gosec + setID: uint64(setIdx), PeerID: pid, } diff --git a/dot/rpc/modules/grandpa.go b/dot/rpc/modules/grandpa.go index 5e4d2a0e03..94f1ef39ef 100644 --- a/dot/rpc/modules/grandpa.go +++ b/dot/rpc/modules/grandpa.go @@ -103,19 +103,19 @@ func (gm *GrandpaModule) RoundState(r *http.Request, req *EmptyRequest, res *Rou return err } - totalWeight := uint32(len(voters)) //nolint:gosec + totalWeight := uint32(len(voters)) roundstate := RoundStateResponse{ - SetID: uint32(gm.blockFinalityAPI.GetSetID()), //nolint:gosec + SetID: uint32(gm.blockFinalityAPI.GetSetID()), Best: RoundState{ - Round: uint32(gm.blockFinalityAPI.GetRound()), //nolint:gosec + Round: uint32(gm.blockFinalityAPI.GetRound()), ThresholdWeight: thresholdWeight(totalWeight), TotalWeight: totalWeight, Prevotes: Votes{ - CurrentWeight: uint32(len(votes)), //nolint:gosec + CurrentWeight: uint32(len(votes)), Missing: missingPrevotes, }, Precommits: Votes{ - CurrentWeight: uint32(len(commits)), //nolint:gosec + CurrentWeight: uint32(len(commits)), Missing: missingPrecommits, }, }, diff --git a/dot/rpc/modules/system.go b/dot/rpc/modules/system.go index 1bb00fbc05..2f5685de78 100644 --- a/dot/rpc/modules/system.go +++ b/dot/rpc/modules/system.go @@ -236,9 +236,9 @@ func (sm *SystemModule) SyncState(r *http.Request, req *EmptyRequest, res *SyncS } *res = SyncStateResponse{ - CurrentBlock: uint32(h.Number), //nolint:gosec - HighestBlock: uint32(sm.syncAPI.HighestBlock()), //nolint:gosec - StartingBlock: uint32(sm.networkAPI.StartingBlock()), //nolint:gosec + CurrentBlock: uint32(h.Number), + HighestBlock: uint32(sm.syncAPI.HighestBlock()), + StartingBlock: uint32(sm.networkAPI.StartingBlock()), } return nil } diff --git a/dot/state/block.go b/dot/state/block.go index 6ef348b6e3..6167d19ca6 100644 --- a/dot/state/block.go +++ b/dot/state/block.go @@ -748,7 +748,7 @@ func (bs *BlockState) retrieveRangeFromDatabase(startHash common.Hash, lastPosition := blocksInRange - 1 inLoopHash := endHeader.Hash() - for currentPosition := int(lastPosition); currentPosition >= 0; currentPosition-- { //nolint:gosec + for currentPosition := int(lastPosition); currentPosition >= 0; currentPosition-- { hashes[currentPosition] = inLoopHash inLoopHeader, err := bs.loadHeaderFromDatabase(inLoopHash) @@ -840,12 +840,12 @@ func (bs *BlockState) GetArrivalTime(hash common.Hash) (time.Time, error) { } ns := binary.LittleEndian.Uint64(arrivalTime) - return time.Unix(0, int64(ns)), nil //nolint:gosec + return time.Unix(0, int64(ns)), nil } func (bs *BlockState) setArrivalTime(hash common.Hash, arrivalTime time.Time) error { buf := make([]byte, 8) - binary.LittleEndian.PutUint64(buf, uint64(arrivalTime.UnixNano())) //nolint:gosec + binary.LittleEndian.PutUint64(buf, uint64(arrivalTime.UnixNano())) return bs.db.Put(arrivalTimeKey(hash), buf) } diff --git a/dot/state/epoch.go b/dot/state/epoch.go index 5f700ffde9..390818eef4 100644 --- a/dot/state/epoch.go +++ b/dot/state/epoch.go @@ -475,7 +475,7 @@ func (s *EpochState) GetConfigData(epoch uint64, header *types.Header) (configDa } } - for tryEpoch := int(epoch); tryEpoch >= 0; tryEpoch-- { //nolint:gosec + for tryEpoch := int(epoch); tryEpoch >= 0; tryEpoch-- { if tryEpoch == 0 { return s.genesisEpochDescriptor.ConfigData, nil } @@ -819,7 +819,7 @@ func (s *EpochState) GetStartSlotForEpoch(epoch uint64, bestBlockHash common.Has if err != nil { return 0, fmt.Errorf("getting slot duration: %w", err) } - return uint64(time.Now().UnixNano()) / uint64(slotDuration.Nanoseconds()), nil //nolint:gosec + return uint64(time.Now().UnixNano()) / uint64(slotDuration.Nanoseconds()), nil } return 0, fmt.Errorf( diff --git a/dot/state/grandpa.go b/dot/state/grandpa.go index 31e1c30fbb..e74d15968f 100644 --- a/dot/state/grandpa.go +++ b/dot/state/grandpa.go @@ -490,7 +490,7 @@ func (s *GrandpaState) GetSetIDByBlockNumber(blockNumber uint) (uint64, error) { curr = curr - 1 - if int(curr) < 0 { //nolint:gosec + if int(curr) < 0 { return 0, nil } } diff --git a/dot/state/inmemory_storage.go b/dot/state/inmemory_storage.go index 32121dceab..ba4d544dbd 100644 --- a/dot/state/inmemory_storage.go +++ b/dot/state/inmemory_storage.go @@ -70,7 +70,7 @@ func (s *InmemoryStorageState) StoreTrie(ts *storage.TrieState, header *types.He } err = s.pruner.StoreJournalRecord( - deletedNodeHashes, insertedNodeHashes, header.Hash(), int64(header.Number)) //nolint:gosec + deletedNodeHashes, insertedNodeHashes, header.Hash(), int64(header.Number)) if err != nil { return fmt.Errorf("storing journal record: %w", err) } diff --git a/dot/state/test_helpers.go b/dot/state/test_helpers.go index 8eb46b5003..4df4f1a084 100644 --- a/dot/state/test_helpers.go +++ b/dot/state/test_helpers.go @@ -222,7 +222,7 @@ func AddBlocksToStateWithFixedBranches(t *testing.T, blockState *BlockState, dep for i := branch.depth; i < depth; i++ { d, err := types.NewBabePrimaryPreDigest( - 0, uint64(i+uint(j)+99), [32]byte{}, [64]byte{}).ToPreRuntimeDigest() //nolint:gosec + 0, uint64(i+uint(j)+99), [32]byte{}, [64]byte{}).ToPreRuntimeDigest() require.NoError(t, err) require.NotNil(t, d) digest := types.NewDigest() diff --git a/dot/state/transaction.go b/dot/state/transaction.go index 11412f0822..abb92728b1 100644 --- a/dot/state/transaction.go +++ b/dot/state/transaction.go @@ -93,7 +93,7 @@ func (s *TransactionState) AddToPool(vt *transaction.ValidTransaction) common.Ha hash := s.pool.Insert(vt) s.telemetry.SendMessage( - telemetry.NewTxpoolImport(uint(s.queue.Len()), uint(s.pool.Len())), //nolint:gosec + telemetry.NewTxpoolImport(uint(s.queue.Len()), uint(s.pool.Len())), ) return hash diff --git a/dot/sync/fullsync.go b/dot/sync/fullsync.go index 862e74327e..5ae57ea2c8 100644 --- a/dot/sync/fullsync.go +++ b/dot/sync/fullsync.go @@ -111,12 +111,12 @@ func (f *FullSyncStrategy) NextActions() ([]*SyncTask, error) { // our best block is equal or ahead of current target. // in the node's pov we are not legging behind so there's nothing to do // or we didn't receive block announces, so lets ask for more blocks - if uint32(bestBlockHeader.Number) >= currentTarget { //nolint:gosec + if uint32(bestBlockHeader.Number) >= currentTarget { return f.createTasks(reqsFromQueue), nil } startRequestAt := bestBlockHeader.Number + 1 - targetBlockNumber := startRequestAt + uint(f.numOfTasks)*127 //nolint:gosec + targetBlockNumber := startRequestAt + uint(f.numOfTasks)*127 if targetBlockNumber > uint(currentTarget) { targetBlockNumber = uint(currentTarget) @@ -327,7 +327,7 @@ func (f *FullSyncStrategy) OnBlockAnnounce(from peer.ID, msg *network.BlockAnnou } if msg.BestBlock { - f.peers.update(from, blockAnnounceHeaderHash, uint32(blockAnnounceHeader.Number)) //nolint:gosec + f.peers.update(from, blockAnnounceHeaderHash, uint32(blockAnnounceHeader.Number)) } highestFinalized, err := f.blockState.GetHighestFinalisedHeader() @@ -402,7 +402,7 @@ func (f *FullSyncStrategy) IsSynced() bool { } logger.Infof("highest block: %d target %d", highestBlock, f.peers.getTarget()) - return uint32(highestBlock)+messages.MaxBlocksInResponse >= f.peers.getTarget() //nolint:gosec + return uint32(highestBlock)+messages.MaxBlocksInResponse >= f.peers.getTarget() } type RequestResponseData struct { diff --git a/dot/test_utils.go b/dot/test_utils.go index 81eb12c420..423cde6b37 100644 --- a/dot/test_utils.go +++ b/dot/test_utils.go @@ -43,7 +43,7 @@ func NewTestGenesisRawFile(t *testing.T, config *cfg.Config) (filename string) { b, err := json.Marshal(gen) require.NoError(t, err) - err = os.WriteFile(filename, b, os.ModePerm) //nolint:gosec + err = os.WriteFile(filename, b, os.ModePerm) require.NoError(t, err) return filename diff --git a/internal/database/pebble.go b/internal/database/pebble.go index 567014973f..a30fcb39a5 100644 --- a/internal/database/pebble.go +++ b/internal/database/pebble.go @@ -29,7 +29,7 @@ func NewPebble(path string, inMemory bool) (*PebbleDB, error) { if inMemory { opts = &pebble.Options{FS: vfs.NewMem()} } else { - if err := os.MkdirAll(path, os.ModePerm); err != nil { //nolint:gosec + if err := os.MkdirAll(path, os.ModePerm); err != nil { return nil, err } } diff --git a/lib/babe/babe.go b/lib/babe/babe.go index edad571086..06ed8d25ed 100644 --- a/lib/babe/babe.go +++ b/lib/babe/babe.go @@ -176,7 +176,7 @@ func (b *Service) Start() error { // SlotDuration returns the current service slot duration in milliseconds func (b *Service) SlotDuration() uint64 { - return uint64(b.constants.slotDuration.Milliseconds()) //nolint:gosec + return uint64(b.constants.slotDuration.Milliseconds()) } // EpochLength returns the current service epoch duration @@ -266,7 +266,7 @@ func (b *Service) getAuthorityIndex(authorities []types.AuthorityRaw) (uint32, e for i, auth := range authorities { if bytes.Equal(pub.Encode(), auth.Key[:]) { - return uint32(i), nil //nolint:gosec + return uint32(i), nil } } @@ -473,9 +473,9 @@ func (b *Service) handleSlot(epoch uint64, slot Slot, } func getCurrentSlot(slotDuration time.Duration) uint64 { - return uint64(time.Now().UnixNano()) / uint64(slotDuration.Nanoseconds()) //nolint:gosec + return uint64(time.Now().UnixNano()) / uint64(slotDuration.Nanoseconds()) } func getSlotStartTime(slot uint64, slotDuration time.Duration) time.Time { - return time.Unix(0, int64(slot)*slotDuration.Nanoseconds()) //nolint:gosec + return time.Unix(0, int64(slot)*slotDuration.Nanoseconds()) } diff --git a/lib/babe/build.go b/lib/babe/build.go index 57ce4b2ca3..a19e085d2f 100644 --- a/lib/babe/build.go +++ b/lib/babe/build.go @@ -229,7 +229,7 @@ func (b *BlockBuilder) buildBlockExtrinsics(slot Slot, rt ExtrinsicHandler) []*t func buildBlockInherents(slot Slot, rt ExtrinsicHandler, parent *types.Header) ([][]byte, error) { // Setup inherents: add timstap0 idata := types.NewInherentData() - err := idata.SetInherent(types.Timstap0, uint64(slot.start.UnixMilli())) //nolint:gosec + err := idata.SetInherent(types.Timstap0, uint64(slot.start.UnixMilli())) if err != nil { return nil, err } diff --git a/lib/babe/secondary.go b/lib/babe/secondary.go index a5ea4ec769..55bdc00614 100644 --- a/lib/babe/secondary.go +++ b/lib/babe/secondary.go @@ -25,7 +25,7 @@ func getSecondarySlotAuthor(slot uint64, numAuths int, randomness Randomness) (u num := big.NewInt(int64(numAuths)) idx := new(big.Int).Mod(randBig, num) - return uint32(idx.Uint64()), nil //nolint:gosec + return uint32(idx.Uint64()), nil } // see https://github.com/paritytech/substrate/blob/master/client/consensus/babe/src/authorship.rs#L108 diff --git a/lib/babe/slot.go b/lib/babe/slot.go index 604a72bddc..0a1d65b479 100644 --- a/lib/babe/slot.go +++ b/lib/babe/slot.go @@ -48,7 +48,7 @@ func (s *slotHandler) waitForNextSlot(ctx context.Context) (Slot, error) { } currentSystemTime := time.Now() - currentSlotNumber := uint64(currentSystemTime.UnixNano()) / uint64(s.slotDuration.Nanoseconds()) //nolint:gosec + currentSlotNumber := uint64(currentSystemTime.UnixNano()) / uint64(s.slotDuration.Nanoseconds()) currentSlot := Slot{ start: currentSystemTime, duration: s.slotDuration, diff --git a/lib/babe/verify.go b/lib/babe/verify.go index b85c9e094d..aeaacdefd2 100644 --- a/lib/babe/verify.go +++ b/lib/babe/verify.go @@ -79,7 +79,7 @@ func (v *VerificationManager) SetOnDisabled(index uint32, header *types.Header) } // check that index is valid - if index >= uint32(len(v.epochInfo[epoch].authorities)) { //nolint:gosec + if index >= uint32(len(v.epochInfo[epoch].authorities)) { return ErrInvalidBlockProducerIndex } diff --git a/lib/blocktree/blocktree.go b/lib/blocktree/blocktree.go index 6dfe050f0e..0f31f5820f 100644 --- a/lib/blocktree/blocktree.go +++ b/lib/blocktree/blocktree.go @@ -285,7 +285,7 @@ func (bt *BlockTree) Prune(finalised Hash) (pruned []Hash) { } canonicalChainBlock := n newCanonicalChainBlockHashes := make([]common.Hash, newCanonicalChainBlocksCount) - for i := int(newCanonicalChainBlocksCount) - 1; i >= 0; i-- { //nolint:gosec + for i := int(newCanonicalChainBlocksCount) - 1; i >= 0; i-- { newCanonicalChainBlockHashes[i] = canonicalChainBlock.hash canonicalChainBlock = canonicalChainBlock.parent } @@ -565,5 +565,5 @@ func (bt *BlockTree) GetBlockRuntime(hash common.Hash) (runtime.Instance, error) currentNode = currentNode.parent } - return nil, nil //nolint:nilnil + return nil, nil } diff --git a/lib/genesis/helpers.go b/lib/genesis/helpers.go index b8ab3462f3..8d37cdab1f 100644 --- a/lib/genesis/helpers.go +++ b/lib/genesis/helpers.go @@ -294,14 +294,14 @@ func buildRawStructInterface(m interface{}, kv *keyValue) error { kv.value = kv.value + fmt.Sprintf("%x", tba) kv.iVal = append(kv.iVal, tba) case int64: - encVal, err := scale.Marshal(uint64(v2)) //nolint:gosec + encVal, err := scale.Marshal(uint64(v2)) if err != nil { return err } kv.value = kv.value + fmt.Sprintf("%x", encVal) kv.iVal = append(kv.iVal, big.NewInt(v2)) case int: - encVal, err := scale.Marshal(uint64(v2)) //nolint:gosec + encVal, err := scale.Marshal(uint64(v2)) if err != nil { return err } @@ -313,7 +313,7 @@ func buildRawStructInterface(m interface{}, kv *keyValue) error { return err } kv.value = kv.value + fmt.Sprintf("%x", encVal) - kv.iVal = append(kv.iVal, big.NewInt(int64(v2))) //nolint:gosec + kv.iVal = append(kv.iVal, big.NewInt(int64(v2))) case float64: encVal, err := scale.Marshal(uint64(v2)) if err != nil { @@ -357,7 +357,7 @@ func buildRawArrayInterface(a []interface{}, kv *keyValue) error { for _, v := range a { switch v2 := v.(type) { case int: - encVal, err := scale.Marshal(uint64(v2)) //nolint:gosec + encVal, err := scale.Marshal(uint64(v2)) if err != nil { return err } diff --git a/lib/grandpa/grandpa.go b/lib/grandpa/grandpa.go index bd3048b99f..4a3f50d25c 100644 --- a/lib/grandpa/grandpa.go +++ b/lib/grandpa/grandpa.go @@ -383,7 +383,7 @@ func (s *Service) handleIsPrimary() (bool, error) { pv := &Vote{ Hash: best.Hash(), - Number: uint32(best.Number), //nolint:gosec + Number: uint32(best.Number), } // send primary prevote message to network @@ -462,7 +462,7 @@ func (s *Service) retrieveBestFinalCandidate() (bestFinalCandidate *types.Grandp return nil, 0, fmt.Errorf("getting best final candidate: %w", err) } - if bestFinalCandidate.Number < uint32(s.head.Number) { //nolint:gosec + if bestFinalCandidate.Number < uint32(s.head.Number) { return nil, 0, fmt.Errorf("%w: candidate number %d, latest finalized block number %d", errBeforeFinalizedBlock, bestFinalCandidate.Number, s.head.Number) } @@ -484,7 +484,7 @@ func (s *Service) attemptToFinalize() (isFinalizable bool, err error) { } // once we reach the threshold we should stop sending precommit messages to other peers - if bestFinalCandidate.Number < uint32(s.head.Number) || precommitCount <= s.state.threshold() { //nolint:gosec + if bestFinalCandidate.Number < uint32(s.head.Number) || precommitCount <= s.state.threshold() { return false, nil } @@ -572,7 +572,7 @@ func (s *Service) determinePreVote() (*Vote, error) { // otherwise, we simply choose the head of our chain. primary := s.derivePrimary() prm, has := s.loadVote(primary.PublicKeyBytes(), prevote) - if has && prm.Vote.Number >= uint32(s.head.Number) { //nolint:gosec + if has && prm.Vote.Number >= uint32(s.head.Number) { vote = &prm.Vote } else { vote = NewVoteFromHeader(bestBlockHeader) @@ -836,7 +836,7 @@ func (s *Service) getPreVotedBlock() (Vote, error) { // if there are multiple, find the one with the highest number and return it highest := Vote{ Hash: s.head.Hash(), - Number: uint32(s.head.Number), //nolint:gosec + Number: uint32(s.head.Number), } for h, n := range blocks { @@ -881,7 +881,7 @@ func (s *Service) getGrandpaGHOST() (Vote, error) { // if there are multiple, find the one with the highest number and return it highest := Vote{ Hash: s.head.Hash(), - Number: uint32(s.head.Number), //nolint:gosec + Number: uint32(s.head.Number), } for h, n := range blocks { @@ -976,7 +976,7 @@ func (s *Service) getPossibleSelectedAncestors(votes []Vote, curr common.Hash, return nil, err } - selected[pred] = uint32(h.Number) //nolint:gosec + selected[pred] = uint32(h.Number) } else { selected, err = s.getPossibleSelectedAncestors(votes, pred, selected, stage, threshold) if err != nil { @@ -1005,7 +1005,7 @@ func (s *Service) getTotalVotesForBlock(hash common.Hash, stage Subround) (uint6 ev = len(s.pcEquivocations) } - return dv + uint64(ev), nil //nolint:gosec + return dv + uint64(ev), nil } // getVotesForBlock returns the number of observed votes for a block B. @@ -1288,7 +1288,7 @@ func verifyCommitMessageJustification(commitMessage CommitMessage, setID uint64, } } - validAndEqv := uint64(totalValidPrecommits) + uint64(len(eqvVoters)) //nolint:gosec + validAndEqv := uint64(totalValidPrecommits) + uint64(len(eqvVoters)) // confirm total # signatures >= grandpa threshold if validAndEqv < threshold { return fmt.Errorf("%w: for finalisation message; need %d votes but received only %d valid votes", diff --git a/lib/grandpa/message.go b/lib/grandpa/message.go index f69c9a522d..f89bae2d76 100644 --- a/lib/grandpa/message.go +++ b/lib/grandpa/message.go @@ -401,7 +401,7 @@ func (s *Service) newCatchUpResponse(round, setID uint64) (*CatchUpResponse, err PreVoteJustification: pvs, PreCommitJustification: pcs, Hash: header.Hash(), - Number: uint32(header.Number), //nolint:gosec + Number: uint32(header.Number), }, nil } diff --git a/lib/grandpa/message_handler.go b/lib/grandpa/message_handler.go index 041539a8fd..a806e5d9a8 100644 --- a/lib/grandpa/message_handler.go +++ b/lib/grandpa/message_handler.go @@ -50,17 +50,17 @@ func (h *MessageHandler) handleMessage(from peer.ID, m GrandpaMessage) (network. if err != nil { return nil, fmt.Errorf("handling vote message: %w", err) } - return nil, nil //nolint:nilnil + return nil, nil case *CommitMessage: err := h.grandpa.handleCommitMessage(msg) if err != nil { return nil, fmt.Errorf("handling commit message: %w", err) } - return nil, nil //nolint:nilnil + return nil, nil case *NeighbourPacketV1: h.handleNeighbourMessage(msg, from) - return nil, nil //nolint:nilnil + return nil, nil case *CatchUpRequest: return h.handleCatchUpRequest(msg) case *CatchUpResponse: @@ -389,7 +389,7 @@ func (s *Service) VerifyBlockJustification(finalizedHash common.Hash, finalizedN voters := finality_grandpa.NewVoterSet(idsAndWeights) target := client_grandpa.HashNumber[hash.H256, uint32]{ Hash: hash.H256(finalizedHash.ToBytes()), - Number: uint32(finalizedNumber), //nolint:gosec + Number: uint32(finalizedNumber), } justification, err := client_grandpa.DecodeGrandpaJustificationVerifyFinalizes[hash.H256, uint32, runtime.BlakeTwo256]( diff --git a/lib/grandpa/neighbor_tracker.go b/lib/grandpa/neighbor_tracker.go index f01da904dd..e7e375cb0d 100644 --- a/lib/grandpa/neighbor_tracker.go +++ b/lib/grandpa/neighbor_tracker.go @@ -82,7 +82,7 @@ func (nt *neighborTracker) run() { case block := <-nt.finalizationCha: if block != nil { - nt.updateState(block.SetID, block.Round, uint32(block.Header.Number)) //nolint + nt.updateState(block.SetID, block.Round, uint32(block.Header.Number)) err := nt.BroadcastNeighborMsg() if err != nil { logger.Errorf("broadcasting neighbour message: %v", err) diff --git a/lib/grandpa/types.go b/lib/grandpa/types.go index 15437395ae..99661e36c3 100644 --- a/lib/grandpa/types.go +++ b/lib/grandpa/types.go @@ -71,7 +71,7 @@ func (s *State) pubkeyToVoter(pk *ed25519.PublicKey) (*Voter, error) { // threshold returns the 2/3 |voters| threshold value // rounding is currently set to floor, which is ok since we check for strictly greater than the threshold func (s *State) threshold() uint64 { - return uint64(2 * len(s.voters) / 3) //nolint:gosec + return uint64(2 * len(s.voters) / 3) } // NewVote returns a new Vote given a block hash and number @@ -86,7 +86,7 @@ func NewVote(hash common.Hash, number uint32) *Vote { func NewVoteFromHeader(h *types.Header) *Vote { return &Vote{ Hash: h.Hash(), - Number: uint32(h.Number), //nolint:gosec + Number: uint32(h.Number), } } diff --git a/lib/runtime/allocator/freeing_bump.go b/lib/runtime/allocator/freeing_bump.go index b9c434f579..8207ed4273 100644 --- a/lib/runtime/allocator/freeing_bump.go +++ b/lib/runtime/allocator/freeing_bump.go @@ -129,7 +129,7 @@ func orderFromSize(size uint32) (Order, error) { // Compute the number of trailing zeroes to get the order. We adjust it by the number of // trailing zeroes in the minimum possible allocation. value := bits.TrailingZeros32(powerOfTwoSize) - bits.TrailingZeros32(MinPossibleAllocations) - return Order(value), nil //nolint:gosec + return Order(value), nil } // NilMarker is a special magic value for a pointer in a link that denotes the end of the linked list. @@ -234,7 +234,7 @@ func readHeaderFromMemory(mem runtime.Memory, headerPtr uint32) (Header, error) // check if the header represents an occupied or free allocation // and extract the header data by timing (and discarding) the high bits occupied := rawHeader&0x00000001_00000000 != 0 - headerData := uint32(rawHeader) //nolint:gosec + headerData := uint32(rawHeader) if occupied { order, err := orderFromRaw(headerData) diff --git a/lib/runtime/storage/storagediff.go b/lib/runtime/storage/storagediff.go index be93c7980a..d2d3dddf44 100644 --- a/lib/runtime/storage/storagediff.go +++ b/lib/runtime/storage/storagediff.go @@ -100,7 +100,7 @@ func (cs *storageDiff) deleteChildLimit(keyToChild string, if limit == -1 { cs.delete(keyToChild) deletedKeys := len(childChanges.upserts) + len(currentChildKeys) - return uint32(deletedKeys), true //nolint:gosec + return uint32(deletedKeys), true } allKeys := slices.Clone(currentChildKeys) @@ -121,7 +121,7 @@ func (cs *storageDiff) deleteChildLimit(keyToChild string, } cs.childChangeSet[keyToChild] = childChanges - return deleted, deleted == uint32(len(allKeys)) //nolint:gosec + return deleted, deleted == uint32(len(allKeys)) } // clearPrefixInChild clears keys with a specific prefix within a child trie. @@ -165,7 +165,7 @@ func (cs *storageDiff) clearPrefix(prefix []byte, trieKeys []string, limit int) } } - return deleted, deleted == uint32(len(keysToClear)) //nolint:gosec + return deleted, deleted == uint32(len(keysToClear)) } // getFromChild attempts to retrieve a value associated with a specific key diff --git a/lib/runtime/storage/trie.go b/lib/runtime/storage/trie.go index fa7bfe1989..e715a7c80f 100644 --- a/lib/runtime/storage/trie.go +++ b/lib/runtime/storage/trie.go @@ -364,7 +364,7 @@ func (t *TrieState) DeleteChildLimit(key []byte, limit *[]byte) ( } childTrieEntries := child.Entries() - qtyEntries := uint32(len(childTrieEntries)) //nolint:gosec + qtyEntries := uint32(len(childTrieEntries)) if limit == nil { err = t.state.DeleteChild(key) if err != nil { diff --git a/lib/runtime/test_helpers.go b/lib/runtime/test_helpers.go index 52ebba3f4f..46eccc5575 100644 --- a/lib/runtime/test_helpers.go +++ b/lib/runtime/test_helpers.go @@ -260,7 +260,7 @@ func InitializeRuntimeToTest(t *testing.T, instance Instance, parentHeader *type require.NoError(t, err) slotDuration := babeConfig.SlotDuration - timestamp := uint64(time.Now().UnixMilli()) //nolint:gosec + timestamp := uint64(time.Now().UnixMilli()) currentSlot := timestamp / slotDuration babeDigest := types.NewBabeDigest() diff --git a/lib/runtime/wazero/imports.go b/lib/runtime/wazero/imports.go index 250653b5e0..b077d19731 100644 --- a/lib/runtime/wazero/imports.go +++ b/lib/runtime/wazero/imports.go @@ -54,7 +54,7 @@ func newPointerSize(ptr, size uint32) (pointerSize uint64) { // splitPointerSize converts a 64bit pointer size to an // uint32 pointer and a uint32 size. func splitPointerSize(pointerSize uint64) (ptr uint32, size uint64) { - return uint32(pointerSize), pointerSize >> 32 //nolint:gosec + return uint32(pointerSize), pointerSize >> 32 } // read will read from 64 bit pointer size and return a byte slice @@ -70,7 +70,7 @@ func read(m api.Module, pointerSize uint64) (data []byte) { // copies a Go byte slice to wasm memory and returns the corresponding // 64 bit pointer size. func write(m api.Module, allocator runtime.Allocator, data []byte) (pointerSize uint64, err error) { - size := uint32(len(data)) //nolint:gosec + size := uint32(len(data)) pointer, err := allocator.Allocate(m.Memory(), size) if err != nil { return 0, fmt.Errorf("allocating: %w", err) @@ -169,7 +169,7 @@ func ext_crypto_ed25519_generate_version_1( } logger.Debug("generated ed25519 keypair with public key: " + kp.Public().Hex()) - return uint32(ret) //nolint:gosec + return uint32(ret) } func ext_crypto_ed25519_public_keys_version_1(ctx context.Context, m api.Module, keyTypeID uint32) uint64 { @@ -798,7 +798,7 @@ func ext_trie_blake2_256_root_version_2(ctx context.Context, m api.Module, dataS panic("nil runtime context") } - stateVersion, err := trie.ParseVersion(uint8(version)) //nolint:gosec + stateVersion, err := trie.ParseVersion(uint8(version)) if err != nil { logger.Errorf("failed parsing state version: %s", err) return 0 @@ -844,7 +844,7 @@ func ext_trie_blake2_256_ordered_root_version_2( data := read(m, dataSpan) - stateVersion, err := trie.ParseVersion(uint8(version)) //nolint:gosec + stateVersion, err := trie.ParseVersion(uint8(version)) if err != nil { logger.Errorf("failed parsing state version: %s", err) return 0 @@ -926,7 +926,7 @@ func ext_trie_blake2_256_verify_proof_version_2( panic("nil runtime context") } - _, err := trie.ParseVersion(uint8(version)) //nolint:gosec + _, err := trie.ParseVersion(uint8(version)) if err != nil { logger.Errorf("failed parsing state version: %s", err) return 0 @@ -963,7 +963,7 @@ func ext_misc_print_hex_version_1(_ context.Context, m api.Module, dataSpan uint } func ext_misc_print_num_version_1(_ context.Context, _ api.Module, data uint64) { - logger.Debugf("num: %d", int64(data)) //nolint:gosec + logger.Debugf("num: %d", int64(data)) } func ext_misc_print_utf8_version_1(_ context.Context, m api.Module, dataSpan uint64) { @@ -1041,7 +1041,7 @@ func ext_default_child_storage_read_version_1( panic("write overflow") } - size := uint32(len(value[offset:])) //nolint:gosec + size := uint32(len(value[offset:])) sizeBuf := make([]byte, 4) binary.LittleEndian.PutUint32(sizeBuf, size) @@ -1849,11 +1849,11 @@ func ext_offchain_submit_transaction_version_1(ctx context.Context, m api.Module func ext_offchain_timestamp_version_1(_ context.Context, _ api.Module) uint64 { now := time.Now().Unix() - return uint64(now) //nolint:gosec + return uint64(now) } func ext_offchain_sleep_until_version_1(_ context.Context, _ api.Module, deadline uint64) { - dur := time.Until(time.UnixMilli(int64(deadline))) //nolint:gosec + dur := time.Until(time.UnixMilli(int64(deadline))) if dur > 0 { time.Sleep(dur) } @@ -1911,7 +1911,7 @@ func ext_offchain_http_request_add_header_version_1( name := read(m, nameSpan) value := read(m, valueSpan) - offchainReq := rtCtx.OffchainHTTPSet.Get(int16(reqID)) //nolint:gosec + offchainReq := rtCtx.OffchainHTTPSet.Get(int16(reqID)) result := scale.NewResult(nil, nil) resultMode := scale.OK @@ -2239,7 +2239,7 @@ func ext_storage_read_version_1(ctx context.Context, m api.Module, keySpan, valu var data []byte switch { - case offset <= uint32(len(value)): //nolint:gosec + case offset <= uint32(len(value)): data = value[offset:] default: data = value[len(value):] @@ -2258,7 +2258,7 @@ func ext_storage_read_version_1(ctx context.Context, m api.Module, keySpan, valu panic("write overflow") } - size := uint32(len(data)) //nolint:gosec + size := uint32(len(data)) return mustWrite(m, rtCtx.Allocator, scale.MustMarshal(&size)) } diff --git a/lib/runtime/wazero/instance.go b/lib/runtime/wazero/instance.go index 6c53b8b233..d817a2e617 100644 --- a/lib/runtime/wazero/instance.go +++ b/lib/runtime/wazero/instance.go @@ -753,7 +753,7 @@ func (i *Instance) Exec(function string, data []byte) ([]byte, error) { panic("nil memory") } - dataLength := uint32(len(data)) //nolint:gosec + dataLength := uint32(len(data)) inputPtr, err := i.Context.Allocator.Allocate(memory, dataLength) if err != nil { return nil, fmt.Errorf("allocating input memory: %w", err) @@ -1007,7 +1007,7 @@ func (in *Instance) DecodeSessionKeys(enc []byte) ([]byte, error) { // PaymentQueryInfo returns information of a given extrinsic func (in *Instance) PaymentQueryInfo(ext []byte) (*types.RuntimeDispatchInfo, error) { - encLen, err := scale.Marshal(uint32(len(ext))) //nolint:gosec + encLen, err := scale.Marshal(uint32(len(ext))) if err != nil { return nil, err } @@ -1027,7 +1027,7 @@ func (in *Instance) PaymentQueryInfo(ext []byte) (*types.RuntimeDispatchInfo, er // QueryCallInfo returns information of a given extrinsic func (in *Instance) QueryCallInfo(ext []byte) (*types.RuntimeDispatchInfo, error) { - encLen, err := scale.Marshal(uint32(len(ext))) //nolint:gosec + encLen, err := scale.Marshal(uint32(len(ext))) if err != nil { return nil, err } @@ -1047,7 +1047,7 @@ func (in *Instance) QueryCallInfo(ext []byte) (*types.RuntimeDispatchInfo, error // QueryCallFeeDetails returns call fee details for given call func (in *Instance) QueryCallFeeDetails(ext []byte) (*types.FeeDetails, error) { - encLen, err := scale.Marshal(uint32(len(ext))) //nolint:gosec + encLen, err := scale.Marshal(uint32(len(ext))) if err != nil { return nil, err } diff --git a/lib/utils/lru-cache/lru_cache.go b/lib/utils/lru-cache/lru_cache.go index 827a39b239..2737015f69 100644 --- a/lib/utils/lru-cache/lru_cache.go +++ b/lib/utils/lru-cache/lru_cache.go @@ -79,7 +79,7 @@ func (c *LRUCache[K, V]) Put(key K, value V) { } // If the cache is full, remove the least recently used item (from the back of the list). - if len(c.cache) >= int(c.capacity) { //nolint:gosec + if len(c.cache) >= int(c.capacity) { // Get the least recently used item (back of the list). lastElem := c.lruList.Back() if lastElem != nil { diff --git a/lib/utils/utils.go b/lib/utils/utils.go index e6182f43f1..2ad78927cd 100644 --- a/lib/utils/utils.go +++ b/lib/utils/utils.go @@ -75,7 +75,7 @@ func KeystoreDir(basepath string) (keystorepath string, err error) { // if basepath does not exist, create it if _, err = os.Stat(keystorepath); os.IsNotExist(err) { - err = os.Mkdir(keystorepath, os.ModePerm) //nolint:gosec + err = os.Mkdir(keystorepath, os.ModePerm) if err != nil { return "", fmt.Errorf("failed to create data directory: %s", err) } @@ -83,7 +83,7 @@ func KeystoreDir(basepath string) (keystorepath string, err error) { // if basepath/keystore does not exist, create it if _, err = os.Stat(keystorepath); os.IsNotExist(err) { - err = os.Mkdir(keystorepath, os.ModePerm) //nolint:gosec + err = os.Mkdir(keystorepath, os.ModePerm) if err != nil { return "", fmt.Errorf("failed to create keystore directory: %s", err) } diff --git a/pkg/finality-grandpa/bitfield.go b/pkg/finality-grandpa/bitfield.go index d5be57c2b9..86bec52f71 100644 --- a/pkg/finality-grandpa/bitfield.go +++ b/pkg/finality-grandpa/bitfield.go @@ -136,7 +136,7 @@ func iter1s(iter []uint64, start, step uint) (bit1s []bit1) { for j := uint(0); j < steps; j++ { bitPos := start + (j << step) if testBit(word, bitPos) { - bit1s = append(bit1s, bit1{uint(i)*64 + bitPos}) //nolint:gosec + bit1s = append(bit1s, bit1{uint(i)*64 + bitPos}) } } } diff --git a/pkg/scale/decode.go b/pkg/scale/decode.go index 97ebb66308..af52cf5cd7 100644 --- a/pkg/scale/decode.go +++ b/pkg/scale/decode.go @@ -688,7 +688,7 @@ func (ds *decodeState) decodeFixedWidthInt(dstv reflect.Value) (err error) { if err != nil { return } - out = int16(binary.LittleEndian.Uint16(buf)) //nolint:gosec + out = int16(binary.LittleEndian.Uint16(buf)) case uint16: buf := make([]byte, 2) _, err = ds.Read(buf) @@ -702,7 +702,7 @@ func (ds *decodeState) decodeFixedWidthInt(dstv reflect.Value) (err error) { if err != nil { return } - out = int32(binary.LittleEndian.Uint32(buf)) //nolint:gosec + out = int32(binary.LittleEndian.Uint32(buf)) case uint32: buf := make([]byte, 4) _, err = ds.Read(buf) @@ -716,7 +716,7 @@ func (ds *decodeState) decodeFixedWidthInt(dstv reflect.Value) (err error) { if err != nil { return } - out = int64(binary.LittleEndian.Uint64(buf)) //nolint:gosec + out = int64(binary.LittleEndian.Uint64(buf)) case uint64: buf := make([]byte, 8) _, err = ds.Read(buf) diff --git a/pkg/scale/encode.go b/pkg/scale/encode.go index bf4f81682f..9429fb0bff 100644 --- a/pkg/scale/encode.go +++ b/pkg/scale/encode.go @@ -86,7 +86,7 @@ func (es *encodeState) marshal(in interface{}) (err error) { switch in := in.(type) { case int: - err = es.encodeUint(uint(in)) //nolint:gosec + err = es.encodeUint(uint(in)) case uint: err = es.encodeUint(in) case int8, uint8, int16, uint16, int32, uint32, int64, uint64: @@ -279,14 +279,14 @@ func (es *encodeState) encodeBigInt(i *big.Int) (err error) { case i == nil: err = fmt.Errorf("%w", errBigIntIsNil) case i.Cmp(new(big.Int).Lsh(big.NewInt(1), 6)) < 0: - err = binary.Write(es, binary.LittleEndian, uint8(i.Int64()<<2)) //nolint:gosec + err = binary.Write(es, binary.LittleEndian, uint8(i.Int64()<<2)) case i.Cmp(new(big.Int).Lsh(big.NewInt(1), 14)) < 0: - err = binary.Write(es, binary.LittleEndian, uint16(i.Int64()<<2)+1) //nolint:gosec + err = binary.Write(es, binary.LittleEndian, uint16(i.Int64()<<2)+1) case i.Cmp(new(big.Int).Lsh(big.NewInt(1), 30)) < 0: - err = binary.Write(es, binary.LittleEndian, uint32(i.Int64()<<2)+2) //nolint:gosec + err = binary.Write(es, binary.LittleEndian, uint32(i.Int64()<<2)+2) default: numBytes := len(i.Bytes()) - topSixBits := uint8(numBytes - 4) //nolint:gosec + topSixBits := uint8(numBytes - 4) lengthByte := topSixBits<<2 + 3 // write byte which encodes mode and length @@ -337,15 +337,15 @@ func (es *encodeState) encodeFixedWidthInt(i interface{}) (err error) { case uint8: err = binary.Write(es, binary.LittleEndian, i) case int16: - err = binary.Write(es, binary.LittleEndian, uint16(i)) //nolint:gosec + err = binary.Write(es, binary.LittleEndian, uint16(i)) case uint16: err = binary.Write(es, binary.LittleEndian, i) case int32: - err = binary.Write(es, binary.LittleEndian, uint32(i)) //nolint:gosec + err = binary.Write(es, binary.LittleEndian, uint32(i)) case uint32: err = binary.Write(es, binary.LittleEndian, i) case int64: - err = binary.Write(es, binary.LittleEndian, uint64(i)) //nolint:gosec + err = binary.Write(es, binary.LittleEndian, uint64(i)) case uint64: err = binary.Write(es, binary.LittleEndian, i) default: @@ -377,7 +377,7 @@ func (es *encodeState) encodeStruct(in interface{}) (err error) { // encodeLength is a helper function that calls encodeUint, which is the scale length encoding func (es *encodeState) encodeLength(l int) (err error) { - return es.encodeUint(uint(l)) //nolint:gosec + return es.encodeUint(uint(l)) } // encodeUint performs the following on integer i: @@ -394,9 +394,9 @@ func (es *encodeState) encodeUint(i uint) (err error) { case i < 1<<6: err = binary.Write(es, binary.LittleEndian, byte(i)<<2) case i < 1<<14: - err = binary.Write(es, binary.LittleEndian, uint16(i<<2)+1) //nolint:gosec + err = binary.Write(es, binary.LittleEndian, uint16(i<<2)+1) case i < 1<<30: - err = binary.Write(es, binary.LittleEndian, uint32(i<<2)+2) //nolint:gosec + err = binary.Write(es, binary.LittleEndian, uint32(i<<2)+2) default: o := make([]byte, 8) m := i @@ -409,7 +409,7 @@ func (es *encodeState) encodeUint(i uint) (err error) { m = m >> 8 } - topSixBits := uint8(numBytes - 4) //nolint:gosec + topSixBits := uint8(numBytes - 4) lengthByte := topSixBits<<2 + 3 err = binary.Write(es, binary.LittleEndian, lengthByte) diff --git a/pkg/trie/node/children.go b/pkg/trie/node/children.go index 0502264a3f..725366b42e 100644 --- a/pkg/trie/node/children.go +++ b/pkg/trie/node/children.go @@ -15,7 +15,7 @@ func (n *Node) ChildrenBitmap() (bitmap uint16) { if n.Children[i] == nil { continue } - bitmap |= 1 << uint(i) //nolint:gosec + bitmap |= 1 << uint(i) } return bitmap } diff --git a/pkg/trie/node/node.go b/pkg/trie/node/node.go index c0c860dc23..42296e5026 100644 --- a/pkg/trie/node/node.go +++ b/pkg/trie/node/node.go @@ -57,13 +57,13 @@ func (n *Node) StringNode() (stringNode *gotree.Node) { stringNode = gotree.New(n.Kind().String()) stringNode.Appendf("Generation: %d", n.Generation) stringNode.Appendf("Dirty: %t", n.Dirty) - stringNode.Appendf("Key: " + bytesToString(n.PartialKey)) //nolint:govet - stringNode.Appendf("Storage value: " + bytesToString(n.StorageValue)) //nolint:govet - stringNode.Appendf("IsHashed: " + strconv.FormatBool(n.IsHashedValue)) //nolint:govet - if n.Descendants > 0 { // must be a branch + stringNode.Appendf("Key: " + bytesToString(n.PartialKey)) + stringNode.Appendf("Storage value: " + bytesToString(n.StorageValue)) + stringNode.Appendf("IsHashed: " + strconv.FormatBool(n.IsHashedValue)) + if n.Descendants > 0 { // must be a branch stringNode.Appendf("Descendants: %d", n.Descendants) } - stringNode.Appendf("Merkle value: " + bytesToString(n.MerkleValue)) //nolint:govet + stringNode.Appendf("Merkle value: " + bytesToString(n.MerkleValue)) for i, child := range n.Children { if child == nil { diff --git a/pkg/trie/triedb/cache.go b/pkg/trie/triedb/cache.go index c73db2aede..b5517ccfa4 100644 --- a/pkg/trie/triedb/cache.go +++ b/pkg/trie/triedb/cache.go @@ -187,7 +187,7 @@ func (no BranchCachedNode[H]) children() []child[H] { //nolint:unused r := []child[H]{} for i, ch := range no.Children { if ch != nil { - nibble := uint8(i) //nolint:gosec + nibble := uint8(i) r = append(r, child[H]{ nibble: &nibble, CachedNodeHandle: ch, diff --git a/pkg/trie/triedb/iterator.go b/pkg/trie/triedb/iterator.go index 4bb664217e..83a7cb1ff3 100644 --- a/pkg/trie/triedb/iterator.go +++ b/pkg/trie/triedb/iterator.go @@ -411,7 +411,7 @@ func (ri *rawIterator[H, Hasher]) nextRawItem(fwd bool) (*rawItem[H], error) { child := children[i] if child != nil { ri.keyNibbles.Pop() - ri.keyNibbles.Push(uint8(i)) //nolint:gosec + ri.keyNibbles.Push(uint8(i)) node, nodeHash, err := ri.db.getNodeOrLookup(children[i], ri.keyNibbles.Prefix(), true) if err != nil { diff --git a/pkg/trie/triedb/nibbles/leftnibbles.go b/pkg/trie/triedb/nibbles/leftnibbles.go index 8e0bb5ef44..115cd4345a 100644 --- a/pkg/trie/triedb/nibbles/leftnibbles.go +++ b/pkg/trie/triedb/nibbles/leftnibbles.go @@ -31,7 +31,7 @@ func (ln LeftNibbles) Len() uint { } func leftNibbleAt(v1 []byte, ix uint) uint8 { - return atLeft(uint8(ix%NibblesPerByte), v1[ix/NibblesPerByte]) //nolint:gosec + return atLeft(uint8(ix%NibblesPerByte), v1[ix/NibblesPerByte]) } // Get the nibble at a nibble index padding with a 0 nibble. Returns nil if the index is diff --git a/pkg/trie/triedb/nibbles/nibbles.go b/pkg/trie/triedb/nibbles/nibbles.go index 6bba9564a5..690cffb727 100644 --- a/pkg/trie/triedb/nibbles/nibbles.go +++ b/pkg/trie/triedb/nibbles/nibbles.go @@ -44,7 +44,7 @@ func NewNibblesFromNodeKey(from NodeKey) Nibbles { // Get the nibble at position i. func (n Nibbles) At(i uint) uint8 { ix := (n.offset + i) / NibblesPerByte - pad := uint8((n.offset + i) % NibblesPerByte) //nolint:gosec + pad := uint8((n.offset + i) % NibblesPerByte) return atLeft(pad, n.data[ix]) } @@ -98,7 +98,7 @@ func (p Prefix) JoinedBytes() []byte { // the node. func (n Nibbles) Left() Prefix { split := n.offset / NibblesPerByte - ix := uint8(n.offset % NibblesPerByte) //nolint:gosec + ix := uint8(n.offset % NibblesPerByte) if ix == 0 { return Prefix{Key: n.data[:split]} } @@ -150,10 +150,10 @@ func biggestDepth(v1 []uint8, v2 []uint8) uint { } for a := 0; a < upperBound; a++ { if v1[a] != v2[a] { - return uint(a)*NibblesPerByte + leftCommon(v1[a], v2[a]) //nolint:gosec + return uint(a)*NibblesPerByte + leftCommon(v1[a], v2[a]) } } - return uint(upperBound) * NibblesPerByte //nolint:gosec + return uint(upperBound) * NibblesPerByte } // How many of the same nibbles at the beginning do we match with them? @@ -245,7 +245,7 @@ type Partial struct { // first encoded byte and following slice. func (n Nibbles) RightPartial() Partial { split := n.offset / NibblesPerByte - nb := uint8(n.Len() % NibblesPerByte) //nolint:gosec + nb := uint8(n.Len() % NibblesPerByte) if nb > 0 { return Partial{ First: nb, diff --git a/pkg/trie/triedb/nibbles/nibbleslice.go b/pkg/trie/triedb/nibbles/nibbleslice.go index 2b70eb9d1a..21aa282a62 100644 --- a/pkg/trie/triedb/nibbles/nibbleslice.go +++ b/pkg/trie/triedb/nibbles/nibbleslice.go @@ -37,7 +37,7 @@ func (n NibbleSlice) IsEmpty() bool { func (n NibbleSlice) At(idx uint) uint8 { ix := idx / NibblesPerByte pad := idx % NibblesPerByte - return atLeft(uint8(pad), n.inner[ix]) //nolint:gosec + return atLeft(uint8(pad), n.inner[ix]) } // Push a nibble onto the [NibbleSlice]. Ignores the high 4 bits. @@ -47,7 +47,7 @@ func (n *NibbleSlice) Push(nibble uint8) { n.inner = append(n.inner, PushAtLeft(0, nibble, 0)) } else { output := n.inner[len(n.inner)-1] - n.inner[len(n.inner)-1] = PushAtLeft(uint8(i), nibble, output) //nolint:gosec + n.inner[len(n.inner)-1] = PushAtLeft(uint8(i), nibble, output) } n.len++ } @@ -135,7 +135,7 @@ func (n *NibbleSlice) AppendOptionalSliceAndNibble(oSlice *Nibbles, oIndex *uint // Get Prefix representation of this [NibbleSlice]. func (n NibbleSlice) Prefix() Prefix { split := n.len / NibblesPerByte - pos := uint8(n.len % NibblesPerByte) //nolint:gosec + pos := uint8(n.len % NibblesPerByte) if pos == 0 { return Prefix{ Key: n.inner[:split], diff --git a/pkg/trie/triedb/node.go b/pkg/trie/triedb/node.go index 851775a5d9..ad07800a3c 100644 --- a/pkg/trie/triedb/node.go +++ b/pkg/trie/triedb/node.go @@ -218,7 +218,7 @@ func newNodeFromEncoded[H hash.Hash](nodeHash H, data []byte, storage *nodeStora } return newChild, nil } - return nil, nil //nolint:nilnil + return nil, nil } children := [codec.ChildrenCapacity]NodeHandle{} diff --git a/scripts/p2p/common_p2p.go b/scripts/p2p/common_p2p.go index f0c1419141..82c97333dd 100644 --- a/scripts/p2p/common_p2p.go +++ b/scripts/p2p/common_p2p.go @@ -142,7 +142,7 @@ func ReadStream(stream lip2pnetwork.Stream) ([]byte, error) { } var tot int - for tot < int(length) { //nolint:gosec + for tot < int(length) { n, err := stream.Read(responseBuf[tot:]) if err != nil { return nil, fmt.Errorf("reading stream: %w", err) @@ -150,7 +150,7 @@ func ReadStream(stream lip2pnetwork.Stream) ([]byte, error) { tot += n } - if tot != int(length) { //nolint:gosec + if tot != int(length) { return nil, fmt.Errorf("%w: expected %d bytes, received %d bytes", network.ErrFailedToReadEntireMessage, length, tot) } diff --git a/scripts/retrieve_block/retrieve_block.go b/scripts/retrieve_block/retrieve_block.go index 0d4fc45387..38a31af304 100644 --- a/scripts/retrieve_block/retrieve_block.go +++ b/scripts/retrieve_block/retrieve_block.go @@ -35,10 +35,10 @@ func buildRequestMessage(arg string) *messages.BlockRequestMessage { switch strings.ToLower(params[1]) { case "asc": - return messages.NewBlockRequest(targetBlock, uint32(amount), //nolint:gosec + return messages.NewBlockRequest(targetBlock, uint32(amount), messages.BootstrapRequestData, messages.Ascending) case "desc": - return messages.NewBlockRequest(targetBlock, uint32(amount), //nolint:gosec + return messages.NewBlockRequest(targetBlock, uint32(amount), messages.BootstrapRequestData, messages.Descending) } @@ -57,7 +57,7 @@ func parseTargetBlock(arg string) messages.FromBlock { return messages.FromBlock{} } - return *messages.NewFromBlock(uint(value)) //nolint:gosec + return *messages.NewFromBlock(uint(value)) } func waitAndStoreResponse(stream lip2pnetwork.Stream, outputFile string) bool { @@ -86,7 +86,7 @@ func waitAndStoreResponse(stream lip2pnetwork.Stream, outputFile string) bool { } log.Println(resultOutput.String()) - err = os.WriteFile(outputFile, []byte(common.BytesToHex(output)), os.ModePerm) //nolint:gosec + err = os.WriteFile(outputFile, []byte(common.BytesToHex(output)), os.ModePerm) if err != nil { log.Printf("failed to write response to file %s: %s\n", outputFile, err.Error()) return false diff --git a/tests/rpc/rpc_03-chain_test.go b/tests/rpc/rpc_03-chain_test.go index a9c355b052..18d87b0d5b 100644 --- a/tests/rpc/rpc_03-chain_test.go +++ b/tests/rpc/rpc_03-chain_test.go @@ -47,7 +47,7 @@ func TestChainRPC(t *testing.T) { assert.Regexp(t, regex32BytesHex, finalizedHead) var finalizedBlock modules.ChainBlockResponse - fetchWithTimeout(ctx, t, "chain_getBlock", fmt.Sprintf(`["`+finalizedHead+`"]`), &finalizedBlock) //nolint:govet + fetchWithTimeout(ctx, t, "chain_getBlock", fmt.Sprintf(`["`+finalizedHead+`"]`), &finalizedBlock) finalizedNumber, err := common.HexToUint(finalizedBlock.Block.Header.Number) if err != nil { return false, fmt.Errorf("cannot convert header number to uint: %w", err) @@ -68,7 +68,7 @@ func TestChainRPC(t *testing.T) { assert.Regexp(t, regex32BytesHex, finalizedHash) var finalizedBlock modules.ChainBlockResponse - fetchWithTimeout(ctx, t, "chain_getBlock", fmt.Sprintf(`["`+finalizedHash+`"]`), &finalizedBlock) //nolint:govet + fetchWithTimeout(ctx, t, "chain_getBlock", fmt.Sprintf(`["`+finalizedHash+`"]`), &finalizedBlock) finalizedHeader := finalizedBlock.Block.Header @@ -89,7 +89,7 @@ func TestChainRPC(t *testing.T) { var parentBlock modules.ChainBlockResponse fetchWithTimeout(ctx, t, "chain_getBlock", - fmt.Sprintf(`["`+finalizedHeader.ParentHash+`"]`), &parentBlock) //nolint:govet + fmt.Sprintf(`["`+finalizedHeader.ParentHash+`"]`), &parentBlock) // Check and clear unpredictable fields assert.Regexp(t, regex32BytesHex, parentBlock.Block.Header.ParentHash) diff --git a/tests/utils/gossamer_utils.go b/tests/utils/gossamer_utils.go index ed12e5888f..e508bab9b8 100644 --- a/tests/utils/gossamer_utils.go +++ b/tests/utils/gossamer_utils.go @@ -30,7 +30,7 @@ func GenerateGenesisAuths(t *testing.T, numAuths int) (genesisPath string) { require.NoError(t, err) genesisPath = filepath.Join(t.TempDir(), "chain-spec.json") - err = os.WriteFile(genesisPath, buildSpecJSON, os.ModePerm) //nolint:gosec + err = os.WriteFile(genesisPath, buildSpecJSON, os.ModePerm) require.NoError(t, err) return genesisPath diff --git a/tests/utils/node/node.go b/tests/utils/node/node.go index d8e0c7452e..0d97eba40e 100644 --- a/tests/utils/node/node.go +++ b/tests/utils/node/node.go @@ -95,17 +95,17 @@ func (n *Node) setDefaults(t *testing.T) { if n.tomlConfig.Network.Port == 0 { const basePort uint16 = 7004 - n.tomlConfig.Network.Port = basePort + uint16(*n.index) //nolint:gosec + n.tomlConfig.Network.Port = basePort + uint16(*n.index) } if n.tomlConfig.RPC.IsRPCEnabled() && n.tomlConfig.RPC.Port == 0 { const basePort uint32 = 8540 - n.tomlConfig.RPC.Port = basePort + uint32(*n.index) //nolint:gosec + n.tomlConfig.RPC.Port = basePort + uint32(*n.index) } if n.tomlConfig.RPC.IsWSEnabled() && n.tomlConfig.RPC.WSPort == 0 { const basePort uint32 = 8546 - n.tomlConfig.RPC.WSPort = basePort + uint32(*n.index) //nolint:gosec + n.tomlConfig.RPC.WSPort = basePort + uint32(*n.index) } userSetWriter := n.writer != nil && n.writer != io.Discard diff --git a/tests/utils/rpc/chain.go b/tests/utils/rpc/chain.go index 94fb0dc995..74094ff7cb 100644 --- a/tests/utils/rpc/chain.go +++ b/tests/utils/rpc/chain.go @@ -69,7 +69,7 @@ func GetFinalizedHead(ctx context.Context, rpcPort string) ( // TODO: add setID, hard-coded at 1 for now func GetFinalizedHeadByRound(ctx context.Context, rpcPort string, round uint64) ( hash common.Hash, err error) { - p := strconv.Itoa(int(round)) //nolint:gosec + p := strconv.Itoa(int(round)) endpoint := NewEndpoint(rpcPort) const method = "chain_getFinalizedHeadByRound" params := "[" + p + ",1]" diff --git a/tests/utils/rpc/dev.go b/tests/utils/rpc/dev.go index a02f2640b4..4c4e81efae 100644 --- a/tests/utils/rpc/dev.go +++ b/tests/utils/rpc/dev.go @@ -45,7 +45,7 @@ func SlotDuration(ctx context.Context, rpcPort string) ( slotDurationUint64 := binary.LittleEndian.Uint64(b) - slotDuration = time.Millisecond * time.Duration(slotDurationUint64) //nolint:gosec + slotDuration = time.Millisecond * time.Duration(slotDurationUint64) return slotDuration, nil }