From dca93ce64190549da1807382fc47f6aceee43b69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Kapka?= Date: Wed, 23 Sep 2020 18:14:34 +0200 Subject: [PATCH] Unnecessary Slice-to-Slice Conversion analyzer (#7321) * analyzer with tests * fix bazel file * modify analyzer to fix build issues * add analyzer to tool chain * remove arrays from inspections * fix redundant [:] operator * Merge branch 'master' into use-slice-directly * Merge branch 'master' into use-slice-directly * fix another inspection * add package-level comment --- BUILD.bazel | 1 + beacon-chain/blockchain/log.go | 2 +- beacon-chain/blockchain/process_block_test.go | 2 +- beacon-chain/core/blocks/attestation_test.go | 10 +-- .../core/blocks/attester_slashing_test.go | 4 +- .../core/blocks/block_regression_test.go | 4 +- beacon-chain/core/blocks/exit_test.go | 2 +- beacon-chain/core/blocks/randao.go | 2 +- beacon-chain/core/blocks/signature.go | 4 +- beacon-chain/core/helpers/attestation_test.go | 2 +- beacon-chain/core/state/transition_test.go | 10 +-- beacon-chain/db/kv/state.go | 4 +- beacon-chain/p2p/fork_test.go | 2 +- beacon-chain/powchain/deposit_test.go | 2 +- beacon-chain/rpc/validator/aggregator_test.go | 4 +- beacon-chain/rpc/validator/attester.go | 4 +- beacon-chain/rpc/validator/proposer.go | 2 +- beacon-chain/rpc/validator/proposer_test.go | 4 +- beacon-chain/rpc/validator/server_test.go | 12 ++-- beacon-chain/state/cloners.go | 20 +++--- beacon-chain/state/getters.go | 2 +- .../sync/pending_attestations_queue_test.go | 2 +- beacon-chain/sync/validate_aggregate_proof.go | 4 +- .../sync/validate_aggregate_proof_test.go | 8 +-- .../sync/validate_attester_slashing_test.go | 4 +- .../sync/validate_proposer_slashing_test.go | 2 +- .../sync/validate_voluntary_exit_test.go | 2 +- .../deposit-contract/depositContract_test.go | 2 +- contracts/deposit-contract/testutils.go | 2 +- nogo_config.json | 7 +++ shared/bytesutil/bytes_test.go | 12 ++-- shared/depositutil/deposit_test.go | 2 +- shared/hashutil/merkleRoot_test.go | 4 +- shared/htrutils/merkleize.go | 8 +-- shared/testutil/deposits.go | 2 +- shared/testutil/helpers_test.go | 8 +-- slasher/db/kv/indexed_attestations.go | 2 +- slasher/rpc/server.go | 2 +- tools/analyzers/slicedirect/BUILD.bazel | 28 +++++++++ tools/analyzers/slicedirect/analyzer.go | 63 +++++++++++++++++++ tools/analyzers/slicedirect/analyzer_test.go | 11 ++++ .../slicedirect/testdata/BUILD.bazel | 8 +++ tools/analyzers/slicedirect/testdata/slice.go | 46 ++++++++++++++ validator/accounts/v1/account.go | 2 +- validator/client/metrics.go | 2 +- validator/client/propose.go | 2 +- validator/client/validator.go | 2 +- validator/db/kv/new_proposal_history.go | 2 +- 48 files changed, 251 insertions(+), 87 deletions(-) create mode 100644 tools/analyzers/slicedirect/BUILD.bazel create mode 100644 tools/analyzers/slicedirect/analyzer.go create mode 100644 tools/analyzers/slicedirect/analyzer_test.go create mode 100644 tools/analyzers/slicedirect/testdata/BUILD.bazel create mode 100644 tools/analyzers/slicedirect/testdata/slice.go diff --git a/BUILD.bazel b/BUILD.bazel index 93bb8f328..977976189 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -110,6 +110,7 @@ nogo( "//tools/analyzers/comparesame:go_tool_library", "//tools/analyzers/shadowpredecl:go_tool_library", "//tools/analyzers/nop:go_tool_library", + "//tools/analyzers/slicedirect:go_tool_library", ] + select({ # nogo checks that fail with coverage enabled. ":coverage_enabled": [], diff --git a/beacon-chain/blockchain/log.go b/beacon-chain/blockchain/log.go index 34dc02f3b..62fd55e64 100644 --- a/beacon-chain/blockchain/log.go +++ b/beacon-chain/blockchain/log.go @@ -30,6 +30,6 @@ func logBlockSyncStatus(block *ethpb.BeaconBlock, blockRoot [32]byte, finalized "block": fmt.Sprintf("0x%s...", hex.EncodeToString(blockRoot[:])[:8]), "epoch": helpers.SlotToEpoch(block.Slot), "finalizedEpoch": finalized.Epoch, - "finalizedRoot": fmt.Sprintf("0x%s...", hex.EncodeToString(finalized.Root[:])[:8]), + "finalizedRoot": fmt.Sprintf("0x%s...", hex.EncodeToString(finalized.Root)[:8]), }).Info("Synced new block") } diff --git a/beacon-chain/blockchain/process_block_test.go b/beacon-chain/blockchain/process_block_test.go index a68c94633..101c56f79 100644 --- a/beacon-chain/blockchain/process_block_test.go +++ b/beacon-chain/blockchain/process_block_test.go @@ -55,7 +55,7 @@ func TestStore_OnBlock(t *testing.T) { require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: st.Slot(), Root: randomParentRoot[:]})) require.NoError(t, service.beaconDB.SaveState(ctx, st.Copy(), randomParentRoot)) randomParentRoot2 := roots[1] - require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: st.Slot(), Root: randomParentRoot2[:]})) + require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: st.Slot(), Root: randomParentRoot2})) require.NoError(t, service.beaconDB.SaveState(ctx, st.Copy(), bytesutil.ToBytes32(randomParentRoot2))) tests := []struct { diff --git a/beacon-chain/core/blocks/attestation_test.go b/beacon-chain/core/blocks/attestation_test.go index c7b011be4..0d9a489f3 100644 --- a/beacon-chain/core/blocks/attestation_test.go +++ b/beacon-chain/core/blocks/attestation_test.go @@ -238,7 +238,7 @@ func TestProcessAttestations_OK(t *testing.T) { require.NoError(t, err) sigs[i] = sig } - att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + att.Signature = bls.AggregateSignatures(sigs).Marshal() block := testutil.NewBeaconBlock() block.Block.Body.Attestations = []*ethpb.Attestation{att} @@ -282,7 +282,7 @@ func TestProcessAggregatedAttestation_OverlappingBits(t *testing.T) { require.NoError(t, err) sigs[i] = sig } - att1.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + att1.Signature = bls.AggregateSignatures(sigs).Marshal() aggBits2 := bitfield.NewBitlist(4) aggBits2.SetBitAt(1, true) @@ -305,7 +305,7 @@ func TestProcessAggregatedAttestation_OverlappingBits(t *testing.T) { require.NoError(t, err) sigs[i] = sig } - att2.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + att2.Signature = bls.AggregateSignatures(sigs).Marshal() _, err = attaggregation.AggregatePair(att1, att2) assert.ErrorContains(t, aggregation.ErrBitsOverlap.Error(), err) @@ -347,7 +347,7 @@ func TestProcessAggregatedAttestation_NoOverlappingBits(t *testing.T) { require.NoError(t, err) sigs[i] = sig } - att1.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + att1.Signature = bls.AggregateSignatures(sigs).Marshal() aggBits2 := bitfield.NewBitlist(9) aggBits2.SetBitAt(2, true) @@ -370,7 +370,7 @@ func TestProcessAggregatedAttestation_NoOverlappingBits(t *testing.T) { require.NoError(t, err) sigs[i] = sig } - att2.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + att2.Signature = bls.AggregateSignatures(sigs).Marshal() aggregatedAtt, err := attaggregation.AggregatePair(att1, att2) require.NoError(t, err) diff --git a/beacon-chain/core/blocks/attester_slashing_test.go b/beacon-chain/core/blocks/attester_slashing_test.go index dbb96c838..9fd136190 100644 --- a/beacon-chain/core/blocks/attester_slashing_test.go +++ b/beacon-chain/core/blocks/attester_slashing_test.go @@ -142,7 +142,7 @@ func TestProcessAttesterSlashings_AppliesCorrectStatus(t *testing.T) { sig0 := privKeys[0].Sign(signingRoot[:]) sig1 := privKeys[1].Sign(signingRoot[:]) aggregateSig := bls.AggregateSignatures([]bls.Signature{sig0, sig1}) - att1.Signature = aggregateSig.Marshal()[:] + att1.Signature = aggregateSig.Marshal() att2 := ðpb.IndexedAttestation{ Data: ðpb.AttestationData{ @@ -157,7 +157,7 @@ func TestProcessAttesterSlashings_AppliesCorrectStatus(t *testing.T) { sig0 = privKeys[0].Sign(signingRoot[:]) sig1 = privKeys[1].Sign(signingRoot[:]) aggregateSig = bls.AggregateSignatures([]bls.Signature{sig0, sig1}) - att2.Signature = aggregateSig.Marshal()[:] + att2.Signature = aggregateSig.Marshal() slashings := []*ethpb.AttesterSlashing{ { diff --git a/beacon-chain/core/blocks/block_regression_test.go b/beacon-chain/core/blocks/block_regression_test.go index 6f1b3d16b..75976aad6 100644 --- a/beacon-chain/core/blocks/block_regression_test.go +++ b/beacon-chain/core/blocks/block_regression_test.go @@ -56,7 +56,7 @@ func TestProcessAttesterSlashings_RegressionSlashableIndices(t *testing.T) { aggSigs = append(aggSigs, sig) } aggregateSig := bls.AggregateSignatures(aggSigs) - att1.Signature = aggregateSig.Marshal()[:] + att1.Signature = aggregateSig.Marshal() root2 := [32]byte{'d', 'o', 'u', 'b', 'l', 'e', '2'} att2 := ðpb.IndexedAttestation{ @@ -76,7 +76,7 @@ func TestProcessAttesterSlashings_RegressionSlashableIndices(t *testing.T) { aggSigs = append(aggSigs, sig) } aggregateSig = bls.AggregateSignatures(aggSigs) - att2.Signature = aggregateSig.Marshal()[:] + att2.Signature = aggregateSig.Marshal() slashings := []*ethpb.AttesterSlashing{ { diff --git a/beacon-chain/core/blocks/exit_test.go b/beacon-chain/core/blocks/exit_test.go index 4b2820ddc..001ef046b 100644 --- a/beacon-chain/core/blocks/exit_test.go +++ b/beacon-chain/core/blocks/exit_test.go @@ -174,7 +174,7 @@ func TestProcessVoluntaryExits_AppliesCorrectStatus(t *testing.T) { priv := bls.RandKey() val, err := state.ValidatorAtIndex(0) require.NoError(t, err) - val.PublicKey = priv.PublicKey().Marshal()[:] + val.PublicKey = priv.PublicKey().Marshal() require.NoError(t, state.UpdateValidatorAtIndex(0, val)) exits[0].Signature, err = helpers.ComputeDomainAndSign(state, helpers.CurrentEpoch(state), exits[0].Exit, params.BeaconConfig().DomainVoluntaryExit, priv) require.NoError(t, err) diff --git a/beacon-chain/core/blocks/randao.go b/beacon-chain/core/blocks/randao.go index 119fc75fc..b6b6d99f5 100644 --- a/beacon-chain/core/blocks/randao.go +++ b/beacon-chain/core/blocks/randao.go @@ -39,7 +39,7 @@ func ProcessRandao( if err != nil { return nil, err } - if err := verifySignature(buf, proposerPub[:], body.RandaoReveal, domain); err != nil { + if err := verifySignature(buf, proposerPub, body.RandaoReveal, domain); err != nil { return nil, errors.Wrap(err, "could not verify block randao") } diff --git a/beacon-chain/core/blocks/signature.go b/beacon-chain/core/blocks/signature.go index e84cdd9d0..69d036931 100644 --- a/beacon-chain/core/blocks/signature.go +++ b/beacon-chain/core/blocks/signature.go @@ -70,7 +70,7 @@ func VerifyBlockSignature(beaconState *stateTrie.BeaconState, block *ethpb.Signe return err } proposerPubKey := proposer.PublicKey - return helpers.VerifyBlockSigningRoot(block.Block, proposerPubKey[:], block.Signature, domain) + return helpers.VerifyBlockSigningRoot(block.Block, proposerPubKey, block.Signature, domain) } // BlockSignatureSet retrieves the block signature set from the provided block and its corresponding state. @@ -97,7 +97,7 @@ func RandaoSignatureSet(beaconState *stateTrie.BeaconState, if err != nil { return nil, nil, err } - set, err := retrieveSignatureSet(buf, proposerPub[:], body.RandaoReveal, domain) + set, err := retrieveSignatureSet(buf, proposerPub, body.RandaoReveal, domain) if err != nil { return nil, nil, err } diff --git a/beacon-chain/core/helpers/attestation_test.go b/beacon-chain/core/helpers/attestation_test.go index 6fd9c92c6..19b422c6d 100644 --- a/beacon-chain/core/helpers/attestation_test.go +++ b/beacon-chain/core/helpers/attestation_test.go @@ -89,7 +89,7 @@ func TestAttestation_AggregateSignature(t *testing.T) { for i := 0; i < 100; i++ { priv := bls.RandKey() pub := priv.PublicKey() - sig := priv.Sign(msg[:]) + sig := priv.Sign(msg) pubkeys = append(pubkeys, pub) att := ðpb.Attestation{Signature: sig.Marshal()} atts = append(atts, att) diff --git a/beacon-chain/core/state/transition_test.go b/beacon-chain/core/state/transition_test.go index b955fada6..aa7d47e8a 100644 --- a/beacon-chain/core/state/transition_test.go +++ b/beacon-chain/core/state/transition_test.go @@ -387,7 +387,7 @@ func createFullBlockWithOperations(t *testing.T) (*beaconstate.BeaconState, }, } validators := beaconState.Validators() - validators[proposerSlashIdx].PublicKey = privKeys[proposerSlashIdx].PublicKey().Marshal()[:] + validators[proposerSlashIdx].PublicKey = privKeys[proposerSlashIdx].PublicKey().Marshal() require.NoError(t, beaconState.SetValidators(validators)) mockRoot2 := [32]byte{'A'} @@ -407,7 +407,7 @@ func createFullBlockWithOperations(t *testing.T) (*beaconstate.BeaconState, sig0 := privKeys[0].Sign(hashTreeRoot[:]) sig1 := privKeys[1].Sign(hashTreeRoot[:]) aggregateSig := bls.AggregateSignatures([]bls.Signature{sig0, sig1}) - att1.Signature = aggregateSig.Marshal()[:] + att1.Signature = aggregateSig.Marshal() mockRoot3 := [32]byte{'B'} att2 := ðpb.IndexedAttestation{ @@ -425,7 +425,7 @@ func createFullBlockWithOperations(t *testing.T) (*beaconstate.BeaconState, sig0 = privKeys[0].Sign(hashTreeRoot[:]) sig1 = privKeys[1].Sign(hashTreeRoot[:]) aggregateSig = bls.AggregateSignatures([]bls.Signature{sig0, sig1}) - att2.Signature = aggregateSig.Marshal()[:] + att2.Signature = aggregateSig.Marshal() attesterSlashings := []*ethpb.AttesterSlashing{ { @@ -466,7 +466,7 @@ func createFullBlockWithOperations(t *testing.T) (*beaconstate.BeaconState, sig := privKeys[indice].Sign(hashTreeRoot[:]) sigs[i] = sig } - blockAtt.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + blockAtt.Signature = bls.AggregateSignatures(sigs).Marshal() exit := ðpb.SignedVoluntaryExit{ Exit: ðpb.VoluntaryExit{ @@ -784,7 +784,7 @@ func TestProcessBlk_AttsBasedOnValidatorCount(t *testing.T) { sig := privKeys[indice].Sign(hashTreeRoot[:]) sigs[i] = sig } - att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + att.Signature = bls.AggregateSignatures(sigs).Marshal() atts[i] = att } diff --git a/beacon-chain/db/kv/state.go b/beacon-chain/db/kv/state.go index 44e823898..3413abaa8 100644 --- a/beacon-chain/db/kv/state.go +++ b/beacon-chain/db/kv/state.go @@ -194,7 +194,7 @@ func (kv *Store) DeleteStates(ctx context.Context, blockRoots [][32]byte) error continue } // Safe guard against deleting genesis, finalized, head state. - if bytes.Equal(blockRoot[:], checkpoint.Root) || bytes.Equal(blockRoot[:], genesisBlockRoot) || bytes.Equal(blockRoot[:], headBlkRoot) { + if bytes.Equal(blockRoot, checkpoint.Root) || bytes.Equal(blockRoot, genesisBlockRoot) || bytes.Equal(blockRoot, headBlkRoot) { return errors.New("cannot delete genesis, finalized, or head state") } @@ -203,7 +203,7 @@ func (kv *Store) DeleteStates(ctx context.Context, blockRoots [][32]byte) error return err } indicesByBucket := createStateIndicesFromStateSlot(ctx, slot) - if err := deleteValueForIndices(ctx, indicesByBucket, blockRoot[:], tx); err != nil { + if err := deleteValueForIndices(ctx, indicesByBucket, blockRoot, tx); err != nil { return errors.Wrap(err, "could not delete root for DB indices") } diff --git a/beacon-chain/p2p/fork_test.go b/beacon-chain/p2p/fork_test.go index 276838928..8ae52b335 100644 --- a/beacon-chain/p2p/fork_test.go +++ b/beacon-chain/p2p/fork_test.go @@ -245,7 +245,7 @@ func TestDiscv5_AddRetrieveForkEntryENR(t *testing.T) { if !bytes.Equal(resp.CurrentForkDigest, want[:]) { t.Errorf("Wanted fork digest: %v, received %v", want, resp.CurrentForkDigest) } - if !bytes.Equal(resp.NextForkVersion[:], nextForkVersion) { + if !bytes.Equal(resp.NextForkVersion, nextForkVersion) { t.Errorf("Wanted next fork version: %v, received %v", nextForkVersion, resp.NextForkVersion) } assert.Equal(t, nextForkEpoch, resp.NextForkEpoch, "Unexpected next fork epoch") diff --git a/beacon-chain/powchain/deposit_test.go b/beacon-chain/powchain/deposit_test.go index 954026927..009af9fb5 100644 --- a/beacon-chain/powchain/deposit_test.go +++ b/beacon-chain/powchain/deposit_test.go @@ -154,7 +154,7 @@ func TestProcessDeposit_UnableToVerify(t *testing.T) { deposits, keys, err := testutil.DeterministicDepositsAndKeys(1) require.NoError(t, err) sig := keys[0].Sign([]byte{'F', 'A', 'K', 'E'}) - deposits[0].Data.Signature = sig.Marshal()[:] + deposits[0].Data.Signature = sig.Marshal() trie, _, err := testutil.DepositTrieFromDeposits(deposits) require.NoError(t, err) diff --git a/beacon-chain/rpc/validator/aggregator_test.go b/beacon-chain/rpc/validator/aggregator_test.go index c52b55e65..3dbe0f5b3 100644 --- a/beacon-chain/rpc/validator/aggregator_test.go +++ b/beacon-chain/rpc/validator/aggregator_test.go @@ -249,7 +249,7 @@ func generateAtt(state *beaconstate.BeaconState, index uint64, privKeys []bls.Se sigs[i] = sig } - att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + att.Signature = bls.AggregateSignatures(sigs).Marshal() return att, nil } @@ -290,7 +290,7 @@ func generateUnaggregatedAtt(state *beaconstate.BeaconState, index uint64, privK sigs[i] = sig } - att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + att.Signature = bls.AggregateSignatures(sigs).Marshal() return att, nil } diff --git a/beacon-chain/rpc/validator/attester.go b/beacon-chain/rpc/validator/attester.go index c2cc19ed1..5e80bb135 100644 --- a/beacon-chain/rpc/validator/attester.go +++ b/beacon-chain/rpc/validator/attester.go @@ -110,7 +110,7 @@ func (vs *Server) GetAttestationData(ctx context.Context, req *ethpb.Attestation } targetRoot := make([]byte, 32) if epochStartSlot == headState.Slot() { - targetRoot = headRoot[:] + targetRoot = headRoot } else { targetRoot, err = helpers.BlockRootAtSlot(headState, epochStartSlot) if err != nil { @@ -124,7 +124,7 @@ func (vs *Server) GetAttestationData(ctx context.Context, req *ethpb.Attestation res = ðpb.AttestationData{ Slot: req.Slot, CommitteeIndex: req.CommitteeIndex, - BeaconBlockRoot: headRoot[:], + BeaconBlockRoot: headRoot, Source: headState.CurrentJustifiedCheckpoint(), Target: ðpb.Checkpoint{ Epoch: targetEpoch, diff --git a/beacon-chain/rpc/validator/proposer.go b/beacon-chain/rpc/validator/proposer.go index 4da53196b..c2ebfe482 100644 --- a/beacon-chain/rpc/validator/proposer.go +++ b/beacon-chain/rpc/validator/proposer.go @@ -109,7 +109,7 @@ func (vs *Server) GetBlock(ctx context.Context, req *ethpb.BlockRequest) (*ethpb blk := ðpb.BeaconBlock{ Slot: req.Slot, - ParentRoot: parentRoot[:], + ParentRoot: parentRoot, StateRoot: stateRoot, ProposerIndex: idx, Body: ðpb.BeaconBlockBody{ diff --git a/beacon-chain/rpc/validator/proposer_test.go b/beacon-chain/rpc/validator/proposer_test.go index 112446a3d..f4c0ab76c 100644 --- a/beacon-chain/rpc/validator/proposer_test.go +++ b/beacon-chain/rpc/validator/proposer_test.go @@ -280,7 +280,7 @@ func TestProposer_ComputeStateRoot_OK(t *testing.T) { proposerIdx, err := helpers.BeaconProposerIndex(beaconState) require.NoError(t, err) require.NoError(t, beaconState.SetSlot(beaconState.Slot()-1)) - req.Block.Body.RandaoReveal = randaoReveal[:] + req.Block.Body.RandaoReveal = randaoReveal currentEpoch := helpers.CurrentEpoch(beaconState) req.Signature, err = helpers.ComputeDomainAndSign(beaconState, currentEpoch, req.Block, params.BeaconConfig().DomainBeaconProposer, privKeys[proposerIdx]) require.NoError(t, err) @@ -1892,7 +1892,7 @@ func TestProposer_FilterAttestation(t *testing.T) { sig := privKeys[indice].Sign(hashTreeRoot[:]) sigs[i] = sig } - atts[i].Signature = bls.AggregateSignatures(sigs).Marshal()[:] + atts[i].Signature = bls.AggregateSignatures(sigs).Marshal() } return atts }, diff --git a/beacon-chain/rpc/validator/server_test.go b/beacon-chain/rpc/validator/server_test.go index d29f47255..8f7e411fe 100644 --- a/beacon-chain/rpc/validator/server_test.go +++ b/beacon-chain/rpc/validator/server_test.go @@ -112,8 +112,8 @@ func TestWaitForActivation_ValidatorOriginallyExists(t *testing.T) { priv1 := bls.RandKey() priv2 := bls.RandKey() - pubKey1 := priv1.PublicKey().Marshal()[:] - pubKey2 := priv2.PublicKey().Marshal()[:] + pubKey1 := priv1.PublicKey().Marshal() + pubKey2 := priv2.PublicKey().Marshal() beaconState := &pbp2p.BeaconState{ Slot: 4000, @@ -138,7 +138,7 @@ func TestWaitForActivation_ValidatorOriginallyExists(t *testing.T) { require.NoError(t, err) signingRoot, err := helpers.ComputeSigningRoot(depData, domain) require.NoError(t, err) - depData.Signature = priv1.Sign(signingRoot[:]).Marshal()[:] + depData.Signature = priv1.Sign(signingRoot[:]).Marshal() deposit := ðpb.Deposit{ Data: depData, @@ -200,9 +200,9 @@ func TestWaitForActivation_MultipleStatuses(t *testing.T) { priv2 := bls.RandKey() priv3 := bls.RandKey() - pubKey1 := priv1.PublicKey().Marshal()[:] - pubKey2 := priv2.PublicKey().Marshal()[:] - pubKey3 := priv3.PublicKey().Marshal()[:] + pubKey1 := priv1.PublicKey().Marshal() + pubKey2 := priv2.PublicKey().Marshal() + pubKey3 := priv3.PublicKey().Marshal() beaconState := &pbp2p.BeaconState{ Slot: 4000, diff --git a/beacon-chain/state/cloners.go b/beacon-chain/state/cloners.go index 3ae7bf25e..df54bb34f 100644 --- a/beacon-chain/state/cloners.go +++ b/beacon-chain/state/cloners.go @@ -120,7 +120,7 @@ func CopyProposerSlashings(slashings []*ethpb.ProposerSlashing) []*ethpb.Propose for i, att := range slashings { newSlashings[i] = CopyProposerSlashing(att) } - return newSlashings[:] + return newSlashings } // CopyProposerSlashing copies the provided ProposerSlashing. @@ -156,9 +156,9 @@ func CopyBeaconBlockHeader(header *ethpb.BeaconBlockHeader) *ethpb.BeaconBlockHe return ðpb.BeaconBlockHeader{ Slot: header.Slot, ProposerIndex: header.ProposerIndex, - ParentRoot: parentRoot[:], - StateRoot: stateRoot[:], - BodyRoot: bodyRoot[:], + ParentRoot: parentRoot, + StateRoot: stateRoot, + BodyRoot: bodyRoot, } } @@ -184,10 +184,10 @@ func CopyIndexedAttestation(indexedAtt *ethpb.IndexedAttestation) *ethpb.Indexed return nil } else if indexedAtt.AttestingIndices != nil { indices = make([]uint64, len(indexedAtt.AttestingIndices)) - copy(indices[:], indexedAtt.AttestingIndices) + copy(indices, indexedAtt.AttestingIndices) } return ðpb.IndexedAttestation{ - AttestingIndices: indices[:], + AttestingIndices: indices, Data: CopyAttestationData(indexedAtt.Data), Signature: bytesutil.SafeCopyBytes(indexedAtt.Signature), } @@ -202,7 +202,7 @@ func CopyAttestations(attestations []*ethpb.Attestation) []*ethpb.Attestation { for i, att := range attestations { newAttestations[i] = CopyAttestation(att) } - return newAttestations[:] + return newAttestations } // CopyDeposits copies the provided deposit array. @@ -214,7 +214,7 @@ func CopyDeposits(deposits []*ethpb.Deposit) []*ethpb.Deposit { for i, dep := range deposits { newDeposits[i] = CopyDeposit(dep) } - return newDeposits[:] + return newDeposits } // CopyDeposit copies the provided deposit. @@ -250,7 +250,7 @@ func CopySignedVoluntaryExits(exits []*ethpb.SignedVoluntaryExit) []*ethpb.Signe for i, exit := range exits { newExits[i] = CopySignedVoluntaryExit(exit) } - return newExits[:] + return newExits } // CopySignedVoluntaryExit copies the provided SignedVoluntaryExit. @@ -274,7 +274,7 @@ func CopyValidator(val *ethpb.Validator) *ethpb.Validator { withdrawalCreds := make([]byte, len(val.WithdrawalCredentials)) copy(withdrawalCreds, val.WithdrawalCredentials) return ðpb.Validator{ - PublicKey: pubKey[:], + PublicKey: pubKey, WithdrawalCredentials: withdrawalCreds, EffectiveBalance: val.EffectiveBalance, Slashed: val.Slashed, diff --git a/beacon-chain/state/getters.go b/beacon-chain/state/getters.go index 4034be43d..d3d7ace15 100644 --- a/beacon-chain/state/getters.go +++ b/beacon-chain/state/getters.go @@ -73,7 +73,7 @@ func (v *ReadOnlyValidator) PublicKey() [48]byte { // read only validator. func (v *ReadOnlyValidator) WithdrawalCredentials() []byte { creds := make([]byte, len(v.validator.WithdrawalCredentials)) - copy(creds[:], v.validator.WithdrawalCredentials) + copy(creds, v.validator.WithdrawalCredentials) return creds } diff --git a/beacon-chain/sync/pending_attestations_queue_test.go b/beacon-chain/sync/pending_attestations_queue_test.go index 1fcd95d91..21f471e77 100644 --- a/beacon-chain/sync/pending_attestations_queue_test.go +++ b/beacon-chain/sync/pending_attestations_queue_test.go @@ -185,7 +185,7 @@ func TestProcessPendingAtts_HasBlockSaveAggregatedAtt(t *testing.T) { sig := privKeys[indice].Sign(hashTreeRoot[:]) sigs[i] = sig } - att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + att.Signature = bls.AggregateSignatures(sigs).Marshal() // Arbitrary aggregator index for testing purposes. aggregatorIndex := committee[0] diff --git a/beacon-chain/sync/validate_aggregate_proof.go b/beacon-chain/sync/validate_aggregate_proof.go index 64d691bc1..dadea06c3 100644 --- a/beacon-chain/sync/validate_aggregate_proof.go +++ b/beacon-chain/sync/validate_aggregate_proof.go @@ -132,7 +132,7 @@ func (s *Service) validateAggregatedAtt(ctx context.Context, signed *ethpb.Signe return pubsub.ValidationReject } pk := c.PubKeys[signed.Message.AggregatorIndex] - if err := helpers.VerifySigningRoot(a.Data.Slot, pk[:], signed.Message.SelectionProof, d); err != nil { + if err := helpers.VerifySigningRoot(a.Data.Slot, pk, signed.Message.SelectionProof, d); err != nil { return pubsub.ValidationReject } // Is the attestation signature correct. @@ -140,7 +140,7 @@ func (s *Service) validateAggregatedAtt(ctx context.Context, signed *ethpb.Signe if err != nil { return pubsub.ValidationReject } - if err := helpers.VerifySigningRoot(signed.Message, pk[:], signed.Signature, d); err != nil { + if err := helpers.VerifySigningRoot(signed.Message, pk, signed.Signature, d); err != nil { return pubsub.ValidationReject } if err := blocks.VerifyAttSigUseCheckPt(ctx, c, signed.Message.Aggregate); err != nil { diff --git a/beacon-chain/sync/validate_aggregate_proof_test.go b/beacon-chain/sync/validate_aggregate_proof_test.go index ffcf9d29e..397991403 100644 --- a/beacon-chain/sync/validate_aggregate_proof_test.go +++ b/beacon-chain/sync/validate_aggregate_proof_test.go @@ -372,7 +372,7 @@ func TestValidateAggregateAndProof_CanValidate(t *testing.T) { sig := privKeys[indice].Sign(hashTreeRoot[:]) sigs[i] = sig } - att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + att.Signature = bls.AggregateSignatures(sigs).Marshal() ai := committee[0] sig, err := helpers.ComputeDomainAndSign(beaconState, 0, att.Data.Slot, params.BeaconConfig().DomainSelectionProof, privKeys[ai]) require.NoError(t, err) @@ -463,7 +463,7 @@ func TestValidateAggregateAndProofUseCheckptCache_CanValidate(t *testing.T) { sig := privKeys[indice].Sign(hashTreeRoot[:]) sigs[i] = sig } - att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + att.Signature = bls.AggregateSignatures(sigs).Marshal() ai := committee[0] sig, err := helpers.ComputeDomainAndSign(beaconState, 0, att.Data.Slot, params.BeaconConfig().DomainSelectionProof, privKeys[ai]) require.NoError(t, err) @@ -550,7 +550,7 @@ func TestVerifyIndexInCommittee_SeenAggregatorEpoch(t *testing.T) { sig := privKeys[indice].Sign(hashTreeRoot[:]) sigs[i] = sig } - att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + att.Signature = bls.AggregateSignatures(sigs).Marshal() ai := committee[0] sig, err := helpers.ComputeDomainAndSign(beaconState, 0, att.Data.Slot, params.BeaconConfig().DomainSelectionProof, privKeys[ai]) require.NoError(t, err) @@ -658,7 +658,7 @@ func TestValidateAggregateAndProof_BadBlock(t *testing.T) { sig := privKeys[indice].Sign(hashTreeRoot[:]) sigs[i] = sig } - att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] + att.Signature = bls.AggregateSignatures(sigs).Marshal() ai := committee[0] sig, err := helpers.ComputeDomainAndSign(beaconState, 0, att.Data.Slot, params.BeaconConfig().DomainSelectionProof, privKeys[ai]) require.NoError(t, err) diff --git a/beacon-chain/sync/validate_attester_slashing_test.go b/beacon-chain/sync/validate_attester_slashing_test.go index cb1b25c2f..64765bfbd 100644 --- a/beacon-chain/sync/validate_attester_slashing_test.go +++ b/beacon-chain/sync/validate_attester_slashing_test.go @@ -49,7 +49,7 @@ func setupValidAttesterSlashing(t *testing.T) (*ethpb.AttesterSlashing, *stateTr sig0 := privKeys[0].Sign(hashTreeRoot[:]) sig1 := privKeys[1].Sign(hashTreeRoot[:]) aggregateSig := bls.AggregateSignatures([]bls.Signature{sig0, sig1}) - att1.Signature = aggregateSig.Marshal()[:] + att1.Signature = aggregateSig.Marshal() att2 := ðpb.IndexedAttestation{ Data: ðpb.AttestationData{ @@ -65,7 +65,7 @@ func setupValidAttesterSlashing(t *testing.T) (*ethpb.AttesterSlashing, *stateTr sig0 = privKeys[0].Sign(hashTreeRoot[:]) sig1 = privKeys[1].Sign(hashTreeRoot[:]) aggregateSig = bls.AggregateSignatures([]bls.Signature{sig0, sig1}) - att2.Signature = aggregateSig.Marshal()[:] + att2.Signature = aggregateSig.Marshal() slashing := ðpb.AttesterSlashing{ Attestation_1: att1, diff --git a/beacon-chain/sync/validate_proposer_slashing_test.go b/beacon-chain/sync/validate_proposer_slashing_test.go index 2740b2f27..a251ce209 100644 --- a/beacon-chain/sync/validate_proposer_slashing_test.go +++ b/beacon-chain/sync/validate_proposer_slashing_test.go @@ -94,7 +94,7 @@ func setupValidProposerSlashing(t *testing.T) (*ethpb.ProposerSlashing, *stateTr } val, err := state.ValidatorAtIndex(1) require.NoError(t, err) - val.PublicKey = privKey.PublicKey().Marshal()[:] + val.PublicKey = privKey.PublicKey().Marshal() require.NoError(t, state.UpdateValidatorAtIndex(1, val)) b := make([]byte, 32) diff --git a/beacon-chain/sync/validate_voluntary_exit_test.go b/beacon-chain/sync/validate_voluntary_exit_test.go index e9b176c4d..7a0d8ddb4 100644 --- a/beacon-chain/sync/validate_voluntary_exit_test.go +++ b/beacon-chain/sync/validate_voluntary_exit_test.go @@ -55,7 +55,7 @@ func setupValidExit(t *testing.T) (*ethpb.SignedVoluntaryExit, *stateTrie.Beacon val, err := state.ValidatorAtIndex(0) require.NoError(t, err) - val.PublicKey = priv.PublicKey().Marshal()[:] + val.PublicKey = priv.PublicKey().Marshal() require.NoError(t, state.UpdateValidatorAtIndex(0, val)) b := make([]byte, 32) diff --git a/contracts/deposit-contract/depositContract_test.go b/contracts/deposit-contract/depositContract_test.go index 43dbfb249..64e022f34 100644 --- a/contracts/deposit-contract/depositContract_test.go +++ b/contracts/deposit-contract/depositContract_test.go @@ -75,7 +75,7 @@ func TestValidatorRegister_OK(t *testing.T) { for i, log := range logs { _, _, _, _, idx, err := depositcontract.UnpackDepositLogData(log.Data) require.NoError(t, err, "Unable to unpack log data") - merkleTreeIndex[i] = binary.LittleEndian.Uint64(idx[:]) + merkleTreeIndex[i] = binary.LittleEndian.Uint64(idx) } assert.Equal(t, uint64(0), merkleTreeIndex[0], "Deposit event total desposit count miss matched") diff --git a/contracts/deposit-contract/testutils.go b/contracts/deposit-contract/testutils.go index 43e5b26bc..55db7d887 100644 --- a/contracts/deposit-contract/testutils.go +++ b/contracts/deposit-contract/testutils.go @@ -42,7 +42,7 @@ func Setup() (*TestAccount, error) { // strip off the 0x and the first 2 characters 04 which is always the EC prefix and is not required. publicKeyBytes := crypto.FromECDSAPub(pubKeyECDSA)[4:] var pubKey = make([]byte, 48) - copy(pubKey[:], publicKeyBytes) + copy(pubKey, publicKeyBytes) addr := crypto.PubkeyToAddress(privKey.PublicKey) txOpts := bind.NewKeyedTransactor(privKey) diff --git a/nogo_config.json b/nogo_config.json index 461447e80..9d5913a17 100644 --- a/nogo_config.json +++ b/nogo_config.json @@ -114,5 +114,12 @@ "rules_go_work-.*": "Third party code", "tools/analyzers/nop/testdata/no_op.go": "Analyzer testdata has to break rules" } + }, + "slicedirect": { + "exclude_files": { + "external/.*": "Third party code", + "rules_go_work-.*": "Third party code", + "tools/analyzers/slicedirect/testdata/slice.go": "Analyzer testdata has to break rules" + } } } diff --git a/shared/bytesutil/bytes_test.go b/shared/bytesutil/bytes_test.go index 4ea9ba2cb..9a3a3ff08 100644 --- a/shared/bytesutil/bytes_test.go +++ b/shared/bytesutil/bytes_test.go @@ -46,7 +46,7 @@ func TestToBytes(t *testing.T) { } for _, tt := range tests { b := bytesutil.ToBytes(tt.a, len(tt.b)) - assert.DeepEqual(t, tt.b, b[:]) + assert.DeepEqual(t, tt.b, b) } } @@ -64,7 +64,7 @@ func TestBytes1(t *testing.T) { } for _, tt := range tests { b := bytesutil.Bytes1(tt.a) - assert.DeepEqual(t, tt.b, b[:]) + assert.DeepEqual(t, tt.b, b) } } @@ -82,7 +82,7 @@ func TestBytes2(t *testing.T) { } for _, tt := range tests { b := bytesutil.Bytes2(tt.a) - assert.DeepEqual(t, tt.b, b[:]) + assert.DeepEqual(t, tt.b, b) } } @@ -100,7 +100,7 @@ func TestBytes3(t *testing.T) { } for _, tt := range tests { b := bytesutil.Bytes3(tt.a) - assert.DeepEqual(t, tt.b, b[:]) + assert.DeepEqual(t, tt.b, b) } } @@ -118,7 +118,7 @@ func TestBytes4(t *testing.T) { } for _, tt := range tests { b := bytesutil.Bytes4(tt.a) - assert.DeepEqual(t, tt.b, b[:]) + assert.DeepEqual(t, tt.b, b) } } @@ -136,7 +136,7 @@ func TestBytes8(t *testing.T) { } for _, tt := range tests { b := bytesutil.Bytes8(tt.a) - assert.DeepEqual(t, tt.b, b[:]) + assert.DeepEqual(t, tt.b, b) } } diff --git a/shared/depositutil/deposit_test.go b/shared/depositutil/deposit_test.go index 1e415f01c..fd5e1bebe 100644 --- a/shared/depositutil/deposit_test.go +++ b/shared/depositutil/deposit_test.go @@ -32,7 +32,7 @@ func TestDepositInput_GeneratesPb(t *testing.T) { nil, /*genesisValidatorsRoot*/ ) require.NoError(t, err) - root, err := (&pb.SigningData{ObjectRoot: sr[:], Domain: domain[:]}).HashTreeRoot() + root, err := (&pb.SigningData{ObjectRoot: sr[:], Domain: domain}).HashTreeRoot() require.NoError(t, err) assert.Equal(t, true, sig.Verify(k1.PublicKey(), root[:])) } diff --git a/shared/hashutil/merkleRoot_test.go b/shared/hashutil/merkleRoot_test.go index 13fd8cdc2..6e3662dc4 100644 --- a/shared/hashutil/merkleRoot_test.go +++ b/shared/hashutil/merkleRoot_test.go @@ -20,8 +20,8 @@ func TestMerkleRoot(t *testing.T) { hashedV3 := []byte{'c'} hashedV4 := []byte{'d'} - leftNode := hashutil.Hash(append(hashedV1[:], hashedV2[:]...)) - rightNode := hashutil.Hash(append(hashedV3[:], hashedV4[:]...)) + leftNode := hashutil.Hash(append(hashedV1, hashedV2...)) + rightNode := hashutil.Hash(append(hashedV3, hashedV4...)) expectedRoot := hashutil.Hash(append(leftNode[:], rightNode[:]...)) assert.DeepEqual(t, expectedRoot[:], hashutil.MerkleRoot(valueSet)) } diff --git a/shared/htrutils/merkleize.go b/shared/htrutils/merkleize.go index e3286c3ed..b4d28553e 100644 --- a/shared/htrutils/merkleize.go +++ b/shared/htrutils/merkleize.go @@ -113,13 +113,13 @@ func Merkleize(hasher Hasher, count uint64, limit uint64, leaf func(i uint64) [] // merge in leaf by leaf. for i := uint64(0); i < count; i++ { - copy(h[:], leaf(i)) + copy(h, leaf(i)) merge(i) } // complement with 0 if empty, or if not the right power of 2 if (uint64(1) << depth) != count { - copy(h[:], trieutil.ZeroHashes[0][:]) + copy(h, trieutil.ZeroHashes[0][:]) merge(count) } @@ -185,13 +185,13 @@ func ConstructProof(hasher Hasher, count uint64, limit uint64, leaf func(i uint6 // merge in leaf by leaf. for i := uint64(0); i < count; i++ { - copy(h[:], leaf(i)) + copy(h, leaf(i)) merge(i) } // complement with 0 if empty, or if not the right power of 2 if (uint64(1) << depth) != count { - copy(h[:], trieutil.ZeroHashes[0][:]) + copy(h, trieutil.ZeroHashes[0][:]) merge(count) } diff --git a/shared/testutil/deposits.go b/shared/testutil/deposits.go index fc4c792d4..6d2d58c40 100644 --- a/shared/testutil/deposits.go +++ b/shared/testutil/deposits.go @@ -61,7 +61,7 @@ func DeterministicDepositsAndKeys(numDeposits uint64) ([]*ethpb.Deposit, []bls.S withdrawalCreds[0] = params.BeaconConfig().BLSWithdrawalPrefixByte depositData := ðpb.Deposit_Data{ - PublicKey: publicKeys[i].Marshal()[:], + PublicKey: publicKeys[i].Marshal(), Amount: params.BeaconConfig().MaxEffectiveBalance, WithdrawalCredentials: withdrawalCreds[:], } diff --git a/shared/testutil/helpers_test.go b/shared/testutil/helpers_test.go index 4818421b1..b54ae09ba 100644 --- a/shared/testutil/helpers_test.go +++ b/shared/testutil/helpers_test.go @@ -28,8 +28,8 @@ func TestBlockSignature(t *testing.T) { signature, err := BlockSignature(beaconState, block.Block, privKeys) assert.NoError(t, err) - if !bytes.Equal(blockSig[:], signature.Marshal()) { - t.Errorf("Expected block signatures to be equal, received %#x != %#x", blockSig[:], signature.Marshal()) + if !bytes.Equal(blockSig, signature.Marshal()) { + t.Errorf("Expected block signatures to be equal, received %#x != %#x", blockSig, signature.Marshal()) } } @@ -48,7 +48,7 @@ func TestRandaoReveal(t *testing.T) { epochSignature, err := helpers.ComputeDomainAndSign(beaconState, epoch, epoch, params.BeaconConfig().DomainRandao, privKeys[proposerIdx]) require.NoError(t, err) - if !bytes.Equal(randaoReveal[:], epochSignature[:]) { - t.Errorf("Expected randao reveals to be equal, received %#x != %#x", randaoReveal[:], epochSignature[:]) + if !bytes.Equal(randaoReveal, epochSignature) { + t.Errorf("Expected randao reveals to be equal, received %#x != %#x", randaoReveal, epochSignature) } } diff --git a/slasher/db/kv/indexed_attestations.go b/slasher/db/kv/indexed_attestations.go index e8869574c..670a0bd42 100644 --- a/slasher/db/kv/indexed_attestations.go +++ b/slasher/db/kv/indexed_attestations.go @@ -51,7 +51,7 @@ func (db *Store) IndexedAttestationsWithPrefix(ctx context.Context, targetEpoch ctx, span := trace.StartSpan(ctx, "slasherDB.IndexedAttestationsWithPrefix") defer span.End() var idxAtts []*ethpb.IndexedAttestation - key := encodeEpochSig(targetEpoch, sigBytes[:]) + key := encodeEpochSig(targetEpoch, sigBytes) err := db.view(func(tx *bolt.Tx) error { c := tx.Bucket(historicIndexedAttestationsBucket).Cursor() for k, enc := c.Seek(key); k != nil && bytes.Equal(k[:len(key)], key); k, enc = c.Next() { diff --git a/slasher/rpc/server.go b/slasher/rpc/server.go index 3a6aa2da2..fb447bcaf 100644 --- a/slasher/rpc/server.go +++ b/slasher/rpc/server.go @@ -81,7 +81,7 @@ func (ss *Server) IsSlashableAttestation(ctx context.Context, req *ethpb.Indexed } pubkeys := []bls.PublicKey{} for _, pkBytes := range pkMap { - pk, err := bls.PublicKeyFromBytes(pkBytes[:]) + pk, err := bls.PublicKeyFromBytes(pkBytes) if err != nil { return nil, errors.Wrap(err, "could not deserialize validator public key") } diff --git a/tools/analyzers/slicedirect/BUILD.bazel b/tools/analyzers/slicedirect/BUILD.bazel new file mode 100644 index 000000000..2eedb0165 --- /dev/null +++ b/tools/analyzers/slicedirect/BUILD.bazel @@ -0,0 +1,28 @@ +load("@prysm//tools/go:def.bzl", "go_library") +load("@io_bazel_rules_go//go:def.bzl", "go_tool_library") + +go_library( + name = "go_default_library", + srcs = ["analyzer.go"], + importpath = "github.com/prysmaticlabs/prysm/tools/analyzers/slicedirect", + visibility = ["//visibility:public"], + deps = [ + "@org_golang_x_tools//go/analysis:go_default_library", + "@org_golang_x_tools//go/analysis/passes/inspect:go_default_library", + "@org_golang_x_tools//go/ast/inspector:go_default_library", + ], +) + +go_tool_library( + name = "go_tool_library", + srcs = ["analyzer.go"], + importpath = "github.com/prysmaticlabs/prysm/tools/analyzers/slicedirect", + visibility = ["//visibility:public"], + deps = [ + "@org_golang_x_tools//go/analysis:go_tool_library", + "@org_golang_x_tools//go/analysis/passes/inspect:go_tool_library", + "@org_golang_x_tools//go/ast/inspector:go_tool_library", + ], +) + +# gazelle:exclude analyzer_test.go diff --git a/tools/analyzers/slicedirect/analyzer.go b/tools/analyzers/slicedirect/analyzer.go new file mode 100644 index 000000000..2e81d67e8 --- /dev/null +++ b/tools/analyzers/slicedirect/analyzer.go @@ -0,0 +1,63 @@ +// Package slicedirect implements a static analyzer to ensure that code does not contain +// applications of [:] on expressions which are already slices. +package slicedirect + +import ( + "errors" + "go/ast" + "go/types" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +// Doc explaining the tool. +const Doc = "Tool to detect unnecessary slice-to-slice conversion by applying [:] to a slice expression." + +// Analyzer runs static analysis. +var Analyzer = &analysis.Analyzer{ + Name: "slicedirect", + Doc: Doc, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + Run: run, +} + +func run(pass *analysis.Pass) (interface{}, error) { + inspect, ok := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + if !ok { + return nil, errors.New("analyzer is not type *inspector.Inspector") + } + + nodeFilter := []ast.Node{ + (*ast.SliceExpr)(nil), + } + + typeInfo := types.Info{Types: make(map[ast.Expr]types.TypeAndValue)} + + inspect.Preorder(nodeFilter, func(node ast.Node) { + sliceExpr, ok := node.(*ast.SliceExpr) + if !ok { + return + } + + if err := types.CheckExpr(pass.Fset, pass.Pkg, sliceExpr.X.Pos(), sliceExpr.X, &typeInfo); err != nil { + return + } + + if sliceExpr.Low != nil || sliceExpr.High != nil { + return + } + + switch x := typeInfo.Types[sliceExpr.X].Type.(type) { + case *types.Slice: + pass.Reportf(sliceExpr.Pos(), "Expression is already a slice.") + case *types.Basic: + if x.String() == "string" { + pass.Reportf(sliceExpr.Pos(), "Expression is already a slice.") + } + } + }) + + return nil, nil +} diff --git a/tools/analyzers/slicedirect/analyzer_test.go b/tools/analyzers/slicedirect/analyzer_test.go new file mode 100644 index 000000000..072ca3751 --- /dev/null +++ b/tools/analyzers/slicedirect/analyzer_test.go @@ -0,0 +1,11 @@ +package slicedirect + +import ( + "testing" + + "golang.org/x/tools/go/analysis/analysistest" +) + +func TestAnalyzer(t *testing.T) { + analysistest.Run(t, analysistest.TestData(), Analyzer) +} diff --git a/tools/analyzers/slicedirect/testdata/BUILD.bazel b/tools/analyzers/slicedirect/testdata/BUILD.bazel new file mode 100644 index 000000000..6fa86bfa3 --- /dev/null +++ b/tools/analyzers/slicedirect/testdata/BUILD.bazel @@ -0,0 +1,8 @@ +load("@prysm//tools/go:def.bzl", "go_library") + +go_library( + name = "go_default_library", + srcs = ["slice.go"], + importpath = "github.com/prysmaticlabs/prysm/tools/analyzers/slicedirect/testdata", + visibility = ["//visibility:public"], +) diff --git a/tools/analyzers/slicedirect/testdata/slice.go b/tools/analyzers/slicedirect/testdata/slice.go new file mode 100644 index 000000000..74710ee47 --- /dev/null +++ b/tools/analyzers/slicedirect/testdata/slice.go @@ -0,0 +1,46 @@ +package testdata + +func NoIndexProvided() { + x := []byte{'f', 'o', 'o'} + y := x[:] // want "Expression is already a slice." + if len(y) == 3 { + } +} + +func StartIndexProvided_NoDiagnostic() { + x := []byte{'f', 'o', 'o'} + y := x[1:] + if len(y) == 3 { + } +} + +func EndIndexProvided_NoDiagnostic() { + x := []byte{'f', 'o', 'o'} + y := x[:2] + if len(y) == 3 { + } +} + +func BothIndicesProvided_NoDiagnostic() { + x := []byte{'f', 'o', 'o'} + y := x[1:2] + if len(y) == 3 { + } +} + +func StringSlice() { + x := "foo" + y := x[:] // want "Expression is already a slice." + if len(y) == 3 { + } +} + +func SliceFromFunction() { + x := getSlice()[:] // want "Expression is already a slice." + if len(x) == 3 { + } +} + +func getSlice() []string { + return []string{"bar"} +} diff --git a/validator/accounts/v1/account.go b/validator/accounts/v1/account.go index 68125ed2c..d5c17eee5 100644 --- a/validator/accounts/v1/account.go +++ b/validator/accounts/v1/account.go @@ -127,7 +127,7 @@ func NewValidatorAccount(directory string, password string) error { =================================================================== `, tx.Data()) fmt.Println("***Enter the above deposit data into step 3 on https://prylabs.net/participate***") - publicKey := validatorKey.PublicKey.Marshal()[:] + publicKey := validatorKey.PublicKey.Marshal() log.Infof("Public key: %#x", publicKey) return nil } diff --git a/validator/client/metrics.go b/validator/client/metrics.go index 2df33b416..77110707f 100644 --- a/validator/client/metrics.go +++ b/validator/client/metrics.go @@ -153,7 +153,7 @@ func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot uint64) if v.emitAccountMetrics { for _, missingPubKey := range resp.MissingValidators { - fmtKey := fmt.Sprintf("%#x", missingPubKey[:]) + fmtKey := fmt.Sprintf("%#x", missingPubKey) ValidatorBalancesGaugeVec.WithLabelValues(fmtKey).Set(0) } } diff --git a/validator/client/propose.go b/validator/client/propose.go index 90178be9e..50ef63780 100644 --- a/validator/client/propose.go +++ b/validator/client/propose.go @@ -282,7 +282,7 @@ func signVoluntaryExit( } sig, err := signer(ctx, &validatorpb.SignRequest{ - PublicKey: pubKey[:], + PublicKey: pubKey, SigningRoot: exitRoot[:], SignatureDomain: domain.SignatureDomain, Object: &validatorpb.SignRequest_Exit{Exit: exit}, diff --git a/validator/client/validator.go b/validator/client/validator.go index a0f285141..13affb16c 100644 --- a/validator/client/validator.go +++ b/validator/client/validator.go @@ -298,7 +298,7 @@ func (v *validator) checkAndLogValidatorStatus(validatorStatuses []*ethpb.Valida var validatorActivated bool for _, status := range validatorStatuses { fields := logrus.Fields{ - "pubKey": fmt.Sprintf("%#x", bytesutil.Trunc(status.PublicKey[:])), + "pubKey": fmt.Sprintf("%#x", bytesutil.Trunc(status.PublicKey)), "status": status.Status.Status.String(), } if status.Index != nonexistentIndex { diff --git a/validator/db/kv/new_proposal_history.go b/validator/db/kv/new_proposal_history.go index 2019adfd3..baa3ce2f3 100644 --- a/validator/db/kv/new_proposal_history.go +++ b/validator/db/kv/new_proposal_history.go @@ -30,7 +30,7 @@ func (store *Store) ProposalHistoryForSlot(ctx context.Context, publicKey []byte if sr == nil || len(sr) == 0 { return nil } - copy(signingRoot[:], sr[:]) + copy(signingRoot, sr) return nil }) return signingRoot, err