diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..05efd04a9 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,69 @@ +linters-settings: + govet: + check-shadowing: true + settings: + printf: + funcs: + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf + golint: + min-confidence: 0 + gocyclo: + min-complexity: 10 + maligned: + suggest-new: true + dupl: + threshold: 100 + goconst: + min-len: 2 + min-occurrences: 2 + depguard: + list-type: blacklist + packages: + # logging is allowed only by logutils.Log, logrus + # is allowed to use only in logutils package + - github.com/sirupsen/logrus + misspell: + locale: US + lll: + line-length: 140 + goimports: + local-prefixes: github.com/golangci/golangci-lint + gocritic: + enabled-tags: + - performance + - style + - experimental + disabled-checks: + - wrapperFunc + +linters: + enable: + - deadcode + - goconst + - goimports + - golint + - gosec + - misspell + - structcheck + - typecheck + - unparam + - varcheck + - gofmt + - unused + disable-all: true + +run: + skip-dirs: + - proto/ + - ^contracts/ + deadline: 10m + +# golangci.com configuration +# https://github.com/golangci/golangci/wiki/Configuration +service: + golangci-lint-version: 1.15.0 # use the fixed version to not introduce new linters unexpectedly + prepare: + - echo "here I can run custom commands, but no preparation needed for this repo" diff --git a/.gometalinter.json b/.gometalinter.json deleted file mode 100644 index 927c09f48..000000000 --- a/.gometalinter.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "Deadline": "10m", - "Exclude": [ - "^proto/", - "^contracts/" - ], - "DisableAll": true, - "Enable": [ - "deadcode", - "goconst", - "goimports", - "golint", - "gosec", - "gotype", - "misspell", - "structcheck", - "unparam", - "varcheck" - ] -} diff --git a/.travis.yml b/.travis.yml index a972f2245..e4785b7a0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,8 +10,9 @@ matrix: - lint install: - go get ${gobuild_args} -t ./... + - go get ${gobuild_args} github.com/golangci/golangci-lint/cmd/golangci-lint script: - - go get ${gobuild_args} github.com/alecthomas/gometalinter && gometalinter --install && gometalinter ./... + - golangci-lint run email: false after_success: - wget https://raw.githubusercontent.com/k3rn31p4nic/travis-ci-discord-webhook/master/send.sh diff --git a/README.md b/README.md index b1b92ea1d..0f146ae82 100644 --- a/README.md +++ b/README.md @@ -169,10 +169,10 @@ To run the unit tests of our system do: bazel test //... ``` -To run our linter, make sure you have [gometalinter](https://github.com/alecthomas/gometalinter) installed and then run: +To run our linter, make sure you have [golangci-lint](https://https://github.com/golangci/golangci-lint) installed and then run: ``` -gometalinter ./... +golangci-lint run ``` # Contributing diff --git a/beacon-chain/blockchain/block_processing_test.go b/beacon-chain/blockchain/block_processing_test.go index 0d34221e1..3e9c54fd4 100644 --- a/beacon-chain/blockchain/block_processing_test.go +++ b/beacon-chain/blockchain/block_processing_test.go @@ -191,7 +191,7 @@ func TestReceiveBlock_UsesParentBlockState(t *testing.T) { t.Fatalf("Could not tree hash state: %v", err) } - parentHash, genesisBlock := setupGenesisBlock(t, chainService, beaconState) + parentHash, genesisBlock := setupGenesisBlock(t, chainService) if err := chainService.beaconDB.UpdateChainHead(ctx, genesisBlock, beaconState); err != nil { t.Fatal(err) } @@ -246,7 +246,7 @@ func TestReceiveBlock_DeletesBadBlock(t *testing.T) { t.Fatal(err) } - parentHash, genesisBlock := setupGenesisBlock(t, chainService, beaconState) + parentHash, genesisBlock := setupGenesisBlock(t, chainService) if err := chainService.beaconDB.UpdateChainHead(ctx, genesisBlock, beaconState); err != nil { t.Fatal(err) } @@ -324,7 +324,7 @@ func TestReceiveBlock_CheckBlockStateRoot_GoodState(t *testing.T) { if err := chainService.beaconDB.SaveHistoricalState(ctx, beaconState); err != nil { t.Fatal(err) } - parentHash, genesisBlock := setupGenesisBlock(t, chainService, beaconState) + parentHash, genesisBlock := setupGenesisBlock(t, chainService) beaconState.Slot++ if err := chainService.beaconDB.UpdateChainHead(ctx, genesisBlock, beaconState); err != nil { t.Fatal(err) @@ -368,7 +368,7 @@ func TestReceiveBlock_CheckBlockStateRoot_BadState(t *testing.T) { if err := chainService.beaconDB.SaveHistoricalState(ctx, beaconState); err != nil { t.Fatal(err) } - parentHash, genesisBlock := setupGenesisBlock(t, chainService, beaconState) + parentHash, genesisBlock := setupGenesisBlock(t, chainService) beaconState.Slot++ if err := chainService.beaconDB.UpdateChainHead(ctx, genesisBlock, beaconState); err != nil { t.Fatal(err) @@ -423,7 +423,7 @@ func TestReceiveBlock_RemovesPendingDeposits(t *testing.T) { if err != nil { t.Fatalf("Could not tree hash state: %v", err) } - parentHash, genesisBlock := setupGenesisBlock(t, chainService, beaconState) + parentHash, genesisBlock := setupGenesisBlock(t, chainService) beaconState.Slot++ if err := chainService.beaconDB.UpdateChainHead(ctx, genesisBlock, beaconState); err != nil { t.Fatal(err) @@ -578,7 +578,7 @@ func TestReceiveBlock_OnChainSplit(t *testing.T) { if err != nil { t.Fatalf("Could not tree hash state: %v", err) } - parentHash, genesisBlock := setupGenesisBlock(t, chainService, beaconState) + parentHash, genesisBlock := setupGenesisBlock(t, chainService) if err := db.UpdateChainHead(ctx, genesisBlock, beaconState); err != nil { t.Fatal(err) } diff --git a/beacon-chain/blockchain/fork_choice_test.go b/beacon-chain/blockchain/fork_choice_test.go index 5ab18d340..0902c19a3 100644 --- a/beacon-chain/blockchain/fork_choice_test.go +++ b/beacon-chain/blockchain/fork_choice_test.go @@ -29,6 +29,7 @@ import ( // Ensure ChainService implements interfaces. var _ = ForkChoice(&ChainService{}) +var endpoint = "ws://127.0.0.1" func TestApplyForkChoice_SetsCanonicalHead(t *testing.T) { deposits, _ := setupInitialDeposits(t, 5) @@ -804,7 +805,7 @@ func BenchmarkLMDGhost_8Slots_8Validators(b *testing.B) { balances[i] = params.BeaconConfig().MaxDepositAmount } - chainService := setupBeaconChainBenchmark(b, false, beaconDB, true, nil) + chainService := setupBeaconChainBenchmark(b, beaconDB) // Construct 8 blocks. (Epoch length = 8) epochLength := uint64(8) @@ -885,7 +886,7 @@ func BenchmarkLMDGhost_32Slots_8Validators(b *testing.B) { balances[i] = params.BeaconConfig().MaxDepositAmount } - chainService := setupBeaconChainBenchmark(b, false, beaconDB, true, nil) + chainService := setupBeaconChainBenchmark(b, beaconDB) // Construct 8 blocks. (Epoch length = 8) epochLength := uint64(8) @@ -964,7 +965,7 @@ func BenchmarkLMDGhost_32Slots_64Validators(b *testing.B) { balances[i] = params.BeaconConfig().MaxDepositAmount } - chainService := setupBeaconChainBenchmark(b, false, beaconDB, true, nil) + chainService := setupBeaconChainBenchmark(b, beaconDB) // Construct 64 blocks. (Epoch length = 64) epochLength := uint64(32) @@ -1043,7 +1044,7 @@ func BenchmarkLMDGhost_64Slots_16384Validators(b *testing.B) { balances[i] = params.BeaconConfig().MaxDepositAmount } - chainService := setupBeaconChainBenchmark(b, false, beaconDB, true, nil) + chainService := setupBeaconChainBenchmark(b, beaconDB) // Construct 64 blocks. (Epoch length = 64) epochLength := uint64(64) @@ -1107,32 +1108,19 @@ func BenchmarkLMDGhost_64Slots_16384Validators(b *testing.B) { } } -func setupBeaconChainBenchmark(b *testing.B, faultyPoWClient bool, beaconDB *db.BeaconDB, enablePOWChain bool, attsService *attestation.Service) *ChainService { - endpoint := "ws://127.0.0.1" +func setupBeaconChainBenchmark(b *testing.B, beaconDB *db.BeaconDB) *ChainService { ctx := context.Background() var web3Service *powchain.Web3Service var err error - if enablePOWChain { - if faultyPoWClient { - client := &faultyClient{} - web3Service, err = powchain.NewWeb3Service(ctx, &powchain.Web3ServiceConfig{ - Endpoint: endpoint, - DepositContract: common.Address{}, - Reader: client, - Client: client, - Logger: client, - }) - } else { - client := &mockClient{} - web3Service, err = powchain.NewWeb3Service(ctx, &powchain.Web3ServiceConfig{ - Endpoint: endpoint, - DepositContract: common.Address{}, - Reader: client, - Client: client, - Logger: client, - }) - } - } + client := &faultyClient{} + web3Service, err = powchain.NewWeb3Service(ctx, &powchain.Web3ServiceConfig{ + Endpoint: endpoint, + DepositContract: common.Address{}, + Reader: client, + Client: client, + Logger: client, + }) + if err != nil { b.Fatalf("unable to set up web3 service: %v", err) } @@ -1142,7 +1130,7 @@ func setupBeaconChainBenchmark(b *testing.B, faultyPoWClient bool, beaconDB *db. BeaconDB: beaconDB, Web3Service: web3Service, OpsPoolService: &mockOperationService{}, - AttsService: attsService, + AttsService: nil, } if err != nil { b.Fatalf("could not register blockchain service: %v", err) diff --git a/beacon-chain/blockchain/service_test.go b/beacon-chain/blockchain/service_test.go index be07bf043..5a108a853 100644 --- a/beacon-chain/blockchain/service_test.go +++ b/beacon-chain/blockchain/service_test.go @@ -206,7 +206,7 @@ func createRandaoReveal(t *testing.T, beaconState *pb.BeaconState, privKeys []*b return epochSignature.Marshal() } -func setupGenesisBlock(t *testing.T, cs *ChainService, beaconState *pb.BeaconState) ([32]byte, *pb.BeaconBlock) { +func setupGenesisBlock(t *testing.T, cs *ChainService) ([32]byte, *pb.BeaconBlock) { genesis := b.NewGenesisBlock([]byte{}) if err := cs.beaconDB.SaveBlock(genesis); err != nil { t.Fatalf("could not save block to db: %v", err) @@ -307,7 +307,6 @@ func TestChainStartStop_Initialized(t *testing.T) { hook := logTest.NewGlobal() db := internal.SetupDB(t) defer internal.TeardownDB(t, db) - ctx := context.Background() chainService := setupBeaconChain(t, db, nil) @@ -316,11 +315,7 @@ func TestChainStartStop_Initialized(t *testing.T) { if err := db.InitializeState(context.Background(), unixTime, deposits, &pb.Eth1Data{}); err != nil { t.Fatalf("Could not initialize beacon state to disk: %v", err) } - beaconState, err := db.HeadState(ctx) - if err != nil { - t.Fatalf("Could not fetch beacon state: %v", err) - } - setupGenesisBlock(t, chainService, beaconState) + setupGenesisBlock(t, chainService) // Test the start function. chainService.Start() diff --git a/beacon-chain/core/helpers/committee.go b/beacon-chain/core/helpers/committee.go index 949f6ca56..6e48f1d59 100644 --- a/beacon-chain/core/helpers/committee.go +++ b/beacon-chain/core/helpers/committee.go @@ -364,7 +364,7 @@ func VerifyBitfield(bitfield []byte, committeeSize int) (bool, error) { // * ``assignment[0]`` is the list of validators in the committee // * ``assignment[1]`` is the shard to which the committee is assigned // * ``assignment[2]`` is the slot at which the committee is assigned -// * ``assignment[3]`` is a bool signalling if the validator is expected to propose +// * ``assignment[3]`` is a bool signaling if the validator is expected to propose // a beacon block at the assigned slot. // """ // previous_epoch = get_previous_epoch(state) diff --git a/beacon-chain/db/state_test.go b/beacon-chain/db/state_test.go index 91099117d..f28028aaa 100644 --- a/beacon-chain/db/state_test.go +++ b/beacon-chain/db/state_test.go @@ -93,7 +93,7 @@ func TestFinalizeState_OK(t *testing.T) { defer teardownDB(t, db) genesisTime := uint64(time.Now().Unix()) - deposits, _ := setupInitialDeposits(t, 10) + deposits, _ := setupInitialDeposits(t, 20) if err := db.InitializeState(context.Background(), genesisTime, deposits, &pb.Eth1Data{}); err != nil { t.Fatalf("Failed to initialize state: %v", err) } diff --git a/beacon-chain/operations/service_test.go b/beacon-chain/operations/service_test.go index e85601572..13ecb6a3e 100644 --- a/beacon-chain/operations/service_test.go +++ b/beacon-chain/operations/service_test.go @@ -72,11 +72,11 @@ func TestRoutineContextClosing_Ok(t *testing.T) { s := NewOpsPoolService(context.Background(), &Config{BeaconDB: db}) exitRoutine := make(chan bool) - go func(tt *testing.T) { + go func() { s.removeOperations() s.saveOperations() <-exitRoutine - }(t) + }() s.cancel() exitRoutine <- true testutil.AssertLogsContain(t, hook, "operations service context closed, exiting remove goroutine") diff --git a/beacon-chain/powchain/block_reader_test.go b/beacon-chain/powchain/block_reader_test.go index 70d5a5c43..656a455a9 100644 --- a/beacon-chain/powchain/block_reader_test.go +++ b/beacon-chain/powchain/block_reader_test.go @@ -13,8 +13,9 @@ import ( gethTypes "github.com/ethereum/go-ethereum/core/types" ) +var endpoint = "ws://127.0.0.1" + func TestLatestMainchainInfo_OK(t *testing.T) { - endpoint := "ws://127.0.0.1" testAcc, err := setup() if err != nil { t.Fatalf("Unable to set up simulated backend %v", err) @@ -84,7 +85,6 @@ func TestLatestMainchainInfo_OK(t *testing.T) { } func TestBlockHashByHeight_ReturnsHash(t *testing.T) { - endpoint := "ws://127.0.0.1" web3Service, err := NewWeb3Service(context.Background(), &Web3ServiceConfig{ Endpoint: endpoint, BlockFetcher: &goodFetcher{}, @@ -123,7 +123,6 @@ func TestBlockHashByHeight_ReturnsHash(t *testing.T) { } func TestBlockExists_ValidHash(t *testing.T) { - endpoint := "ws://127.0.0.1" web3Service, err := NewWeb3Service(context.Background(), &Web3ServiceConfig{ Endpoint: endpoint, BlockFetcher: &goodFetcher{}, @@ -163,7 +162,6 @@ func TestBlockExists_ValidHash(t *testing.T) { } func TestBlockExists_InvalidHash(t *testing.T) { - endpoint := "ws://127.0.0.1" web3Service, err := NewWeb3Service(context.Background(), &Web3ServiceConfig{ Endpoint: endpoint, BlockFetcher: &goodFetcher{}, @@ -179,7 +177,6 @@ func TestBlockExists_InvalidHash(t *testing.T) { } func TestBlockExists_UsesCachedBlockInfo(t *testing.T) { - endpoint := "ws://127.0.0.1" web3Service, err := NewWeb3Service(context.Background(), &Web3ServiceConfig{ Endpoint: endpoint, BlockFetcher: nil, // nil blockFetcher would panic if cached value not used diff --git a/beacon-chain/powchain/log_processing.go b/beacon-chain/powchain/log_processing.go index 246fca144..c9a922505 100644 --- a/beacon-chain/powchain/log_processing.go +++ b/beacon-chain/powchain/log_processing.go @@ -189,7 +189,7 @@ func (w *Web3Service) processPastLogs() error { // last polled to now. func (w *Web3Service) requestBatchedLogs() error { // We request for the nth block behind the current head, in order to have - // stabilised logs when we retrieve it from the 1.0 chain. + // stabilized logs when we retrieve it from the 1.0 chain. requestedBlock := big.NewInt(0).Sub(w.blockHeight, big.NewInt(params.BeaconConfig().LogBlockDelay)) query := ethereum.FilterQuery{ Addresses: []common.Address{ diff --git a/beacon-chain/powchain/log_processing_test.go b/beacon-chain/powchain/log_processing_test.go index 2ebd064fb..4ef751136 100644 --- a/beacon-chain/powchain/log_processing_test.go +++ b/beacon-chain/powchain/log_processing_test.go @@ -28,7 +28,6 @@ func init() { func TestProcessDepositLog_OK(t *testing.T) { hook := logTest.NewGlobal() - endpoint := "ws://127.0.0.1" testAcc, err := setup() if err != nil { t.Fatalf("Unable to set up simulated backend %v", err) @@ -91,7 +90,6 @@ func TestProcessDepositLog_OK(t *testing.T) { } func TestProcessDepositLog_InsertsPendingDeposit(t *testing.T) { - endpoint := "ws://127.0.0.1" testAcc, err := setup() if err != nil { t.Fatalf("Unable to set up simulated backend %v", err) @@ -153,7 +151,6 @@ func TestProcessDepositLog_InsertsPendingDeposit(t *testing.T) { } func TestUnpackDepositLogData_OK(t *testing.T) { - endpoint := "ws://127.0.0.1" testAcc, err := setup() if err != nil { t.Fatalf("Unable to set up simulated backend %v", err) @@ -237,7 +234,6 @@ func TestUnpackDepositLogData_OK(t *testing.T) { func TestProcessChainStartLog_8DuplicatePubkeys(t *testing.T) { hook := logTest.NewGlobal() - endpoint := "ws://127.0.0.1" testAcc, err := setup() if err != nil { t.Fatalf("Unable to set up simulated backend %v", err) @@ -323,7 +319,6 @@ func TestProcessChainStartLog_8DuplicatePubkeys(t *testing.T) { func TestProcessChainStartLog_8UniquePubkeys(t *testing.T) { hook := logTest.NewGlobal() - endpoint := "ws://127.0.0.1" testAcc, err := setup() if err != nil { t.Fatalf("Unable to set up simulated backend %v", err) @@ -408,7 +403,6 @@ func TestProcessChainStartLog_8UniquePubkeys(t *testing.T) { } func TestUnpackChainStartLogData_OK(t *testing.T) { - endpoint := "ws://127.0.0.1" testAcc, err := setup() if err != nil { t.Fatalf("Unable to set up simulated backend %v", err) @@ -477,7 +471,6 @@ func TestUnpackChainStartLogData_OK(t *testing.T) { } func TestHasChainStartLogOccurred_OK(t *testing.T) { - endpoint := "ws://127.0.0.1" testAcc, err := setup() if err != nil { t.Fatalf("Unable to set up simulated backend %v", err) @@ -538,7 +531,6 @@ func TestHasChainStartLogOccurred_OK(t *testing.T) { } func TestETH1DataGenesis_OK(t *testing.T) { - endpoint := "ws://127.0.0.1" testAcc, err := setup() if err != nil { t.Fatalf("Unable to set up simulated backend %v", err) diff --git a/beacon-chain/powchain/service_test.go b/beacon-chain/powchain/service_test.go index 73b7557ee..d10d8e692 100644 --- a/beacon-chain/powchain/service_test.go +++ b/beacon-chain/powchain/service_test.go @@ -38,16 +38,6 @@ func (g *goodReader) SubscribeNewHead(ctx context.Context, ch chan<- *gethTypes. return new(event.Feed).Subscribe(ch), nil } -type badLogger struct{} - -func (b *badLogger) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]gethTypes.Log, error) { - return nil, errors.New("unable to retrieve logs") -} - -func (b *badLogger) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- gethTypes.Log) (ethereum.Subscription, error) { - return nil, errors.New("subscription has failed") -} - type goodLogger struct{} func (g *goodLogger) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- gethTypes.Log) (ethereum.Subscription, error) { @@ -198,7 +188,6 @@ func TestNewWeb3Service_OK(t *testing.T) { func TestStart_OK(t *testing.T) { hook := logTest.NewGlobal() - endpoint := "ws://127.0.0.1" testAcc, err := setup() if err != nil { t.Fatalf("Unable to set up simulated backend %v", err) @@ -237,7 +226,6 @@ func TestStart_OK(t *testing.T) { func TestStop_OK(t *testing.T) { hook := logTest.NewGlobal() - endpoint := "ws://127.0.0.1" testAcc, err := setup() if err != nil { t.Fatalf("Unable to set up simulated backend %v", err) @@ -274,7 +262,7 @@ func TestStop_OK(t *testing.T) { } func TestInitDataFromContract_OK(t *testing.T) { - endpoint := "ws://127.0.0.1" + testAcc, err := setup() if err != nil { t.Fatalf("Unable to set up simulated backend %v", err) @@ -304,7 +292,7 @@ func TestInitDataFromContract_OK(t *testing.T) { func TestWeb3Service_BadReader(t *testing.T) { hook := logTest.NewGlobal() - endpoint := "ws://127.0.0.1" + testAcc, err := setup() if err != nil { t.Fatalf("Unable to set up simulated backend %v", err) @@ -367,7 +355,7 @@ func TestStatus(t *testing.T) { func TestHandlePanic_OK(t *testing.T) { hook := logTest.NewGlobal() - endpoint := "ws://127.0.0.1" + web3Service, err := NewWeb3Service(context.Background(), &Web3ServiceConfig{ Endpoint: endpoint, BlockFetcher: nil, // nil blockFetcher would panic if cached value not used diff --git a/beacon-chain/rpc/beacon_server_test.go b/beacon-chain/rpc/beacon_server_test.go index 52c428969..67166e519 100644 --- a/beacon-chain/rpc/beacon_server_test.go +++ b/beacon-chain/rpc/beacon_server_test.go @@ -24,6 +24,8 @@ import ( logTest "github.com/sirupsen/logrus/hooks/test" ) +var closedContext = "context closed" + type faultyPOWChainService struct { chainStartFeed *event.Feed hashesByHeight map[int][]byte @@ -129,8 +131,7 @@ func TestWaitForChainStart_ContextClosed(t *testing.T) { defer ctrl.Finish() mockStream := internal.NewMockBeaconService_WaitForChainStartServer(ctrl) go func(tt *testing.T) { - want := "context closed" - if err := beaconServer.WaitForChainStart(&ptypes.Empty{}, mockStream); !strings.Contains(err.Error(), want) { + if err := beaconServer.WaitForChainStart(&ptypes.Empty{}, mockStream); !strings.Contains(err.Error(), closedContext) { tt.Errorf("Could not call RPC method: %v", err) } <-exitRoutine diff --git a/beacon-chain/rpc/validator_server.go b/beacon-chain/rpc/validator_server.go index 39fce0986..7830d4b37 100644 --- a/beacon-chain/rpc/validator_server.go +++ b/beacon-chain/rpc/validator_server.go @@ -109,7 +109,7 @@ func (vs *ValidatorServer) ValidatorPerformance( // 1.) The list of validators in the committee. // 2.) The shard to which the committee is assigned. // 3.) The slot at which the committee is assigned. -// 4.) The bool signalling if the validator is expected to propose a block at the assigned slot. +// 4.) The bool signaling if the validator is expected to propose a block at the assigned slot. func (vs *ValidatorServer) CommitteeAssignment( ctx context.Context, req *pb.CommitteeAssignmentsRequest) (*pb.CommitteeAssignmentResponse, error) { diff --git a/beacon-chain/sync/initial-sync/helpers.go b/beacon-chain/sync/initial-sync/helpers.go index 3e2744b10..74681d884 100644 --- a/beacon-chain/sync/initial-sync/helpers.go +++ b/beacon-chain/sync/initial-sync/helpers.go @@ -15,6 +15,8 @@ import ( "go.opencensus.io/trace" ) +const noMsgData = "message contains no data" + func (s *InitialSync) checkBlockValidity(ctx context.Context, block *pb.BeaconBlock) error { ctx, span := trace.StartSpan(ctx, "beacon-chain.sync.initial-sync.checkBlockValidity") defer span.End() @@ -41,7 +43,7 @@ func (s *InitialSync) doesParentExist(block *pb.BeaconBlock) bool { func safelyHandleMessage(fn func(p2p.Message), msg p2p.Message) { defer func() { if r := recover(); r != nil { - printedMsg := "message contains no data" + printedMsg := noMsgData if msg.Data != nil { printedMsg = proto.MarshalTextString(msg.Data) } diff --git a/beacon-chain/sync/regular_sync_test.go b/beacon-chain/sync/regular_sync_test.go index 200077a9f..658b26ecc 100644 --- a/beacon-chain/sync/regular_sync_test.go +++ b/beacon-chain/sync/regular_sync_test.go @@ -120,7 +120,7 @@ func (ma *mockAttestationService) IncomingAttestationFeed() *event.Feed { return new(event.Feed) } -func setupService(t *testing.T, db *db.BeaconDB) *RegularSync { +func setupService(db *db.BeaconDB) *RegularSync { cfg := &RegularSyncConfig{ BlockAnnounceBufferSize: 0, BlockBufferSize: 0, @@ -178,7 +178,7 @@ func TestProcessBlock_OK(t *testing.T) { } } genesisTime := uint64(time.Now().Unix()) - deposits, _ := setupInitialDeposits(t, 10) + deposits, _ := setupInitialDeposits(t) if err := db.InitializeState(context.Background(), genesisTime, deposits, &pb.Eth1Data{}); err != nil { t.Fatalf("Failed to initialize state: %v", err) } @@ -253,7 +253,7 @@ func TestProcessBlock_MultipleBlocksProcessedOK(t *testing.T) { } } genesisTime := uint64(time.Now().Unix()) - deposits, _ := setupInitialDeposits(t, 10) + deposits, _ := setupInitialDeposits(t) if err := db.InitializeState(context.Background(), genesisTime, deposits, &pb.Eth1Data{}); err != nil { t.Fatal(err) } @@ -347,7 +347,7 @@ func TestBlockRequest_InvalidMsg(t *testing.T) { db := internal.SetupDB(t) defer internal.TeardownDB(t, db) - ss := setupService(t, db) + ss := setupService(db) malformedRequest := &pb.BeaconBlockAnnounce{ Hash: []byte{'t', 'e', 's', 't'}, @@ -370,7 +370,7 @@ func TestBlockRequest_OK(t *testing.T) { db := internal.SetupDB(t) defer internal.TeardownDB(t, db) - ss := setupService(t, db) + ss := setupService(db) request1 := &pb.BeaconBlockRequestBySlotNumber{ SlotNumber: 20, @@ -670,10 +670,10 @@ func TestHandleStateReq_NOState(t *testing.T) { db := internal.SetupDB(t) defer internal.TeardownDB(t, db) - ss := setupService(t, db) + ss := setupService(db) genesisTime := uint64(time.Now().Unix()) - deposits, _ := setupInitialDeposits(t, 10) + deposits, _ := setupInitialDeposits(t) if err := db.InitializeState(context.Background(), genesisTime, deposits, &pb.Eth1Data{}); err != nil { t.Fatalf("Failed to initialize state: %v", err) } @@ -722,7 +722,7 @@ func TestHandleStateReq_OK(t *testing.T) { t.Fatalf("could not hash beacon state: %v", err) } - ss := setupService(t, db) + ss := setupService(db) request1 := &pb.BeaconStateRequest{ FinalizedStateRootHash32S: stateRoot[:], diff --git a/beacon-chain/sync/service_test.go b/beacon-chain/sync/service_test.go index 631ed9b87..e020fbcd3 100644 --- a/beacon-chain/sync/service_test.go +++ b/beacon-chain/sync/service_test.go @@ -45,9 +45,10 @@ func initializeTestSyncService(ctx context.Context, cfg *Config, synced bool) *S return services } -func setupInitialDeposits(t *testing.T, numDeposits int) ([]*pb.Deposit, []*bls.SecretKey) { - privKeys := make([]*bls.SecretKey, numDeposits) - deposits := make([]*pb.Deposit, numDeposits) +func setupInitialDeposits(t *testing.T) ([]*pb.Deposit, []*bls.SecretKey) { + numOfDeposits := 10 + privKeys := make([]*bls.SecretKey, numOfDeposits) + deposits := make([]*pb.Deposit, numOfDeposits) for i := 0; i < len(deposits); i++ { priv, err := bls.RandKey(rand.Reader) if err != nil { @@ -71,7 +72,7 @@ func setupTestSyncService(t *testing.T, synced bool) (*Service, *db.BeaconDB) { db := internal.SetupDB(t) unixTime := uint64(time.Now().Unix()) - deposits, _ := setupInitialDeposits(t, 10) + deposits, _ := setupInitialDeposits(t) if err := db.InitializeState(context.Background(), unixTime, deposits, &pb.Eth1Data{}); err != nil { t.Fatalf("Failed to initialize state: %v", err) } diff --git a/shared/messagehandler/messagehandler.go b/shared/messagehandler/messagehandler.go index 90ceeb9d0..250cb8e46 100644 --- a/shared/messagehandler/messagehandler.go +++ b/shared/messagehandler/messagehandler.go @@ -10,6 +10,8 @@ import ( "go.opencensus.io/trace" ) +const noMsgData = "message contains no data" + var log = logrus.WithField("prefix", "message-handler") // SafelyHandleMessage will recover and log any panic that occurs from the @@ -17,7 +19,7 @@ var log = logrus.WithField("prefix", "message-handler") func SafelyHandleMessage(ctx context.Context, fn func(ctx context.Context, message proto.Message) error, msg proto.Message) { defer func() { if r := recover(); r != nil { - printedMsg := "message contains no data" + printedMsg := noMsgData if msg != nil { printedMsg = proto.MarshalTextString(msg) } diff --git a/shared/p2p/service_norace_test.go b/shared/p2p/service_norace_test.go index 47e591b6a..f430f45bc 100644 --- a/shared/p2p/service_norace_test.go +++ b/shared/p2p/service_norace_test.go @@ -28,7 +28,7 @@ func TestLifecycle(t *testing.T) { t.Errorf("incorrect log. wanted: %s. got: %v", want, msg) } - // The context should have been cancelled. + // The context should have been canceled. if s.ctx.Err() == nil { t.Error("Context was not cancelled") } diff --git a/shared/p2p/service_test.go b/shared/p2p/service_test.go index 60091f805..3595be614 100644 --- a/shared/p2p/service_test.go +++ b/shared/p2p/service_test.go @@ -32,6 +32,9 @@ var _ = shared.Service(&Server{}) var _ = Broadcaster(&Server{}) var _ = Sender(&Server{}) +const bar = "bar" +const testTopic = "test_topic" + func init() { logrus.SetLevel(logrus.DebugLevel) } @@ -84,7 +87,7 @@ func TestBroadcast_OK(t *testing.T) { func TestEmit_OK(t *testing.T) { s, _ := NewServer(&ServerConfig{}) - p := &testpb.TestMessage{Foo: "bar"} + p := &testpb.TestMessage{Foo: bar} ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -302,8 +305,8 @@ func TestRegisterTopic_WithoutAdapters(t *testing.T) { if err != nil { t.Fatalf("Failed to create new server: %v", err) } - topic := "test_topic" - testMessage := &testpb.TestMessage{Foo: "bar"} + topic := testTopic + testMessage := &testpb.TestMessage{Foo: bar} s.RegisterTopic(topic, testMessage) @@ -316,8 +319,8 @@ func TestRegisterTopic_WithoutAdapters(t *testing.T) { defer close(wait) msg := <-ch tmsg := msg.Data.(*testpb.TestMessage) - if tmsg.Foo != "bar" { - t.Errorf("Expected test message Foo: \"bar\". Got: %v", tmsg) + if tmsg.Foo != bar { + t.Errorf("Expected test message foo:\"bar\". Got: %v", tmsg) } }() @@ -338,8 +341,8 @@ func TestRegisterTopic_WithAdapters(t *testing.T) { if err != nil { t.Fatalf("Failed to create new server: %v", err) } - topic := "test_topic" - testMessage := &testpb.TestMessage{Foo: "bar"} + topic := testTopic + testMessage := &testpb.TestMessage{Foo: bar} i := 0 var testAdapter Adapter = func(next Handler) Handler { @@ -368,7 +371,7 @@ func TestRegisterTopic_WithAdapters(t *testing.T) { defer close(wait) msg := <-ch tmsg := msg.Data.(*testpb.TestMessage) - if tmsg.Foo != "bar" { + if tmsg.Foo != bar { t.Errorf("Expected test message Foo: \"bar\". Got: %v", tmsg) } }() @@ -395,8 +398,8 @@ func TestRegisterTopic_HandlesPanic(t *testing.T) { if err != nil { t.Fatalf("Failed to create new server: %v", err) } - topic := "test_topic" - testMessage := &testpb.TestMessage{Foo: "bar"} + topic := testTopic + testMessage := &testpb.TestMessage{Foo: bar} var panicAdapter Adapter = func(next Handler) Handler { return func(msg Message) { diff --git a/validator/client/runner.go b/validator/client/runner.go index fda25f50c..5ac9f05ea 100644 --- a/validator/client/runner.go +++ b/validator/client/runner.go @@ -28,7 +28,7 @@ type Validator interface { } // Run the main validator routine. This routine exits if the context is -// cancelled. +// canceled. // // Order of operations: // 1 - Initialize validator data diff --git a/validator/client/service_test.go b/validator/client/service_test.go index 201ef3d23..f920bdfc3 100644 --- a/validator/client/service_test.go +++ b/validator/client/service_test.go @@ -69,7 +69,7 @@ func TestStop_CancelsContext(t *testing.T) { func TestLifecycle(t *testing.T) { hook := logTest.NewGlobal() - // Use cancelled context so that the run function exits immediately.. + // Use canceled context so that the run function exits immediately.. ctx, cancel := context.WithCancel(context.Background()) cancel() validatorService := &ValidatorService{ @@ -88,7 +88,7 @@ func TestLifecycle(t *testing.T) { func TestLifecycle_Insecure(t *testing.T) { hook := logTest.NewGlobal() - // Use cancelled context so that the run function exits immediately. + // Use canceled context so that the run function exits immediately. ctx, cancel := context.WithCancel(context.Background()) cancel() validatorService := &ValidatorService{ diff --git a/validator/client/validator_metrics.go b/validator/client/validator_metrics.go index a88e14268..9eee658c2 100644 --- a/validator/client/validator_metrics.go +++ b/validator/client/validator_metrics.go @@ -47,7 +47,7 @@ func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot uint64) log.WithFields(logrus.Fields{ "totalValidators": resp.TotalValidators, "numActiveValidators": resp.TotalActiveValidators, - }).Infof("Validator registry information") + }).Info("Validator registry information") log.Info("Generating validator performance report from the previous epoch...") avgBalance := resp.AverageValidatorBalance / float32(params.BeaconConfig().GweiPerEth) log.WithField( @@ -66,7 +66,7 @@ func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot uint64) "delta": fmt.Sprintf("%f", newBalance-prevBalance), "percentChange": fmt.Sprintf("%.2f%%", percentNet*100), "pubKey": tpk, - }).Infof("Net gains/losses in eth") + }).Info("Net gains/losses in eth") } totalPrevBalance += resp.Balance } diff --git a/validator/client/validator_test.go b/validator/client/validator_test.go index d9e8440ad..29a6a571a 100644 --- a/validator/client/validator_test.go +++ b/validator/client/validator_test.go @@ -28,6 +28,8 @@ func init() { var _ = Validator(&validator{}) +const cancelledCtx = "context has been canceled" + func publicKeys(keys map[string]*keystore.Key) [][]byte { pks := make([][]byte, 0, len(keys)) for _, value := range keys { @@ -94,7 +96,7 @@ func TestWaitForChainStart_ContextCanceled(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() err := v.WaitForChainStart(ctx) - want := "context has been canceled" + want := cancelledCtx if !strings.Contains(err.Error(), want) { t.Errorf("Expected %v, received %v", want, err) } @@ -174,7 +176,7 @@ func TestWaitActivation_ContextCanceled(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() err := v.WaitForActivation(ctx) - want := "context has been canceled" + want := cancelledCtx if !strings.Contains(err.Error(), want) { t.Errorf("Expected %v, received %v", want, err) }