diff --git a/.golangci.yml b/.golangci.yml index 4b746afea..734d3b026 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -16,6 +16,7 @@ linters: - bodyclose - gosec # - forcetypeassert + - prealloc linters-settings: gocritic: diff --git a/cmd/downloader/downloader/util.go b/cmd/downloader/downloader/util.go index 1b566d78a..8e10d79af 100644 --- a/cmd/downloader/downloader/util.go +++ b/cmd/downloader/downloader/util.go @@ -42,7 +42,7 @@ func AllTorrentPaths(dir string) ([]string, error) { if err != nil { return nil, err } - var res []string + res := make([]string, 0, len(files)) for _, f := range files { torrentFilePath := filepath.Join(dir, f) res = append(res, torrentFilePath) @@ -55,7 +55,7 @@ func AllTorrentFiles(dir string) ([]string, error) { if err != nil { return nil, err } - var res []string + res := make([]string, 0, len(files)) for _, f := range files { if !snap.IsCorrectFileName(f.Name()) { continue @@ -79,7 +79,7 @@ func seedableSegmentFiles(dir string) ([]string, error) { if err != nil { return nil, err } - var res []string + res := make([]string, 0, len(files)) for _, f := range files { if !snap.IsCorrectFileName(f.Name()) { continue diff --git a/cmd/rpcdaemon/commands/bor_helper.go b/cmd/rpcdaemon/commands/bor_helper.go index ef5cf774b..5c9ecf482 100644 --- a/cmd/rpcdaemon/commands/bor_helper.go +++ b/cmd/rpcdaemon/commands/bor_helper.go @@ -131,7 +131,7 @@ func getUpdatedValidatorSet(oldValidatorSet *ValidatorSet, newVals []*bor.Valida v := oldValidatorSet oldVals := v.Validators - var changes []*bor.Validator + changes := make([]*bor.Validator, 0, len(oldVals)) for _, ov := range oldVals { if f, ok := validatorContains(newVals, ov); ok { ov.VotingPower = f.VotingPower diff --git a/cmd/rpcdaemon/commands/call_traces_test.go b/cmd/rpcdaemon/commands/call_traces_test.go index 5ee49cec7..08d4e7b2a 100644 --- a/cmd/rpcdaemon/commands/call_traces_test.go +++ b/cmd/rpcdaemon/commands/call_traces_test.go @@ -34,7 +34,7 @@ func blockNumbersFromTraces(t *testing.T, b []byte) []int { if elems, err = v.Array(); err != nil { t.Fatalf("expected array in the response: %v", err) } - var numbers []int + numbers := make([]int, 0, len(elems)) for _, elem := range elems { bn := elem.GetInt("blockNumber") numbers = append(numbers, bn) diff --git a/cmd/rpcdaemon/commands/starknet_call.go b/cmd/rpcdaemon/commands/starknet_call.go index 3312f6cda..56533bb72 100644 --- a/cmd/rpcdaemon/commands/starknet_call.go +++ b/cmd/rpcdaemon/commands/starknet_call.go @@ -86,7 +86,7 @@ func (api *StarknetImpl) Call(ctx context.Context, request StarknetCallRequest, return nil, err } - var result []string + result := make([]string, 0, len(response.Result)) for _, v := range response.Result { s := wrapperspb.String("") v.UnmarshalTo(s) diff --git a/cmd/rpcdaemon22/commands/bor_helper.go b/cmd/rpcdaemon22/commands/bor_helper.go index ef5cf774b..5c9ecf482 100644 --- a/cmd/rpcdaemon22/commands/bor_helper.go +++ b/cmd/rpcdaemon22/commands/bor_helper.go @@ -131,7 +131,7 @@ func getUpdatedValidatorSet(oldValidatorSet *ValidatorSet, newVals []*bor.Valida v := oldValidatorSet oldVals := v.Validators - var changes []*bor.Validator + changes := make([]*bor.Validator, 0, len(oldVals)) for _, ov := range oldVals { if f, ok := validatorContains(newVals, ov); ok { ov.VotingPower = f.VotingPower diff --git a/cmd/rpcdaemon22/commands/call_traces_test.go b/cmd/rpcdaemon22/commands/call_traces_test.go index cd2ea4fde..5e88fdf8d 100644 --- a/cmd/rpcdaemon22/commands/call_traces_test.go +++ b/cmd/rpcdaemon22/commands/call_traces_test.go @@ -34,7 +34,7 @@ func blockNumbersFromTraces(t *testing.T, b []byte) []int { if elems, err = v.Array(); err != nil { t.Fatalf("expected array in the response: %v", err) } - var numbers []int + numbers := make([]int, 0, len(elems)) for _, elem := range elems { bn := elem.GetInt("blockNumber") numbers = append(numbers, bn) diff --git a/cmd/rpcdaemon22/commands/starknet_call.go b/cmd/rpcdaemon22/commands/starknet_call.go index 3312f6cda..56533bb72 100644 --- a/cmd/rpcdaemon22/commands/starknet_call.go +++ b/cmd/rpcdaemon22/commands/starknet_call.go @@ -86,7 +86,7 @@ func (api *StarknetImpl) Call(ctx context.Context, request StarknetCallRequest, return nil, err } - var result []string + result := make([]string, 0, len(response.Result)) for _, v := range response.Result { s := wrapperspb.String("") v.UnmarshalTo(s) diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index 709f09929..d6b35b86f 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -1604,9 +1604,9 @@ func MakeConsolePreloads(ctx *cli.Context) []string { return nil } // Otherwise resolve absolute paths and return them - var preloads []string - - for _, file := range strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") { + files := strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") + preloads := make([]string, 0, len(files)) + for _, file := range files { preloads = append(preloads, strings.TrimSpace(file)) } return preloads diff --git a/consensus/aura/aura.go b/consensus/aura/aura.go index 1700cb1d0..5ecad42aa 100644 --- a/consensus/aura/aura.go +++ b/consensus/aura/aura.go @@ -417,7 +417,7 @@ func NewAuRa(config *params.AuRaConfig, db kv.RwDB, ourSigningAddress common.Add if auraParams.StartStep != nil { initialStep = *auraParams.StartStep } - var durations []StepDurationInfo + durations := make([]StepDurationInfo, 0, 1+len(auraParams.StepDurations)) durInfo := StepDurationInfo{ TransitionStep: 0, TransitionTimestamp: 0, diff --git a/consensus/bor/bor.go b/consensus/bor/bor.go index 41ffd9cb1..6fb69f3f1 100644 --- a/consensus/bor/bor.go +++ b/consensus/bor/bor.go @@ -1137,7 +1137,7 @@ func (c *Bor) fetchAndCommitSpan( } // get validators bytes - var validators []MinimalVal + validators := make([]MinimalVal, 0, len(heimdallSpan.ValidatorSet.Validators)) for _, val := range heimdallSpan.ValidatorSet.Validators { validators = append(validators, val.MinimalVal()) } @@ -1147,7 +1147,7 @@ func (c *Bor) fetchAndCommitSpan( } // get producers bytes - var producers []MinimalVal + producers := make([]MinimalVal, 0, len(heimdallSpan.SelectedProducers)) for _, val := range heimdallSpan.SelectedProducers { producers = append(producers, val.MinimalVal()) } @@ -1330,7 +1330,7 @@ func getUpdatedValidatorSet(oldValidatorSet *ValidatorSet, newVals []*Validator) v := oldValidatorSet oldVals := v.Validators - var changes []*Validator + changes := make([]*Validator, 0, len(oldVals)) for _, ov := range oldVals { if f, ok := validatorContains(newVals, ov); ok { ov.VotingPower = f.VotingPower diff --git a/consensus/bor/merkle.go b/consensus/bor/merkle.go index c0c76fd66..ba00bc53e 100644 --- a/consensus/bor/merkle.go +++ b/consensus/bor/merkle.go @@ -37,7 +37,7 @@ func ConvertTo32(input []byte) (output [32]byte, err error) { } func Convert(input [][32]byte) [][]byte { - var output [][]byte + output := make([][]byte, 0, len(input)) for _, in := range input { newInput := make([]byte, len(in[:])) copy(newInput, in[:]) diff --git a/core/asm/lex_test.go b/core/asm/lex_test.go index 6b8bd3d74..c3a97aa50 100644 --- a/core/asm/lex_test.go +++ b/core/asm/lex_test.go @@ -24,7 +24,7 @@ import ( func lexAll(src string) []token { ch := Lex([]byte(src), false) - var tokens []token + var tokens []token // nolint:prealloc for i := range ch { tokens = append(tokens, i) } diff --git a/core/state/access_list_test.go b/core/state/access_list_test.go index b81182079..6fc898271 100644 --- a/core/state/access_list_test.go +++ b/core/state/access_list_test.go @@ -10,7 +10,7 @@ import ( func verifyAddrs(t *testing.T, s *IntraBlockState, astrings ...string) { t.Helper() // convert to common.Address form - var addresses []common.Address + addresses := make([]common.Address, 0, len(astrings)) var addressMap = make(map[common.Address]struct{}) for _, astring := range astrings { address := common.HexToAddress(astring) @@ -37,7 +37,7 @@ func verifySlots(t *testing.T, s *IntraBlockState, addrString string, slotString } var address = common.HexToAddress(addrString) // convert to common.Hash form - var slots []common.Hash + slots := make([]common.Hash, 0, len(slotStrings)) var slotMap = make(map[common.Hash]struct{}) for _, slotString := range slotStrings { s := common.HexToHash(slotString) diff --git a/eth/backend.go b/eth/backend.go index de385b761..b0da9018f 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -866,7 +866,7 @@ func (s *Ethereum) Peers(ctx context.Context) (*remote.PeersReply, error) { // Protocols returns all the currently configured // network protocols to start. func (s *Ethereum) Protocols() []p2p.Protocol { - var protocols []p2p.Protocol + protocols := make([]p2p.Protocol, 0, len(s.sentryServers)) for i := range s.sentryServers { protocols = append(protocols, s.sentryServers[i].Protocol) } diff --git a/eth/filters/filter.go b/eth/filters/filter.go index df78dffeb..bacf99db4 100644 --- a/eth/filters/filter.go +++ b/eth/filters/filter.go @@ -66,7 +66,7 @@ func NewRangeFilter(backend Backend, begin, end int64, addresses []common.Addres // Flatten the address and topic filter clauses into a single bloombits filter // system. Since the bloombits are not positional, nil topics are permitted, // which get flattened into a nil byte slice. - var filters [][][]byte + filters := make([][][]byte, 0, len(topics)) if len(addresses) > 0 { filter := make([][]byte, len(addresses)) for i, address := range addresses { diff --git a/eth/protocols/eth/handlers.go b/eth/protocols/eth/handlers.go index f8090451a..4b30b0462 100644 --- a/eth/protocols/eth/handlers.go +++ b/eth/protocols/eth/handlers.go @@ -133,10 +133,9 @@ func AnswerGetBlockHeadersQuery(db kv.Tx, query *GetBlockHeadersPacket, blockRea func AnswerGetBlockBodiesQuery(db kv.Tx, query GetBlockBodiesPacket) []rlp.RawValue { //nolint:unparam // Gather blocks until the fetch or network limits is reached - var ( - bytes int - bodies []rlp.RawValue - ) + var bytes int + bodies := make([]rlp.RawValue, 0, len(query)) + for lookups, hash := range query { if bytes >= softResponseLimit || len(bodies) >= MaxBodiesServe || lookups >= 2*MaxBodiesServe { diff --git a/eth/stagedsync/stage_headers.go b/eth/stagedsync/stage_headers.go index d3bbe26f4..3a84b002a 100644 --- a/eth/stagedsync/stage_headers.go +++ b/eth/stagedsync/stage_headers.go @@ -1326,7 +1326,7 @@ func WaitForDownloader(ctx context.Context, cfg HeadersCfg, tx kv.RwTx) error { // send all hashes to the Downloader service preverified := snapcfg.KnownCfg(cfg.chainConfig.ChainName, snInDB).Preverified - var downloadRequest []snapshotsync.DownloadRequest + downloadRequest := make([]snapshotsync.DownloadRequest, 0, len(preverified)+len(missingSnapshots)) // build all download requests // builds preverified snapshots request for _, p := range preverified { diff --git a/ethstats/ethstats.go b/ethstats/ethstats.go index 86689bcb2..7e6160600 100644 --- a/ethstats/ethstats.go +++ b/ethstats/ethstats.go @@ -365,7 +365,7 @@ func (s *Service) login(conn *connWrapper) error { // Construct and send the login authentication // infos := s.server.NodeInfo() - var protocols []string + protocols := make([]string, 0, len(s.servers)) for _, srv := range s.servers { protocols = append(protocols, fmt.Sprintf("%s/%d", srv.Protocol.Name, srv.Protocol.Version)) } @@ -542,9 +542,7 @@ func (s *Service) assembleBlockStats(block *types.Block, td *big.Int) *blockStat td = common.Big0 } // Gather the block infos from the local blockchain - var ( - txs []txStats - ) + txs := make([]txStats, 0, len(block.Transactions())) for _, tx := range block.Transactions() { txs = append(txs, txStats{tx.Hash()}) } diff --git a/node/nodecfg/config.go b/node/nodecfg/config.go index da6d2dc8e..e73a79b14 100644 --- a/node/nodecfg/config.go +++ b/node/nodecfg/config.go @@ -313,7 +313,7 @@ func (c *Config) parsePersistentNodes(w *bool, path string) []*enode.Node { return nil } // Interpret the list as a discovery node array - var nodes []*enode.Node + nodes := make([]*enode.Node, 0, len(nodelist)) for _, url := range nodelist { if url == "" { continue diff --git a/p2p/discover/table.go b/p2p/discover/table.go index 0505e6f3b..638159ec8 100644 --- a/p2p/discover/table.go +++ b/p2p/discover/table.go @@ -159,7 +159,7 @@ func (tab *Table) ReadRandomNodes(buf []*enode.Node) (n int) { tab.mutex.Lock() defer tab.mutex.Unlock() - var nodes []*enode.Node + nodes := make([]*enode.Node, 0, len(&tab.buckets)) for _, b := range &tab.buckets { for _, n := range b.entries { nodes = append(nodes, unwrapNode(n)) diff --git a/p2p/discover/v5_udp.go b/p2p/discover/v5_udp.go index b02ad6faa..1a88744d5 100644 --- a/p2p/discover/v5_udp.go +++ b/p2p/discover/v5_udp.go @@ -790,7 +790,7 @@ func (t *UDPv5) handleFindnode(p *v5wire.Findnode, fromID enode.ID, fromAddr *ne // collectTableNodes creates a FINDNODE result set for the given distances. func (t *UDPv5) collectTableNodes(rip net.IP, distances []uint, limit int) []*enode.Node { - var nodes []*enode.Node + nodes := make([]*enode.Node, 0, len(distances)) var processed = make(map[uint]struct{}) for _, dist := range distances { // Reject duplicate / invalid distances. diff --git a/p2p/discover/v5_udp_test.go b/p2p/discover/v5_udp_test.go index a94f1f91e..753404918 100644 --- a/p2p/discover/v5_udp_test.go +++ b/p2p/discover/v5_udp_test.go @@ -172,7 +172,7 @@ func TestUDPv5_findnodeHandling(t *testing.T) { // This request gets all the distance-249 nodes and some more at 248 because // the bucket at 249 is not full. test.packetIn(&v5wire.Findnode{ReqID: []byte{5}, Distances: []uint{249, 248}}) - var nodes []*enode.Node + nodes := make([]*enode.Node, 0, len(nodes249)+len(nodes248[:10])) nodes = append(nodes, nodes249...) nodes = append(nodes, nodes248[:10]...) test.expectNodes([]byte{5}, 5, nodes) diff --git a/p2p/dnsdisc/tree.go b/p2p/dnsdisc/tree.go index 1da6858f1..63f2207bd 100644 --- a/p2p/dnsdisc/tree.go +++ b/p2p/dnsdisc/tree.go @@ -104,7 +104,7 @@ func (t *Tree) Links() []string { // Nodes returns all nodes contained in the tree. func (t *Tree) Nodes() []*enode.Node { - var nodes []*enode.Node + nodes := make([]*enode.Node, 0, len(t.entries)) for _, e := range t.entries { if ee, ok := e.(*enrEntry); ok { nodes = append(nodes, ee.node) diff --git a/p2p/peer.go b/p2p/peer.go index 93222940e..abc67526c 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -490,7 +490,7 @@ type PeerInfo struct { // Info gathers and returns a collection of metadata known about a peer. func (p *Peer) Info() *PeerInfo { // Gather the protocol capabilities - var caps []string + caps := make([]string, 0, len(p.Caps())) for _, cap := range p.Caps() { caps = append(caps, cap.String()) } diff --git a/turbo/snapshotsync/block_snapshots.go b/turbo/snapshotsync/block_snapshots.go index c9da75bd9..e8c6c4785 100644 --- a/turbo/snapshotsync/block_snapshots.go +++ b/turbo/snapshotsync/block_snapshots.go @@ -598,7 +598,7 @@ func (s *RoSnapshots) ReopenFolder() error { if err != nil { return err } - var list []string + list := make([]string, 0, len(files)) for _, f := range files { _, fName := filepath.Split(f.Path) list = append(list, fName) @@ -1085,7 +1085,7 @@ func retireBlocks(ctx context.Context, blockFrom, blockTo uint64, chainID uint25 notifier.OnNewSnapshot() } - var downloadRequest []DownloadRequest + downloadRequest := make([]DownloadRequest, 0, len(rangesToMerge)) for i := range rangesToMerge { downloadRequest = append(downloadRequest, NewDownloadRequest(&rangesToMerge[i], "", "")) }