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
This commit is contained in:
Radosław Kapka 2020-09-23 18:14:34 +02:00 committed by GitHub
parent 347aa14a28
commit dca93ce641
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
48 changed files with 251 additions and 87 deletions

View File

@ -110,6 +110,7 @@ nogo(
"//tools/analyzers/comparesame:go_tool_library", "//tools/analyzers/comparesame:go_tool_library",
"//tools/analyzers/shadowpredecl:go_tool_library", "//tools/analyzers/shadowpredecl:go_tool_library",
"//tools/analyzers/nop:go_tool_library", "//tools/analyzers/nop:go_tool_library",
"//tools/analyzers/slicedirect:go_tool_library",
] + select({ ] + select({
# nogo checks that fail with coverage enabled. # nogo checks that fail with coverage enabled.
":coverage_enabled": [], ":coverage_enabled": [],

View File

@ -30,6 +30,6 @@ func logBlockSyncStatus(block *ethpb.BeaconBlock, blockRoot [32]byte, finalized
"block": fmt.Sprintf("0x%s...", hex.EncodeToString(blockRoot[:])[:8]), "block": fmt.Sprintf("0x%s...", hex.EncodeToString(blockRoot[:])[:8]),
"epoch": helpers.SlotToEpoch(block.Slot), "epoch": helpers.SlotToEpoch(block.Slot),
"finalizedEpoch": finalized.Epoch, "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") }).Info("Synced new block")
} }

View File

@ -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.SaveStateSummary(ctx, &pb.StateSummary{Slot: st.Slot(), Root: randomParentRoot[:]}))
require.NoError(t, service.beaconDB.SaveState(ctx, st.Copy(), randomParentRoot)) require.NoError(t, service.beaconDB.SaveState(ctx, st.Copy(), randomParentRoot))
randomParentRoot2 := roots[1] 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))) require.NoError(t, service.beaconDB.SaveState(ctx, st.Copy(), bytesutil.ToBytes32(randomParentRoot2)))
tests := []struct { tests := []struct {

View File

@ -238,7 +238,7 @@ func TestProcessAttestations_OK(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
sigs[i] = sig sigs[i] = sig
} }
att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] att.Signature = bls.AggregateSignatures(sigs).Marshal()
block := testutil.NewBeaconBlock() block := testutil.NewBeaconBlock()
block.Block.Body.Attestations = []*ethpb.Attestation{att} block.Block.Body.Attestations = []*ethpb.Attestation{att}
@ -282,7 +282,7 @@ func TestProcessAggregatedAttestation_OverlappingBits(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
sigs[i] = sig sigs[i] = sig
} }
att1.Signature = bls.AggregateSignatures(sigs).Marshal()[:] att1.Signature = bls.AggregateSignatures(sigs).Marshal()
aggBits2 := bitfield.NewBitlist(4) aggBits2 := bitfield.NewBitlist(4)
aggBits2.SetBitAt(1, true) aggBits2.SetBitAt(1, true)
@ -305,7 +305,7 @@ func TestProcessAggregatedAttestation_OverlappingBits(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
sigs[i] = sig sigs[i] = sig
} }
att2.Signature = bls.AggregateSignatures(sigs).Marshal()[:] att2.Signature = bls.AggregateSignatures(sigs).Marshal()
_, err = attaggregation.AggregatePair(att1, att2) _, err = attaggregation.AggregatePair(att1, att2)
assert.ErrorContains(t, aggregation.ErrBitsOverlap.Error(), err) assert.ErrorContains(t, aggregation.ErrBitsOverlap.Error(), err)
@ -347,7 +347,7 @@ func TestProcessAggregatedAttestation_NoOverlappingBits(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
sigs[i] = sig sigs[i] = sig
} }
att1.Signature = bls.AggregateSignatures(sigs).Marshal()[:] att1.Signature = bls.AggregateSignatures(sigs).Marshal()
aggBits2 := bitfield.NewBitlist(9) aggBits2 := bitfield.NewBitlist(9)
aggBits2.SetBitAt(2, true) aggBits2.SetBitAt(2, true)
@ -370,7 +370,7 @@ func TestProcessAggregatedAttestation_NoOverlappingBits(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
sigs[i] = sig sigs[i] = sig
} }
att2.Signature = bls.AggregateSignatures(sigs).Marshal()[:] att2.Signature = bls.AggregateSignatures(sigs).Marshal()
aggregatedAtt, err := attaggregation.AggregatePair(att1, att2) aggregatedAtt, err := attaggregation.AggregatePair(att1, att2)
require.NoError(t, err) require.NoError(t, err)

View File

@ -142,7 +142,7 @@ func TestProcessAttesterSlashings_AppliesCorrectStatus(t *testing.T) {
sig0 := privKeys[0].Sign(signingRoot[:]) sig0 := privKeys[0].Sign(signingRoot[:])
sig1 := privKeys[1].Sign(signingRoot[:]) sig1 := privKeys[1].Sign(signingRoot[:])
aggregateSig := bls.AggregateSignatures([]bls.Signature{sig0, sig1}) aggregateSig := bls.AggregateSignatures([]bls.Signature{sig0, sig1})
att1.Signature = aggregateSig.Marshal()[:] att1.Signature = aggregateSig.Marshal()
att2 := &ethpb.IndexedAttestation{ att2 := &ethpb.IndexedAttestation{
Data: &ethpb.AttestationData{ Data: &ethpb.AttestationData{
@ -157,7 +157,7 @@ func TestProcessAttesterSlashings_AppliesCorrectStatus(t *testing.T) {
sig0 = privKeys[0].Sign(signingRoot[:]) sig0 = privKeys[0].Sign(signingRoot[:])
sig1 = privKeys[1].Sign(signingRoot[:]) sig1 = privKeys[1].Sign(signingRoot[:])
aggregateSig = bls.AggregateSignatures([]bls.Signature{sig0, sig1}) aggregateSig = bls.AggregateSignatures([]bls.Signature{sig0, sig1})
att2.Signature = aggregateSig.Marshal()[:] att2.Signature = aggregateSig.Marshal()
slashings := []*ethpb.AttesterSlashing{ slashings := []*ethpb.AttesterSlashing{
{ {

View File

@ -56,7 +56,7 @@ func TestProcessAttesterSlashings_RegressionSlashableIndices(t *testing.T) {
aggSigs = append(aggSigs, sig) aggSigs = append(aggSigs, sig)
} }
aggregateSig := bls.AggregateSignatures(aggSigs) aggregateSig := bls.AggregateSignatures(aggSigs)
att1.Signature = aggregateSig.Marshal()[:] att1.Signature = aggregateSig.Marshal()
root2 := [32]byte{'d', 'o', 'u', 'b', 'l', 'e', '2'} root2 := [32]byte{'d', 'o', 'u', 'b', 'l', 'e', '2'}
att2 := &ethpb.IndexedAttestation{ att2 := &ethpb.IndexedAttestation{
@ -76,7 +76,7 @@ func TestProcessAttesterSlashings_RegressionSlashableIndices(t *testing.T) {
aggSigs = append(aggSigs, sig) aggSigs = append(aggSigs, sig)
} }
aggregateSig = bls.AggregateSignatures(aggSigs) aggregateSig = bls.AggregateSignatures(aggSigs)
att2.Signature = aggregateSig.Marshal()[:] att2.Signature = aggregateSig.Marshal()
slashings := []*ethpb.AttesterSlashing{ slashings := []*ethpb.AttesterSlashing{
{ {

View File

@ -174,7 +174,7 @@ func TestProcessVoluntaryExits_AppliesCorrectStatus(t *testing.T) {
priv := bls.RandKey() priv := bls.RandKey()
val, err := state.ValidatorAtIndex(0) val, err := state.ValidatorAtIndex(0)
require.NoError(t, err) require.NoError(t, err)
val.PublicKey = priv.PublicKey().Marshal()[:] val.PublicKey = priv.PublicKey().Marshal()
require.NoError(t, state.UpdateValidatorAtIndex(0, val)) require.NoError(t, state.UpdateValidatorAtIndex(0, val))
exits[0].Signature, err = helpers.ComputeDomainAndSign(state, helpers.CurrentEpoch(state), exits[0].Exit, params.BeaconConfig().DomainVoluntaryExit, priv) exits[0].Signature, err = helpers.ComputeDomainAndSign(state, helpers.CurrentEpoch(state), exits[0].Exit, params.BeaconConfig().DomainVoluntaryExit, priv)
require.NoError(t, err) require.NoError(t, err)

View File

@ -39,7 +39,7 @@ func ProcessRandao(
if err != nil { if err != nil {
return nil, err 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") return nil, errors.Wrap(err, "could not verify block randao")
} }

View File

@ -70,7 +70,7 @@ func VerifyBlockSignature(beaconState *stateTrie.BeaconState, block *ethpb.Signe
return err return err
} }
proposerPubKey := proposer.PublicKey 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. // 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 { if err != nil {
return nil, nil, err return nil, nil, err
} }
set, err := retrieveSignatureSet(buf, proposerPub[:], body.RandaoReveal, domain) set, err := retrieveSignatureSet(buf, proposerPub, body.RandaoReveal, domain)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }

View File

@ -89,7 +89,7 @@ func TestAttestation_AggregateSignature(t *testing.T) {
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
priv := bls.RandKey() priv := bls.RandKey()
pub := priv.PublicKey() pub := priv.PublicKey()
sig := priv.Sign(msg[:]) sig := priv.Sign(msg)
pubkeys = append(pubkeys, pub) pubkeys = append(pubkeys, pub)
att := &ethpb.Attestation{Signature: sig.Marshal()} att := &ethpb.Attestation{Signature: sig.Marshal()}
atts = append(atts, att) atts = append(atts, att)

View File

@ -387,7 +387,7 @@ func createFullBlockWithOperations(t *testing.T) (*beaconstate.BeaconState,
}, },
} }
validators := beaconState.Validators() validators := beaconState.Validators()
validators[proposerSlashIdx].PublicKey = privKeys[proposerSlashIdx].PublicKey().Marshal()[:] validators[proposerSlashIdx].PublicKey = privKeys[proposerSlashIdx].PublicKey().Marshal()
require.NoError(t, beaconState.SetValidators(validators)) require.NoError(t, beaconState.SetValidators(validators))
mockRoot2 := [32]byte{'A'} mockRoot2 := [32]byte{'A'}
@ -407,7 +407,7 @@ func createFullBlockWithOperations(t *testing.T) (*beaconstate.BeaconState,
sig0 := privKeys[0].Sign(hashTreeRoot[:]) sig0 := privKeys[0].Sign(hashTreeRoot[:])
sig1 := privKeys[1].Sign(hashTreeRoot[:]) sig1 := privKeys[1].Sign(hashTreeRoot[:])
aggregateSig := bls.AggregateSignatures([]bls.Signature{sig0, sig1}) aggregateSig := bls.AggregateSignatures([]bls.Signature{sig0, sig1})
att1.Signature = aggregateSig.Marshal()[:] att1.Signature = aggregateSig.Marshal()
mockRoot3 := [32]byte{'B'} mockRoot3 := [32]byte{'B'}
att2 := &ethpb.IndexedAttestation{ att2 := &ethpb.IndexedAttestation{
@ -425,7 +425,7 @@ func createFullBlockWithOperations(t *testing.T) (*beaconstate.BeaconState,
sig0 = privKeys[0].Sign(hashTreeRoot[:]) sig0 = privKeys[0].Sign(hashTreeRoot[:])
sig1 = privKeys[1].Sign(hashTreeRoot[:]) sig1 = privKeys[1].Sign(hashTreeRoot[:])
aggregateSig = bls.AggregateSignatures([]bls.Signature{sig0, sig1}) aggregateSig = bls.AggregateSignatures([]bls.Signature{sig0, sig1})
att2.Signature = aggregateSig.Marshal()[:] att2.Signature = aggregateSig.Marshal()
attesterSlashings := []*ethpb.AttesterSlashing{ attesterSlashings := []*ethpb.AttesterSlashing{
{ {
@ -466,7 +466,7 @@ func createFullBlockWithOperations(t *testing.T) (*beaconstate.BeaconState,
sig := privKeys[indice].Sign(hashTreeRoot[:]) sig := privKeys[indice].Sign(hashTreeRoot[:])
sigs[i] = sig sigs[i] = sig
} }
blockAtt.Signature = bls.AggregateSignatures(sigs).Marshal()[:] blockAtt.Signature = bls.AggregateSignatures(sigs).Marshal()
exit := &ethpb.SignedVoluntaryExit{ exit := &ethpb.SignedVoluntaryExit{
Exit: &ethpb.VoluntaryExit{ Exit: &ethpb.VoluntaryExit{
@ -784,7 +784,7 @@ func TestProcessBlk_AttsBasedOnValidatorCount(t *testing.T) {
sig := privKeys[indice].Sign(hashTreeRoot[:]) sig := privKeys[indice].Sign(hashTreeRoot[:])
sigs[i] = sig sigs[i] = sig
} }
att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] att.Signature = bls.AggregateSignatures(sigs).Marshal()
atts[i] = att atts[i] = att
} }

View File

@ -194,7 +194,7 @@ func (kv *Store) DeleteStates(ctx context.Context, blockRoots [][32]byte) error
continue continue
} }
// Safe guard against deleting genesis, finalized, head state. // 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") 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 return err
} }
indicesByBucket := createStateIndicesFromStateSlot(ctx, slot) 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") return errors.Wrap(err, "could not delete root for DB indices")
} }

View File

@ -245,7 +245,7 @@ func TestDiscv5_AddRetrieveForkEntryENR(t *testing.T) {
if !bytes.Equal(resp.CurrentForkDigest, want[:]) { if !bytes.Equal(resp.CurrentForkDigest, want[:]) {
t.Errorf("Wanted fork digest: %v, received %v", want, resp.CurrentForkDigest) 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) t.Errorf("Wanted next fork version: %v, received %v", nextForkVersion, resp.NextForkVersion)
} }
assert.Equal(t, nextForkEpoch, resp.NextForkEpoch, "Unexpected next fork epoch") assert.Equal(t, nextForkEpoch, resp.NextForkEpoch, "Unexpected next fork epoch")

View File

@ -154,7 +154,7 @@ func TestProcessDeposit_UnableToVerify(t *testing.T) {
deposits, keys, err := testutil.DeterministicDepositsAndKeys(1) deposits, keys, err := testutil.DeterministicDepositsAndKeys(1)
require.NoError(t, err) require.NoError(t, err)
sig := keys[0].Sign([]byte{'F', 'A', 'K', 'E'}) 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) trie, _, err := testutil.DepositTrieFromDeposits(deposits)
require.NoError(t, err) require.NoError(t, err)

View File

@ -249,7 +249,7 @@ func generateAtt(state *beaconstate.BeaconState, index uint64, privKeys []bls.Se
sigs[i] = sig sigs[i] = sig
} }
att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] att.Signature = bls.AggregateSignatures(sigs).Marshal()
return att, nil return att, nil
} }
@ -290,7 +290,7 @@ func generateUnaggregatedAtt(state *beaconstate.BeaconState, index uint64, privK
sigs[i] = sig sigs[i] = sig
} }
att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] att.Signature = bls.AggregateSignatures(sigs).Marshal()
return att, nil return att, nil
} }

View File

@ -110,7 +110,7 @@ func (vs *Server) GetAttestationData(ctx context.Context, req *ethpb.Attestation
} }
targetRoot := make([]byte, 32) targetRoot := make([]byte, 32)
if epochStartSlot == headState.Slot() { if epochStartSlot == headState.Slot() {
targetRoot = headRoot[:] targetRoot = headRoot
} else { } else {
targetRoot, err = helpers.BlockRootAtSlot(headState, epochStartSlot) targetRoot, err = helpers.BlockRootAtSlot(headState, epochStartSlot)
if err != nil { if err != nil {
@ -124,7 +124,7 @@ func (vs *Server) GetAttestationData(ctx context.Context, req *ethpb.Attestation
res = &ethpb.AttestationData{ res = &ethpb.AttestationData{
Slot: req.Slot, Slot: req.Slot,
CommitteeIndex: req.CommitteeIndex, CommitteeIndex: req.CommitteeIndex,
BeaconBlockRoot: headRoot[:], BeaconBlockRoot: headRoot,
Source: headState.CurrentJustifiedCheckpoint(), Source: headState.CurrentJustifiedCheckpoint(),
Target: &ethpb.Checkpoint{ Target: &ethpb.Checkpoint{
Epoch: targetEpoch, Epoch: targetEpoch,

View File

@ -109,7 +109,7 @@ func (vs *Server) GetBlock(ctx context.Context, req *ethpb.BlockRequest) (*ethpb
blk := &ethpb.BeaconBlock{ blk := &ethpb.BeaconBlock{
Slot: req.Slot, Slot: req.Slot,
ParentRoot: parentRoot[:], ParentRoot: parentRoot,
StateRoot: stateRoot, StateRoot: stateRoot,
ProposerIndex: idx, ProposerIndex: idx,
Body: &ethpb.BeaconBlockBody{ Body: &ethpb.BeaconBlockBody{

View File

@ -280,7 +280,7 @@ func TestProposer_ComputeStateRoot_OK(t *testing.T) {
proposerIdx, err := helpers.BeaconProposerIndex(beaconState) proposerIdx, err := helpers.BeaconProposerIndex(beaconState)
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, beaconState.SetSlot(beaconState.Slot()-1)) require.NoError(t, beaconState.SetSlot(beaconState.Slot()-1))
req.Block.Body.RandaoReveal = randaoReveal[:] req.Block.Body.RandaoReveal = randaoReveal
currentEpoch := helpers.CurrentEpoch(beaconState) currentEpoch := helpers.CurrentEpoch(beaconState)
req.Signature, err = helpers.ComputeDomainAndSign(beaconState, currentEpoch, req.Block, params.BeaconConfig().DomainBeaconProposer, privKeys[proposerIdx]) req.Signature, err = helpers.ComputeDomainAndSign(beaconState, currentEpoch, req.Block, params.BeaconConfig().DomainBeaconProposer, privKeys[proposerIdx])
require.NoError(t, err) require.NoError(t, err)
@ -1892,7 +1892,7 @@ func TestProposer_FilterAttestation(t *testing.T) {
sig := privKeys[indice].Sign(hashTreeRoot[:]) sig := privKeys[indice].Sign(hashTreeRoot[:])
sigs[i] = sig sigs[i] = sig
} }
atts[i].Signature = bls.AggregateSignatures(sigs).Marshal()[:] atts[i].Signature = bls.AggregateSignatures(sigs).Marshal()
} }
return atts return atts
}, },

View File

@ -112,8 +112,8 @@ func TestWaitForActivation_ValidatorOriginallyExists(t *testing.T) {
priv1 := bls.RandKey() priv1 := bls.RandKey()
priv2 := bls.RandKey() priv2 := bls.RandKey()
pubKey1 := priv1.PublicKey().Marshal()[:] pubKey1 := priv1.PublicKey().Marshal()
pubKey2 := priv2.PublicKey().Marshal()[:] pubKey2 := priv2.PublicKey().Marshal()
beaconState := &pbp2p.BeaconState{ beaconState := &pbp2p.BeaconState{
Slot: 4000, Slot: 4000,
@ -138,7 +138,7 @@ func TestWaitForActivation_ValidatorOriginallyExists(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
signingRoot, err := helpers.ComputeSigningRoot(depData, domain) signingRoot, err := helpers.ComputeSigningRoot(depData, domain)
require.NoError(t, err) require.NoError(t, err)
depData.Signature = priv1.Sign(signingRoot[:]).Marshal()[:] depData.Signature = priv1.Sign(signingRoot[:]).Marshal()
deposit := &ethpb.Deposit{ deposit := &ethpb.Deposit{
Data: depData, Data: depData,
@ -200,9 +200,9 @@ func TestWaitForActivation_MultipleStatuses(t *testing.T) {
priv2 := bls.RandKey() priv2 := bls.RandKey()
priv3 := bls.RandKey() priv3 := bls.RandKey()
pubKey1 := priv1.PublicKey().Marshal()[:] pubKey1 := priv1.PublicKey().Marshal()
pubKey2 := priv2.PublicKey().Marshal()[:] pubKey2 := priv2.PublicKey().Marshal()
pubKey3 := priv3.PublicKey().Marshal()[:] pubKey3 := priv3.PublicKey().Marshal()
beaconState := &pbp2p.BeaconState{ beaconState := &pbp2p.BeaconState{
Slot: 4000, Slot: 4000,

View File

@ -120,7 +120,7 @@ func CopyProposerSlashings(slashings []*ethpb.ProposerSlashing) []*ethpb.Propose
for i, att := range slashings { for i, att := range slashings {
newSlashings[i] = CopyProposerSlashing(att) newSlashings[i] = CopyProposerSlashing(att)
} }
return newSlashings[:] return newSlashings
} }
// CopyProposerSlashing copies the provided ProposerSlashing. // CopyProposerSlashing copies the provided ProposerSlashing.
@ -156,9 +156,9 @@ func CopyBeaconBlockHeader(header *ethpb.BeaconBlockHeader) *ethpb.BeaconBlockHe
return &ethpb.BeaconBlockHeader{ return &ethpb.BeaconBlockHeader{
Slot: header.Slot, Slot: header.Slot,
ProposerIndex: header.ProposerIndex, ProposerIndex: header.ProposerIndex,
ParentRoot: parentRoot[:], ParentRoot: parentRoot,
StateRoot: stateRoot[:], StateRoot: stateRoot,
BodyRoot: bodyRoot[:], BodyRoot: bodyRoot,
} }
} }
@ -184,10 +184,10 @@ func CopyIndexedAttestation(indexedAtt *ethpb.IndexedAttestation) *ethpb.Indexed
return nil return nil
} else if indexedAtt.AttestingIndices != nil { } else if indexedAtt.AttestingIndices != nil {
indices = make([]uint64, len(indexedAtt.AttestingIndices)) indices = make([]uint64, len(indexedAtt.AttestingIndices))
copy(indices[:], indexedAtt.AttestingIndices) copy(indices, indexedAtt.AttestingIndices)
} }
return &ethpb.IndexedAttestation{ return &ethpb.IndexedAttestation{
AttestingIndices: indices[:], AttestingIndices: indices,
Data: CopyAttestationData(indexedAtt.Data), Data: CopyAttestationData(indexedAtt.Data),
Signature: bytesutil.SafeCopyBytes(indexedAtt.Signature), Signature: bytesutil.SafeCopyBytes(indexedAtt.Signature),
} }
@ -202,7 +202,7 @@ func CopyAttestations(attestations []*ethpb.Attestation) []*ethpb.Attestation {
for i, att := range attestations { for i, att := range attestations {
newAttestations[i] = CopyAttestation(att) newAttestations[i] = CopyAttestation(att)
} }
return newAttestations[:] return newAttestations
} }
// CopyDeposits copies the provided deposit array. // CopyDeposits copies the provided deposit array.
@ -214,7 +214,7 @@ func CopyDeposits(deposits []*ethpb.Deposit) []*ethpb.Deposit {
for i, dep := range deposits { for i, dep := range deposits {
newDeposits[i] = CopyDeposit(dep) newDeposits[i] = CopyDeposit(dep)
} }
return newDeposits[:] return newDeposits
} }
// CopyDeposit copies the provided deposit. // CopyDeposit copies the provided deposit.
@ -250,7 +250,7 @@ func CopySignedVoluntaryExits(exits []*ethpb.SignedVoluntaryExit) []*ethpb.Signe
for i, exit := range exits { for i, exit := range exits {
newExits[i] = CopySignedVoluntaryExit(exit) newExits[i] = CopySignedVoluntaryExit(exit)
} }
return newExits[:] return newExits
} }
// CopySignedVoluntaryExit copies the provided SignedVoluntaryExit. // CopySignedVoluntaryExit copies the provided SignedVoluntaryExit.
@ -274,7 +274,7 @@ func CopyValidator(val *ethpb.Validator) *ethpb.Validator {
withdrawalCreds := make([]byte, len(val.WithdrawalCredentials)) withdrawalCreds := make([]byte, len(val.WithdrawalCredentials))
copy(withdrawalCreds, val.WithdrawalCredentials) copy(withdrawalCreds, val.WithdrawalCredentials)
return &ethpb.Validator{ return &ethpb.Validator{
PublicKey: pubKey[:], PublicKey: pubKey,
WithdrawalCredentials: withdrawalCreds, WithdrawalCredentials: withdrawalCreds,
EffectiveBalance: val.EffectiveBalance, EffectiveBalance: val.EffectiveBalance,
Slashed: val.Slashed, Slashed: val.Slashed,

View File

@ -73,7 +73,7 @@ func (v *ReadOnlyValidator) PublicKey() [48]byte {
// read only validator. // read only validator.
func (v *ReadOnlyValidator) WithdrawalCredentials() []byte { func (v *ReadOnlyValidator) WithdrawalCredentials() []byte {
creds := make([]byte, len(v.validator.WithdrawalCredentials)) creds := make([]byte, len(v.validator.WithdrawalCredentials))
copy(creds[:], v.validator.WithdrawalCredentials) copy(creds, v.validator.WithdrawalCredentials)
return creds return creds
} }

View File

@ -185,7 +185,7 @@ func TestProcessPendingAtts_HasBlockSaveAggregatedAtt(t *testing.T) {
sig := privKeys[indice].Sign(hashTreeRoot[:]) sig := privKeys[indice].Sign(hashTreeRoot[:])
sigs[i] = sig sigs[i] = sig
} }
att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] att.Signature = bls.AggregateSignatures(sigs).Marshal()
// Arbitrary aggregator index for testing purposes. // Arbitrary aggregator index for testing purposes.
aggregatorIndex := committee[0] aggregatorIndex := committee[0]

View File

@ -132,7 +132,7 @@ func (s *Service) validateAggregatedAtt(ctx context.Context, signed *ethpb.Signe
return pubsub.ValidationReject return pubsub.ValidationReject
} }
pk := c.PubKeys[signed.Message.AggregatorIndex] 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 return pubsub.ValidationReject
} }
// Is the attestation signature correct. // Is the attestation signature correct.
@ -140,7 +140,7 @@ func (s *Service) validateAggregatedAtt(ctx context.Context, signed *ethpb.Signe
if err != nil { if err != nil {
return pubsub.ValidationReject 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 return pubsub.ValidationReject
} }
if err := blocks.VerifyAttSigUseCheckPt(ctx, c, signed.Message.Aggregate); err != nil { if err := blocks.VerifyAttSigUseCheckPt(ctx, c, signed.Message.Aggregate); err != nil {

View File

@ -372,7 +372,7 @@ func TestValidateAggregateAndProof_CanValidate(t *testing.T) {
sig := privKeys[indice].Sign(hashTreeRoot[:]) sig := privKeys[indice].Sign(hashTreeRoot[:])
sigs[i] = sig sigs[i] = sig
} }
att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] att.Signature = bls.AggregateSignatures(sigs).Marshal()
ai := committee[0] ai := committee[0]
sig, err := helpers.ComputeDomainAndSign(beaconState, 0, att.Data.Slot, params.BeaconConfig().DomainSelectionProof, privKeys[ai]) sig, err := helpers.ComputeDomainAndSign(beaconState, 0, att.Data.Slot, params.BeaconConfig().DomainSelectionProof, privKeys[ai])
require.NoError(t, err) require.NoError(t, err)
@ -463,7 +463,7 @@ func TestValidateAggregateAndProofUseCheckptCache_CanValidate(t *testing.T) {
sig := privKeys[indice].Sign(hashTreeRoot[:]) sig := privKeys[indice].Sign(hashTreeRoot[:])
sigs[i] = sig sigs[i] = sig
} }
att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] att.Signature = bls.AggregateSignatures(sigs).Marshal()
ai := committee[0] ai := committee[0]
sig, err := helpers.ComputeDomainAndSign(beaconState, 0, att.Data.Slot, params.BeaconConfig().DomainSelectionProof, privKeys[ai]) sig, err := helpers.ComputeDomainAndSign(beaconState, 0, att.Data.Slot, params.BeaconConfig().DomainSelectionProof, privKeys[ai])
require.NoError(t, err) require.NoError(t, err)
@ -550,7 +550,7 @@ func TestVerifyIndexInCommittee_SeenAggregatorEpoch(t *testing.T) {
sig := privKeys[indice].Sign(hashTreeRoot[:]) sig := privKeys[indice].Sign(hashTreeRoot[:])
sigs[i] = sig sigs[i] = sig
} }
att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] att.Signature = bls.AggregateSignatures(sigs).Marshal()
ai := committee[0] ai := committee[0]
sig, err := helpers.ComputeDomainAndSign(beaconState, 0, att.Data.Slot, params.BeaconConfig().DomainSelectionProof, privKeys[ai]) sig, err := helpers.ComputeDomainAndSign(beaconState, 0, att.Data.Slot, params.BeaconConfig().DomainSelectionProof, privKeys[ai])
require.NoError(t, err) require.NoError(t, err)
@ -658,7 +658,7 @@ func TestValidateAggregateAndProof_BadBlock(t *testing.T) {
sig := privKeys[indice].Sign(hashTreeRoot[:]) sig := privKeys[indice].Sign(hashTreeRoot[:])
sigs[i] = sig sigs[i] = sig
} }
att.Signature = bls.AggregateSignatures(sigs).Marshal()[:] att.Signature = bls.AggregateSignatures(sigs).Marshal()
ai := committee[0] ai := committee[0]
sig, err := helpers.ComputeDomainAndSign(beaconState, 0, att.Data.Slot, params.BeaconConfig().DomainSelectionProof, privKeys[ai]) sig, err := helpers.ComputeDomainAndSign(beaconState, 0, att.Data.Slot, params.BeaconConfig().DomainSelectionProof, privKeys[ai])
require.NoError(t, err) require.NoError(t, err)

View File

@ -49,7 +49,7 @@ func setupValidAttesterSlashing(t *testing.T) (*ethpb.AttesterSlashing, *stateTr
sig0 := privKeys[0].Sign(hashTreeRoot[:]) sig0 := privKeys[0].Sign(hashTreeRoot[:])
sig1 := privKeys[1].Sign(hashTreeRoot[:]) sig1 := privKeys[1].Sign(hashTreeRoot[:])
aggregateSig := bls.AggregateSignatures([]bls.Signature{sig0, sig1}) aggregateSig := bls.AggregateSignatures([]bls.Signature{sig0, sig1})
att1.Signature = aggregateSig.Marshal()[:] att1.Signature = aggregateSig.Marshal()
att2 := &ethpb.IndexedAttestation{ att2 := &ethpb.IndexedAttestation{
Data: &ethpb.AttestationData{ Data: &ethpb.AttestationData{
@ -65,7 +65,7 @@ func setupValidAttesterSlashing(t *testing.T) (*ethpb.AttesterSlashing, *stateTr
sig0 = privKeys[0].Sign(hashTreeRoot[:]) sig0 = privKeys[0].Sign(hashTreeRoot[:])
sig1 = privKeys[1].Sign(hashTreeRoot[:]) sig1 = privKeys[1].Sign(hashTreeRoot[:])
aggregateSig = bls.AggregateSignatures([]bls.Signature{sig0, sig1}) aggregateSig = bls.AggregateSignatures([]bls.Signature{sig0, sig1})
att2.Signature = aggregateSig.Marshal()[:] att2.Signature = aggregateSig.Marshal()
slashing := &ethpb.AttesterSlashing{ slashing := &ethpb.AttesterSlashing{
Attestation_1: att1, Attestation_1: att1,

View File

@ -94,7 +94,7 @@ func setupValidProposerSlashing(t *testing.T) (*ethpb.ProposerSlashing, *stateTr
} }
val, err := state.ValidatorAtIndex(1) val, err := state.ValidatorAtIndex(1)
require.NoError(t, err) require.NoError(t, err)
val.PublicKey = privKey.PublicKey().Marshal()[:] val.PublicKey = privKey.PublicKey().Marshal()
require.NoError(t, state.UpdateValidatorAtIndex(1, val)) require.NoError(t, state.UpdateValidatorAtIndex(1, val))
b := make([]byte, 32) b := make([]byte, 32)

View File

@ -55,7 +55,7 @@ func setupValidExit(t *testing.T) (*ethpb.SignedVoluntaryExit, *stateTrie.Beacon
val, err := state.ValidatorAtIndex(0) val, err := state.ValidatorAtIndex(0)
require.NoError(t, err) require.NoError(t, err)
val.PublicKey = priv.PublicKey().Marshal()[:] val.PublicKey = priv.PublicKey().Marshal()
require.NoError(t, state.UpdateValidatorAtIndex(0, val)) require.NoError(t, state.UpdateValidatorAtIndex(0, val))
b := make([]byte, 32) b := make([]byte, 32)

View File

@ -75,7 +75,7 @@ func TestValidatorRegister_OK(t *testing.T) {
for i, log := range logs { for i, log := range logs {
_, _, _, _, idx, err := depositcontract.UnpackDepositLogData(log.Data) _, _, _, _, idx, err := depositcontract.UnpackDepositLogData(log.Data)
require.NoError(t, err, "Unable to unpack 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") assert.Equal(t, uint64(0), merkleTreeIndex[0], "Deposit event total desposit count miss matched")

View File

@ -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. // 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:] publicKeyBytes := crypto.FromECDSAPub(pubKeyECDSA)[4:]
var pubKey = make([]byte, 48) var pubKey = make([]byte, 48)
copy(pubKey[:], publicKeyBytes) copy(pubKey, publicKeyBytes)
addr := crypto.PubkeyToAddress(privKey.PublicKey) addr := crypto.PubkeyToAddress(privKey.PublicKey)
txOpts := bind.NewKeyedTransactor(privKey) txOpts := bind.NewKeyedTransactor(privKey)

View File

@ -114,5 +114,12 @@
"rules_go_work-.*": "Third party code", "rules_go_work-.*": "Third party code",
"tools/analyzers/nop/testdata/no_op.go": "Analyzer testdata has to break rules" "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"
}
} }
} }

View File

@ -46,7 +46,7 @@ func TestToBytes(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
b := bytesutil.ToBytes(tt.a, len(tt.b)) 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 { for _, tt := range tests {
b := bytesutil.Bytes1(tt.a) 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 { for _, tt := range tests {
b := bytesutil.Bytes2(tt.a) 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 { for _, tt := range tests {
b := bytesutil.Bytes3(tt.a) 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 { for _, tt := range tests {
b := bytesutil.Bytes4(tt.a) 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 { for _, tt := range tests {
b := bytesutil.Bytes8(tt.a) b := bytesutil.Bytes8(tt.a)
assert.DeepEqual(t, tt.b, b[:]) assert.DeepEqual(t, tt.b, b)
} }
} }

View File

@ -32,7 +32,7 @@ func TestDepositInput_GeneratesPb(t *testing.T) {
nil, /*genesisValidatorsRoot*/ nil, /*genesisValidatorsRoot*/
) )
require.NoError(t, err) 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) require.NoError(t, err)
assert.Equal(t, true, sig.Verify(k1.PublicKey(), root[:])) assert.Equal(t, true, sig.Verify(k1.PublicKey(), root[:]))
} }

View File

@ -20,8 +20,8 @@ func TestMerkleRoot(t *testing.T) {
hashedV3 := []byte{'c'} hashedV3 := []byte{'c'}
hashedV4 := []byte{'d'} hashedV4 := []byte{'d'}
leftNode := hashutil.Hash(append(hashedV1[:], hashedV2[:]...)) leftNode := hashutil.Hash(append(hashedV1, hashedV2...))
rightNode := hashutil.Hash(append(hashedV3[:], hashedV4[:]...)) rightNode := hashutil.Hash(append(hashedV3, hashedV4...))
expectedRoot := hashutil.Hash(append(leftNode[:], rightNode[:]...)) expectedRoot := hashutil.Hash(append(leftNode[:], rightNode[:]...))
assert.DeepEqual(t, expectedRoot[:], hashutil.MerkleRoot(valueSet)) assert.DeepEqual(t, expectedRoot[:], hashutil.MerkleRoot(valueSet))
} }

View File

@ -113,13 +113,13 @@ func Merkleize(hasher Hasher, count uint64, limit uint64, leaf func(i uint64) []
// merge in leaf by leaf. // merge in leaf by leaf.
for i := uint64(0); i < count; i++ { for i := uint64(0); i < count; i++ {
copy(h[:], leaf(i)) copy(h, leaf(i))
merge(i) merge(i)
} }
// complement with 0 if empty, or if not the right power of 2 // complement with 0 if empty, or if not the right power of 2
if (uint64(1) << depth) != count { if (uint64(1) << depth) != count {
copy(h[:], trieutil.ZeroHashes[0][:]) copy(h, trieutil.ZeroHashes[0][:])
merge(count) merge(count)
} }
@ -185,13 +185,13 @@ func ConstructProof(hasher Hasher, count uint64, limit uint64, leaf func(i uint6
// merge in leaf by leaf. // merge in leaf by leaf.
for i := uint64(0); i < count; i++ { for i := uint64(0); i < count; i++ {
copy(h[:], leaf(i)) copy(h, leaf(i))
merge(i) merge(i)
} }
// complement with 0 if empty, or if not the right power of 2 // complement with 0 if empty, or if not the right power of 2
if (uint64(1) << depth) != count { if (uint64(1) << depth) != count {
copy(h[:], trieutil.ZeroHashes[0][:]) copy(h, trieutil.ZeroHashes[0][:])
merge(count) merge(count)
} }

View File

@ -61,7 +61,7 @@ func DeterministicDepositsAndKeys(numDeposits uint64) ([]*ethpb.Deposit, []bls.S
withdrawalCreds[0] = params.BeaconConfig().BLSWithdrawalPrefixByte withdrawalCreds[0] = params.BeaconConfig().BLSWithdrawalPrefixByte
depositData := &ethpb.Deposit_Data{ depositData := &ethpb.Deposit_Data{
PublicKey: publicKeys[i].Marshal()[:], PublicKey: publicKeys[i].Marshal(),
Amount: params.BeaconConfig().MaxEffectiveBalance, Amount: params.BeaconConfig().MaxEffectiveBalance,
WithdrawalCredentials: withdrawalCreds[:], WithdrawalCredentials: withdrawalCreds[:],
} }

View File

@ -28,8 +28,8 @@ func TestBlockSignature(t *testing.T) {
signature, err := BlockSignature(beaconState, block.Block, privKeys) signature, err := BlockSignature(beaconState, block.Block, privKeys)
assert.NoError(t, err) assert.NoError(t, err)
if !bytes.Equal(blockSig[:], signature.Marshal()) { if !bytes.Equal(blockSig, signature.Marshal()) {
t.Errorf("Expected block signatures to be equal, received %#x != %#x", 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]) epochSignature, err := helpers.ComputeDomainAndSign(beaconState, epoch, epoch, params.BeaconConfig().DomainRandao, privKeys[proposerIdx])
require.NoError(t, err) require.NoError(t, err)
if !bytes.Equal(randaoReveal[:], epochSignature[:]) { if !bytes.Equal(randaoReveal, epochSignature) {
t.Errorf("Expected randao reveals to be equal, received %#x != %#x", randaoReveal[:], epochSignature[:]) t.Errorf("Expected randao reveals to be equal, received %#x != %#x", randaoReveal, epochSignature)
} }
} }

View File

@ -51,7 +51,7 @@ func (db *Store) IndexedAttestationsWithPrefix(ctx context.Context, targetEpoch
ctx, span := trace.StartSpan(ctx, "slasherDB.IndexedAttestationsWithPrefix") ctx, span := trace.StartSpan(ctx, "slasherDB.IndexedAttestationsWithPrefix")
defer span.End() defer span.End()
var idxAtts []*ethpb.IndexedAttestation var idxAtts []*ethpb.IndexedAttestation
key := encodeEpochSig(targetEpoch, sigBytes[:]) key := encodeEpochSig(targetEpoch, sigBytes)
err := db.view(func(tx *bolt.Tx) error { err := db.view(func(tx *bolt.Tx) error {
c := tx.Bucket(historicIndexedAttestationsBucket).Cursor() c := tx.Bucket(historicIndexedAttestationsBucket).Cursor()
for k, enc := c.Seek(key); k != nil && bytes.Equal(k[:len(key)], key); k, enc = c.Next() { for k, enc := c.Seek(key); k != nil && bytes.Equal(k[:len(key)], key); k, enc = c.Next() {

View File

@ -81,7 +81,7 @@ func (ss *Server) IsSlashableAttestation(ctx context.Context, req *ethpb.Indexed
} }
pubkeys := []bls.PublicKey{} pubkeys := []bls.PublicKey{}
for _, pkBytes := range pkMap { for _, pkBytes := range pkMap {
pk, err := bls.PublicKeyFromBytes(pkBytes[:]) pk, err := bls.PublicKeyFromBytes(pkBytes)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not deserialize validator public key") return nil, errors.Wrap(err, "could not deserialize validator public key")
} }

View File

@ -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

View File

@ -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
}

View File

@ -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)
}

View File

@ -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"],
)

View File

@ -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"}
}

View File

@ -127,7 +127,7 @@ func NewValidatorAccount(directory string, password string) error {
=================================================================== ===================================================================
`, tx.Data()) `, tx.Data())
fmt.Println("***Enter the above deposit data into step 3 on https://prylabs.net/participate***") 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) log.Infof("Public key: %#x", publicKey)
return nil return nil
} }

View File

@ -153,7 +153,7 @@ func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot uint64)
if v.emitAccountMetrics { if v.emitAccountMetrics {
for _, missingPubKey := range resp.MissingValidators { for _, missingPubKey := range resp.MissingValidators {
fmtKey := fmt.Sprintf("%#x", missingPubKey[:]) fmtKey := fmt.Sprintf("%#x", missingPubKey)
ValidatorBalancesGaugeVec.WithLabelValues(fmtKey).Set(0) ValidatorBalancesGaugeVec.WithLabelValues(fmtKey).Set(0)
} }
} }

View File

@ -282,7 +282,7 @@ func signVoluntaryExit(
} }
sig, err := signer(ctx, &validatorpb.SignRequest{ sig, err := signer(ctx, &validatorpb.SignRequest{
PublicKey: pubKey[:], PublicKey: pubKey,
SigningRoot: exitRoot[:], SigningRoot: exitRoot[:],
SignatureDomain: domain.SignatureDomain, SignatureDomain: domain.SignatureDomain,
Object: &validatorpb.SignRequest_Exit{Exit: exit}, Object: &validatorpb.SignRequest_Exit{Exit: exit},

View File

@ -298,7 +298,7 @@ func (v *validator) checkAndLogValidatorStatus(validatorStatuses []*ethpb.Valida
var validatorActivated bool var validatorActivated bool
for _, status := range validatorStatuses { for _, status := range validatorStatuses {
fields := logrus.Fields{ fields := logrus.Fields{
"pubKey": fmt.Sprintf("%#x", bytesutil.Trunc(status.PublicKey[:])), "pubKey": fmt.Sprintf("%#x", bytesutil.Trunc(status.PublicKey)),
"status": status.Status.Status.String(), "status": status.Status.Status.String(),
} }
if status.Index != nonexistentIndex { if status.Index != nonexistentIndex {

View File

@ -30,7 +30,7 @@ func (store *Store) ProposalHistoryForSlot(ctx context.Context, publicKey []byte
if sr == nil || len(sr) == 0 { if sr == nil || len(sr) == 0 {
return nil return nil
} }
copy(signingRoot[:], sr[:]) copy(signingRoot, sr)
return nil return nil
}) })
return signingRoot, err return signingRoot, err