diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4f4252792d..836b92cc30 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -103,7 +103,7 @@ jobs: - name: Generate coverage report run: | go test ./... -coverprofile=coverage.out -covermode=atomic -timeout=20m - - uses: codecov/codecov-action@v4.5.0 + - uses: codecov/codecov-action@v4.6.0 with: files: ./coverage.out flags: unit-tests diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index ebb15214aa..0a025d00c2 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -89,7 +89,7 @@ jobs: - name: Test - Race run: make test-using-race-detector - - uses: codecov/codecov-action@v4.5.0 + - uses: codecov/codecov-action@v4.6.0 with: if_ci_failed: success informational: true diff --git a/.gitignore b/.gitignore index d5d719704f..3b90a7520f 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,6 @@ tmp # node_modules used by polkadot.js/api tests tests/polkadotjs_test/node_modules !tests/polkadotjs_test/test/*.wasm + +# mac specific +.DS_Store \ No newline at end of file diff --git a/.golangci.yml b/.golangci.yml index 8f4967776a..e0a2706c61 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -6,14 +6,10 @@ run: build-tags: - integration - skip-files: - - .*mock_.*\.go - - .*mocks\/.*\.go - linters-settings: govet: # report about shadowed variables - check-shadowing: true + shadow: true revive: severity: warning @@ -41,12 +37,12 @@ linters-settings: - finalized - finalize - initialize + - color linters: enable: - bodyclose - errcheck - - exportloopref - goconst - gocyclo - gofmt @@ -70,6 +66,10 @@ linters: - unused issues: + exclude-files: + - .*mock_.*\.go + - .*mocks\/.*\.go + exclude-rules: - path: _test\.go linters: diff --git a/Makefile b/Makefile index c25f80ba7d..4b24ceeff2 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.54 + go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.61 golangci-lint run clean: diff --git a/dot/network/block_announce.go b/dot/network/block_announce.go index a526b2f7f5..03da62da12 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), + BestBlockNumber: uint32(latestBlock.Number), //nolint:gosec BestBlockHash: latestBlock.Hash(), GenesisHash: s.blockState.GenesisHash(), }, nil diff --git a/dot/network/host.go b/dot/network/host.go index a838c585b0..a84eff48e8 100644 --- a/dot/network/host.go +++ b/dot/network/host.go @@ -157,9 +157,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), + uint32(cfg.MaxPeers-cfg.MinPeers), //nolint:gosec // maxOutPeers is later used in peerstate only and defines available Outgoing connection slots - uint32(cfg.MaxPeers/2), + uint32(cfg.MaxPeers/2), //nolint:gosec reservedOnly, peerSetSlotAllocTime, ) diff --git a/dot/network/messages/block.go b/dot/network/messages/block.go index b65a593594..fdd1cb17aa 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)) + binary.LittleEndian.PutUint32(encoded, uint32(rawValue)) //nolint:gosec 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 24ee655f4f..16ecdc9e13 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 + return uint32(len(recentRequests)) > rl.maxReqs //nolint:gosec } func (rl *SlidingWindowRateLimiter) recentRequests(id common.Hash) []time.Time { diff --git a/dot/network/utils.go b/dot/network/utils.go index 2029280298..3b376c769c 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 + return nil, nil //nolint:nilnil } 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) + e = os.Mkdir(fp, os.ModePerm) //nolint:gosec 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) + b := uint8(in & 0x7f) //nolint:gosec 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) + extraBytes := int(length) - len(buf) //nolint:gosec *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) { + for tot < int(length) { //nolint:gosec 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) { + if tot != int(length) { //nolint:gosec 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 2397206c96..daca1f9a75 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), + setID: uint64(i), //nolint:gosec PeerID: pid, } @@ -406,7 +406,7 @@ func (ps *PeerSet) allocSlots(setIdx int) error { ps.resultMsgCh <- Message{ Status: Connect, - setID: uint64(setIdx), + setID: uint64(setIdx), //nolint:gosec PeerID: reservePeer, } } @@ -444,7 +444,7 @@ func (ps *PeerSet) allocSlots(setIdx int) error { ps.resultMsgCh <- Message{ Status: Connect, - setID: uint64(setIdx), + setID: uint64(setIdx), //nolint:gosec PeerID: peerID, } @@ -507,7 +507,7 @@ func (ps *PeerSet) removeReservedPeers(setID int, peers ...peer.ID) error { ps.resultMsgCh <- Message{ Status: Drop, - setID: uint64(setID), + setID: uint64(setID), //nolint:gosec 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), + setID: uint64(setID), //nolint:gosec 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), + setID: uint64(setID), //nolint:gosec PeerID: pid, } continue @@ -643,7 +643,7 @@ func (ps *PeerSet) incoming(setID int, peers ...peer.ID) error { state.RUnlock() message := Message{ - setID: uint64(setID), + setID: uint64(setID), //nolint:gosec 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), + setID: uint64(setIdx), //nolint:gosec PeerID: pid, } diff --git a/dot/rpc/modules/grandpa.go b/dot/rpc/modules/grandpa.go index 94f1ef39ef..5e4d2a0e03 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)) + totalWeight := uint32(len(voters)) //nolint:gosec roundstate := RoundStateResponse{ - SetID: uint32(gm.blockFinalityAPI.GetSetID()), + SetID: uint32(gm.blockFinalityAPI.GetSetID()), //nolint:gosec Best: RoundState{ - Round: uint32(gm.blockFinalityAPI.GetRound()), + Round: uint32(gm.blockFinalityAPI.GetRound()), //nolint:gosec ThresholdWeight: thresholdWeight(totalWeight), TotalWeight: totalWeight, Prevotes: Votes{ - CurrentWeight: uint32(len(votes)), + CurrentWeight: uint32(len(votes)), //nolint:gosec Missing: missingPrevotes, }, Precommits: Votes{ - CurrentWeight: uint32(len(commits)), + CurrentWeight: uint32(len(commits)), //nolint:gosec Missing: missingPrecommits, }, }, diff --git a/dot/rpc/modules/system.go b/dot/rpc/modules/system.go index 2f5685de78..1bb00fbc05 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), - HighestBlock: uint32(sm.syncAPI.HighestBlock()), - StartingBlock: uint32(sm.networkAPI.StartingBlock()), + CurrentBlock: uint32(h.Number), //nolint:gosec + HighestBlock: uint32(sm.syncAPI.HighestBlock()), //nolint:gosec + StartingBlock: uint32(sm.networkAPI.StartingBlock()), //nolint:gosec } return nil } diff --git a/dot/state/block.go b/dot/state/block.go index 6167d19ca6..6ef348b6e3 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-- { + for currentPosition := int(lastPosition); currentPosition >= 0; currentPosition-- { //nolint:gosec 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 + return time.Unix(0, int64(ns)), nil //nolint:gosec } func (bs *BlockState) setArrivalTime(hash common.Hash, arrivalTime time.Time) error { buf := make([]byte, 8) - binary.LittleEndian.PutUint64(buf, uint64(arrivalTime.UnixNano())) + binary.LittleEndian.PutUint64(buf, uint64(arrivalTime.UnixNano())) //nolint:gosec return bs.db.Put(arrivalTimeKey(hash), buf) } diff --git a/dot/state/epoch.go b/dot/state/epoch.go index 390818eef4..5f700ffde9 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-- { + for tryEpoch := int(epoch); tryEpoch >= 0; tryEpoch-- { //nolint:gosec 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 + return uint64(time.Now().UnixNano()) / uint64(slotDuration.Nanoseconds()), nil //nolint:gosec } return 0, fmt.Errorf( diff --git a/dot/state/grandpa.go b/dot/state/grandpa.go index cbea1ed38c..aad8693f35 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 { + if int(curr) < 0 { //nolint:gosec return 0, nil } } diff --git a/dot/state/inmemory_storage.go b/dot/state/inmemory_storage.go index 592852836d..32121dceab 100644 --- a/dot/state/inmemory_storage.go +++ b/dot/state/inmemory_storage.go @@ -69,7 +69,8 @@ func (s *InmemoryStorageState) StoreTrie(ts *storage.TrieState, header *types.He return fmt.Errorf("getting trie changed node hashes for block hash %s: %w", header.Hash(), err) } - err = s.pruner.StoreJournalRecord(deletedNodeHashes, insertedNodeHashes, header.Hash(), int64(header.Number)) + err = s.pruner.StoreJournalRecord( + deletedNodeHashes, insertedNodeHashes, header.Hash(), int64(header.Number)) //nolint:gosec 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 73fdbddfe6..8eb46b5003 100644 --- a/dot/state/test_helpers.go +++ b/dot/state/test_helpers.go @@ -221,7 +221,8 @@ func AddBlocksToStateWithFixedBranches(t *testing.T, blockState *BlockState, dep bestBlockHash = branch.hash for i := branch.depth; i < depth; i++ { - d, err := types.NewBabePrimaryPreDigest(0, uint64(i+uint(j)+99), [32]byte{}, [64]byte{}).ToPreRuntimeDigest() + d, err := types.NewBabePrimaryPreDigest( + 0, uint64(i+uint(j)+99), [32]byte{}, [64]byte{}).ToPreRuntimeDigest() //nolint:gosec require.NoError(t, err) require.NotNil(t, d) digest := types.NewDigest() diff --git a/dot/state/transaction.go b/dot/state/transaction.go index abb92728b1..11412f0822 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())), + telemetry.NewTxpoolImport(uint(s.queue.Len()), uint(s.pool.Len())), //nolint:gosec ) return hash diff --git a/dot/sync/fullsync.go b/dot/sync/fullsync.go index a0930d548d..79db8b4a29 100644 --- a/dot/sync/fullsync.go +++ b/dot/sync/fullsync.go @@ -110,12 +110,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 { + if uint32(bestBlockHeader.Number) >= currentTarget { //nolint:gosec return f.createTasks(reqsFromQueue), nil } startRequestAt := bestBlockHeader.Number + 1 - targetBlockNumber := startRequestAt + uint(f.numOfTasks)*127 + targetBlockNumber := startRequestAt + uint(f.numOfTasks)*127 //nolint:gosec if targetBlockNumber > uint(currentTarget) { targetBlockNumber = uint(currentTarget) @@ -312,7 +312,7 @@ func (f *FullSyncStrategy) OnBlockAnnounce(from peer.ID, msg *network.BlockAnnou } if msg.BestBlock { - f.peers.update(from, blockAnnounceHeaderHash, uint32(blockAnnounceHeader.Number)) + f.peers.update(from, blockAnnounceHeaderHash, uint32(blockAnnounceHeader.Number)) //nolint:gosec } highestFinalized, err := f.blockState.GetHighestFinalisedHeader() @@ -387,7 +387,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() + return uint32(highestBlock)+messages.MaxBlocksInResponse >= f.peers.getTarget() //nolint:gosec } type RequestResponseData struct { diff --git a/dot/test_utils.go b/dot/test_utils.go index 423cde6b37..81eb12c420 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) + err = os.WriteFile(filename, b, os.ModePerm) //nolint:gosec require.NoError(t, err) return filename diff --git a/internal/database/pebble.go b/internal/database/pebble.go index a30fcb39a5..567014973f 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 { + if err := os.MkdirAll(path, os.ModePerm); err != nil { //nolint:gosec return nil, err } } diff --git a/internal/log/level.go b/internal/log/level.go index 7531c7a421..169127061c 100644 --- a/internal/log/level.go +++ b/internal/log/level.go @@ -9,7 +9,7 @@ import ( "strconv" "strings" - "github.com/fatih/color" //nolint:misspell + "github.com/fatih/color" ) // Level is the level of the logger. diff --git a/internal/log/log.go b/internal/log/log.go index 1ba748f349..ef32634ca5 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -9,7 +9,7 @@ import ( "strings" "time" - "github.com/fatih/color" //nolint:misspell + "github.com/fatih/color" ) func (l *Logger) log(logLevel Level, s string, args ...interface{}) { diff --git a/lib/babe/babe.go b/lib/babe/babe.go index 06ed8d25ed..edad571086 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()) + return uint64(b.constants.slotDuration.Milliseconds()) //nolint:gosec } // 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 + return uint32(i), nil //nolint:gosec } } @@ -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()) + return uint64(time.Now().UnixNano()) / uint64(slotDuration.Nanoseconds()) //nolint:gosec } func getSlotStartTime(slot uint64, slotDuration time.Duration) time.Time { - return time.Unix(0, int64(slot)*slotDuration.Nanoseconds()) + return time.Unix(0, int64(slot)*slotDuration.Nanoseconds()) //nolint:gosec } diff --git a/lib/babe/build.go b/lib/babe/build.go index a19e085d2f..57ce4b2ca3 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())) + err := idata.SetInherent(types.Timstap0, uint64(slot.start.UnixMilli())) //nolint:gosec if err != nil { return nil, err } diff --git a/lib/babe/secondary.go b/lib/babe/secondary.go index 55bdc00614..a5ea4ec769 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 + return uint32(idx.Uint64()), nil //nolint:gosec } // 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 0a1d65b479..604a72bddc 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()) + currentSlotNumber := uint64(currentSystemTime.UnixNano()) / uint64(s.slotDuration.Nanoseconds()) //nolint:gosec currentSlot := Slot{ start: currentSystemTime, duration: s.slotDuration, diff --git a/lib/babe/verify.go b/lib/babe/verify.go index aeaacdefd2..b85c9e094d 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)) { + if index >= uint32(len(v.epochInfo[epoch].authorities)) { //nolint:gosec return ErrInvalidBlockProducerIndex } diff --git a/lib/blocktree/blocktree.go b/lib/blocktree/blocktree.go index 0f31f5820f..6dfe050f0e 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-- { + for i := int(newCanonicalChainBlocksCount) - 1; i >= 0; i-- { //nolint:gosec 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 + return nil, nil //nolint:nilnil } diff --git a/lib/blocktree/node.go b/lib/blocktree/node.go index 5eb4556860..ccca544f08 100644 --- a/lib/blocktree/node.go +++ b/lib/blocktree/node.go @@ -112,7 +112,7 @@ func (n *node) getLeaves(leaves []*node) []*node { leaves = []*node{} } - if n.children == nil || len(n.children) == 0 { + if len(n.children) == 0 { leaves = append(leaves, n) } diff --git a/lib/genesis/helpers.go b/lib/genesis/helpers.go index 8d37cdab1f..b8ab3462f3 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)) + encVal, err := scale.Marshal(uint64(v2)) //nolint:gosec 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)) + encVal, err := scale.Marshal(uint64(v2)) //nolint:gosec 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))) + kv.iVal = append(kv.iVal, big.NewInt(int64(v2))) //nolint:gosec 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)) + encVal, err := scale.Marshal(uint64(v2)) //nolint:gosec if err != nil { return err } diff --git a/lib/grandpa/grandpa.go b/lib/grandpa/grandpa.go index a4ed7159b0..74296c6aaa 100644 --- a/lib/grandpa/grandpa.go +++ b/lib/grandpa/grandpa.go @@ -370,7 +370,7 @@ func (s *Service) handleIsPrimary() (bool, error) { pv := &Vote{ Hash: best.Hash(), - Number: uint32(best.Number), + Number: uint32(best.Number), //nolint:gosec } // send primary prevote message to network @@ -449,7 +449,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) { + if bestFinalCandidate.Number < uint32(s.head.Number) { //nolint:gosec return nil, 0, fmt.Errorf("%w: candidate number %d, latest finalized block number %d", errBeforeFinalizedBlock, bestFinalCandidate.Number, s.head.Number) } @@ -471,7 +471,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() { + if bestFinalCandidate.Number < uint32(s.head.Number) || precommitCount <= s.state.threshold() { //nolint:gosec return false, nil } @@ -559,7 +559,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) { + if has && prm.Vote.Number >= uint32(s.head.Number) { //nolint:gosec vote = &prm.Vote } else { vote = NewVoteFromHeader(bestBlockHeader) @@ -823,7 +823,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), + Number: uint32(s.head.Number), //nolint:gosec } for h, n := range blocks { @@ -868,7 +868,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), + Number: uint32(s.head.Number), //nolint:gosec } for h, n := range blocks { @@ -963,7 +963,7 @@ func (s *Service) getPossibleSelectedAncestors(votes []Vote, curr common.Hash, return nil, err } - selected[pred] = uint32(h.Number) + selected[pred] = uint32(h.Number) //nolint:gosec } else { selected, err = s.getPossibleSelectedAncestors(votes, pred, selected, stage, threshold) if err != nil { @@ -992,7 +992,7 @@ func (s *Service) getTotalVotesForBlock(hash common.Hash, stage Subround) (uint6 ev = len(s.pcEquivocations) } - return dv + uint64(ev), nil + return dv + uint64(ev), nil //nolint:gosec } // getVotesForBlock returns the number of observed votes for a block B. @@ -1274,7 +1274,7 @@ func verifyCommitMessageJustification(commitMessage CommitMessage, setID uint64, } } - validAndEqv := uint64(totalValidPrecommits) + uint64(len(eqvVoters)) + validAndEqv := uint64(totalValidPrecommits) + uint64(len(eqvVoters)) //nolint:gosec // 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 f89bae2d76..f69c9a522d 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), + Number: uint32(header.Number), //nolint:gosec }, nil } diff --git a/lib/grandpa/message_handler.go b/lib/grandpa/message_handler.go index 47837dc797..df607d6915 100644 --- a/lib/grandpa/message_handler.go +++ b/lib/grandpa/message_handler.go @@ -54,14 +54,14 @@ 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 + return nil, nil //nolint:nilnil case *CommitMessage: err := h.grandpa.handleCommitMessage(msg) if err != nil { return nil, fmt.Errorf("handling commit message: %w", err) } - return nil, nil + return nil, nil //nolint:nilnil case *NeighbourPacketV1: // we can afford to not retry handling neighbour message, if it errors. return nil, h.handleNeighbourMessage(msg) @@ -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), + Number: uint32(finalizedNumber), //nolint:gosec } justification, err := client_grandpa.DecodeGrandpaJustificationVerifyFinalizes[hash.H256, uint32, runtime.BlakeTwo256]( diff --git a/lib/grandpa/types.go b/lib/grandpa/types.go index 99661e36c3..15437395ae 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) + return uint64(2 * len(s.voters) / 3) //nolint:gosec } // 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), + Number: uint32(h.Number), //nolint:gosec } } diff --git a/lib/runtime/allocator/freeing_bump.go b/lib/runtime/allocator/freeing_bump.go index 8207ed4273..b9c434f579 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 + return Order(value), nil //nolint:gosec } // 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) + headerData := uint32(rawHeader) //nolint:gosec if occupied { order, err := orderFromRaw(headerData) diff --git a/lib/runtime/storage/storagediff.go b/lib/runtime/storage/storagediff.go index d2d3dddf44..be93c7980a 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 + return uint32(deletedKeys), true //nolint:gosec } allKeys := slices.Clone(currentChildKeys) @@ -121,7 +121,7 @@ func (cs *storageDiff) deleteChildLimit(keyToChild string, } cs.childChangeSet[keyToChild] = childChanges - return deleted, deleted == uint32(len(allKeys)) + return deleted, deleted == uint32(len(allKeys)) //nolint:gosec } // 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)) + return deleted, deleted == uint32(len(keysToClear)) //nolint:gosec } // 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 c8a1eb5828..ac2767814a 100644 --- a/lib/runtime/storage/trie.go +++ b/lib/runtime/storage/trie.go @@ -362,7 +362,7 @@ func (t *TrieState) DeleteChildLimit(key []byte, limit *[]byte) ( } childTrieEntries := child.Entries() - qtyEntries := uint32(len(childTrieEntries)) + qtyEntries := uint32(len(childTrieEntries)) //nolint:gosec 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 46eccc5575..52ebba3f4f 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()) + timestamp := uint64(time.Now().UnixMilli()) //nolint:gosec currentSlot := timestamp / slotDuration babeDigest := types.NewBabeDigest() diff --git a/lib/runtime/wazero/imports.go b/lib/runtime/wazero/imports.go index b077d19731..250653b5e0 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 + return uint32(pointerSize), pointerSize >> 32 //nolint:gosec } // 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)) + size := uint32(len(data)) //nolint:gosec 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) + return uint32(ret) //nolint:gosec } 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)) + stateVersion, err := trie.ParseVersion(uint8(version)) //nolint:gosec 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)) + stateVersion, err := trie.ParseVersion(uint8(version)) //nolint:gosec 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)) + _, err := trie.ParseVersion(uint8(version)) //nolint:gosec 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)) + logger.Debugf("num: %d", int64(data)) //nolint:gosec } 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:])) + size := uint32(len(value[offset:])) //nolint:gosec 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) + return uint64(now) //nolint:gosec } func ext_offchain_sleep_until_version_1(_ context.Context, _ api.Module, deadline uint64) { - dur := time.Until(time.UnixMilli(int64(deadline))) + dur := time.Until(time.UnixMilli(int64(deadline))) //nolint:gosec 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)) + offchainReq := rtCtx.OffchainHTTPSet.Get(int16(reqID)) //nolint:gosec 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)): + case offset <= uint32(len(value)): //nolint:gosec 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)) + size := uint32(len(data)) //nolint:gosec return mustWrite(m, rtCtx.Allocator, scale.MustMarshal(&size)) } diff --git a/lib/runtime/wazero/instance.go b/lib/runtime/wazero/instance.go index d817a2e617..6c53b8b233 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)) + dataLength := uint32(len(data)) //nolint:gosec 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))) + encLen, err := scale.Marshal(uint32(len(ext))) //nolint:gosec 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))) + encLen, err := scale.Marshal(uint32(len(ext))) //nolint:gosec 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))) + encLen, err := scale.Marshal(uint32(len(ext))) //nolint:gosec 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 2737015f69..827a39b239 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) { + if len(c.cache) >= int(c.capacity) { //nolint:gosec // 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 2ad78927cd..e6182f43f1 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) + err = os.Mkdir(keystorepath, os.ModePerm) //nolint:gosec 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) + err = os.Mkdir(keystorepath, os.ModePerm) //nolint:gosec 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 86bec52f71..d5be57c2b9 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}) + bit1s = append(bit1s, bit1{uint(i)*64 + bitPos}) //nolint:gosec } } } diff --git a/pkg/finality-grandpa/voting_round.go b/pkg/finality-grandpa/voting_round.go index 32b6485c21..60266f1f69 100644 --- a/pkg/finality-grandpa/voting_round.go +++ b/pkg/finality-grandpa/voting_round.go @@ -108,7 +108,7 @@ func newVotingRound[ votes := NewRound[ID, Hash, Number, Signature](roundParams) primaryVoterID, _ := votes.PrimaryVoter() - var voting voting //nolint:govet + var voting voting if roundData.VoterID != nil && *roundData.VoterID == primaryVoterID { voting = votingPrimary } else if roundData.VoterID != nil && votes.Voters().Contains(*roundData.VoterID) { diff --git a/pkg/scale/decode.go b/pkg/scale/decode.go index af52cf5cd7..97ebb66308 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)) + out = int16(binary.LittleEndian.Uint16(buf)) //nolint:gosec 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)) + out = int32(binary.LittleEndian.Uint32(buf)) //nolint:gosec 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)) + out = int64(binary.LittleEndian.Uint64(buf)) //nolint:gosec case uint64: buf := make([]byte, 8) _, err = ds.Read(buf) diff --git a/pkg/scale/decode_test.go b/pkg/scale/decode_test.go index 0a75f25f0d..828ae43576 100644 --- a/pkg/scale/decode_test.go +++ b/pkg/scale/decode_test.go @@ -307,7 +307,7 @@ func Test_unmarshal_optionality_nil_case(t *testing.T) { temp := reflect.New(reflect.TypeOf(t.in)) // create a new pointer to type of temp - tempv := reflect.New(reflect.PtrTo(temp.Type()).Elem()) + tempv := reflect.New(reflect.PointerTo(temp.Type()).Elem()) // set zero value to elem of **temp so that is nil tempv.Elem().Set(reflect.Zero(tempv.Elem().Type())) // set test.in to *temp diff --git a/pkg/scale/encode.go b/pkg/scale/encode.go index 9429fb0bff..bf4f81682f 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)) + err = es.encodeUint(uint(in)) //nolint:gosec 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)) + err = binary.Write(es, binary.LittleEndian, uint8(i.Int64()<<2)) //nolint:gosec case i.Cmp(new(big.Int).Lsh(big.NewInt(1), 14)) < 0: - err = binary.Write(es, binary.LittleEndian, uint16(i.Int64()<<2)+1) + err = binary.Write(es, binary.LittleEndian, uint16(i.Int64()<<2)+1) //nolint:gosec case i.Cmp(new(big.Int).Lsh(big.NewInt(1), 30)) < 0: - err = binary.Write(es, binary.LittleEndian, uint32(i.Int64()<<2)+2) + err = binary.Write(es, binary.LittleEndian, uint32(i.Int64()<<2)+2) //nolint:gosec default: numBytes := len(i.Bytes()) - topSixBits := uint8(numBytes - 4) + topSixBits := uint8(numBytes - 4) //nolint:gosec 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)) + err = binary.Write(es, binary.LittleEndian, uint16(i)) //nolint:gosec case uint16: err = binary.Write(es, binary.LittleEndian, i) case int32: - err = binary.Write(es, binary.LittleEndian, uint32(i)) + err = binary.Write(es, binary.LittleEndian, uint32(i)) //nolint:gosec case uint32: err = binary.Write(es, binary.LittleEndian, i) case int64: - err = binary.Write(es, binary.LittleEndian, uint64(i)) + err = binary.Write(es, binary.LittleEndian, uint64(i)) //nolint:gosec 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)) + return es.encodeUint(uint(l)) //nolint:gosec } // 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) + err = binary.Write(es, binary.LittleEndian, uint16(i<<2)+1) //nolint:gosec case i < 1<<30: - err = binary.Write(es, binary.LittleEndian, uint32(i<<2)+2) + err = binary.Write(es, binary.LittleEndian, uint32(i<<2)+2) //nolint:gosec 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) + topSixBits := uint8(numBytes - 4) //nolint:gosec lengthByte := topSixBits<<2 + 3 err = binary.Write(es, binary.LittleEndian, lengthByte) diff --git a/pkg/scale/encode_test.go b/pkg/scale/encode_test.go index 8984725dcf..35993b2138 100644 --- a/pkg/scale/encode_test.go +++ b/pkg/scale/encode_test.go @@ -1222,7 +1222,7 @@ func Test_marshal_optionality_nil_cases(t *testing.T) { // create a new pointer to new zero value of t.in temp := reflect.New(reflect.TypeOf(t.in)) // create a new pointer to type of temp - tempv := reflect.New(reflect.PtrTo(temp.Type()).Elem()) + tempv := reflect.New(reflect.PointerTo(temp.Type()).Elem()) // set zero value to elem of **temp so that is nil tempv.Elem().Set(reflect.Zero(tempv.Elem().Type())) // set test.in to *temp diff --git a/pkg/trie/node/children.go b/pkg/trie/node/children.go index 725366b42e..0502264a3f 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) + bitmap |= 1 << uint(i) //nolint:gosec } return bitmap } diff --git a/pkg/trie/node/node.go b/pkg/trie/node/node.go index 42296e5026..52dccdc079 100644 --- a/pkg/trie/node/node.go +++ b/pkg/trie/node/node.go @@ -54,16 +54,16 @@ func (n *Node) String() string { // StringNode returns a gotree compatible node for String methods. func (n *Node) StringNode() (stringNode *gotree.Node) { - stringNode = gotree.New(n.Kind().String()) + stringNode = gotree.New(n.Kind().String()) //nolint:govet stringNode.Appendf("Generation: %d", n.Generation) stringNode.Appendf("Dirty: %t", n.Dirty) - 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("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("Descendants: %d", n.Descendants) } - stringNode.Appendf("Merkle value: " + bytesToString(n.MerkleValue)) + stringNode.Appendf("Merkle value: " + bytesToString(n.MerkleValue)) //nolint:govet for i, child := range n.Children { if child == nil { diff --git a/pkg/trie/triedb/lookup.go b/pkg/trie/triedb/lookup.go index 93ab6cc879..84cab5d467 100644 --- a/pkg/trie/triedb/lookup.go +++ b/pkg/trie/triedb/lookup.go @@ -72,7 +72,7 @@ func (l *TrieLookup) lookupNode(keyNibbles []byte) (codec.EncodedNode, error) { switch n := decodedNode.(type) { case codec.Empty: - return nil, nil + return nil, nil //nolint:nilnil case codec.Leaf: // We are in the node we were looking for if bytes.Equal(partialKey, n.PartialKey) { @@ -81,7 +81,7 @@ func (l *TrieLookup) lookupNode(keyNibbles []byte) (codec.EncodedNode, error) { l.recordAccess(nonExistingNodeAccess{fullKey: keyNibbles}) - return nil, nil + return nil, nil //nolint:nilnil case codec.Branch: nodePartialKey := n.PartialKey @@ -90,7 +90,7 @@ func (l *TrieLookup) lookupNode(keyNibbles []byte) (codec.EncodedNode, error) { // doesn't share the prefix we are expecting if !bytes.HasPrefix(partialKey, nodePartialKey) { l.recordAccess(nonExistingNodeAccess{fullKey: keyNibbles}) - return nil, nil + return nil, nil //nolint:nilnil } // We are in the node we were looking for @@ -100,7 +100,7 @@ func (l *TrieLookup) lookupNode(keyNibbles []byte) (codec.EncodedNode, error) { } l.recordAccess(nonExistingNodeAccess{fullKey: keyNibbles}) - return nil, nil + return nil, nil //nolint:nilnil } // This is not the node we were looking for but it might be in @@ -109,7 +109,7 @@ func (l *TrieLookup) lookupNode(keyNibbles []byte) (codec.EncodedNode, error) { nextNode = n.Children[childIdx] if nextNode == nil { l.recordAccess(nonExistingNodeAccess{fullKey: keyNibbles}) - return nil, nil + return nil, nil //nolint:nilnil } // Advance the partial key consuming the part we already checked diff --git a/pkg/trie/triedb/triedb.go b/pkg/trie/triedb/triedb.go index 4e9af6ba9d..b7d01de767 100644 --- a/pkg/trie/triedb/triedb.go +++ b/pkg/trie/triedb/triedb.go @@ -406,7 +406,7 @@ func (t *TrieDB) fix(branch Branch) (Node, error) { return Leaf{branch.partialKey, branch.value}, nil } else if len(usedIndex) == 1 && branch.value == nil { // Only one onward node. use child instead - idx := usedIndex[0] //nolint:gosec + idx := usedIndex[0] // take child and replace it to nil child := branch.children[idx] branch.children[idx] = nil diff --git a/scripts/p2p/common_p2p.go b/scripts/p2p/common_p2p.go index 82c97333dd..f0c1419141 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) { + for tot < int(length) { //nolint:gosec 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) { + if tot != int(length) { //nolint:gosec 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 38a31af304..0d4fc45387 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), + return messages.NewBlockRequest(targetBlock, uint32(amount), //nolint:gosec messages.BootstrapRequestData, messages.Ascending) case "desc": - return messages.NewBlockRequest(targetBlock, uint32(amount), + return messages.NewBlockRequest(targetBlock, uint32(amount), //nolint:gosec messages.BootstrapRequestData, messages.Descending) } @@ -57,7 +57,7 @@ func parseTargetBlock(arg string) messages.FromBlock { return messages.FromBlock{} } - return *messages.NewFromBlock(uint(value)) + return *messages.NewFromBlock(uint(value)) //nolint:gosec } 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) + err = os.WriteFile(outputFile, []byte(common.BytesToHex(output)), os.ModePerm) //nolint:gosec 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 18d87b0d5b..a9c355b052 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) + fetchWithTimeout(ctx, t, "chain_getBlock", fmt.Sprintf(`["`+finalizedHead+`"]`), &finalizedBlock) //nolint:govet 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) + fetchWithTimeout(ctx, t, "chain_getBlock", fmt.Sprintf(`["`+finalizedHash+`"]`), &finalizedBlock) //nolint:govet 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) + fmt.Sprintf(`["`+finalizedHeader.ParentHash+`"]`), &parentBlock) //nolint:govet // 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 e508bab9b8..ed12e5888f 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) + err = os.WriteFile(genesisPath, buildSpecJSON, os.ModePerm) //nolint:gosec require.NoError(t, err) return genesisPath diff --git a/tests/utils/node/node.go b/tests/utils/node/node.go index 0d97eba40e..d8e0c7452e 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) + n.tomlConfig.Network.Port = basePort + uint16(*n.index) //nolint:gosec } if n.tomlConfig.RPC.IsRPCEnabled() && n.tomlConfig.RPC.Port == 0 { const basePort uint32 = 8540 - n.tomlConfig.RPC.Port = basePort + uint32(*n.index) + n.tomlConfig.RPC.Port = basePort + uint32(*n.index) //nolint:gosec } if n.tomlConfig.RPC.IsWSEnabled() && n.tomlConfig.RPC.WSPort == 0 { const basePort uint32 = 8546 - n.tomlConfig.RPC.WSPort = basePort + uint32(*n.index) + n.tomlConfig.RPC.WSPort = basePort + uint32(*n.index) //nolint:gosec } userSetWriter := n.writer != nil && n.writer != io.Discard diff --git a/tests/utils/rpc/chain.go b/tests/utils/rpc/chain.go index 74094ff7cb..94fb0dc995 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)) + p := strconv.Itoa(int(round)) //nolint:gosec 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 4c4e81efae..a02f2640b4 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) + slotDuration = time.Millisecond * time.Duration(slotDurationUint64) //nolint:gosec return slotDuration, nil }