diff --git a/.avalanche-golangci.yml b/.avalanche-golangci.yml index ecb14ae843..17bfe92a88 100644 --- a/.avalanche-golangci.yml +++ b/.avalanche-golangci.yml @@ -75,7 +75,7 @@ linters: - predeclared - revive - spancheck - # - staticcheck + - staticcheck - tagalign # - testifylint - unconvert diff --git a/accounts/abi/abi_extra_test.go b/accounts/abi/abi_extra_test.go index ed412467f7..08c5824007 100644 --- a/accounts/abi/abi_extra_test.go +++ b/accounts/abi/abi_extra_test.go @@ -15,10 +15,10 @@ import ( // Note: This file contains tests in addition to those found in go-ethereum. -const TEST_ABI = `[{"type":"function","name":"receive","inputs":[{"name":"sender","type":"address"},{"name":"amount","type":"uint256"},{"name":"memo","type":"bytes"}],"outputs":[{"internalType":"bool","name":"isAllowed","type":"bool"}]}]` +const TestABI = `[{"type":"function","name":"receive","inputs":[{"name":"sender","type":"address"},{"name":"amount","type":"uint256"},{"name":"memo","type":"bytes"}],"outputs":[{"internalType":"bool","name":"isAllowed","type":"bool"}]}]` func TestUnpackInputIntoInterface(t *testing.T) { - abi, err := JSON(strings.NewReader(TEST_ABI)) + abi, err := JSON(strings.NewReader(TestABI)) require.NoError(t, err) type inputType struct { @@ -35,7 +35,7 @@ func TestUnpackInputIntoInterface(t *testing.T) { rawData, err := abi.Pack("receive", input.Sender, input.Amount, input.Memo) require.NoError(t, err) - abi, err = JSON(strings.NewReader(TEST_ABI)) + abi, err = JSON(strings.NewReader(TestABI)) require.NoError(t, err) for _, test := range []struct { @@ -97,7 +97,7 @@ func TestUnpackInputIntoInterface(t *testing.T) { } func TestPackOutput(t *testing.T) { - abi, err := JSON(strings.NewReader(TEST_ABI)) + abi, err := JSON(strings.NewReader(TestABI)) require.NoError(t, err) bytes, err := abi.PackOutput("receive", true) diff --git a/cmd/simulator/load/loader.go b/cmd/simulator/load/loader.go index aa37ccd57e..1b9e735751 100644 --- a/cmd/simulator/load/loader.go +++ b/cmd/simulator/load/loader.go @@ -196,10 +196,8 @@ func ExecuteLoader(ctx context.Context, config config.Config) error { log.Info("Distributed funds successfully", "time", time.Since(fundStart)) pks := make([]*ecdsa.PrivateKey, 0, len(keys)) - senders := make([]common.Address, 0, len(keys)) for _, key := range keys { pks = append(pks, key.PrivKey) - senders = append(senders, key.Address) } bigGwei := big.NewInt(params.GWei) diff --git a/core/extstate/database.go b/core/extstate/database.go index aad66fe2b3..111938dca2 100644 --- a/core/extstate/database.go +++ b/core/extstate/database.go @@ -26,7 +26,7 @@ func wrapIfFirewood(db state.Database) state.Database { if !ok { return db } - return &firewoodAccessorDb{ + return &firewoodAccessorDB{ Database: db, fw: fw, } diff --git a/core/extstate/firewood_database.go b/core/extstate/firewood_database.go index 08f821e6c6..657654e884 100644 --- a/core/extstate/firewood_database.go +++ b/core/extstate/firewood_database.go @@ -13,35 +13,35 @@ import ( ) var ( - _ state.Database = (*firewoodAccessorDb)(nil) + _ state.Database = (*firewoodAccessorDB)(nil) _ state.Trie = (*firewood.AccountTrie)(nil) _ state.Trie = (*firewood.StorageTrie)(nil) ) -type firewoodAccessorDb struct { +type firewoodAccessorDB struct { state.Database fw *firewood.Database } // OpenTrie opens the main account trie. -func (db *firewoodAccessorDb) OpenTrie(root common.Hash) (state.Trie, error) { +func (db *firewoodAccessorDB) OpenTrie(root common.Hash) (state.Trie, error) { return firewood.NewAccountTrie(root, db.fw) } // OpenStorageTrie opens a wrapped version of the account trie. // //nolint:revive // removing names loses context. -func (*firewoodAccessorDb) OpenStorageTrie(stateRoot common.Hash, addr common.Address, accountRoot common.Hash, self state.Trie) (state.Trie, error) { +func (*firewoodAccessorDB) OpenStorageTrie(stateRoot common.Hash, addr common.Address, accountRoot common.Hash, self state.Trie) (state.Trie, error) { accountTrie, ok := self.(*firewood.AccountTrie) if !ok { - return nil, fmt.Errorf("Invalid account trie type: %T", self) + return nil, fmt.Errorf("invalid account trie type: %T", self) } return firewood.NewStorageTrie(accountTrie) } // CopyTrie returns a deep copy of the given trie. // It can be altered by the caller. -func (*firewoodAccessorDb) CopyTrie(t state.Trie) state.Trie { +func (*firewoodAccessorDB) CopyTrie(t state.Trie) state.Trie { switch t := t.(type) { case *firewood.AccountTrie: return t.Copy() diff --git a/network/waiting_handler.go b/network/waiting_handler.go index 4ee71caf98..d0847e3d09 100644 --- a/network/waiting_handler.go +++ b/network/waiting_handler.go @@ -49,12 +49,12 @@ func (w *waitingResponseHandler) OnFailure() error { return nil } -func (waitingHandler *waitingResponseHandler) WaitForResult(ctx context.Context) ([]byte, error) { +func (w *waitingResponseHandler) WaitForResult(ctx context.Context) ([]byte, error) { select { case <-ctx.Done(): return nil, ctx.Err() - case response := <-waitingHandler.responseChan: - if waitingHandler.failed { + case response := <-w.responseChan: + if w.failed { return nil, errRequestFailed } return response, nil diff --git a/params/extras/network_upgrades.go b/params/extras/network_upgrades.go index 4b9b4c05b2..b6737683cf 100644 --- a/params/extras/network_upgrades.go +++ b/params/extras/network_upgrades.go @@ -105,19 +105,19 @@ func (n *NetworkUpgrades) SetDefaults(agoUpgrades upgrade.Config) { func (n *NetworkUpgrades) verifyNetworkUpgrades(agoUpgrades upgrade.Config) error { defaults := GetNetworkUpgrades(agoUpgrades) if err := verifyWithDefault(n.SubnetEVMTimestamp, defaults.SubnetEVMTimestamp); err != nil { - return fmt.Errorf("SubnetEVM fork block timestamp is invalid: %w", err) + return fmt.Errorf("subnetEVM fork block timestamp is invalid: %w", err) } if err := verifyWithDefault(n.DurangoTimestamp, defaults.DurangoTimestamp); err != nil { - return fmt.Errorf("Durango fork block timestamp is invalid: %w", err) + return fmt.Errorf("durango fork block timestamp is invalid: %w", err) } if err := verifyWithDefault(n.EtnaTimestamp, defaults.EtnaTimestamp); err != nil { - return fmt.Errorf("Etna fork block timestamp is invalid: %w", err) + return fmt.Errorf("etna fork block timestamp is invalid: %w", err) } if err := verifyWithDefault(n.FortunaTimestamp, defaults.FortunaTimestamp); err != nil { - return fmt.Errorf("Fortuna fork block timestamp is invalid: %w", err) + return fmt.Errorf("fortuna fork block timestamp is invalid: %w", err) } if err := verifyWithDefault(n.GraniteTimestamp, defaults.GraniteTimestamp); err != nil { - return fmt.Errorf("Granite fork block timestamp is invalid: %w", err) + return fmt.Errorf("granite fork block timestamp is invalid: %w", err) } return nil } diff --git a/plugin/evm/blockgascost/cost.go b/plugin/evm/blockgascost/cost.go index 891200d355..9dbaf91e33 100644 --- a/plugin/evm/blockgascost/cost.go +++ b/plugin/evm/blockgascost/cost.go @@ -30,10 +30,10 @@ func BlockGasCost( } var ( - minBlockGasCost uint64 = feeConfig.MinBlockGasCost.Uint64() - maxBlockGasCost uint64 = feeConfig.MaxBlockGasCost.Uint64() - op = safemath.Add[uint64] - defaultCost uint64 = feeConfig.MaxBlockGasCost.Uint64() + minBlockGasCost = feeConfig.MinBlockGasCost.Uint64() + maxBlockGasCost = feeConfig.MaxBlockGasCost.Uint64() + op = safemath.Add[uint64] + defaultCost = feeConfig.MaxBlockGasCost.Uint64() ) if timeElapsed > feeConfig.TargetBlockRate { op = safemath.Sub diff --git a/plugin/evm/client/client.go b/plugin/evm/client/client.go index 7eda012058..03850eb93e 100644 --- a/plugin/evm/client/client.go +++ b/plugin/evm/client/client.go @@ -49,8 +49,8 @@ type client struct { // NewClient returns a Client for interacting with EVM [chain] func NewClient(uri, chain string) Client { - requestUri := fmt.Sprintf("%s/ext/bc/%s", uri, chain) - return NewClientWithURL(requestUri) + requestURI := fmt.Sprintf("%s/ext/bc/%s", uri, chain) + return NewClientWithURL(requestURI) } // NewClientWithURL returns a Client for interacting with EVM [chain] diff --git a/plugin/evm/config/config.go b/plugin/evm/config/config.go index f750abbd6d..c10f0d2232 100644 --- a/plugin/evm/config/config.go +++ b/plugin/evm/config/config.go @@ -173,7 +173,7 @@ type Config struct { WarpOffChainMessages []hexutil.Bytes `json:"warp-off-chain-messages"` // RPC settings - HttpBodyLimit uint64 `json:"http-body-limit"` + HTTPBodyLimit uint64 `json:"http-body-limit"` BatchRequestLimit uint64 `json:"batch-request-limit"` BatchResponseMaxSize uint64 `json:"batch-response-max-size"` diff --git a/plugin/evm/customrawdb/database_ext.go b/plugin/evm/customrawdb/database_ext.go index 961b1000d6..76c320de06 100644 --- a/plugin/evm/customrawdb/database_ext.go +++ b/plugin/evm/customrawdb/database_ext.go @@ -70,7 +70,7 @@ func ParseStateSchemeExt(provided string, disk ethdb.Database) (string, error) { if provided == FirewoodScheme { if diskScheme := rawdb.ReadStateScheme(disk); diskScheme != "" { // Valid scheme on disk mismatched - return "", fmt.Errorf("State scheme %s already set on disk, can't use Firewood", diskScheme) + return "", fmt.Errorf("state scheme %s already set on disk, can't use Firewood", diskScheme) } // If no conflicting scheme is found, is valid. return FirewoodScheme, nil diff --git a/plugin/evm/database/wrapped_database.go b/plugin/evm/database/wrapped_database.go index bcc1999901..69425bf038 100644 --- a/plugin/evm/database/wrapped_database.go +++ b/plugin/evm/database/wrapped_database.go @@ -11,29 +11,29 @@ import ( ) var ( - _ ethdb.KeyValueStore = (*ethDbWrapper)(nil) + _ ethdb.KeyValueStore = (*ethDBWrapper)(nil) ErrSnapshotNotSupported = errors.New("snapshot is not supported") ) // ethDbWrapper implements ethdb.Database -type ethDbWrapper struct{ database.Database } +type ethDBWrapper struct{ database.Database } -func WrapDatabase(db database.Database) ethdb.KeyValueStore { return ethDbWrapper{db} } +func WrapDatabase(db database.Database) ethdb.KeyValueStore { return ethDBWrapper{db} } // Stat implements ethdb.Database -func (ethDbWrapper) Stat(string) (string, error) { return "", database.ErrNotFound } +func (ethDBWrapper) Stat(string) (string, error) { return "", database.ErrNotFound } // NewBatch implements ethdb.Database -func (db ethDbWrapper) NewBatch() ethdb.Batch { return wrappedBatch{db.Database.NewBatch()} } +func (db ethDBWrapper) NewBatch() ethdb.Batch { return wrappedBatch{db.Database.NewBatch()} } // NewBatchWithSize implements ethdb.Database // TODO: propagate size through avalanchego Database interface -func (db ethDbWrapper) NewBatchWithSize(int) ethdb.Batch { +func (db ethDBWrapper) NewBatchWithSize(int) ethdb.Batch { return wrappedBatch{db.Database.NewBatch()} } -func (ethDbWrapper) NewSnapshot() (ethdb.Snapshot, error) { +func (ethDBWrapper) NewSnapshot() (ethdb.Snapshot, error) { return nil, ErrSnapshotNotSupported } @@ -41,7 +41,7 @@ func (ethDbWrapper) NewSnapshot() (ethdb.Snapshot, error) { // // Note: This method assumes that the prefix is NOT part of the start, so there's // no need for the caller to prepend the prefix to the start. -func (db ethDbWrapper) NewIterator(prefix []byte, start []byte) ethdb.Iterator { +func (db ethDBWrapper) NewIterator(prefix []byte, start []byte) ethdb.Iterator { // avalanchego's database implementation assumes that the prefix is part of the // start, so it is added here (if it is provided). if len(prefix) > 0 { @@ -54,7 +54,7 @@ func (db ethDbWrapper) NewIterator(prefix []byte, start []byte) ethdb.Iterator { } // NewIteratorWithStart implements ethdb.Database -func (db ethDbWrapper) NewIteratorWithStart(start []byte) ethdb.Iterator { +func (db ethDBWrapper) NewIteratorWithStart(start []byte) ethdb.Iterator { return db.Database.NewIteratorWithStart(start) } diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index f922e41668..a2e6619307 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -153,7 +153,7 @@ var ( // legacyApiNames maps pre geth v1.10.20 api names to their updated counterparts. // used in attachEthService for backward configuration compatibility. -var legacyApiNames = map[string]string{ +var legacyAPINames = map[string]string{ "internal-public-eth": "internal-eth", "internal-public-blockchain": "internal-blockchain", "internal-public-transaction-pool": "internal-transaction", @@ -1140,8 +1140,8 @@ func (vm *VM) CreateHandlers(context.Context) (map[string]http.Handler, error) { if vm.config.BatchRequestLimit > 0 && vm.config.BatchResponseMaxSize > 0 { handler.SetBatchLimits(int(vm.config.BatchRequestLimit), int(vm.config.BatchResponseMaxSize)) } - if vm.config.HttpBodyLimit > 0 { - handler.SetHTTPBodyLimit(int(vm.config.HttpBodyLimit)) + if vm.config.HTTPBodyLimit > 0 { + handler.SetHTTPBodyLimit(int(vm.config.HTTPBodyLimit)) } enabledAPIs := vm.config.EthAPIs() @@ -1309,7 +1309,7 @@ func attachEthService(handler *rpc.Server, apis []rpc.API, names []string) error for _, ns := range names { // handle pre geth v1.10.20 api names as aliases for their updated values // to allow configurations to be backwards compatible. - if newName, isLegacy := legacyApiNames[ns]; isLegacy { + if newName, isLegacy := legacyAPINames[ns]; isLegacy { log.Info("deprecated api name referenced in configuration.", "deprecated", ns, "new", newName) enabledServicesSet[newName] = struct{}{} continue diff --git a/precompile/contracts/feemanager/unpack_pack_test.go b/precompile/contracts/feemanager/unpack_pack_test.go index a686dc1455..bb00be8ccb 100644 --- a/precompile/contracts/feemanager/unpack_pack_test.go +++ b/precompile/contracts/feemanager/unpack_pack_test.go @@ -42,13 +42,10 @@ func FuzzPackGetFeeConfigOutputEqualTest(f *testing.F) { MaxBlockGasCost: bigIntVal, BlockGasCostStep: bigIntVal, } - doCheckOutputs := true // we can only check if outputs are correct if the value is less than MaxUint256 // otherwise the value will be truncated when packed, // and thus unpacked output will not be equal to the value - if bigIntVal.Cmp(abi.MaxUint256) > 0 { - doCheckOutputs = false - } + doCheckOutputs := bigIntVal.Cmp(abi.MaxUint256) <= 0 testOldPackGetFeeConfigOutputEqual(t, feeConfig, doCheckOutputs) }) } @@ -173,13 +170,10 @@ func FuzzPackGetLastChangedAtOutput(f *testing.F) { f.Add(math.MaxBig256.Add(math.MaxBig256, common.Big1).Bytes()) f.Fuzz(func(t *testing.T, bigIntBytes []byte) { bigIntVal := new(big.Int).SetBytes(bigIntBytes) - doCheckOutputs := true // we can only check if outputs are correct if the value is less than MaxUint256 // otherwise the value will be truncated when packed, // and thus unpacked output will not be equal to the value - if bigIntVal.Cmp(abi.MaxUint256) > 0 { - doCheckOutputs = false - } + doCheckOutputs := bigIntVal.Cmp(abi.MaxUint256) <= 0 testOldPackGetLastChangedAtOutputEqual(t, bigIntVal, doCheckOutputs) }) } @@ -203,13 +197,10 @@ func FuzzPackSetFeeConfigEqualTest(f *testing.F) { MaxBlockGasCost: bigIntVal, BlockGasCostStep: bigIntVal, } - doCheckOutputs := true // we can only check if outputs are correct if the value is less than MaxUint256 // otherwise the value will be truncated when packed, // and thus unpacked output will not be equal to the value - if bigIntVal.Cmp(abi.MaxUint256) > 0 { - doCheckOutputs = false - } + doCheckOutputs := bigIntVal.Cmp(abi.MaxUint256) <= 0 testOldPackSetFeeConfigInputEqual(t, feeConfig, doCheckOutputs) }) } diff --git a/precompile/contracts/nativeminter/unpack_pack_test.go b/precompile/contracts/nativeminter/unpack_pack_test.go index c133510e4f..c5ba7f7405 100644 --- a/precompile/contracts/nativeminter/unpack_pack_test.go +++ b/precompile/contracts/nativeminter/unpack_pack_test.go @@ -32,13 +32,10 @@ func FuzzPackMintNativeCoinEqualTest(f *testing.F) { f.Add(constants.BlackholeAddr.Bytes(), common.Big2.Bytes()) f.Fuzz(func(t *testing.T, b []byte, bigIntBytes []byte) { bigIntVal := new(big.Int).SetBytes(bigIntBytes) - doCheckOutputs := true // we can only check if outputs are correct if the value is less than MaxUint256 // otherwise the value will be truncated when packed, // and thus unpacked output will not be equal to the value - if bigIntVal.Cmp(abi.MaxUint256) > 0 { - doCheckOutputs = false - } + doCheckOutputs := bigIntVal.Cmp(abi.MaxUint256) <= 0 testOldPackMintNativeCoinEqual(t, common.BytesToAddress(b), bigIntVal, doCheckOutputs) }) } diff --git a/precompile/modules/module.go b/precompile/modules/module.go index a36fd72f6d..e417ca88d4 100644 --- a/precompile/modules/module.go +++ b/precompile/modules/module.go @@ -25,12 +25,12 @@ type Module struct { type moduleArray []Module -func (u moduleArray) Len() int { - return len(u) +func (m moduleArray) Len() int { + return len(m) } -func (u moduleArray) Swap(i, j int) { - u[i], u[j] = u[j], u[i] +func (m moduleArray) Swap(i, j int) { + m[i], m[j] = m[j], m[i] } func (m moduleArray) Less(i, j int) bool { diff --git a/sync/client/client.go b/sync/client/client.go index a9f32f8c9a..facbf86461 100644 --- a/sync/client/client.go +++ b/sync/client/client.go @@ -316,7 +316,7 @@ func (c *client) get(ctx context.Context, request message.Request, parseFn parse var ( response []byte nodeID ids.NodeID - start time.Time = time.Now() + start = time.Now() ) if len(c.stateSyncNodes) == 0 { response, nodeID, err = c.networkClient.SendSyncedAppRequestAny(ctx, StateSyncVersion, requestBytes) diff --git a/sync/handlers/leafs_request.go b/sync/handlers/leafs_request.go index 73595e227d..48ddb1ea3f 100644 --- a/sync/handlers/leafs_request.go +++ b/sync/handlers/leafs_request.go @@ -6,7 +6,6 @@ package handlers import ( "bytes" "context" - "sync" "time" "github.com/ava-labs/avalanchego/codec" @@ -47,7 +46,6 @@ type LeafsRequestHandler struct { snapshotProvider SnapshotProvider codec codec.Manager stats stats.LeafsRequestHandlerStats - pool sync.Pool } func NewLeafsRequestHandler(trieDB *triedb.Database, snapshotProvider SnapshotProvider, codec codec.Manager, syncerStats stats.LeafsRequestHandlerStats) *LeafsRequestHandler { @@ -56,9 +54,6 @@ func NewLeafsRequestHandler(trieDB *triedb.Database, snapshotProvider SnapshotPr snapshotProvider: snapshotProvider, codec: codec, stats: syncerStats, - pool: sync.Pool{ - New: func() interface{} { return make([][]byte, 0, maxLeavesLimit) }, - }, } } @@ -108,19 +103,8 @@ func (lrh *LeafsRequestHandler) OnLeafsRequest(ctx context.Context, nodeID ids.N } var leafsResponse message.LeafsResponse - // pool response's key/val allocations - leafsResponse.Keys = lrh.pool.Get().([][]byte) - leafsResponse.Vals = lrh.pool.Get().([][]byte) - defer func() { - for i := range leafsResponse.Keys { - // clear out slices before returning them to the pool - // to avoid memory leak. - leafsResponse.Keys[i] = nil - leafsResponse.Vals[i] = nil - } - lrh.pool.Put(leafsResponse.Keys[:0]) - lrh.pool.Put(leafsResponse.Vals[:0]) - }() + leafsResponse.Keys = make([][]byte, 0, limit) + leafsResponse.Vals = make([][]byte, 0, limit) responseBuilder := &responseBuilder{ request: &leafsRequest, diff --git a/sync/handlers/leafs_request_test.go b/sync/handlers/leafs_request_test.go index 0bfe48cbae..ee28bf45af 100644 --- a/sync/handlers/leafs_request_test.go +++ b/sync/handlers/leafs_request_test.go @@ -49,9 +49,10 @@ func TestLeafsRequestHandler_OnLeafsRequest(t *testing.T) { 10_000, func(_ *testing.T, i int, acc types.StateAccount) types.StateAccount { // set the storage trie root for two accounts - if i == 0 { + switch i { + case 0: acc.Root = largeTrieRoot - } else if i == 1 { + case 1: acc.Root = smallTrieRoot } @@ -418,9 +419,10 @@ func TestLeafsRequestHandler_OnLeafsRequest(t *testing.T) { }, assertResponseFn: func(t *testing.T, request message.LeafsRequest, response []byte, err error) { assert.NotEmpty(t, response) + assert.NoError(t, err) var leafsResponse message.LeafsResponse - if _, err = message.Codec.Unmarshal(response, &leafsResponse); err != nil { + if _, err := message.Codec.Unmarshal(response, &leafsResponse); err != nil { t.Fatalf("unexpected error when unmarshalling LeafsResponse: %v", err) } diff --git a/triedb/firewood/account_trie.go b/triedb/firewood/account_trie.go index 417b7b20ec..d5e72c1f53 100644 --- a/triedb/firewood/account_trie.go +++ b/triedb/firewood/account_trie.go @@ -59,8 +59,7 @@ func (a *AccountTrie) GetAccount(addr common.Address) (*types.StateAccount, erro key := crypto.Keccak256Hash(addr.Bytes()).Bytes() // First check if there's a pending update for this account - keyStr := string(key) - if updateValue, exists := a.dirtyKeys[keyStr]; exists { + if updateValue, exists := a.dirtyKeys[string(key)]; exists { // If the value is empty, it indicates deletion // Invariant: All encoded values have length > 0 if len(updateValue) == 0 { @@ -105,8 +104,7 @@ func (a *AccountTrie) GetStorage(addr common.Address, key []byte) ([]byte, error copy(combinedKey[common.HashLength:], storageKey) // Check if there's a pending update for this storage slot - keyStr := string(combinedKey[:]) - if updateValue, exists := a.dirtyKeys[keyStr]; exists { + if updateValue, exists := a.dirtyKeys[string(combinedKey[:])]; exists { // If the value is empty, it indicates deletion if len(updateValue) == 0 { return nil, nil