Use Custom Type ValidatorIndex Across Prysm (#8478)

* Use ValidtorIndex across Prysm. Build ok

* First take at fixing tests

* Clean up e2e, fuzz... etc

* Fix new lines

* Update beacon-chain/cache/proposer_indices_test.go

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>

* Update beacon-chain/core/helpers/rewards_penalties.go

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>

* Update beacon-chain/core/helpers/shuffle.go

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>

* Update validator/graffiti/parse_graffiti_test.go

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>

* Raul's feedback

* Fix downcast int -> uint64

* Victor's feedback

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
This commit is contained in:
terence tsao
2021-02-22 16:14:50 -08:00
committed by GitHub
parent b577869ed6
commit 3edfa8cb88
120 changed files with 737 additions and 657 deletions

View File

@@ -42,7 +42,7 @@ type HeadFetcher interface {
HeadRoot(ctx context.Context) ([]byte, error) HeadRoot(ctx context.Context) ([]byte, error)
HeadBlock(ctx context.Context) (*ethpb.SignedBeaconBlock, error) HeadBlock(ctx context.Context) (*ethpb.SignedBeaconBlock, error)
HeadState(ctx context.Context) (*state.BeaconState, error) HeadState(ctx context.Context) (*state.BeaconState, error)
HeadValidatorsIndices(ctx context.Context, epoch types.Epoch) ([]uint64, error) HeadValidatorsIndices(ctx context.Context, epoch types.Epoch) ([]types.ValidatorIndex, error)
HeadSeed(ctx context.Context, epoch types.Epoch) ([32]byte, error) HeadSeed(ctx context.Context, epoch types.Epoch) ([32]byte, error)
HeadGenesisValidatorRoot() [32]byte HeadGenesisValidatorRoot() [32]byte
HeadETH1Data() *ethpb.Eth1Data HeadETH1Data() *ethpb.Eth1Data
@@ -167,12 +167,12 @@ func (s *Service) HeadState(ctx context.Context) (*state.BeaconState, error) {
} }
// HeadValidatorsIndices returns a list of active validator indices from the head view of a given epoch. // HeadValidatorsIndices returns a list of active validator indices from the head view of a given epoch.
func (s *Service) HeadValidatorsIndices(ctx context.Context, epoch types.Epoch) ([]uint64, error) { func (s *Service) HeadValidatorsIndices(ctx context.Context, epoch types.Epoch) ([]types.ValidatorIndex, error) {
s.headLock.RLock() s.headLock.RLock()
defer s.headLock.RUnlock() defer s.headLock.RUnlock()
if !s.hasHeadState() { if !s.hasHeadState() {
return []uint64{}, nil return []types.ValidatorIndex{}, nil
} }
return helpers.ActiveValidatorIndices(s.headState(ctx), epoch) return helpers.ActiveValidatorIndices(s.headState(ctx), epoch)
} }

View File

@@ -140,7 +140,7 @@ func reportEpochMetrics(ctx context.Context, postState, headState *stateTrie.Bea
slashingEffectiveBalance := uint64(0) slashingEffectiveBalance := uint64(0)
for i, validator := range postState.Validators() { for i, validator := range postState.Validators() {
bal, err := postState.BalanceAtIndex(uint64(i)) bal, err := postState.BalanceAtIndex(types.ValidatorIndex(i))
if err != nil { if err != nil {
log.Errorf("Could not load validator balance: %v", err) log.Errorf("Could not load validator balance: %v", err)
continue continue

View File

@@ -291,9 +291,9 @@ func (s *ChainService) AttestationPreState(_ context.Context, _ *ethpb.Attestati
} }
// HeadValidatorsIndices mocks the same method in the chain service. // HeadValidatorsIndices mocks the same method in the chain service.
func (s *ChainService) HeadValidatorsIndices(_ context.Context, epoch types.Epoch) ([]uint64, error) { func (s *ChainService) HeadValidatorsIndices(_ context.Context, epoch types.Epoch) ([]types.ValidatorIndex, error) {
if s.State == nil { if s.State == nil {
return []uint64{}, nil return []types.ValidatorIndex{}, nil
} }
return helpers.ActiveValidatorIndices(s.State, epoch) return helpers.ActiveValidatorIndices(s.State, epoch)
} }

View File

@@ -56,7 +56,7 @@ func NewCommitteesCache() *CommitteeCache {
// Committee fetches the shuffled indices by slot and committee index. Every list of indices // Committee fetches the shuffled indices by slot and committee index. Every list of indices
// represent one committee. Returns true if the list exists with slot and committee index. Otherwise returns false, nil. // represent one committee. Returns true if the list exists with slot and committee index. Otherwise returns false, nil.
func (c *CommitteeCache) Committee(slot types.Slot, seed [32]byte, index types.CommitteeIndex) ([]uint64, error) { func (c *CommitteeCache) Committee(slot types.Slot, seed [32]byte, index types.CommitteeIndex) ([]types.ValidatorIndex, error) {
c.lock.RLock() c.lock.RLock()
defer c.lock.RUnlock() defer c.lock.RUnlock()
@@ -106,7 +106,7 @@ func (c *CommitteeCache) AddCommitteeShuffledList(committees *Committees) error
} }
// ActiveIndices returns the active indices of a given seed stored in cache. // ActiveIndices returns the active indices of a given seed stored in cache.
func (c *CommitteeCache) ActiveIndices(seed [32]byte) ([]uint64, error) { func (c *CommitteeCache) ActiveIndices(seed [32]byte) ([]types.ValidatorIndex, error) {
c.lock.RLock() c.lock.RLock()
defer c.lock.RUnlock() defer c.lock.RUnlock()
obj, exists, err := c.CommitteeCache.GetByKey(key(seed)) obj, exists, err := c.CommitteeCache.GetByKey(key(seed))

View File

@@ -16,7 +16,7 @@ func NewCommitteesCache() *FakeCommitteeCache {
// Committee fetches the shuffled indices by slot and committee index. Every list of indices // Committee fetches the shuffled indices by slot and committee index. Every list of indices
// represent one committee. Returns true if the list exists with slot and committee index. Otherwise returns false, nil. // represent one committee. Returns true if the list exists with slot and committee index. Otherwise returns false, nil.
func (c *FakeCommitteeCache) Committee(slot types.Slot, seed [32]byte, index types.CommitteeIndex) ([]uint64, error) { func (c *FakeCommitteeCache) Committee(slot types.Slot, seed [32]byte, index types.CommitteeIndex) ([]types.ValidatorIndex, error) {
return nil, nil return nil, nil
} }
@@ -27,12 +27,12 @@ func (c *FakeCommitteeCache) AddCommitteeShuffledList(committees *Committees) er
} }
// AddProposerIndicesList updates the committee shuffled list with proposer indices. // AddProposerIndicesList updates the committee shuffled list with proposer indices.
func (c *FakeCommitteeCache) AddProposerIndicesList(seed [32]byte, indices []uint64) error { func (c *FakeCommitteeCache) AddProposerIndicesList(seed [32]byte, indices []types.ValidatorIndex) error {
return nil return nil
} }
// ActiveIndices returns the active indices of a given seed stored in cache. // ActiveIndices returns the active indices of a given seed stored in cache.
func (c *FakeCommitteeCache) ActiveIndices(seed [32]byte) ([]uint64, error) { func (c *FakeCommitteeCache) ActiveIndices(seed [32]byte) ([]types.ValidatorIndex, error) {
return nil, nil return nil, nil
} }
@@ -42,7 +42,7 @@ func (c *FakeCommitteeCache) ActiveIndicesCount(seed [32]byte) (int, error) {
} }
// ProposerIndices returns the proposer indices of a given seed. // ProposerIndices returns the proposer indices of a given seed.
func (c *FakeCommitteeCache) ProposerIndices(seed [32]byte) ([]uint64, error) { func (c *FakeCommitteeCache) ProposerIndices(seed [32]byte) ([]types.ValidatorIndex, error) {
return nil, nil return nil, nil
} }

View File

@@ -17,7 +17,7 @@ func TestCommitteeKeyFn_OK(t *testing.T) {
item := &Committees{ item := &Committees{
CommitteeCount: 1, CommitteeCount: 1,
Seed: [32]byte{'A'}, Seed: [32]byte{'A'},
ShuffledIndices: []uint64{1, 2, 3, 4, 5}, ShuffledIndices: []types.ValidatorIndex{1, 2, 3, 4, 5},
} }
k, err := committeeKeyFn(item) k, err := committeeKeyFn(item)
@@ -34,7 +34,7 @@ func TestCommitteeCache_CommitteesByEpoch(t *testing.T) {
cache := NewCommitteesCache() cache := NewCommitteesCache()
item := &Committees{ item := &Committees{
ShuffledIndices: []uint64{1, 2, 3, 4, 5, 6}, ShuffledIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6},
Seed: [32]byte{'A'}, Seed: [32]byte{'A'},
CommitteeCount: 3, CommitteeCount: 3,
} }
@@ -59,7 +59,7 @@ func TestCommitteeCache_CommitteesByEpoch(t *testing.T) {
func TestCommitteeCache_ActiveIndices(t *testing.T) { func TestCommitteeCache_ActiveIndices(t *testing.T) {
cache := NewCommitteesCache() cache := NewCommitteesCache()
item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []uint64{1, 2, 3, 4, 5, 6}} item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}}
indices, err := cache.ActiveIndices(item.Seed) indices, err := cache.ActiveIndices(item.Seed)
require.NoError(t, err) require.NoError(t, err)
if indices != nil { if indices != nil {
@@ -76,7 +76,7 @@ func TestCommitteeCache_ActiveIndices(t *testing.T) {
func TestCommitteeCache_ActiveCount(t *testing.T) { func TestCommitteeCache_ActiveCount(t *testing.T) {
cache := NewCommitteesCache() cache := NewCommitteesCache()
item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []uint64{1, 2, 3, 4, 5, 6}} item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}}
count, err := cache.ActiveIndicesCount(item.Seed) count, err := cache.ActiveIndicesCount(item.Seed)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, 0, count, "Expected active count not to exist in empty cache") assert.Equal(t, 0, count, "Expected active count not to exist in empty cache")
@@ -120,8 +120,8 @@ func TestCommitteeCacheOutOfRange(t *testing.T) {
err := cache.CommitteeCache.Add(&Committees{ err := cache.CommitteeCache.Add(&Committees{
CommitteeCount: 1, CommitteeCount: 1,
Seed: seed, Seed: seed,
ShuffledIndices: []uint64{0}, ShuffledIndices: []types.ValidatorIndex{0},
SortedIndices: []uint64{}, SortedIndices: []types.ValidatorIndex{},
}) })
require.NoError(t, err) require.NoError(t, err)

View File

@@ -1,6 +1,10 @@
package cache package cache
import "errors" import (
"errors"
types "github.com/prysmaticlabs/eth2-types"
)
// ErrNotCommittee will be returned when a cache object is not a pointer to // ErrNotCommittee will be returned when a cache object is not a pointer to
// a Committee struct. // a Committee struct.
@@ -10,6 +14,6 @@ var ErrNotCommittee = errors.New("object is not a committee struct")
type Committees struct { type Committees struct {
CommitteeCount uint64 CommitteeCount uint64
Seed [32]byte Seed [32]byte
ShuffledIndices []uint64 ShuffledIndices []types.ValidatorIndex
SortedIndices []uint64 SortedIndices []types.ValidatorIndex
} }

View File

@@ -7,6 +7,7 @@ import (
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto" "github.com/prometheus/client_golang/prometheus/promauto"
types "github.com/prysmaticlabs/eth2-types"
"k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/cache"
) )
@@ -75,7 +76,7 @@ func (c *ProposerIndicesCache) HasProposerIndices(r [32]byte) (bool, error) {
} }
// ProposerIndices returns the proposer indices of a block root seed. // ProposerIndices returns the proposer indices of a block root seed.
func (c *ProposerIndicesCache) ProposerIndices(r [32]byte) ([]uint64, error) { func (c *ProposerIndicesCache) ProposerIndices(r [32]byte) ([]types.ValidatorIndex, error) {
c.lock.RLock() c.lock.RLock()
defer c.lock.RUnlock() defer c.lock.RUnlock()
obj, exists, err := c.ProposerIndicesCache.GetByKey(key(r)) obj, exists, err := c.ProposerIndicesCache.GetByKey(key(r))

View File

@@ -3,6 +3,8 @@
// This file is used in fuzzer builds to bypass proposer indices caches. // This file is used in fuzzer builds to bypass proposer indices caches.
package cache package cache
import types "github.com/prysmaticlabs/eth2-types"
// FakeProposerIndicesCache is a struct with 1 queue for looking up proposer indices by root. // FakeProposerIndicesCache is a struct with 1 queue for looking up proposer indices by root.
type FakeProposerIndicesCache struct { type FakeProposerIndicesCache struct {
} }
@@ -19,7 +21,7 @@ func (c *FakeProposerIndicesCache) AddProposerIndices(p *ProposerIndices) error
} }
// ProposerIndices returns the proposer indices of a block root seed. // ProposerIndices returns the proposer indices of a block root seed.
func (c *FakeProposerIndicesCache) ProposerIndices(r [32]byte) ([]uint64, error) { func (c *FakeProposerIndicesCache) ProposerIndices(r [32]byte) ([]types.ValidatorIndex, error) {
return nil, nil return nil, nil
} }

View File

@@ -4,6 +4,7 @@ import (
"strconv" "strconv"
"testing" "testing"
types "github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require" "github.com/prysmaticlabs/prysm/shared/testutil/require"
@@ -12,7 +13,7 @@ import (
func TestProposerKeyFn_OK(t *testing.T) { func TestProposerKeyFn_OK(t *testing.T) {
item := &ProposerIndices{ item := &ProposerIndices{
BlockRoot: [32]byte{'A'}, BlockRoot: [32]byte{'A'},
ProposerIndices: []uint64{1, 2, 3, 4, 5}, ProposerIndices: []types.ValidatorIndex{1, 2, 3, 4, 5},
} }
k, err := proposerIndicesKeyFn(item) k, err := proposerIndicesKeyFn(item)
@@ -48,7 +49,7 @@ func TestProposerCache_AddProposerIndicesList(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, true, has) assert.Equal(t, true, has)
item := &ProposerIndices{BlockRoot: [32]byte{'B'}, ProposerIndices: []uint64{1, 2, 3, 4, 5, 6}} item := &ProposerIndices{BlockRoot: [32]byte{'B'}, ProposerIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}}
require.NoError(t, cache.AddProposerIndices(item)) require.NoError(t, cache.AddProposerIndices(item))
received, err = cache.ProposerIndices(item.BlockRoot) received, err = cache.ProposerIndices(item.BlockRoot)

View File

@@ -1,6 +1,10 @@
package cache package cache
import "errors" import (
"errors"
types "github.com/prysmaticlabs/eth2-types"
)
// ErrNotProposerIndices will be returned when a cache object is not a pointer to // ErrNotProposerIndices will be returned when a cache object is not a pointer to
// a ProposerIndices struct. // a ProposerIndices struct.
@@ -9,5 +13,5 @@ var ErrNotProposerIndices = errors.New("object is not a proposer indices struct"
// ProposerIndices defines the cached struct for proposer indices. // ProposerIndices defines the cached struct for proposer indices.
type ProposerIndices struct { type ProposerIndices struct {
BlockRoot [32]byte BlockRoot [32]byte
ProposerIndices []uint64 ProposerIndices []types.ValidatorIndex
} }

View File

@@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"github.com/pkg/errors" "github.com/pkg/errors"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
@@ -248,7 +249,7 @@ func VerifyIndexedAttestation(ctx context.Context, beaconState *stateTrie.Beacon
indices := indexedAtt.AttestingIndices indices := indexedAtt.AttestingIndices
var pubkeys []bls.PublicKey var pubkeys []bls.PublicKey
for i := 0; i < len(indices); i++ { for i := 0; i < len(indices); i++ {
pubkeyAtIdx := beaconState.PubkeyAtIndex(indices[i]) pubkeyAtIdx := beaconState.PubkeyAtIndex(types.ValidatorIndex(indices[i]))
pk, err := bls.PublicKeyFromBytes(pubkeyAtIdx[:]) pk, err := bls.PublicKeyFromBytes(pubkeyAtIdx[:])
if err != nil { if err != nil {
return errors.Wrap(err, "could not deserialize validator public key") return errors.Wrap(err, "could not deserialize validator public key")

View File

@@ -5,6 +5,7 @@ import (
"sort" "sort"
"github.com/pkg/errors" "github.com/pkg/errors"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
v "github.com/prysmaticlabs/prysm/beacon-chain/core/validators" v "github.com/prysmaticlabs/prysm/beacon-chain/core/validators"
@@ -56,12 +57,12 @@ func ProcessAttesterSlashings(
var slashedAny bool var slashedAny bool
var val stateTrie.ReadOnlyValidator var val stateTrie.ReadOnlyValidator
for _, validatorIndex := range slashableIndices { for _, validatorIndex := range slashableIndices {
val, err = beaconState.ValidatorAtIndexReadOnly(validatorIndex) val, err = beaconState.ValidatorAtIndexReadOnly(types.ValidatorIndex(validatorIndex))
if err != nil { if err != nil {
return nil, err return nil, err
} }
if helpers.IsSlashableValidator(val.ActivationEpoch(), val.WithdrawableEpoch(), val.Slashed(), currentEpoch) { if helpers.IsSlashableValidator(val.ActivationEpoch(), val.WithdrawableEpoch(), val.Slashed(), currentEpoch) {
beaconState, err = v.SlashValidator(beaconState, validatorIndex) beaconState, err = v.SlashValidator(beaconState, types.ValidatorIndex(validatorIndex))
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "could not slash validator index %d", return nil, errors.Wrapf(err, "could not slash validator index %d",
validatorIndex) validatorIndex)

View File

@@ -317,7 +317,7 @@ func TestPreGenesisDeposits_SkipInvalidDeposit(t *testing.T) {
require.Equal(t, false, ok, "bad pubkey should not exist in state") require.Equal(t, false, ok, "bad pubkey should not exist in state")
for i := 1; i < newState.NumValidators(); i++ { for i := 1; i < newState.NumValidators(); i++ {
val, err := newState.ValidatorAtIndex(uint64(i)) val, err := newState.ValidatorAtIndex(types.ValidatorIndex(i))
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, params.BeaconConfig().MaxEffectiveBalance, val.EffectiveBalance, "unequal effective balance") require.Equal(t, params.BeaconConfig().MaxEffectiveBalance, val.EffectiveBalance, "unequal effective balance")
require.Equal(t, types.Epoch(0), val.ActivationEpoch) require.Equal(t, types.Epoch(0), val.ActivationEpoch)

View File

@@ -139,7 +139,7 @@ func TestProcessProposerSlashings_AppliesCorrectStatus(t *testing.T) {
// We test the case when data is correct and verify the validator // We test the case when data is correct and verify the validator
// registry has been updated. // registry has been updated.
beaconState, privKeys := testutil.DeterministicGenesisState(t, 100) beaconState, privKeys := testutil.DeterministicGenesisState(t, 100)
proposerIdx := uint64(1) proposerIdx := types.ValidatorIndex(1)
header1 := &ethpb.SignedBeaconBlockHeader{ header1 := &ethpb.SignedBeaconBlockHeader{
Header: testutil.HydrateBeaconHeader(&ethpb.BeaconBlockHeader{ Header: testutil.HydrateBeaconHeader(&ethpb.BeaconBlockHeader{

View File

@@ -5,6 +5,7 @@ import (
"encoding/binary" "encoding/binary"
"github.com/pkg/errors" "github.com/pkg/errors"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
@@ -148,7 +149,7 @@ func createAttestationSignatureSet(ctx context.Context, beaconState *stateTrie.B
indices := ia.AttestingIndices indices := ia.AttestingIndices
pubkeys := make([][]byte, len(indices)) pubkeys := make([][]byte, len(indices))
for i := 0; i < len(indices); i++ { for i := 0; i < len(indices); i++ {
pubkeyAtIdx := beaconState.PubkeyAtIndex(indices[i]) pubkeyAtIdx := beaconState.PubkeyAtIndex(types.ValidatorIndex(indices[i]))
pubkeys[i] = pubkeyAtIdx[:] pubkeys[i] = pubkeyAtIdx[:]
} }
aggP, err := bls.AggregatePublicKeys(pubkeys) aggP, err := bls.AggregatePublicKeys(pubkeys)

View File

@@ -15,6 +15,7 @@ go_library(
"//shared/mathutil:go_default_library", "//shared/mathutil:go_default_library",
"//shared/params:go_default_library", "//shared/params:go_default_library",
"@com_github_pkg_errors//:go_default_library", "@com_github_pkg_errors//:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
], ],
) )

View File

@@ -9,6 +9,7 @@ import (
"sort" "sort"
"github.com/pkg/errors" "github.com/pkg/errors"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/core/validators" "github.com/prysmaticlabs/prysm/beacon-chain/core/validators"
@@ -22,7 +23,7 @@ import (
// sortableIndices implements the Sort interface to sort newly activated validator indices // sortableIndices implements the Sort interface to sort newly activated validator indices
// by activation epoch and by index number. // by activation epoch and by index number.
type sortableIndices struct { type sortableIndices struct {
indices []uint64 indices []types.ValidatorIndex
validators []*ethpb.Validator validators []*ethpb.Validator
} }
@@ -85,7 +86,7 @@ func ProcessRegistryUpdates(state *stateTrie.BeaconState) (*stateTrie.BeaconStat
// Process the validators for activation eligibility. // Process the validators for activation eligibility.
if helpers.IsEligibleForActivationQueue(validator) { if helpers.IsEligibleForActivationQueue(validator) {
validator.ActivationEligibilityEpoch = activationEligibilityEpoch validator.ActivationEligibilityEpoch = activationEligibilityEpoch
if err := state.UpdateValidatorAtIndex(uint64(idx), validator); err != nil { if err := state.UpdateValidatorAtIndex(types.ValidatorIndex(idx), validator); err != nil {
return nil, err return nil, err
} }
} }
@@ -94,7 +95,7 @@ func ProcessRegistryUpdates(state *stateTrie.BeaconState) (*stateTrie.BeaconStat
isActive := helpers.IsActiveValidator(validator, currentEpoch) isActive := helpers.IsActiveValidator(validator, currentEpoch)
belowEjectionBalance := validator.EffectiveBalance <= ejectionBal belowEjectionBalance := validator.EffectiveBalance <= ejectionBal
if isActive && belowEjectionBalance { if isActive && belowEjectionBalance {
state, err = validators.InitiateValidatorExit(state, uint64(idx)) state, err = validators.InitiateValidatorExit(state, types.ValidatorIndex(idx))
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "could not initiate exit for validator %d", idx) return nil, errors.Wrapf(err, "could not initiate exit for validator %d", idx)
} }
@@ -102,10 +103,10 @@ func ProcessRegistryUpdates(state *stateTrie.BeaconState) (*stateTrie.BeaconStat
} }
// Queue validators eligible for activation and not yet dequeued for activation. // Queue validators eligible for activation and not yet dequeued for activation.
var activationQ []uint64 var activationQ []types.ValidatorIndex
for idx, validator := range vals { for idx, validator := range vals {
if helpers.IsEligibleForActivation(state, validator) { if helpers.IsEligibleForActivation(state, validator) {
activationQ = append(activationQ, uint64(idx)) activationQ = append(activationQ, types.ValidatorIndex(idx))
} }
} }
@@ -180,7 +181,7 @@ func ProcessSlashings(state *stateTrie.BeaconState) (*stateTrie.BeaconState, err
if val.Slashed && correctEpoch { if val.Slashed && correctEpoch {
penaltyNumerator := val.EffectiveBalance / increment * minSlashing penaltyNumerator := val.EffectiveBalance / increment * minSlashing
penalty := penaltyNumerator / totalBalance * increment penalty := penaltyNumerator / totalBalance * increment
if err := helpers.DecreaseBalance(state, uint64(idx), penalty); err != nil { if err := helpers.DecreaseBalance(state, types.ValidatorIndex(idx), penalty); err != nil {
return false, val, err return false, val, err
} }
return true, val, nil return true, val, nil
@@ -341,8 +342,8 @@ func ProcessFinalUpdates(state *stateTrie.BeaconState) (*stateTrie.BeaconState,
// for a in attestations: // for a in attestations:
// output = output.union(get_attesting_indices(state, a.data, a.aggregation_bits)) // output = output.union(get_attesting_indices(state, a.data, a.aggregation_bits))
// return set(filter(lambda index: not state.validators[index].slashed, output)) // return set(filter(lambda index: not state.validators[index].slashed, output))
func UnslashedAttestingIndices(state *stateTrie.BeaconState, atts []*pb.PendingAttestation) ([]uint64, error) { func UnslashedAttestingIndices(state *stateTrie.BeaconState, atts []*pb.PendingAttestation) ([]types.ValidatorIndex, error) {
var setIndices []uint64 var setIndices []types.ValidatorIndex
seen := make(map[uint64]bool) seen := make(map[uint64]bool)
for _, att := range atts { for _, att := range atts {
@@ -357,7 +358,7 @@ func UnslashedAttestingIndices(state *stateTrie.BeaconState, atts []*pb.PendingA
// Create a set for attesting indices // Create a set for attesting indices
for _, index := range attestingIndices { for _, index := range attestingIndices {
if !seen[index] { if !seen[index] {
setIndices = append(setIndices, index) setIndices = append(setIndices, types.ValidatorIndex(index))
} }
seen[index] = true seen[index] = true
} }
@@ -389,7 +390,7 @@ func UnslashedAttestingIndices(state *stateTrie.BeaconState, atts []*pb.PendingA
// total_balance = get_total_active_balance(state) // total_balance = get_total_active_balance(state)
// effective_balance = state.validator_registry[index].effective_balance // effective_balance = state.validator_registry[index].effective_balance
// return effective_balance * BASE_REWARD_FACTOR // integer_squareroot(total_balance) // BASE_REWARDS_PER_EPOCH // return effective_balance * BASE_REWARD_FACTOR // integer_squareroot(total_balance) // BASE_REWARDS_PER_EPOCH
func BaseReward(state *stateTrie.BeaconState, index uint64) (uint64, error) { func BaseReward(state *stateTrie.BeaconState, index types.ValidatorIndex) (uint64, error) {
totalBalance, err := helpers.TotalActiveBalance(state) totalBalance, err := helpers.TotalActiveBalance(state)
if err != nil { if err != nil {
return 0, errors.Wrap(err, "could not calculate active balance") return 0, errors.Wrap(err, "could not calculate active balance")

View File

@@ -163,7 +163,7 @@ func ProposersDelta(state *stateTrie.BeaconState, pBal *Balance, vp []*Validator
baseRewardsPerEpoch := params.BeaconConfig().BaseRewardsPerEpoch baseRewardsPerEpoch := params.BeaconConfig().BaseRewardsPerEpoch
proposerRewardQuotient := params.BeaconConfig().ProposerRewardQuotient proposerRewardQuotient := params.BeaconConfig().ProposerRewardQuotient
for _, v := range vp { for _, v := range vp {
if v.ProposerIndex >= uint64(len(rewards)) { if uint64(v.ProposerIndex) >= uint64(len(rewards)) {
// This should never happen with a valid state / validator. // This should never happen with a valid state / validator.
return nil, errors.New("proposer index out of range") return nil, errors.New("proposer index out of range")
} }

View File

@@ -78,7 +78,7 @@ func TestAttestationDeltaPrecompute(t *testing.T) {
base.PreviousEpochAttestations = atts base.PreviousEpochAttestations = atts
beaconState, err := state.InitializeFromProto(base) beaconState, err := state.InitializeFromProto(base)
require.NoError(t, err) require.NoError(t, err)
slashedAttestedIndices := []uint64{1413} slashedAttestedIndices := []types.ValidatorIndex{1413}
for _, i := range slashedAttestedIndices { for _, i := range slashedAttestedIndices {
vs := beaconState.Validators() vs := beaconState.Validators()
vs[i].Slashed = true vs[i].Slashed = true
@@ -101,7 +101,7 @@ func TestAttestationDeltaPrecompute(t *testing.T) {
totalBalance, err := helpers.TotalActiveBalance(beaconState) totalBalance, err := helpers.TotalActiveBalance(beaconState)
require.NoError(t, err) require.NoError(t, err)
attestedIndices := []uint64{55, 1339, 1746, 1811, 1569} attestedIndices := []types.ValidatorIndex{55, 1339, 1746, 1811, 1569}
for _, i := range attestedIndices { for _, i := range attestedIndices {
base, err := epoch.BaseReward(beaconState, i) base, err := epoch.BaseReward(beaconState, i)
require.NoError(t, err, "Could not get base reward") require.NoError(t, err, "Could not get base reward")
@@ -126,7 +126,7 @@ func TestAttestationDeltaPrecompute(t *testing.T) {
assert.Equal(t, 3*base, penalties[i], "Unexpected slashed indices penalty balance") assert.Equal(t, 3*base, penalties[i], "Unexpected slashed indices penalty balance")
} }
nonAttestedIndices := []uint64{434, 677, 872, 791} nonAttestedIndices := []types.ValidatorIndex{434, 677, 872, 791}
for _, i := range nonAttestedIndices { for _, i := range nonAttestedIndices {
base, err := epoch.BaseReward(beaconState, i) base, err := epoch.BaseReward(beaconState, i)
assert.NoError(t, err, "Could not get base reward") assert.NoError(t, err, "Could not get base reward")
@@ -228,7 +228,7 @@ func TestProcessRewardsAndPenaltiesPrecompute_SlashedInactivePenalty(t *testing.
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch*10)) require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch*10))
slashedAttestedIndices := []uint64{14, 37, 68, 77, 139} slashedAttestedIndices := []types.ValidatorIndex{14, 37, 68, 77, 139}
for _, i := range slashedAttestedIndices { for _, i := range slashedAttestedIndices {
vs := beaconState.Validators() vs := beaconState.Validators()
vs[i].Slashed = true vs[i].Slashed = true
@@ -301,7 +301,7 @@ func TestProposerDeltaPrecompute_HappyCase(t *testing.T) {
beaconState, err := state.InitializeFromProto(base) beaconState, err := state.InitializeFromProto(base)
require.NoError(t, err) require.NoError(t, err)
proposerIndex := uint64(1) proposerIndex := types.ValidatorIndex(1)
b := &Balance{ActiveCurrentEpoch: 1000} b := &Balance{ActiveCurrentEpoch: 1000}
v := []*Validator{ v := []*Validator{
{IsPrevEpochAttester: true, CurrentEpochEffectiveBalance: 32, ProposerIndex: proposerIndex}, {IsPrevEpochAttester: true, CurrentEpochEffectiveBalance: 32, ProposerIndex: proposerIndex},
@@ -323,7 +323,7 @@ func TestProposerDeltaPrecompute_ValidatorIndexOutOfRange(t *testing.T) {
beaconState, err := state.InitializeFromProto(base) beaconState, err := state.InitializeFromProto(base)
require.NoError(t, err) require.NoError(t, err)
proposerIndex := validatorCount proposerIndex := types.ValidatorIndex(validatorCount)
b := &Balance{ActiveCurrentEpoch: 1000} b := &Balance{ActiveCurrentEpoch: 1000}
v := []*Validator{ v := []*Validator{
{IsPrevEpochAttester: true, CurrentEpochEffectiveBalance: 32, ProposerIndex: proposerIndex}, {IsPrevEpochAttester: true, CurrentEpochEffectiveBalance: 32, ProposerIndex: proposerIndex},
@@ -339,7 +339,7 @@ func TestProposerDeltaPrecompute_SlashedCase(t *testing.T) {
beaconState, err := state.InitializeFromProto(base) beaconState, err := state.InitializeFromProto(base)
require.NoError(t, err) require.NoError(t, err)
proposerIndex := uint64(1) proposerIndex := types.ValidatorIndex(1)
b := &Balance{ActiveCurrentEpoch: 1000} b := &Balance{ActiveCurrentEpoch: 1000}
v := []*Validator{ v := []*Validator{
{IsPrevEpochAttester: true, CurrentEpochEffectiveBalance: 32, ProposerIndex: proposerIndex, IsSlashed: true}, {IsPrevEpochAttester: true, CurrentEpochEffectiveBalance: 32, ProposerIndex: proposerIndex, IsSlashed: true},

View File

@@ -1,6 +1,7 @@
package precompute package precompute
import ( import (
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
@@ -47,7 +48,7 @@ func ProcessSlashingsPrecompute(state *stateTrie.BeaconState, pBal *Balance) err
if val.Slashed && correctEpoch { if val.Slashed && correctEpoch {
penaltyNumerator := val.EffectiveBalance / increment * minSlashing penaltyNumerator := val.EffectiveBalance / increment * minSlashing
penalty := penaltyNumerator / pBal.ActiveCurrentEpoch * increment penalty := penaltyNumerator / pBal.ActiveCurrentEpoch * increment
if err := helpers.DecreaseBalance(state, uint64(idx), penalty); err != nil { if err := helpers.DecreaseBalance(state, types.ValidatorIndex(idx), penalty); err != nil {
return false, val, err return false, val, err
} }
return true, val, nil return true, val, nil

View File

@@ -32,7 +32,7 @@ type Validator struct {
// InclusionDistance is the distance between the assigned slot and this validator's attestation was included in block. // InclusionDistance is the distance between the assigned slot and this validator's attestation was included in block.
InclusionDistance types.Slot InclusionDistance types.Slot
// ProposerIndex is the index of proposer at slot where this validator's attestation was included. // ProposerIndex is the index of proposer at slot where this validator's attestation was included.
ProposerIndex uint64 ProposerIndex types.ValidatorIndex
// BeforeEpochTransitionBalance is the validator balance prior to epoch transition. // BeforeEpochTransitionBalance is the validator balance prior to epoch transition.
BeforeEpochTransitionBalance uint64 BeforeEpochTransitionBalance uint64
// AfterEpochTransitionBalance is the validator balance after epoch transition. // AfterEpochTransitionBalance is the validator balance after epoch transition.

View File

@@ -68,7 +68,7 @@ func SlotCommitteeCount(activeValidatorCount uint64) uint64 {
// index=(slot % SLOTS_PER_EPOCH) * committees_per_slot + index, // index=(slot % SLOTS_PER_EPOCH) * committees_per_slot + index,
// count=committees_per_slot * SLOTS_PER_EPOCH, // count=committees_per_slot * SLOTS_PER_EPOCH,
// ) // )
func BeaconCommitteeFromState(state *stateTrie.BeaconState, slot types.Slot, committeeIndex types.CommitteeIndex) ([]uint64, error) { func BeaconCommitteeFromState(state *stateTrie.BeaconState, slot types.Slot, committeeIndex types.CommitteeIndex) ([]types.ValidatorIndex, error) {
epoch := SlotToEpoch(slot) epoch := SlotToEpoch(slot)
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester) seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
if err != nil { if err != nil {
@@ -94,7 +94,7 @@ func BeaconCommitteeFromState(state *stateTrie.BeaconState, slot types.Slot, com
// BeaconCommittee returns the crosslink committee of a given slot and committee index. The // BeaconCommittee returns the crosslink committee of a given slot and committee index. The
// validator indices and seed are provided as an argument rather than a imported implementation // validator indices and seed are provided as an argument rather than a imported implementation
// from the spec definition. Having them as an argument allows for cheaper computation run time. // from the spec definition. Having them as an argument allows for cheaper computation run time.
func BeaconCommittee(validatorIndices []uint64, seed [32]byte, slot types.Slot, committeeIndex types.CommitteeIndex) ([]uint64, error) { func BeaconCommittee(validatorIndices []types.ValidatorIndex, seed [32]byte, slot types.Slot, committeeIndex types.CommitteeIndex) ([]types.ValidatorIndex, error) {
indices, err := committeeCache.Committee(slot, seed, committeeIndex) indices, err := committeeCache.Committee(slot, seed, committeeIndex)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not interface with committee cache") return nil, errors.Wrap(err, "could not interface with committee cache")
@@ -126,10 +126,10 @@ func BeaconCommittee(validatorIndices []uint64, seed [32]byte, slot types.Slot,
// end = (len(indices) * (index + 1)) // count // end = (len(indices) * (index + 1)) // count
// return [indices[compute_shuffled_index(ValidatorIndex(i), len(indices), seed)] for i in range(start, end) // return [indices[compute_shuffled_index(ValidatorIndex(i), len(indices), seed)] for i in range(start, end)
func ComputeCommittee( func ComputeCommittee(
indices []uint64, indices []types.ValidatorIndex,
seed [32]byte, seed [32]byte,
index, count uint64, index, count uint64,
) ([]uint64, error) { ) ([]types.ValidatorIndex, error) {
validatorCount := uint64(len(indices)) validatorCount := uint64(len(indices))
start := sliceutil.SplitOffset(validatorCount, count, index) start := sliceutil.SplitOffset(validatorCount, count, index)
end := sliceutil.SplitOffset(validatorCount, count, index+1) end := sliceutil.SplitOffset(validatorCount, count, index+1)
@@ -139,7 +139,7 @@ func ComputeCommittee(
} }
// Save the shuffled indices in cache, this is only needed once per epoch or once per new committee index. // Save the shuffled indices in cache, this is only needed once per epoch or once per new committee index.
shuffledIndices := make([]uint64, len(indices)) shuffledIndices := make([]types.ValidatorIndex, len(indices))
copy(shuffledIndices, indices) copy(shuffledIndices, indices)
// UnshuffleList is used here as it is an optimized implementation created // UnshuffleList is used here as it is an optimized implementation created
// for fast computation of committees. // for fast computation of committees.
@@ -154,7 +154,7 @@ func ComputeCommittee(
// CommitteeAssignmentContainer represents a committee, index, and attester slot for a given epoch. // CommitteeAssignmentContainer represents a committee, index, and attester slot for a given epoch.
type CommitteeAssignmentContainer struct { type CommitteeAssignmentContainer struct {
Committee []uint64 Committee []types.ValidatorIndex
AttesterSlot types.Slot AttesterSlot types.Slot
CommitteeIndex types.CommitteeIndex CommitteeIndex types.CommitteeIndex
} }
@@ -169,7 +169,7 @@ type CommitteeAssignmentContainer struct {
func CommitteeAssignments( func CommitteeAssignments(
state *stateTrie.BeaconState, state *stateTrie.BeaconState,
epoch types.Epoch, epoch types.Epoch,
) (map[uint64]*CommitteeAssignmentContainer, map[uint64][]types.Slot, error) { ) (map[types.ValidatorIndex]*CommitteeAssignmentContainer, map[types.ValidatorIndex][]types.Slot, error) {
nextEpoch := NextEpoch(state) nextEpoch := NextEpoch(state)
if epoch > nextEpoch { if epoch > nextEpoch {
return nil, nil, fmt.Errorf( return nil, nil, fmt.Errorf(
@@ -186,7 +186,7 @@ func CommitteeAssignments(
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
proposerIndexToSlots := make(map[uint64][]types.Slot, params.BeaconConfig().SlotsPerEpoch) proposerIndexToSlots := make(map[types.ValidatorIndex][]types.Slot, params.BeaconConfig().SlotsPerEpoch)
// Proposal epochs do not have a look ahead, so we skip them over here. // Proposal epochs do not have a look ahead, so we skip them over here.
validProposalEpoch := epoch < nextEpoch validProposalEpoch := epoch < nextEpoch
for slot := startSlot; slot < startSlot+params.BeaconConfig().SlotsPerEpoch && validProposalEpoch; slot++ { for slot := startSlot; slot < startSlot+params.BeaconConfig().SlotsPerEpoch && validProposalEpoch; slot++ {
@@ -211,7 +211,7 @@ func CommitteeAssignments(
// Each slot in an epoch has a different set of committees. This value is derived from the // Each slot in an epoch has a different set of committees. This value is derived from the
// active validator set, which does not change. // active validator set, which does not change.
numCommitteesPerSlot := SlotCommitteeCount(uint64(len(activeValidatorIndices))) numCommitteesPerSlot := SlotCommitteeCount(uint64(len(activeValidatorIndices)))
validatorIndexToCommittee := make(map[uint64]*CommitteeAssignmentContainer, params.BeaconConfig().SlotsPerEpoch.Mul(numCommitteesPerSlot)) validatorIndexToCommittee := make(map[types.ValidatorIndex]*CommitteeAssignmentContainer, params.BeaconConfig().SlotsPerEpoch.Mul(numCommitteesPerSlot))
// Compute all committees for all slots. // Compute all committees for all slots.
for i := types.Slot(0); i < params.BeaconConfig().SlotsPerEpoch; i++ { for i := types.Slot(0); i < params.BeaconConfig().SlotsPerEpoch; i++ {
@@ -268,16 +268,16 @@ func VerifyAttestationBitfieldLengths(state *stateTrie.BeaconState, att *ethpb.A
// ShuffledIndices uses input beacon state and returns the shuffled indices of the input epoch, // ShuffledIndices uses input beacon state and returns the shuffled indices of the input epoch,
// the shuffled indices then can be used to break up into committees. // the shuffled indices then can be used to break up into committees.
func ShuffledIndices(state *stateTrie.BeaconState, epoch types.Epoch) ([]uint64, error) { func ShuffledIndices(state *stateTrie.BeaconState, epoch types.Epoch) ([]types.ValidatorIndex, error) {
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester) seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "could not get seed for epoch %d", epoch) return nil, errors.Wrapf(err, "could not get seed for epoch %d", epoch)
} }
indices := make([]uint64, 0, state.NumValidators()) indices := make([]types.ValidatorIndex, 0, state.NumValidators())
if err := state.ReadFromEveryValidator(func(idx int, val stateTrie.ReadOnlyValidator) error { if err := state.ReadFromEveryValidator(func(idx int, val stateTrie.ReadOnlyValidator) error {
if IsActiveValidatorUsingTrie(val, epoch) { if IsActiveValidatorUsingTrie(val, epoch) {
indices = append(indices, uint64(idx)) indices = append(indices, types.ValidatorIndex(idx))
} }
return nil return nil
}); err != nil { }); err != nil {
@@ -311,7 +311,7 @@ func UpdateCommitteeCache(state *stateTrie.BeaconState, epoch types.Epoch) error
// Store the sorted indices as well as shuffled indices. In current spec, // Store the sorted indices as well as shuffled indices. In current spec,
// sorted indices is required to retrieve proposer index. This is also // sorted indices is required to retrieve proposer index. This is also
// used for failing verify signature fallback. // used for failing verify signature fallback.
sortedIndices := make([]uint64, len(shuffledIndices)) sortedIndices := make([]types.ValidatorIndex, len(shuffledIndices))
copy(sortedIndices, shuffledIndices) copy(sortedIndices, shuffledIndices)
sort.Slice(sortedIndices, func(i, j int) bool { sort.Slice(sortedIndices, func(i, j int) bool {
return sortedIndices[i] < sortedIndices[j] return sortedIndices[i] < sortedIndices[j]
@@ -386,9 +386,9 @@ func ClearCache() {
// This computes proposer indices of the current epoch and returns a list of proposer indices, // This computes proposer indices of the current epoch and returns a list of proposer indices,
// the index of the list represents the slot number. // the index of the list represents the slot number.
func precomputeProposerIndices(state *stateTrie.BeaconState, activeIndices []uint64) ([]uint64, error) { func precomputeProposerIndices(state *stateTrie.BeaconState, activeIndices []types.ValidatorIndex) ([]types.ValidatorIndex, error) {
hashFunc := hashutil.CustomSHA256Hasher() hashFunc := hashutil.CustomSHA256Hasher()
proposerIndices := make([]uint64, params.BeaconConfig().SlotsPerEpoch) proposerIndices := make([]types.ValidatorIndex, params.BeaconConfig().SlotsPerEpoch)
e := CurrentEpoch(state) e := CurrentEpoch(state)
seed, err := Seed(state, e, params.BeaconConfig().DomainBeaconProposer) seed, err := Seed(state, e, params.BeaconConfig().DomainBeaconProposer)

View File

@@ -70,7 +70,7 @@ func TestComputeCommittee_WithoutCache(t *testing.T) {
} }
func TestComputeCommittee_RegressionTest(t *testing.T) { func TestComputeCommittee_RegressionTest(t *testing.T) {
indices := []uint64{1, 3, 8, 16, 18, 19, 20, 23, 30, 35, 43, 46, 47, 54, 56, 58, 69, 70, 71, 83, 84, 85, 91, 96, 100, 103, 105, 106, 112, 121, 127, 128, 129, 140, 142, 144, 146, 147, 149, 152, 153, 154, 157, 160, 173, 175, 180, 182, 188, 189, 191, 194, 201, 204, 217, 221, 226, 228, 230, 231, 239, 241, 249, 250, 255} indices := []types.ValidatorIndex{1, 3, 8, 16, 18, 19, 20, 23, 30, 35, 43, 46, 47, 54, 56, 58, 69, 70, 71, 83, 84, 85, 91, 96, 100, 103, 105, 106, 112, 121, 127, 128, 129, 140, 142, 144, 146, 147, 149, 152, 153, 154, 157, 160, 173, 175, 180, 182, 188, 189, 191, 194, 201, 204, 217, 221, 226, 228, 230, 231, 239, 241, 249, 250, 255}
seed := [32]byte{68, 110, 161, 250, 98, 230, 161, 172, 227, 226, 99, 11, 138, 124, 201, 134, 38, 197, 0, 120, 6, 165, 122, 34, 19, 216, 43, 226, 210, 114, 165, 183} seed := [32]byte{68, 110, 161, 250, 98, 230, 161, 172, 227, 226, 99, 11, 138, 124, 201, 134, 38, 197, 0, 120, 6, 165, 122, 34, 19, 216, 43, 226, 210, 114, 165, 183}
index := uint64(215) index := uint64(215)
count := uint64(32) count := uint64(32)
@@ -150,9 +150,9 @@ func TestCommitteeAssignments_CanRetrieve(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
tests := []struct { tests := []struct {
index uint64 index types.ValidatorIndex
slot types.Slot slot types.Slot
committee []uint64 committee []types.ValidatorIndex
committeeIndex types.CommitteeIndex committeeIndex types.CommitteeIndex
isProposer bool isProposer bool
proposerSlot types.Slot proposerSlot types.Slot
@@ -160,14 +160,14 @@ func TestCommitteeAssignments_CanRetrieve(t *testing.T) {
{ {
index: 0, index: 0,
slot: 78, slot: 78,
committee: []uint64{0, 38}, committee: []types.ValidatorIndex{0, 38},
committeeIndex: 0, committeeIndex: 0,
isProposer: false, isProposer: false,
}, },
{ {
index: 1, index: 1,
slot: 71, slot: 71,
committee: []uint64{1, 4}, committee: []types.ValidatorIndex{1, 4},
committeeIndex: 0, committeeIndex: 0,
isProposer: true, isProposer: true,
proposerSlot: 79, proposerSlot: 79,
@@ -175,13 +175,13 @@ func TestCommitteeAssignments_CanRetrieve(t *testing.T) {
{ {
index: 11, index: 11,
slot: 90, slot: 90,
committee: []uint64{31, 11}, committee: []types.ValidatorIndex{31, 11},
committeeIndex: 0, committeeIndex: 0,
isProposer: false, isProposer: false,
}, { }, {
index: 2, index: 2,
slot: 127, // 3rd epoch has more active validators slot: 127, // 3rd epoch has more active validators
committee: []uint64{89, 2, 81, 5}, committee: []types.ValidatorIndex{89, 2, 81, 5},
committeeIndex: 0, committeeIndex: 0,
isProposer: false, isProposer: false,
}, },
@@ -404,8 +404,8 @@ func TestUpdateCommitteeCache_CanUpdate(t *testing.T) {
ClearCache() ClearCache()
validatorCount := params.BeaconConfig().MinGenesisActiveValidatorCount validatorCount := params.BeaconConfig().MinGenesisActiveValidatorCount
validators := make([]*ethpb.Validator, validatorCount) validators := make([]*ethpb.Validator, validatorCount)
indices := make([]uint64, validatorCount) indices := make([]types.ValidatorIndex, validatorCount)
for i := uint64(0); i < validatorCount; i++ { for i := types.ValidatorIndex(0); uint64(i) < validatorCount; i++ {
validators[i] = &ethpb.Validator{ validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch, ExitEpoch: params.BeaconConfig().FarFutureEpoch,
} }
@@ -647,7 +647,7 @@ func TestPrecomputeProposerIndices_Ok(t *testing.T) {
proposerIndices, err := precomputeProposerIndices(state, indices) proposerIndices, err := precomputeProposerIndices(state, indices)
require.NoError(t, err) require.NoError(t, err)
var wantedProposerIndices []uint64 var wantedProposerIndices []types.ValidatorIndex
seed, err := Seed(state, 0, params.BeaconConfig().DomainBeaconProposer) seed, err := Seed(state, 0, params.BeaconConfig().DomainBeaconProposer)
require.NoError(t, err) require.NoError(t, err)
for i := uint64(0); i < uint64(params.BeaconConfig().SlotsPerEpoch); i++ { for i := uint64(0); i < uint64(params.BeaconConfig().SlotsPerEpoch); i++ {

View File

@@ -1,6 +1,7 @@
package helpers package helpers
import ( import (
types "github.com/prysmaticlabs/eth2-types"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
) )
@@ -15,7 +16,7 @@ import (
// ``EFFECTIVE_BALANCE_INCREMENT`` Gwei minimum to avoid divisions by zero. // ``EFFECTIVE_BALANCE_INCREMENT`` Gwei minimum to avoid divisions by zero.
// """ // """
// return Gwei(max(EFFECTIVE_BALANCE_INCREMENT, sum([state.validators[index].effective_balance for index in indices]))) // return Gwei(max(EFFECTIVE_BALANCE_INCREMENT, sum([state.validators[index].effective_balance for index in indices])))
func TotalBalance(state *stateTrie.BeaconState, indices []uint64) uint64 { func TotalBalance(state *stateTrie.BeaconState, indices []types.ValidatorIndex) uint64 {
total := uint64(0) total := uint64(0)
for _, idx := range indices { for _, idx := range indices {
@@ -64,7 +65,7 @@ func TotalActiveBalance(state *stateTrie.BeaconState) (uint64, error) {
// Increase the validator balance at index ``index`` by ``delta``. // Increase the validator balance at index ``index`` by ``delta``.
// """ // """
// state.balances[index] += delta // state.balances[index] += delta
func IncreaseBalance(state *stateTrie.BeaconState, idx, delta uint64) error { func IncreaseBalance(state *stateTrie.BeaconState, idx types.ValidatorIndex, delta uint64) error {
balAtIdx, err := state.BalanceAtIndex(idx) balAtIdx, err := state.BalanceAtIndex(idx)
if err != nil { if err != nil {
return err return err
@@ -94,7 +95,7 @@ func IncreaseBalanceWithVal(currBalance, delta uint64) uint64 {
// Decrease the validator balance at index ``index`` by ``delta``, with underflow protection. // Decrease the validator balance at index ``index`` by ``delta``, with underflow protection.
// """ // """
// state.balances[index] = 0 if delta > state.balances[index] else state.balances[index] - delta // state.balances[index] = 0 if delta > state.balances[index] else state.balances[index] - delta
func DecreaseBalance(state *stateTrie.BeaconState, idx, delta uint64) error { func DecreaseBalance(state *stateTrie.BeaconState, idx types.ValidatorIndex, delta uint64) error {
balAtIdx, err := state.BalanceAtIndex(idx) balAtIdx, err := state.BalanceAtIndex(idx)
if err != nil { if err != nil {
return err return err

View File

@@ -3,6 +3,7 @@ package helpers
import ( import (
"testing" "testing"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state" beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
@@ -18,7 +19,7 @@ func TestTotalBalance_OK(t *testing.T) {
}}) }})
require.NoError(t, err) require.NoError(t, err)
balance := TotalBalance(state, []uint64{0, 1, 2, 3}) balance := TotalBalance(state, []types.ValidatorIndex{0, 1, 2, 3})
wanted := state.Validators()[0].EffectiveBalance + state.Validators()[1].EffectiveBalance + wanted := state.Validators()[0].EffectiveBalance + state.Validators()[1].EffectiveBalance +
state.Validators()[2].EffectiveBalance + state.Validators()[3].EffectiveBalance state.Validators()[2].EffectiveBalance + state.Validators()[3].EffectiveBalance
assert.Equal(t, wanted, balance, "Incorrect TotalBalance") assert.Equal(t, wanted, balance, "Incorrect TotalBalance")
@@ -28,7 +29,7 @@ func TestTotalBalance_ReturnsEffectiveBalanceIncrement(t *testing.T) {
state, err := beaconstate.InitializeFromProto(&pb.BeaconState{Validators: []*ethpb.Validator{}}) state, err := beaconstate.InitializeFromProto(&pb.BeaconState{Validators: []*ethpb.Validator{}})
require.NoError(t, err) require.NoError(t, err)
balance := TotalBalance(state, []uint64{}) balance := TotalBalance(state, []types.ValidatorIndex{})
wanted := params.BeaconConfig().EffectiveBalanceIncrement wanted := params.BeaconConfig().EffectiveBalanceIncrement
assert.Equal(t, wanted, balance, "Incorrect TotalBalance") assert.Equal(t, wanted, balance, "Incorrect TotalBalance")
} }
@@ -81,7 +82,7 @@ func TestGetBalance_OK(t *testing.T) {
func TestIncreaseBalance_OK(t *testing.T) { func TestIncreaseBalance_OK(t *testing.T) {
tests := []struct { tests := []struct {
i uint64 i types.ValidatorIndex
b []uint64 b []uint64
nb uint64 nb uint64
eb uint64 eb uint64
@@ -104,7 +105,7 @@ func TestIncreaseBalance_OK(t *testing.T) {
func TestDecreaseBalance_OK(t *testing.T) { func TestDecreaseBalance_OK(t *testing.T) {
tests := []struct { tests := []struct {
i uint64 i types.ValidatorIndex
b []uint64 b []uint64
nb uint64 nb uint64
eb uint64 eb uint64

View File

@@ -4,6 +4,7 @@ import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
types "github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/hashutil" "github.com/prysmaticlabs/prysm/shared/hashutil"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
@@ -34,13 +35,13 @@ func SplitIndices(l []uint64, n uint64) [][]uint64 {
// We utilize 'swap or not' shuffling in this implementation; we are allocating the memory with the seed that stays // We utilize 'swap or not' shuffling in this implementation; we are allocating the memory with the seed that stays
// constant between iterations instead of reallocating it each iteration as in the spec. This implementation is based // constant between iterations instead of reallocating it each iteration as in the spec. This implementation is based
// on the original implementation from protolambda, https://github.com/protolambda/eth2-shuffle // on the original implementation from protolambda, https://github.com/protolambda/eth2-shuffle
func ShuffledIndex(index, indexCount uint64, seed [32]byte) (uint64, error) { func ShuffledIndex(index types.ValidatorIndex, indexCount uint64, seed [32]byte) (types.ValidatorIndex, error) {
return ComputeShuffledIndex(index, indexCount, seed, true /* shuffle */) return ComputeShuffledIndex(index, indexCount, seed, true /* shuffle */)
} }
// UnShuffledIndex returns the inverse of ShuffledIndex. This implementation is based // UnShuffledIndex returns the inverse of ShuffledIndex. This implementation is based
// on the original implementation from protolambda, https://github.com/protolambda/eth2-shuffle // on the original implementation from protolambda, https://github.com/protolambda/eth2-shuffle
func UnShuffledIndex(index, indexCount uint64, seed [32]byte) (uint64, error) { func UnShuffledIndex(index types.ValidatorIndex, indexCount uint64, seed [32]byte) (types.ValidatorIndex, error) {
return ComputeShuffledIndex(index, indexCount, seed, false /* un-shuffle */) return ComputeShuffledIndex(index, indexCount, seed, false /* un-shuffle */)
} }
@@ -64,11 +65,11 @@ func UnShuffledIndex(index, indexCount uint64, seed [32]byte) (uint64, error) {
// index = flip if bit else index // index = flip if bit else index
// //
// return ValidatorIndex(index) // return ValidatorIndex(index)
func ComputeShuffledIndex(index, indexCount uint64, seed [32]byte, shuffle bool) (uint64, error) { func ComputeShuffledIndex(index types.ValidatorIndex, indexCount uint64, seed [32]byte, shuffle bool) (types.ValidatorIndex, error) {
if params.BeaconConfig().ShuffleRoundCount == 0 { if params.BeaconConfig().ShuffleRoundCount == 0 {
return index, nil return index, nil
} }
if index >= indexCount { if uint64(index) >= indexCount {
return 0, fmt.Errorf("input index %d out of bounds: %d", return 0, fmt.Errorf("input index %d out of bounds: %d",
index, indexCount) index, indexCount)
} }
@@ -95,9 +96,9 @@ func ComputeShuffledIndex(index, indexCount uint64, seed [32]byte, shuffle bool)
hash8 := hash[:8] hash8 := hash[:8]
hash8Int := bytesutil.FromBytes8(hash8) hash8Int := bytesutil.FromBytes8(hash8)
pivot := hash8Int % indexCount pivot := hash8Int % indexCount
flip := (pivot + indexCount - index) % indexCount flip := (pivot + indexCount - uint64(index)) % indexCount
// Consider every pair only once by picking the highest pair index to retrieve randomness. // Consider every pair only once by picking the highest pair index to retrieve randomness.
position := index position := uint64(index)
if flip > position { if flip > position {
position = flip position = flip
} }
@@ -113,7 +114,7 @@ func ComputeShuffledIndex(index, indexCount uint64, seed [32]byte, shuffle bool)
bitV := (byteV >> (position & 0x7)) & 0x1 bitV := (byteV >> (position & 0x7)) & 0x1
// index = flip if bit else index // index = flip if bit else index
if bitV == 1 { if bitV == 1 {
index = flip index = types.ValidatorIndex(flip)
} }
if shuffle { if shuffle {
round++ round++
@@ -144,17 +145,17 @@ func ComputeShuffledIndex(index, indexCount uint64, seed [32]byte, shuffle bool)
// - change byteV every 8 iterations. // - change byteV every 8 iterations.
// - we start at the edges, and work back to the mirror point. // - we start at the edges, and work back to the mirror point.
// this makes us process each pear exactly once (instead of unnecessarily twice, like in the spec). // this makes us process each pear exactly once (instead of unnecessarily twice, like in the spec).
func ShuffleList(input []uint64, seed [32]byte) ([]uint64, error) { func ShuffleList(input []types.ValidatorIndex, seed [32]byte) ([]types.ValidatorIndex, error) {
return innerShuffleList(input, seed, true /* shuffle */) return innerShuffleList(input, seed, true /* shuffle */)
} }
// UnshuffleList un-shuffles the list by running backwards through the round count. // UnshuffleList un-shuffles the list by running backwards through the round count.
func UnshuffleList(input []uint64, seed [32]byte) ([]uint64, error) { func UnshuffleList(input []types.ValidatorIndex, seed [32]byte) ([]types.ValidatorIndex, error) {
return innerShuffleList(input, seed, false /* un-shuffle */) return innerShuffleList(input, seed, false /* un-shuffle */)
} }
// shuffles or unshuffles, shuffle=false to un-shuffle. // shuffles or unshuffles, shuffle=false to un-shuffle.
func innerShuffleList(input []uint64, seed [32]byte, shuffle bool) ([]uint64, error) { func innerShuffleList(input []types.ValidatorIndex, seed [32]byte, shuffle bool) ([]types.ValidatorIndex, error) {
if len(input) <= 1 { if len(input) <= 1 {
return input, nil return input, nil
} }
@@ -183,7 +184,7 @@ func innerShuffleList(input []uint64, seed [32]byte, shuffle bool) ([]uint64, er
source := hashfunc(buf) source := hashfunc(buf)
byteV := source[(pivot&0xff)>>3] byteV := source[(pivot&0xff)>>3]
for i, j := uint64(0), pivot; i < mirror; i, j = i+1, j-1 { for i, j := uint64(0), pivot; i < mirror; i, j = i+1, j-1 {
byteV, source = swapOrNot(buf, byteV, i, input, j, source, hashfunc) byteV, source = swapOrNot(buf, byteV, types.ValidatorIndex(i), input, types.ValidatorIndex(j), source, hashfunc)
} }
// Now repeat, but for the part after the pivot. // Now repeat, but for the part after the pivot.
mirror = (pivot + listSize + 1) >> 1 mirror = (pivot + listSize + 1) >> 1
@@ -192,7 +193,7 @@ func innerShuffleList(input []uint64, seed [32]byte, shuffle bool) ([]uint64, er
source = hashfunc(buf) source = hashfunc(buf)
byteV = source[(end&0xff)>>3] byteV = source[(end&0xff)>>3]
for i, j := pivot+1, end; i < mirror; i, j = i+1, j-1 { for i, j := pivot+1, end; i < mirror; i, j = i+1, j-1 {
byteV, source = swapOrNot(buf, byteV, i, input, j, source, hashfunc) byteV, source = swapOrNot(buf, byteV, types.ValidatorIndex(i), input, types.ValidatorIndex(j), source, hashfunc)
} }
if shuffle { if shuffle {
r++ r++
@@ -211,8 +212,8 @@ func innerShuffleList(input []uint64, seed [32]byte, shuffle bool) ([]uint64, er
// swapOrNot describes the main algorithm behind the shuffle where we swap bytes in the inputted value // swapOrNot describes the main algorithm behind the shuffle where we swap bytes in the inputted value
// depending on if the conditions are met. // depending on if the conditions are met.
func swapOrNot(buf []byte, byteV byte, i uint64, input []uint64, func swapOrNot(buf []byte, byteV byte, i types.ValidatorIndex, input []types.ValidatorIndex,
j uint64, source [32]byte, hashFunc func([]byte) [32]byte) (byte, [32]byte) { j types.ValidatorIndex, source [32]byte, hashFunc func([]byte) [32]byte) (byte, [32]byte) {
if j&0xff == 0xff { if j&0xff == 0xff {
// just overwrite the last part of the buffer, reuse the start (seed, round) // just overwrite the last part of the buffer, reuse the start (seed, round)
binary.LittleEndian.PutUint32(buf[pivotViewSize:], uint32(j>>8)) binary.LittleEndian.PutUint32(buf[pivotViewSize:], uint32(j>>8))

View File

@@ -5,6 +5,7 @@ import (
"reflect" "reflect"
"testing" "testing"
types "github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/sliceutil" "github.com/prysmaticlabs/prysm/shared/sliceutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/assert"
@@ -13,7 +14,7 @@ import (
func TestShuffleList_InvalidValidatorCount(t *testing.T) { func TestShuffleList_InvalidValidatorCount(t *testing.T) {
maxShuffleListSize = 20 maxShuffleListSize = 20
list := make([]uint64, 21) list := make([]types.ValidatorIndex, 21)
if _, err := ShuffleList(list, [32]byte{123, 125}); err == nil { if _, err := ShuffleList(list, [32]byte{123, 125}); err == nil {
t.Error("Shuffle should have failed when validator count exceeds ModuloBias") t.Error("Shuffle should have failed when validator count exceeds ModuloBias")
maxShuffleListSize = 1 << 40 maxShuffleListSize = 1 << 40
@@ -22,14 +23,14 @@ func TestShuffleList_InvalidValidatorCount(t *testing.T) {
} }
func TestShuffleList_OK(t *testing.T) { func TestShuffleList_OK(t *testing.T) {
var list1 []uint64 var list1 []types.ValidatorIndex
seed1 := [32]byte{1, 128, 12} seed1 := [32]byte{1, 128, 12}
seed2 := [32]byte{2, 128, 12} seed2 := [32]byte{2, 128, 12}
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
list1 = append(list1, uint64(i)) list1 = append(list1, types.ValidatorIndex(i))
} }
list2 := make([]uint64, len(list1)) list2 := make([]types.ValidatorIndex, len(list1))
copy(list2, list1) copy(list2, list1)
list1, err := ShuffleList(list1, seed1) list1, err := ShuffleList(list1, seed1)
@@ -41,8 +42,8 @@ func TestShuffleList_OK(t *testing.T) {
if reflect.DeepEqual(list1, list2) { if reflect.DeepEqual(list1, list2) {
t.Errorf("2 shuffled lists shouldn't be equal") t.Errorf("2 shuffled lists shouldn't be equal")
} }
assert.DeepEqual(t, []uint64{0, 7, 8, 6, 3, 9, 4, 5, 2, 1}, list1, "List 1 was incorrectly shuffled got") assert.DeepEqual(t, []types.ValidatorIndex{0, 7, 8, 6, 3, 9, 4, 5, 2, 1}, list1, "List 1 was incorrectly shuffled got")
assert.DeepEqual(t, []uint64{0, 5, 2, 1, 6, 8, 7, 3, 4, 9}, list2, "List 2 was incorrectly shuffled got") assert.DeepEqual(t, []types.ValidatorIndex{0, 5, 2, 1, 6, 8, 7, 3, 4, 9}, list2, "List 2 was incorrectly shuffled got")
} }
func TestSplitIndices_OK(t *testing.T) { func TestSplitIndices_OK(t *testing.T) {
@@ -60,14 +61,14 @@ func TestSplitIndices_OK(t *testing.T) {
} }
func TestShuffleList_Vs_ShuffleIndex(t *testing.T) { func TestShuffleList_Vs_ShuffleIndex(t *testing.T) {
var list []uint64 var list []types.ValidatorIndex
listSize := uint64(1000) listSize := uint64(1000)
seed := [32]byte{123, 42} seed := [32]byte{123, 42}
for i := uint64(0); i < listSize; i++ { for i := types.ValidatorIndex(0); uint64(i) < listSize; i++ {
list = append(list, i) list = append(list, i)
} }
shuffledListByIndex := make([]uint64, listSize) shuffledListByIndex := make([]types.ValidatorIndex, listSize)
for i := uint64(0); i < listSize; i++ { for i := types.ValidatorIndex(0); uint64(i) < listSize; i++ {
si, err := ShuffledIndex(i, listSize, seed) si, err := ShuffledIndex(i, listSize, seed)
assert.NoError(t, err) assert.NoError(t, err)
shuffledListByIndex[si] = i shuffledListByIndex[si] = i
@@ -83,7 +84,7 @@ func BenchmarkShuffledIndex(b *testing.B) {
for _, listSize := range listSizes { for _, listSize := range listSizes {
b.Run(fmt.Sprintf("ShuffledIndex_%d", listSize), func(ib *testing.B) { b.Run(fmt.Sprintf("ShuffledIndex_%d", listSize), func(ib *testing.B) {
for i := uint64(0); i < uint64(ib.N); i++ { for i := uint64(0); i < uint64(ib.N); i++ {
_, err := ShuffledIndex(i%listSize, listSize, seed) _, err := ShuffledIndex(types.ValidatorIndex(i%listSize), listSize, seed)
assert.NoError(b, err) assert.NoError(b, err)
} }
}) })
@@ -97,7 +98,7 @@ func BenchmarkIndexComparison(b *testing.B) {
b.Run(fmt.Sprintf("Indexwise_ShuffleList_%d", listSize), func(ib *testing.B) { b.Run(fmt.Sprintf("Indexwise_ShuffleList_%d", listSize), func(ib *testing.B) {
for i := 0; i < ib.N; i++ { for i := 0; i < ib.N; i++ {
// Simulate a list-shuffle by running shuffle-index listSize times. // Simulate a list-shuffle by running shuffle-index listSize times.
for j := uint64(0); j < listSize; j++ { for j := types.ValidatorIndex(0); uint64(j) < listSize; j++ {
_, err := ShuffledIndex(j, listSize, seed) _, err := ShuffledIndex(j, listSize, seed)
assert.NoError(b, err) assert.NoError(b, err)
} }
@@ -110,9 +111,9 @@ func BenchmarkShuffleList(b *testing.B) {
listSizes := []uint64{400000, 40000, 400} listSizes := []uint64{400000, 40000, 400}
seed := [32]byte{123, 42} seed := [32]byte{123, 42}
for _, listSize := range listSizes { for _, listSize := range listSizes {
testIndices := make([]uint64, listSize) testIndices := make([]types.ValidatorIndex, listSize)
for i := uint64(0); i < listSize; i++ { for i := uint64(0); i < listSize; i++ {
testIndices[i] = i testIndices[i] = types.ValidatorIndex(i)
} }
b.Run(fmt.Sprintf("ShuffleList_%d", listSize), func(ib *testing.B) { b.Run(fmt.Sprintf("ShuffleList_%d", listSize), func(ib *testing.B) {
for i := 0; i < ib.N; i++ { for i := 0; i < ib.N; i++ {
@@ -124,25 +125,25 @@ func BenchmarkShuffleList(b *testing.B) {
} }
func TestShuffledIndex(t *testing.T) { func TestShuffledIndex(t *testing.T) {
var list []uint64 var list []types.ValidatorIndex
listSize := uint64(399) listSize := uint64(399)
for i := uint64(0); i < listSize; i++ { for i := types.ValidatorIndex(0); uint64(i) < listSize; i++ {
list = append(list, i) list = append(list, i)
} }
shuffledList := make([]uint64, listSize) shuffledList := make([]types.ValidatorIndex, listSize)
unShuffledList := make([]uint64, listSize) unshuffledlist := make([]types.ValidatorIndex, listSize)
seed := [32]byte{123, 42} seed := [32]byte{123, 42}
for i := uint64(0); i < listSize; i++ { for i := types.ValidatorIndex(0); uint64(i) < listSize; i++ {
si, err := ShuffledIndex(i, listSize, seed) si, err := ShuffledIndex(i, listSize, seed)
assert.NoError(t, err) assert.NoError(t, err)
shuffledList[si] = i shuffledList[si] = i
} }
for i := uint64(0); i < listSize; i++ { for i := types.ValidatorIndex(0); uint64(i) < listSize; i++ {
ui, err := UnShuffledIndex(i, listSize, seed) ui, err := UnShuffledIndex(i, listSize, seed)
assert.NoError(t, err) assert.NoError(t, err)
unShuffledList[ui] = shuffledList[i] unshuffledlist[ui] = shuffledList[i]
} }
assert.DeepEqual(t, list, unShuffledList) assert.DeepEqual(t, list, unshuffledlist)
} }
func TestSplitIndicesAndOffset_OK(t *testing.T) { func TestSplitIndicesAndOffset_OK(t *testing.T) {

View File

@@ -65,7 +65,7 @@ func signingData(rootFunc func() ([32]byte, error), domain []byte) ([32]byte, er
} }
// ComputeDomainVerifySigningRoot computes domain and verifies signing root of an object given the beacon state, validator index and signature. // ComputeDomainVerifySigningRoot computes domain and verifies signing root of an object given the beacon state, validator index and signature.
func ComputeDomainVerifySigningRoot(st *state.BeaconState, index uint64, epoch types.Epoch, obj fssz.HashRoot, domain [4]byte, sig []byte) error { func ComputeDomainVerifySigningRoot(st *state.BeaconState, index types.ValidatorIndex, epoch types.Epoch, obj fssz.HashRoot, domain [4]byte, sig []byte) error {
v, err := st.ValidatorAtIndex(index) v, err := st.ValidatorAtIndex(index)
if err != nil { if err != nil {
return err return err

View File

@@ -6,6 +6,7 @@ go_library(
srcs = ["shuffle_test_format.go"], srcs = ["shuffle_test_format.go"],
importpath = "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers/spectest", importpath = "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers/spectest",
visibility = ["//beacon-chain:__subpackages__"], visibility = ["//beacon-chain:__subpackages__"],
deps = ["@com_github_prysmaticlabs_eth2_types//:go_default_library"],
) )
go_test( go_test(
@@ -25,5 +26,6 @@ go_test(
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"@com_github_ethereum_go_ethereum//common:go_default_library", "@com_github_ethereum_go_ethereum//common:go_default_library",
"@com_github_go_yaml_yaml//:go_default_library", "@com_github_go_yaml_yaml//:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
], ],
) )

View File

@@ -1,8 +1,10 @@
package spectest package spectest
import types "github.com/prysmaticlabs/eth2-types"
// ShuffleTestCase -- // ShuffleTestCase --
type ShuffleTestCase struct { type ShuffleTestCase struct {
Seed string `yaml:"seed"` Seed string `yaml:"seed"`
Count uint64 `yaml:"count"` Count uint64 `yaml:"count"`
Mapping []uint64 `yaml:"mapping"` Mapping []types.ValidatorIndex `yaml:"mapping"`
} }

View File

@@ -4,13 +4,12 @@ package spectest
import ( import (
"encoding/hex" "encoding/hex"
"fmt"
"path" "path"
"reflect"
"testing" "testing"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/go-yaml/yaml" "github.com/go-yaml/yaml"
types "github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/shared/params/spectest" "github.com/prysmaticlabs/prysm/shared/params/spectest"
"github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil"
@@ -36,34 +35,32 @@ func runShuffleTests(t *testing.T, config string) {
testCase := &ShuffleTestCase{} testCase := &ShuffleTestCase{}
require.NoError(t, yaml.Unmarshal(testCaseFile, testCase), "Could not unmarshal YAML file into test struct") require.NoError(t, yaml.Unmarshal(testCaseFile, testCase), "Could not unmarshal YAML file into test struct")
require.NoError(t, runShuffleTest(testCase), "Shuffle test failed") require.NoError(t, runShuffleTest(t, testCase), "Shuffle test failed")
}) })
} }
} }
// RunShuffleTest uses validator set specified from a YAML file, runs the validator shuffle // RunShuffleTest uses validator set specified from a YAML file, runs the validator shuffle
// algorithm, then compare the output with the expected output from the YAML file. // algorithm, then compare the output with the expected output from the YAML file.
func runShuffleTest(testCase *ShuffleTestCase) error { func runShuffleTest(t *testing.T, testCase *ShuffleTestCase) error {
baseSeed, err := hex.DecodeString(testCase.Seed[2:]) baseSeed, err := hex.DecodeString(testCase.Seed[2:])
if err != nil { if err != nil {
return err return err
} }
seed := common.BytesToHash(baseSeed) seed := common.BytesToHash(baseSeed)
testIndices := make([]uint64, testCase.Count) testIndices := make([]types.ValidatorIndex, testCase.Count)
for i := uint64(0); i < testCase.Count; i++ { for i := types.ValidatorIndex(0); uint64(i) < testCase.Count; i++ {
testIndices[i] = i testIndices[i] = i
} }
shuffledList := make([]uint64, testCase.Count) shuffledList := make([]types.ValidatorIndex, testCase.Count)
for i := uint64(0); i < testCase.Count; i++ { for i := types.ValidatorIndex(0); uint64(i) < testCase.Count; i++ {
si, err := helpers.ShuffledIndex(i, testCase.Count, seed) si, err := helpers.ShuffledIndex(i, testCase.Count, seed)
if err != nil { if err != nil {
return err return err
} }
shuffledList[i] = si shuffledList[i] = si
} }
if !reflect.DeepEqual(shuffledList, testCase.Mapping) { require.DeepSSZEqual(t, shuffledList, testCase.Mapping)
return fmt.Errorf("shuffle result error: expected %v, actual %v", testCase.Mapping, shuffledList)
}
return nil return nil
} }

View File

@@ -73,7 +73,7 @@ func checkValidatorSlashable(activationEpoch, withdrawableEpoch types.Epoch, sla
// Return the sequence of active validator indices at ``epoch``. // Return the sequence of active validator indices at ``epoch``.
// """ // """
// return [ValidatorIndex(i) for i, v in enumerate(state.validators) if is_active_validator(v, epoch)] // return [ValidatorIndex(i) for i, v in enumerate(state.validators) if is_active_validator(v, epoch)]
func ActiveValidatorIndices(state *stateTrie.BeaconState, epoch types.Epoch) ([]uint64, error) { func ActiveValidatorIndices(state *stateTrie.BeaconState, epoch types.Epoch) ([]types.ValidatorIndex, error) {
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester) seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not get seed") return nil, errors.Wrap(err, "could not get seed")
@@ -85,10 +85,10 @@ func ActiveValidatorIndices(state *stateTrie.BeaconState, epoch types.Epoch) ([]
if activeIndices != nil { if activeIndices != nil {
return activeIndices, nil return activeIndices, nil
} }
var indices []uint64 var indices []types.ValidatorIndex
if err := state.ReadFromEveryValidator(func(idx int, val stateTrie.ReadOnlyValidator) error { if err := state.ReadFromEveryValidator(func(idx int, val stateTrie.ReadOnlyValidator) error {
if IsActiveValidatorUsingTrie(val, epoch) { if IsActiveValidatorUsingTrie(val, epoch) {
indices = append(indices, uint64(idx)) indices = append(indices, types.ValidatorIndex(idx))
} }
return nil return nil
}); err != nil { }); err != nil {
@@ -176,7 +176,7 @@ func ValidatorChurnLimit(activeValidatorCount uint64) (uint64, error) {
// seed = hash(get_seed(state, epoch, DOMAIN_BEACON_PROPOSER) + int_to_bytes(state.slot, length=8)) // seed = hash(get_seed(state, epoch, DOMAIN_BEACON_PROPOSER) + int_to_bytes(state.slot, length=8))
// indices = get_active_validator_indices(state, epoch) // indices = get_active_validator_indices(state, epoch)
// return compute_proposer_index(state, indices, seed) // return compute_proposer_index(state, indices, seed)
func BeaconProposerIndex(state *stateTrie.BeaconState) (uint64, error) { func BeaconProposerIndex(state *stateTrie.BeaconState) (types.ValidatorIndex, error) {
e := CurrentEpoch(state) e := CurrentEpoch(state)
// The cache uses the state root of the previous epoch - minimum_seed_lookahead last slot as key. (e.g. Starting epoch 1, slot 32, the key would be block root at slot 31) // The cache uses the state root of the previous epoch - minimum_seed_lookahead last slot as key. (e.g. Starting epoch 1, slot 32, the key would be block root at slot 31)
// For simplicity, the node will skip caching of genesis epoch. // For simplicity, the node will skip caching of genesis epoch.
@@ -243,7 +243,7 @@ func BeaconProposerIndex(state *stateTrie.BeaconState) (uint64, error) {
// if effective_balance * MAX_RANDOM_BYTE >= MAX_EFFECTIVE_BALANCE * random_byte: // if effective_balance * MAX_RANDOM_BYTE >= MAX_EFFECTIVE_BALANCE * random_byte:
// return ValidatorIndex(candidate_index) // return ValidatorIndex(candidate_index)
// i += 1 // i += 1
func ComputeProposerIndex(bState *stateTrie.BeaconState, activeIndices []uint64, seed [32]byte) (uint64, error) { func ComputeProposerIndex(bState *stateTrie.BeaconState, activeIndices []types.ValidatorIndex, seed [32]byte) (types.ValidatorIndex, error) {
length := uint64(len(activeIndices)) length := uint64(len(activeIndices))
if length == 0 { if length == 0 {
return 0, errors.New("empty active indices list") return 0, errors.New("empty active indices list")
@@ -252,12 +252,12 @@ func ComputeProposerIndex(bState *stateTrie.BeaconState, activeIndices []uint64,
hashFunc := hashutil.CustomSHA256Hasher() hashFunc := hashutil.CustomSHA256Hasher()
for i := uint64(0); ; i++ { for i := uint64(0); ; i++ {
candidateIndex, err := ComputeShuffledIndex(i%length, length, seed, true /* shuffle */) candidateIndex, err := ComputeShuffledIndex(types.ValidatorIndex(i%length), length, seed, true /* shuffle */)
if err != nil { if err != nil {
return 0, err return 0, err
} }
candidateIndex = activeIndices[candidateIndex] candidateIndex = activeIndices[candidateIndex]
if candidateIndex >= uint64(bState.NumValidators()) { if uint64(candidateIndex) >= uint64(bState.NumValidators()) {
return 0, errors.New("active index out of range") return 0, errors.New("active index out of range")
} }
b := append(seed[:], bytesutil.Bytes8(i/32)...) b := append(seed[:], bytesutil.Bytes8(i/32)...)

View File

@@ -243,7 +243,7 @@ func TestBeaconProposerIndex_OK(t *testing.T) {
tests := []struct { tests := []struct {
slot types.Slot slot types.Slot
index uint64 index types.ValidatorIndex
}{ }{
{ {
slot: 1, slot: 1,
@@ -326,7 +326,7 @@ func TestComputeProposerIndex_Compatibility(t *testing.T) {
indices, err := ActiveValidatorIndices(state, 0) indices, err := ActiveValidatorIndices(state, 0)
require.NoError(t, err) require.NoError(t, err)
var proposerIndices []uint64 var proposerIndices []types.ValidatorIndex
seed, err := Seed(state, 0, params.BeaconConfig().DomainBeaconProposer) seed, err := Seed(state, 0, params.BeaconConfig().DomainBeaconProposer)
require.NoError(t, err) require.NoError(t, err)
for i := uint64(0); i < uint64(params.BeaconConfig().SlotsPerEpoch); i++ { for i := uint64(0); i < uint64(params.BeaconConfig().SlotsPerEpoch); i++ {
@@ -337,7 +337,7 @@ func TestComputeProposerIndex_Compatibility(t *testing.T) {
proposerIndices = append(proposerIndices, index) proposerIndices = append(proposerIndices, index)
} }
var wantedProposerIndices []uint64 var wantedProposerIndices []types.ValidatorIndex
seed, err = Seed(state, 0, params.BeaconConfig().DomainBeaconProposer) seed, err = Seed(state, 0, params.BeaconConfig().DomainBeaconProposer)
require.NoError(t, err) require.NoError(t, err)
for i := uint64(0); i < uint64(params.BeaconConfig().SlotsPerEpoch); i++ { for i := uint64(0); i < uint64(params.BeaconConfig().SlotsPerEpoch); i++ {
@@ -374,7 +374,7 @@ func TestActiveValidatorCount_Genesis(t *testing.T) {
// Preset cache to a bad count. // Preset cache to a bad count.
seed, err := Seed(beaconState, 0, params.BeaconConfig().DomainBeaconAttester) seed, err := Seed(beaconState, 0, params.BeaconConfig().DomainBeaconAttester)
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, committeeCache.AddCommitteeShuffledList(&cache.Committees{Seed: seed, ShuffledIndices: []uint64{1, 2, 3}})) require.NoError(t, committeeCache.AddCommitteeShuffledList(&cache.Committees{Seed: seed, ShuffledIndices: []types.ValidatorIndex{1, 2, 3}}))
validatorCount, err := ActiveValidatorCount(beaconState, CurrentEpoch(beaconState)) validatorCount, err := ActiveValidatorCount(beaconState, CurrentEpoch(beaconState))
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, uint64(c), validatorCount, "Did not get the correct validator count") assert.Equal(t, uint64(c), validatorCount, "Did not get the correct validator count")
@@ -451,7 +451,7 @@ func TestActiveValidatorIndices(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
args args args args
want []uint64 want []types.ValidatorIndex
wantedErr string wantedErr string
}{ }{
{ {
@@ -476,7 +476,7 @@ func TestActiveValidatorIndices(t *testing.T) {
}, },
epoch: 10, epoch: 10,
}, },
want: []uint64{0, 1, 2}, want: []types.ValidatorIndex{0, 1, 2},
}, },
{ {
name: "some_active_epoch_10", name: "some_active_epoch_10",
@@ -500,7 +500,7 @@ func TestActiveValidatorIndices(t *testing.T) {
}, },
epoch: 10, epoch: 10,
}, },
want: []uint64{0, 1}, want: []types.ValidatorIndex{0, 1},
}, },
{ {
name: "some_active_with_recent_new_epoch_10", name: "some_active_with_recent_new_epoch_10",
@@ -528,7 +528,7 @@ func TestActiveValidatorIndices(t *testing.T) {
}, },
epoch: 10, epoch: 10,
}, },
want: []uint64{0, 1, 3}, want: []types.ValidatorIndex{0, 1, 3},
}, },
{ {
name: "some_active_with_recent_new_epoch_10", name: "some_active_with_recent_new_epoch_10",
@@ -556,7 +556,7 @@ func TestActiveValidatorIndices(t *testing.T) {
}, },
epoch: 10, epoch: 10,
}, },
want: []uint64{0, 1, 3}, want: []types.ValidatorIndex{0, 1, 3},
}, },
{ {
name: "some_active_with_recent_new_epoch_10", name: "some_active_with_recent_new_epoch_10",
@@ -584,7 +584,7 @@ func TestActiveValidatorIndices(t *testing.T) {
}, },
epoch: 10, epoch: 10,
}, },
want: []uint64{0, 2, 3}, want: []types.ValidatorIndex{0, 2, 3},
}, },
} }
for _, tt := range tests { for _, tt := range tests {
@@ -606,13 +606,13 @@ func TestComputeProposerIndex(t *testing.T) {
seed := bytesutil.ToBytes32([]byte("seed")) seed := bytesutil.ToBytes32([]byte("seed"))
type args struct { type args struct {
validators []*ethpb.Validator validators []*ethpb.Validator
indices []uint64 indices []types.ValidatorIndex
seed [32]byte seed [32]byte
} }
tests := []struct { tests := []struct {
name string name string
args args args args
want uint64 want types.ValidatorIndex
wantedErr string wantedErr string
}{ }{
{ {
@@ -625,7 +625,7 @@ func TestComputeProposerIndex(t *testing.T) {
{EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance},
{EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance},
}, },
indices: []uint64{0, 1, 2, 3, 4}, indices: []types.ValidatorIndex{0, 1, 2, 3, 4},
seed: seed, seed: seed,
}, },
want: 2, want: 2,
@@ -640,7 +640,7 @@ func TestComputeProposerIndex(t *testing.T) {
{EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance},
{EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance},
}, },
indices: []uint64{3}, indices: []types.ValidatorIndex{3},
seed: seed, seed: seed,
}, },
want: 3, want: 3,
@@ -655,7 +655,7 @@ func TestComputeProposerIndex(t *testing.T) {
{EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance},
{EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance},
}, },
indices: []uint64{}, indices: []types.ValidatorIndex{},
seed: seed, seed: seed,
}, },
wantedErr: "empty active indices list", wantedErr: "empty active indices list",
@@ -670,7 +670,7 @@ func TestComputeProposerIndex(t *testing.T) {
{EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance},
{EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance},
}, },
indices: []uint64{100}, indices: []types.ValidatorIndex{100},
seed: seed, seed: seed,
}, },
wantedErr: "active index out of range", wantedErr: "active index out of range",
@@ -690,7 +690,7 @@ func TestComputeProposerIndex(t *testing.T) {
{EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance},
{EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance},
}, },
indices: []uint64{5, 6, 7, 8, 9}, indices: []types.ValidatorIndex{5, 6, 7, 8, 9},
seed: seed, seed: seed,
}, },
want: 7, want: 7,
@@ -705,7 +705,7 @@ func TestComputeProposerIndex(t *testing.T) {
{EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance},
{EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance},
}, },
indices: []uint64{0, 1, 2, 3, 4}, indices: []types.ValidatorIndex{0, 1, 2, 3, 4},
seed: seed, seed: seed,
}, },
want: 4, want: 4,
@@ -778,7 +778,7 @@ func TestIsIsEligibleForActivation(t *testing.T) {
} }
} }
func computeProposerIndexWithValidators(validators []*ethpb.Validator, activeIndices []uint64, seed [32]byte) (uint64, error) { func computeProposerIndexWithValidators(validators []*ethpb.Validator, activeIndices []types.ValidatorIndex, seed [32]byte) (types.ValidatorIndex, error) {
length := uint64(len(activeIndices)) length := uint64(len(activeIndices))
if length == 0 { if length == 0 {
return 0, errors.New("empty active indices list") return 0, errors.New("empty active indices list")
@@ -787,12 +787,12 @@ func computeProposerIndexWithValidators(validators []*ethpb.Validator, activeInd
hashFunc := hashutil.CustomSHA256Hasher() hashFunc := hashutil.CustomSHA256Hasher()
for i := uint64(0); ; i++ { for i := uint64(0); ; i++ {
candidateIndex, err := ComputeShuffledIndex(i%length, length, seed, true /* shuffle */) candidateIndex, err := ComputeShuffledIndex(types.ValidatorIndex(i%length), length, seed, true /* shuffle */)
if err != nil { if err != nil {
return 0, err return 0, err
} }
candidateIndex = activeIndices[candidateIndex] candidateIndex = activeIndices[candidateIndex]
if candidateIndex >= uint64(len(validators)) { if uint64(candidateIndex) >= uint64(len(validators)) {
return 0, errors.New("active index out of range") return 0, errors.New("active index out of range")
} }
b := append(seed[:], bytesutil.Bytes8(i/32)...) b := append(seed[:], bytesutil.Bytes8(i/32)...)

View File

@@ -11,6 +11,7 @@ go_library(
], ],
deps = [ deps = [
"//shared/bytesutil:go_default_library", "//shared/bytesutil:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
], ],
) )
@@ -26,6 +27,7 @@ go_test(
"//shared/bytesutil:go_default_library", "//shared/bytesutil:go_default_library",
"//shared/testutil/assert:go_default_library", "//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
], ],
) )

View File

@@ -4,14 +4,15 @@
package stateutils package stateutils
import ( import (
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/bytesutil"
) )
// ValidatorIndexMap builds a lookup map for quickly determining the index of // ValidatorIndexMap builds a lookup map for quickly determining the index of
// a validator by their public key. // a validator by their public key.
func ValidatorIndexMap(validators []*ethpb.Validator) map[[48]byte]uint64 { func ValidatorIndexMap(validators []*ethpb.Validator) map[[48]byte]types.ValidatorIndex {
m := make(map[[48]byte]uint64, len(validators)) m := make(map[[48]byte]types.ValidatorIndex, len(validators))
if validators == nil { if validators == nil {
return m return m
} }
@@ -20,7 +21,7 @@ func ValidatorIndexMap(validators []*ethpb.Validator) map[[48]byte]uint64 {
continue continue
} }
key := bytesutil.ToBytes48(record.PublicKey) key := bytesutil.ToBytes48(record.PublicKey)
m[key] = uint64(idx) m[key] = types.ValidatorIndex(idx)
} }
return m return m
} }

View File

@@ -3,6 +3,7 @@ package stateutils_test
import ( import (
"testing" "testing"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/state/stateutils" "github.com/prysmaticlabs/prysm/beacon-chain/core/state/stateutils"
beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state" beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state"
@@ -28,7 +29,7 @@ func TestValidatorIndexMap_OK(t *testing.T) {
tests := []struct { tests := []struct {
key [48]byte key [48]byte
val uint64 val types.ValidatorIndex
ok bool ok bool
}{ }{
{ {

View File

@@ -320,7 +320,7 @@ func createFullBlockWithOperations(t *testing.T) (*beaconstate.BeaconState,
require.NoError(t, beaconState.SetCurrentJustifiedCheckpoint(cp)) require.NoError(t, beaconState.SetCurrentJustifiedCheckpoint(cp))
require.NoError(t, beaconState.SetCurrentEpochAttestations([]*pb.PendingAttestation{})) require.NoError(t, beaconState.SetCurrentEpochAttestations([]*pb.PendingAttestation{}))
proposerSlashIdx := uint64(3) proposerSlashIdx := types.ValidatorIndex(3)
slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch
err = beaconState.SetSlot(slotsPerEpoch.Mul(uint64(params.BeaconConfig().ShardCommitteePeriod)) + params.BeaconConfig().MinAttestationInclusionDelay) err = beaconState.SetSlot(slotsPerEpoch.Mul(uint64(params.BeaconConfig().ShardCommitteePeriod)) + params.BeaconConfig().MinAttestationInclusionDelay)
require.NoError(t, err) require.NoError(t, err)

View File

@@ -36,7 +36,7 @@ import (
// # Set validator exit epoch and withdrawable epoch // # Set validator exit epoch and withdrawable epoch
// validator.exit_epoch = exit_queue_epoch // validator.exit_epoch = exit_queue_epoch
// validator.withdrawable_epoch = Epoch(validator.exit_epoch + MIN_VALIDATOR_WITHDRAWABILITY_DELAY) // validator.withdrawable_epoch = Epoch(validator.exit_epoch + MIN_VALIDATOR_WITHDRAWABILITY_DELAY)
func InitiateValidatorExit(state *stateTrie.BeaconState, idx uint64) (*stateTrie.BeaconState, error) { func InitiateValidatorExit(state *stateTrie.BeaconState, idx types.ValidatorIndex) (*stateTrie.BeaconState, error) {
validator, err := state.ValidatorAtIndex(idx) validator, err := state.ValidatorAtIndex(idx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -121,7 +121,7 @@ func InitiateValidatorExit(state *stateTrie.BeaconState, idx uint64) (*stateTrie
// proposer_reward = Gwei(whistleblower_reward // PROPOSER_REWARD_QUOTIENT) // proposer_reward = Gwei(whistleblower_reward // PROPOSER_REWARD_QUOTIENT)
// increase_balance(state, proposer_index, proposer_reward) // increase_balance(state, proposer_index, proposer_reward)
// increase_balance(state, whistleblower_index, Gwei(whistleblower_reward - proposer_reward)) // increase_balance(state, whistleblower_index, Gwei(whistleblower_reward - proposer_reward))
func SlashValidator(state *stateTrie.BeaconState, slashedIdx uint64) (*stateTrie.BeaconState, error) { func SlashValidator(state *stateTrie.BeaconState, slashedIdx types.ValidatorIndex) (*stateTrie.BeaconState, error) {
state, err := InitiateValidatorExit(state, slashedIdx) state, err := InitiateValidatorExit(state, slashedIdx)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "could not initiate validator %d exit", slashedIdx) return nil, errors.Wrapf(err, "could not initiate validator %d exit", slashedIdx)
@@ -172,33 +172,33 @@ func SlashValidator(state *stateTrie.BeaconState, slashedIdx uint64) (*stateTrie
} }
// ActivatedValidatorIndices determines the indices activated during the given epoch. // ActivatedValidatorIndices determines the indices activated during the given epoch.
func ActivatedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []uint64 { func ActivatedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []types.ValidatorIndex {
activations := make([]uint64, 0) activations := make([]types.ValidatorIndex, 0)
for i := 0; i < len(validators); i++ { for i := 0; i < len(validators); i++ {
val := validators[i] val := validators[i]
if val.ActivationEpoch <= epoch && epoch < val.ExitEpoch { if val.ActivationEpoch <= epoch && epoch < val.ExitEpoch {
activations = append(activations, uint64(i)) activations = append(activations, types.ValidatorIndex(i))
} }
} }
return activations return activations
} }
// SlashedValidatorIndices determines the indices slashed during the given epoch. // SlashedValidatorIndices determines the indices slashed during the given epoch.
func SlashedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []uint64 { func SlashedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []types.ValidatorIndex {
slashed := make([]uint64, 0) slashed := make([]types.ValidatorIndex, 0)
for i := 0; i < len(validators); i++ { for i := 0; i < len(validators); i++ {
val := validators[i] val := validators[i]
maxWithdrawableEpoch := types.MaxEpoch(val.WithdrawableEpoch, epoch+params.BeaconConfig().EpochsPerSlashingsVector) maxWithdrawableEpoch := types.MaxEpoch(val.WithdrawableEpoch, epoch+params.BeaconConfig().EpochsPerSlashingsVector)
if val.WithdrawableEpoch == maxWithdrawableEpoch && val.Slashed { if val.WithdrawableEpoch == maxWithdrawableEpoch && val.Slashed {
slashed = append(slashed, uint64(i)) slashed = append(slashed, types.ValidatorIndex(i))
} }
} }
return slashed return slashed
} }
// ExitedValidatorIndices determines the indices exited during the current epoch. // ExitedValidatorIndices determines the indices exited during the current epoch.
func ExitedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]uint64, error) { func ExitedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]types.ValidatorIndex, error) {
exited := make([]uint64, 0) exited := make([]types.ValidatorIndex, 0)
exitEpochs := make([]types.Epoch, 0) exitEpochs := make([]types.Epoch, 0)
for i := 0; i < len(validators); i++ { for i := 0; i < len(validators); i++ {
val := validators[i] val := validators[i]
@@ -231,15 +231,15 @@ func ExitedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, ac
for i, val := range validators { for i, val := range validators {
if val.ExitEpoch == epoch && val.WithdrawableEpoch == withdrawableEpoch && if val.ExitEpoch == epoch && val.WithdrawableEpoch == withdrawableEpoch &&
val.EffectiveBalance > params.BeaconConfig().EjectionBalance { val.EffectiveBalance > params.BeaconConfig().EjectionBalance {
exited = append(exited, uint64(i)) exited = append(exited, types.ValidatorIndex(i))
} }
} }
return exited, nil return exited, nil
} }
// EjectedValidatorIndices determines the indices ejected during the given epoch. // EjectedValidatorIndices determines the indices ejected during the given epoch.
func EjectedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]uint64, error) { func EjectedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]types.ValidatorIndex, error) {
ejected := make([]uint64, 0) ejected := make([]types.ValidatorIndex, 0)
exitEpochs := make([]types.Epoch, 0) exitEpochs := make([]types.Epoch, 0)
for i := 0; i < len(validators); i++ { for i := 0; i < len(validators); i++ {
val := validators[i] val := validators[i]
@@ -272,7 +272,7 @@ func EjectedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, a
for i, val := range validators { for i, val := range validators {
if val.ExitEpoch == epoch && val.WithdrawableEpoch == withdrawableEpoch && if val.ExitEpoch == epoch && val.WithdrawableEpoch == withdrawableEpoch &&
val.EffectiveBalance <= params.BeaconConfig().EjectionBalance { val.EffectiveBalance <= params.BeaconConfig().EjectionBalance {
ejected = append(ejected, uint64(i)) ejected = append(ejected, types.ValidatorIndex(i))
} }
} }
return ejected, nil return ejected, nil

View File

@@ -55,7 +55,7 @@ func TestInitiateValidatorExit_AlreadyExited(t *testing.T) {
func TestInitiateValidatorExit_ProperExit(t *testing.T) { func TestInitiateValidatorExit_ProperExit(t *testing.T) {
exitedEpoch := types.Epoch(100) exitedEpoch := types.Epoch(100)
idx := uint64(3) idx := types.ValidatorIndex(3)
base := &pb.BeaconState{Validators: []*ethpb.Validator{ base := &pb.BeaconState{Validators: []*ethpb.Validator{
{ExitEpoch: exitedEpoch}, {ExitEpoch: exitedEpoch},
{ExitEpoch: exitedEpoch + 1}, {ExitEpoch: exitedEpoch + 1},
@@ -73,7 +73,7 @@ func TestInitiateValidatorExit_ProperExit(t *testing.T) {
func TestInitiateValidatorExit_ChurnOverflow(t *testing.T) { func TestInitiateValidatorExit_ChurnOverflow(t *testing.T) {
exitedEpoch := types.Epoch(100) exitedEpoch := types.Epoch(100)
idx := uint64(4) idx := types.ValidatorIndex(4)
base := &pb.BeaconState{Validators: []*ethpb.Validator{ base := &pb.BeaconState{Validators: []*ethpb.Validator{
{ExitEpoch: exitedEpoch + 2}, {ExitEpoch: exitedEpoch + 2},
{ExitEpoch: exitedEpoch + 2}, {ExitEpoch: exitedEpoch + 2},
@@ -119,7 +119,7 @@ func TestSlashValidator_OK(t *testing.T) {
state, err := beaconstate.InitializeFromProto(base) state, err := beaconstate.InitializeFromProto(base)
require.NoError(t, err) require.NoError(t, err)
slashedIdx := uint64(2) slashedIdx := types.ValidatorIndex(2)
proposer, err := helpers.BeaconProposerIndex(state) proposer, err := helpers.BeaconProposerIndex(state)
require.NoError(t, err, "Could not get proposer") require.NoError(t, err, "Could not get proposer")
@@ -152,7 +152,7 @@ func TestSlashValidator_OK(t *testing.T) {
func TestActivatedValidatorIndices(t *testing.T) { func TestActivatedValidatorIndices(t *testing.T) {
tests := []struct { tests := []struct {
state *pb.BeaconState state *pb.BeaconState
wanted []uint64 wanted []types.ValidatorIndex
}{ }{
{ {
state: &pb.BeaconState{ state: &pb.BeaconState{
@@ -174,7 +174,7 @@ func TestActivatedValidatorIndices(t *testing.T) {
}, },
}, },
}, },
wanted: []uint64{0, 1, 3}, wanted: []types.ValidatorIndex{0, 1, 3},
}, },
{ {
state: &pb.BeaconState{ state: &pb.BeaconState{
@@ -184,7 +184,7 @@ func TestActivatedValidatorIndices(t *testing.T) {
}, },
}, },
}, },
wanted: []uint64{}, wanted: []types.ValidatorIndex{},
}, },
{ {
state: &pb.BeaconState{ state: &pb.BeaconState{
@@ -195,7 +195,7 @@ func TestActivatedValidatorIndices(t *testing.T) {
}, },
}, },
}, },
wanted: []uint64{0}, wanted: []types.ValidatorIndex{0},
}, },
} }
for _, tt := range tests { for _, tt := range tests {
@@ -209,7 +209,7 @@ func TestActivatedValidatorIndices(t *testing.T) {
func TestSlashedValidatorIndices(t *testing.T) { func TestSlashedValidatorIndices(t *testing.T) {
tests := []struct { tests := []struct {
state *pb.BeaconState state *pb.BeaconState
wanted []uint64 wanted []types.ValidatorIndex
}{ }{
{ {
state: &pb.BeaconState{ state: &pb.BeaconState{
@@ -228,7 +228,7 @@ func TestSlashedValidatorIndices(t *testing.T) {
}, },
}, },
}, },
wanted: []uint64{0, 2}, wanted: []types.ValidatorIndex{0, 2},
}, },
{ {
state: &pb.BeaconState{ state: &pb.BeaconState{
@@ -238,7 +238,7 @@ func TestSlashedValidatorIndices(t *testing.T) {
}, },
}, },
}, },
wanted: []uint64{}, wanted: []types.ValidatorIndex{},
}, },
{ {
state: &pb.BeaconState{ state: &pb.BeaconState{
@@ -249,7 +249,7 @@ func TestSlashedValidatorIndices(t *testing.T) {
}, },
}, },
}, },
wanted: []uint64{0}, wanted: []types.ValidatorIndex{0},
}, },
} }
for _, tt := range tests { for _, tt := range tests {
@@ -263,7 +263,7 @@ func TestSlashedValidatorIndices(t *testing.T) {
func TestExitedValidatorIndices(t *testing.T) { func TestExitedValidatorIndices(t *testing.T) {
tests := []struct { tests := []struct {
state *pb.BeaconState state *pb.BeaconState
wanted []uint64 wanted []types.ValidatorIndex
}{ }{
{ {
state: &pb.BeaconState{ state: &pb.BeaconState{
@@ -285,7 +285,7 @@ func TestExitedValidatorIndices(t *testing.T) {
}, },
}, },
}, },
wanted: []uint64{0, 2}, wanted: []types.ValidatorIndex{0, 2},
}, },
{ {
state: &pb.BeaconState{ state: &pb.BeaconState{
@@ -297,7 +297,7 @@ func TestExitedValidatorIndices(t *testing.T) {
}, },
}, },
}, },
wanted: []uint64{}, wanted: []types.ValidatorIndex{},
}, },
{ {
state: &pb.BeaconState{ state: &pb.BeaconState{
@@ -309,7 +309,7 @@ func TestExitedValidatorIndices(t *testing.T) {
}, },
}, },
}, },
wanted: []uint64{0}, wanted: []types.ValidatorIndex{0},
}, },
} }
for _, tt := range tests { for _, tt := range tests {

View File

@@ -19,6 +19,7 @@ go_library(
"//shared/interop:go_default_library", "//shared/interop:go_default_library",
"//shared/slotutil:go_default_library", "//shared/slotutil:go_default_library",
"@com_github_pkg_errors//:go_default_library", "@com_github_pkg_errors//:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library",
], ],

View File

@@ -10,6 +10,7 @@ import (
"time" "time"
"github.com/pkg/errors" "github.com/pkg/errors"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache" "github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
@@ -207,7 +208,7 @@ func (s *Service) saveGenesisState(ctx context.Context, genesisState *stateTrie.
return errors.Wrap(err, "could not save finalized checkpoint") return errors.Wrap(err, "could not save finalized checkpoint")
} }
for i := uint64(0); i < uint64(genesisState.NumValidators()); i++ { for i := types.ValidatorIndex(0); uint64(i) < uint64(genesisState.NumValidators()); i++ {
pk := genesisState.PubkeyAtIndex(i) pk := genesisState.PubkeyAtIndex(i)
s.chainStartDeposits[i] = &ethpb.Deposit{ s.chainStartDeposits[i] = &ethpb.Deposit{
Data: &ethpb.Deposit_Data{ Data: &ethpb.Deposit_Data{

View File

@@ -24,6 +24,7 @@ go_library(
"@com_github_pkg_errors//:go_default_library", "@com_github_pkg_errors//:go_default_library",
"@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library",
"@com_github_prometheus_client_golang//prometheus/promauto:go_default_library", "@com_github_prometheus_client_golang//prometheus/promauto:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library",
"@com_github_trailofbits_go_mutexasserts//:go_default_library", "@com_github_trailofbits_go_mutexasserts//:go_default_library",
@@ -47,6 +48,7 @@ go_test(
"//shared/testutil:go_default_library", "//shared/testutil:go_default_library",
"//shared/testutil/assert:go_default_library", "//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
], ],
) )

View File

@@ -6,6 +6,7 @@ import (
"sort" "sort"
"github.com/pkg/errors" "github.com/pkg/errors"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
@@ -21,7 +22,7 @@ func NewPool() *Pool {
return &Pool{ return &Pool{
pendingProposerSlashing: make([]*ethpb.ProposerSlashing, 0), pendingProposerSlashing: make([]*ethpb.ProposerSlashing, 0),
pendingAttesterSlashing: make([]*PendingAttesterSlashing, 0), pendingAttesterSlashing: make([]*PendingAttesterSlashing, 0),
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
} }
} }
@@ -37,7 +38,7 @@ func (p *Pool) PendingAttesterSlashings(ctx context.Context, state *beaconstate.
// Update prom metric. // Update prom metric.
numPendingAttesterSlashings.Set(float64(len(p.pendingAttesterSlashing))) numPendingAttesterSlashings.Set(float64(len(p.pendingAttesterSlashing)))
included := make(map[uint64]bool) included := make(map[types.ValidatorIndex]bool)
// Allocate pending slice with a capacity of maxAttesterSlashings or len(p.pendingAttesterSlashing)) depending on the request. // Allocate pending slice with a capacity of maxAttesterSlashings or len(p.pendingAttesterSlashing)) depending on the request.
maxSlashings := params.BeaconConfig().MaxAttesterSlashings maxSlashings := params.BeaconConfig().MaxAttesterSlashings
@@ -63,7 +64,7 @@ func (p *Pool) PendingAttesterSlashings(ctx context.Context, state *beaconstate.
attSlashing := slashing.attesterSlashing attSlashing := slashing.attesterSlashing
slashedVal := sliceutil.IntersectionUint64(attSlashing.Attestation_1.AttestingIndices, attSlashing.Attestation_2.AttestingIndices) slashedVal := sliceutil.IntersectionUint64(attSlashing.Attestation_1.AttestingIndices, attSlashing.Attestation_2.AttestingIndices)
for _, idx := range slashedVal { for _, idx := range slashedVal {
included[idx] = true included[types.ValidatorIndex(idx)] = true
} }
pending = append(pending, attSlashing) pending = append(pending, attSlashing)
@@ -131,7 +132,7 @@ func (p *Pool) InsertAttesterSlashing(
cantSlash := make([]uint64, 0, len(slashedVal)) cantSlash := make([]uint64, 0, len(slashedVal))
for _, val := range slashedVal { for _, val := range slashedVal {
// Has this validator index been included recently? // Has this validator index been included recently?
ok, err := p.validatorSlashingPreconditionCheck(state, val) ok, err := p.validatorSlashingPreconditionCheck(state, types.ValidatorIndex(val))
if err != nil { if err != nil {
return err return err
} }
@@ -145,16 +146,16 @@ func (p *Pool) InsertAttesterSlashing(
// Check if the validator already exists in the list of slashings. // Check if the validator already exists in the list of slashings.
// Use binary search to find the answer. // Use binary search to find the answer.
found := sort.Search(len(p.pendingAttesterSlashing), func(i int) bool { found := sort.Search(len(p.pendingAttesterSlashing), func(i int) bool {
return p.pendingAttesterSlashing[i].validatorToSlash >= val return uint64(p.pendingAttesterSlashing[i].validatorToSlash) >= val
}) })
if found != len(p.pendingAttesterSlashing) && p.pendingAttesterSlashing[found].validatorToSlash == val { if found != len(p.pendingAttesterSlashing) && uint64(p.pendingAttesterSlashing[found].validatorToSlash) == val {
cantSlash = append(cantSlash, val) cantSlash = append(cantSlash, val)
continue continue
} }
pendingSlashing := &PendingAttesterSlashing{ pendingSlashing := &PendingAttesterSlashing{
attesterSlashing: slashing, attesterSlashing: slashing,
validatorToSlash: val, validatorToSlash: types.ValidatorIndex(val),
} }
// Insert into pending list and sort again. // Insert into pending list and sort again.
p.pendingAttesterSlashing = append(p.pendingAttesterSlashing, pendingSlashing) p.pendingAttesterSlashing = append(p.pendingAttesterSlashing, pendingSlashing)
@@ -226,12 +227,12 @@ func (p *Pool) MarkIncludedAttesterSlashing(as *ethpb.AttesterSlashing) {
slashedVal := sliceutil.IntersectionUint64(as.Attestation_1.AttestingIndices, as.Attestation_2.AttestingIndices) slashedVal := sliceutil.IntersectionUint64(as.Attestation_1.AttestingIndices, as.Attestation_2.AttestingIndices)
for _, val := range slashedVal { for _, val := range slashedVal {
i := sort.Search(len(p.pendingAttesterSlashing), func(i int) bool { i := sort.Search(len(p.pendingAttesterSlashing), func(i int) bool {
return p.pendingAttesterSlashing[i].validatorToSlash >= val return uint64(p.pendingAttesterSlashing[i].validatorToSlash) >= val
}) })
if i != len(p.pendingAttesterSlashing) && p.pendingAttesterSlashing[i].validatorToSlash == val { if i != len(p.pendingAttesterSlashing) && uint64(p.pendingAttesterSlashing[i].validatorToSlash) == val {
p.pendingAttesterSlashing = append(p.pendingAttesterSlashing[:i], p.pendingAttesterSlashing[i+1:]...) p.pendingAttesterSlashing = append(p.pendingAttesterSlashing[:i], p.pendingAttesterSlashing[i+1:]...)
} }
p.included[val] = true p.included[types.ValidatorIndex(val)] = true
numAttesterSlashingsIncluded.Inc() numAttesterSlashingsIncluded.Inc()
} }
} }
@@ -258,7 +259,7 @@ func (p *Pool) MarkIncludedProposerSlashing(ps *ethpb.ProposerSlashing) {
// Note: this method requires caller to hold the lock. // Note: this method requires caller to hold the lock.
func (p *Pool) validatorSlashingPreconditionCheck( func (p *Pool) validatorSlashingPreconditionCheck(
state *beaconstate.BeaconState, state *beaconstate.BeaconState,
valIdx uint64, valIdx types.ValidatorIndex,
) (bool, error) { ) (bool, error) {
if !mutexasserts.RWMutexLocked(&p.lock) && !mutexasserts.RWMutexRLocked(&p.lock) { if !mutexasserts.RWMutexLocked(&p.lock) && !mutexasserts.RWMutexRLocked(&p.lock) {
return false, errors.New("pool.validatorSlashingPreconditionCheck: caller must hold read/write lock") return false, errors.New("pool.validatorSlashingPreconditionCheck: caller must hold read/write lock")

View File

@@ -4,20 +4,20 @@ import (
"context" "context"
"testing" "testing"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/bls" "github.com/prysmaticlabs/prysm/shared/bls"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require" "github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
func validAttesterSlashingForValIdx(t *testing.T, beaconState *state.BeaconState, privs []bls.SecretKey, valIdx ...uint64) *ethpb.AttesterSlashing { func validAttesterSlashingForValIdx(t *testing.T, beaconState *state.BeaconState, privs []bls.SecretKey, valIdx ...uint64) *ethpb.AttesterSlashing {
var slashings []*ethpb.AttesterSlashing var slashings []*ethpb.AttesterSlashing
for _, idx := range valIdx { for _, idx := range valIdx {
slashing, err := testutil.GenerateAttesterSlashingForValidator(beaconState, privs[idx], idx) slashing, err := testutil.GenerateAttesterSlashingForValidator(beaconState, privs[idx], types.ValidatorIndex(idx))
require.NoError(t, err) require.NoError(t, err)
slashings = append(slashings, slashing) slashings = append(slashings, slashing)
} }
@@ -60,14 +60,14 @@ func attesterSlashingForValIdx(valIdx ...uint64) *ethpb.AttesterSlashing {
func pendingSlashingForValIdx(valIdx ...uint64) *PendingAttesterSlashing { func pendingSlashingForValIdx(valIdx ...uint64) *PendingAttesterSlashing {
return &PendingAttesterSlashing{ return &PendingAttesterSlashing{
attesterSlashing: attesterSlashingForValIdx(valIdx...), attesterSlashing: attesterSlashingForValIdx(valIdx...),
validatorToSlash: valIdx[0], validatorToSlash: types.ValidatorIndex(valIdx[0]),
} }
} }
func TestPool_InsertAttesterSlashing(t *testing.T) { func TestPool_InsertAttesterSlashing(t *testing.T) {
type fields struct { type fields struct {
pending []*PendingAttesterSlashing pending []*PendingAttesterSlashing
included map[uint64]bool included map[types.ValidatorIndex]bool
wantErr []bool wantErr []bool
} }
type args struct { type args struct {
@@ -78,33 +78,33 @@ func TestPool_InsertAttesterSlashing(t *testing.T) {
pendingSlashings := make([]*PendingAttesterSlashing, 20) pendingSlashings := make([]*PendingAttesterSlashing, 20)
slashings := make([]*ethpb.AttesterSlashing, 20) slashings := make([]*ethpb.AttesterSlashing, 20)
for i := 0; i < len(pendingSlashings); i++ { for i := 0; i < len(pendingSlashings); i++ {
sl, err := testutil.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], uint64(i)) sl, err := testutil.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i))
require.NoError(t, err) require.NoError(t, err)
pendingSlashings[i] = &PendingAttesterSlashing{ pendingSlashings[i] = &PendingAttesterSlashing{
attesterSlashing: sl, attesterSlashing: sl,
validatorToSlash: uint64(i), validatorToSlash: types.ValidatorIndex(i),
} }
slashings[i] = sl slashings[i] = sl
} }
require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch)) require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch))
// We mark the following validators with some preconditions. // We mark the following validators with some preconditions.
exitedVal, err := beaconState.ValidatorAtIndex(uint64(2)) exitedVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(2))
require.NoError(t, err) require.NoError(t, err)
exitedVal.WithdrawableEpoch = 0 exitedVal.WithdrawableEpoch = 0
require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(2), exitedVal)) require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(2), exitedVal))
futureWithdrawVal, err := beaconState.ValidatorAtIndex(uint64(4)) futureWithdrawVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(4))
require.NoError(t, err) require.NoError(t, err)
futureWithdrawVal.WithdrawableEpoch = 17 futureWithdrawVal.WithdrawableEpoch = 17
require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(4), futureWithdrawVal)) require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(4), futureWithdrawVal))
slashedVal, err := beaconState.ValidatorAtIndex(uint64(5)) slashedVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(5))
require.NoError(t, err) require.NoError(t, err)
slashedVal.Slashed = true slashedVal.Slashed = true
require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(5), slashedVal)) require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(5), slashedVal))
slashedVal2, err := beaconState.ValidatorAtIndex(uint64(21)) slashedVal2, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(21))
require.NoError(t, err) require.NoError(t, err)
slashedVal2.Slashed = true slashedVal2.Slashed = true
require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(21), slashedVal2)) require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(21), slashedVal2))
aggSlashing1 := validAttesterSlashingForValIdx(t, beaconState, privKeys, 0, 1, 2) aggSlashing1 := validAttesterSlashingForValIdx(t, beaconState, privKeys, 0, 1, 2)
aggSlashing2 := validAttesterSlashingForValIdx(t, beaconState, privKeys, 5, 9, 13) aggSlashing2 := validAttesterSlashingForValIdx(t, beaconState, privKeys, 5, 9, 13)
@@ -122,7 +122,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) {
name: "Empty list", name: "Empty list",
fields: fields{ fields: fields{
pending: make([]*PendingAttesterSlashing, 0), pending: make([]*PendingAttesterSlashing, 0),
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
wantErr: []bool{false}, wantErr: []bool{false},
}, },
args: args{ args: args{
@@ -139,7 +139,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) {
name: "Empty list two validators slashed", name: "Empty list two validators slashed",
fields: fields{ fields: fields{
pending: make([]*PendingAttesterSlashing, 0), pending: make([]*PendingAttesterSlashing, 0),
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
wantErr: []bool{false, false}, wantErr: []bool{false, false},
}, },
args: args{ args: args{
@@ -153,7 +153,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) {
pending: []*PendingAttesterSlashing{ pending: []*PendingAttesterSlashing{
pendingSlashings[1], pendingSlashings[1],
}, },
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
wantErr: []bool{true}, wantErr: []bool{true},
}, },
args: args{ args: args{
@@ -165,7 +165,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) {
name: "Slashing for already exit validator", name: "Slashing for already exit validator",
fields: fields{ fields: fields{
pending: []*PendingAttesterSlashing{}, pending: []*PendingAttesterSlashing{},
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
wantErr: []bool{true}, wantErr: []bool{true},
}, },
args: args{ args: args{
@@ -177,7 +177,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) {
name: "Slashing for withdrawable validator", name: "Slashing for withdrawable validator",
fields: fields{ fields: fields{
pending: []*PendingAttesterSlashing{}, pending: []*PendingAttesterSlashing{},
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
wantErr: []bool{true}, wantErr: []bool{true},
}, },
args: args{ args: args{
@@ -189,7 +189,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) {
name: "Slashing for slashed validator", name: "Slashing for slashed validator",
fields: fields{ fields: fields{
pending: []*PendingAttesterSlashing{}, pending: []*PendingAttesterSlashing{},
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
wantErr: []bool{false}, wantErr: []bool{false},
}, },
args: args{ args: args{
@@ -201,7 +201,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) {
name: "Already included", name: "Already included",
fields: fields{ fields: fields{
pending: []*PendingAttesterSlashing{}, pending: []*PendingAttesterSlashing{},
included: map[uint64]bool{ included: map[types.ValidatorIndex]bool{
1: true, 1: true,
}, },
wantErr: []bool{true}, wantErr: []bool{true},
@@ -218,7 +218,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) {
pendingSlashings[0], pendingSlashings[0],
pendingSlashings[2], pendingSlashings[2],
}, },
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
wantErr: []bool{false}, wantErr: []bool{false},
}, },
args: args{ args: args{
@@ -230,7 +230,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) {
name: "Doesn't reject partially slashed slashings", name: "Doesn't reject partially slashed slashings",
fields: fields{ fields: fields{
pending: []*PendingAttesterSlashing{}, pending: []*PendingAttesterSlashing{},
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
wantErr: []bool{false, false, false, true}, wantErr: []bool{false, false, false, true},
}, },
args: args{ args: args{
@@ -303,11 +303,11 @@ func TestPool_InsertAttesterSlashing_SigFailsVerify_ClearPool(t *testing.T) {
pendingSlashings := make([]*PendingAttesterSlashing, 2) pendingSlashings := make([]*PendingAttesterSlashing, 2)
slashings := make([]*ethpb.AttesterSlashing, 2) slashings := make([]*ethpb.AttesterSlashing, 2)
for i := 0; i < 2; i++ { for i := 0; i < 2; i++ {
sl, err := testutil.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], uint64(i)) sl, err := testutil.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i))
require.NoError(t, err) require.NoError(t, err)
pendingSlashings[i] = &PendingAttesterSlashing{ pendingSlashings[i] = &PendingAttesterSlashing{
attesterSlashing: sl, attesterSlashing: sl,
validatorToSlash: uint64(i), validatorToSlash: types.ValidatorIndex(i),
} }
slashings[i] = sl slashings[i] = sl
} }
@@ -328,7 +328,7 @@ func TestPool_InsertAttesterSlashing_SigFailsVerify_ClearPool(t *testing.T) {
func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { func TestPool_MarkIncludedAttesterSlashing(t *testing.T) {
type fields struct { type fields struct {
pending []*PendingAttesterSlashing pending []*PendingAttesterSlashing
included map[uint64]bool included map[types.ValidatorIndex]bool
} }
type args struct { type args struct {
slashing *ethpb.AttesterSlashing slashing *ethpb.AttesterSlashing
@@ -348,7 +348,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) {
validatorToSlash: 1, validatorToSlash: 1,
}, },
}, },
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
}, },
args: args{ args: args{
slashing: attesterSlashingForValIdx(3), slashing: attesterSlashingForValIdx(3),
@@ -357,7 +357,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) {
pending: []*PendingAttesterSlashing{ pending: []*PendingAttesterSlashing{
pendingSlashingForValIdx(1), pendingSlashingForValIdx(1),
}, },
included: map[uint64]bool{ included: map[types.ValidatorIndex]bool{
3: true, 3: true,
}, },
}, },
@@ -370,7 +370,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) {
pendingSlashingForValIdx(2), pendingSlashingForValIdx(2),
pendingSlashingForValIdx(3), pendingSlashingForValIdx(3),
}, },
included: map[uint64]bool{ included: map[types.ValidatorIndex]bool{
0: true, 0: true,
}, },
}, },
@@ -382,7 +382,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) {
pendingSlashingForValIdx(1), pendingSlashingForValIdx(1),
pendingSlashingForValIdx(3), pendingSlashingForValIdx(3),
}, },
included: map[uint64]bool{ included: map[types.ValidatorIndex]bool{
0: true, 0: true,
2: true, 2: true,
}, },
@@ -404,7 +404,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) {
pendingSlashingForValIdx(10), pendingSlashingForValIdx(10),
pendingSlashingForValIdx(11), pendingSlashingForValIdx(11),
}, },
included: map[uint64]bool{ included: map[types.ValidatorIndex]bool{
0: true, 0: true,
}, },
}, },
@@ -424,7 +424,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) {
pendingSlashingForValIdx(10), pendingSlashingForValIdx(10),
pendingSlashingForValIdx(11), pendingSlashingForValIdx(11),
}, },
included: map[uint64]bool{ included: map[types.ValidatorIndex]bool{
0: true, 0: true,
6: true, 6: true,
}, },
@@ -457,11 +457,11 @@ func TestPool_PendingAttesterSlashings(t *testing.T) {
pendingSlashings := make([]*PendingAttesterSlashing, 20) pendingSlashings := make([]*PendingAttesterSlashing, 20)
slashings := make([]*ethpb.AttesterSlashing, 20) slashings := make([]*ethpb.AttesterSlashing, 20)
for i := 0; i < len(pendingSlashings); i++ { for i := 0; i < len(pendingSlashings); i++ {
sl, err := testutil.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], uint64(i)) sl, err := testutil.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i))
require.NoError(t, err) require.NoError(t, err)
pendingSlashings[i] = &PendingAttesterSlashing{ pendingSlashings[i] = &PendingAttesterSlashing{
attesterSlashing: sl, attesterSlashing: sl,
validatorToSlash: uint64(i), validatorToSlash: types.ValidatorIndex(i),
} }
slashings[i] = sl slashings[i] = sl
} }
@@ -532,15 +532,15 @@ func TestPool_PendingAttesterSlashings_Slashed(t *testing.T) {
pendingSlashings2 := make([]*PendingAttesterSlashing, 20) pendingSlashings2 := make([]*PendingAttesterSlashing, 20)
slashings := make([]*ethpb.AttesterSlashing, 20) slashings := make([]*ethpb.AttesterSlashing, 20)
for i := 0; i < len(pendingSlashings); i++ { for i := 0; i < len(pendingSlashings); i++ {
sl, err := testutil.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], uint64(i)) sl, err := testutil.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i))
require.NoError(t, err) require.NoError(t, err)
pendingSlashings[i] = &PendingAttesterSlashing{ pendingSlashings[i] = &PendingAttesterSlashing{
attesterSlashing: sl, attesterSlashing: sl,
validatorToSlash: uint64(i), validatorToSlash: types.ValidatorIndex(i),
} }
pendingSlashings2[i] = &PendingAttesterSlashing{ pendingSlashings2[i] = &PendingAttesterSlashing{
attesterSlashing: sl, attesterSlashing: sl,
validatorToSlash: uint64(i), validatorToSlash: types.ValidatorIndex(i),
} }
slashings[i] = sl slashings[i] = sl
} }
@@ -590,11 +590,11 @@ func TestPool_PendingAttesterSlashings_NoDuplicates(t *testing.T) {
pendingSlashings := make([]*PendingAttesterSlashing, 3) pendingSlashings := make([]*PendingAttesterSlashing, 3)
slashings := make([]*ethpb.AttesterSlashing, 3) slashings := make([]*ethpb.AttesterSlashing, 3)
for i := 0; i < 2; i++ { for i := 0; i < 2; i++ {
sl, err := testutil.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], uint64(i)) sl, err := testutil.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i))
require.NoError(t, err) require.NoError(t, err)
pendingSlashings[i] = &PendingAttesterSlashing{ pendingSlashings[i] = &PendingAttesterSlashing{
attesterSlashing: sl, attesterSlashing: sl,
validatorToSlash: uint64(i), validatorToSlash: types.ValidatorIndex(i),
} }
slashings[i] = sl slashings[i] = sl
} }

View File

@@ -4,6 +4,7 @@ import (
"context" "context"
"testing" "testing"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil"
@@ -11,7 +12,7 @@ import (
"github.com/prysmaticlabs/prysm/shared/testutil/require" "github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
func proposerSlashingForValIdx(valIdx uint64) *ethpb.ProposerSlashing { func proposerSlashingForValIdx(valIdx types.ValidatorIndex) *ethpb.ProposerSlashing {
return &ethpb.ProposerSlashing{ return &ethpb.ProposerSlashing{
Header_1: &ethpb.SignedBeaconBlockHeader{ Header_1: &ethpb.SignedBeaconBlockHeader{
Header: &ethpb.BeaconBlockHeader{ProposerIndex: valIdx}, Header: &ethpb.BeaconBlockHeader{ProposerIndex: valIdx},
@@ -26,7 +27,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
type fields struct { type fields struct {
wantedErr string wantedErr string
pending []*ethpb.ProposerSlashing pending []*ethpb.ProposerSlashing
included map[uint64]bool included map[types.ValidatorIndex]bool
} }
type args struct { type args struct {
slashings []*ethpb.ProposerSlashing slashings []*ethpb.ProposerSlashing
@@ -35,7 +36,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
beaconState, privKeys := testutil.DeterministicGenesisState(t, 64) beaconState, privKeys := testutil.DeterministicGenesisState(t, 64)
slashings := make([]*ethpb.ProposerSlashing, 20) slashings := make([]*ethpb.ProposerSlashing, 20)
for i := 0; i < len(slashings); i++ { for i := 0; i < len(slashings); i++ {
sl, err := testutil.GenerateProposerSlashingForValidator(beaconState, privKeys[i], uint64(i)) sl, err := testutil.GenerateProposerSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i))
require.NoError(t, err) require.NoError(t, err)
slashings[i] = sl slashings[i] = sl
} }
@@ -43,18 +44,18 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch)) require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch))
// We mark the following validators with some preconditions. // We mark the following validators with some preconditions.
exitedVal, err := beaconState.ValidatorAtIndex(uint64(2)) exitedVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(2))
require.NoError(t, err) require.NoError(t, err)
exitedVal.WithdrawableEpoch = 0 exitedVal.WithdrawableEpoch = 0
futureExitedVal, err := beaconState.ValidatorAtIndex(uint64(4)) futureExitedVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(4))
require.NoError(t, err) require.NoError(t, err)
futureExitedVal.WithdrawableEpoch = 17 futureExitedVal.WithdrawableEpoch = 17
slashedVal, err := beaconState.ValidatorAtIndex(uint64(5)) slashedVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(5))
require.NoError(t, err) require.NoError(t, err)
slashedVal.Slashed = true slashedVal.Slashed = true
require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(2), exitedVal)) require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(2), exitedVal))
require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(4), futureExitedVal)) require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(4), futureExitedVal))
require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(5), slashedVal)) require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(5), slashedVal))
tests := []struct { tests := []struct {
name string name string
@@ -66,7 +67,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
name: "Empty list", name: "Empty list",
fields: fields{ fields: fields{
pending: make([]*ethpb.ProposerSlashing, 0), pending: make([]*ethpb.ProposerSlashing, 0),
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
}, },
args: args{ args: args{
slashings: slashings[0:1], slashings: slashings[0:1],
@@ -77,7 +78,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
name: "Duplicate identical slashing", name: "Duplicate identical slashing",
fields: fields{ fields: fields{
pending: slashings[0:1], pending: slashings[0:1],
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
wantedErr: "slashing object already exists in pending proposer slashings", wantedErr: "slashing object already exists in pending proposer slashings",
}, },
args: args{ args: args{
@@ -89,7 +90,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
name: "Slashing for exited validator", name: "Slashing for exited validator",
fields: fields{ fields: fields{
pending: []*ethpb.ProposerSlashing{}, pending: []*ethpb.ProposerSlashing{},
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
wantedErr: "is not slashable", wantedErr: "is not slashable",
}, },
args: args{ args: args{
@@ -101,7 +102,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
name: "Slashing for exiting validator", name: "Slashing for exiting validator",
fields: fields{ fields: fields{
pending: []*ethpb.ProposerSlashing{}, pending: []*ethpb.ProposerSlashing{},
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
}, },
args: args{ args: args{
slashings: slashings[4:5], slashings: slashings[4:5],
@@ -112,7 +113,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
name: "Slashing for slashed validator", name: "Slashing for slashed validator",
fields: fields{ fields: fields{
pending: []*ethpb.ProposerSlashing{}, pending: []*ethpb.ProposerSlashing{},
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
wantedErr: "not slashable", wantedErr: "not slashable",
}, },
args: args{ args: args{
@@ -124,7 +125,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
name: "Already included", name: "Already included",
fields: fields{ fields: fields{
pending: []*ethpb.ProposerSlashing{}, pending: []*ethpb.ProposerSlashing{},
included: map[uint64]bool{ included: map[types.ValidatorIndex]bool{
1: true, 1: true,
}, },
wantedErr: "cannot be slashed", wantedErr: "cannot be slashed",
@@ -141,7 +142,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
slashings[0], slashings[0],
slashings[2], slashings[2],
}, },
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
}, },
args: args{ args: args{
slashings: slashings[1:2], slashings: slashings[1:2],
@@ -185,7 +186,7 @@ func TestPool_InsertProposerSlashing_SigFailsVerify_ClearPool(t *testing.T) {
beaconState, privKeys := testutil.DeterministicGenesisState(t, 64) beaconState, privKeys := testutil.DeterministicGenesisState(t, 64)
slashings := make([]*ethpb.ProposerSlashing, 2) slashings := make([]*ethpb.ProposerSlashing, 2)
for i := 0; i < 2; i++ { for i := 0; i < 2; i++ {
sl, err := testutil.GenerateProposerSlashingForValidator(beaconState, privKeys[i], uint64(i)) sl, err := testutil.GenerateProposerSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i))
require.NoError(t, err) require.NoError(t, err)
slashings[i] = sl slashings[i] = sl
} }
@@ -206,7 +207,7 @@ func TestPool_InsertProposerSlashing_SigFailsVerify_ClearPool(t *testing.T) {
func TestPool_MarkIncludedProposerSlashing(t *testing.T) { func TestPool_MarkIncludedProposerSlashing(t *testing.T) {
type fields struct { type fields struct {
pending []*ethpb.ProposerSlashing pending []*ethpb.ProposerSlashing
included map[uint64]bool included map[types.ValidatorIndex]bool
} }
type args struct { type args struct {
slashing *ethpb.ProposerSlashing slashing *ethpb.ProposerSlashing
@@ -223,7 +224,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) {
pending: []*ethpb.ProposerSlashing{ pending: []*ethpb.ProposerSlashing{
proposerSlashingForValIdx(1), proposerSlashingForValIdx(1),
}, },
included: make(map[uint64]bool), included: make(map[types.ValidatorIndex]bool),
}, },
args: args{ args: args{
slashing: proposerSlashingForValIdx(3), slashing: proposerSlashingForValIdx(3),
@@ -232,7 +233,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) {
pending: []*ethpb.ProposerSlashing{ pending: []*ethpb.ProposerSlashing{
proposerSlashingForValIdx(1), proposerSlashingForValIdx(1),
}, },
included: map[uint64]bool{ included: map[types.ValidatorIndex]bool{
3: true, 3: true,
}, },
}, },
@@ -245,7 +246,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) {
proposerSlashingForValIdx(2), proposerSlashingForValIdx(2),
proposerSlashingForValIdx(3), proposerSlashingForValIdx(3),
}, },
included: map[uint64]bool{ included: map[types.ValidatorIndex]bool{
0: true, 0: true,
}, },
}, },
@@ -257,7 +258,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) {
proposerSlashingForValIdx(1), proposerSlashingForValIdx(1),
proposerSlashingForValIdx(3), proposerSlashingForValIdx(3),
}, },
included: map[uint64]bool{ included: map[types.ValidatorIndex]bool{
0: true, 0: true,
2: true, 2: true,
}, },
@@ -278,7 +279,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) {
proposerSlashingForValIdx(9), proposerSlashingForValIdx(9),
proposerSlashingForValIdx(10), proposerSlashingForValIdx(10),
}, },
included: map[uint64]bool{ included: map[types.ValidatorIndex]bool{
0: true, 0: true,
}, },
}, },
@@ -297,7 +298,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) {
proposerSlashingForValIdx(9), proposerSlashingForValIdx(9),
proposerSlashingForValIdx(10), proposerSlashingForValIdx(10),
}, },
included: map[uint64]bool{ included: map[types.ValidatorIndex]bool{
0: true, 0: true,
7: true, 7: true,
}, },
@@ -328,7 +329,7 @@ func TestPool_PendingProposerSlashings(t *testing.T) {
beaconState, privKeys := testutil.DeterministicGenesisState(t, 64) beaconState, privKeys := testutil.DeterministicGenesisState(t, 64)
slashings := make([]*ethpb.ProposerSlashing, 20) slashings := make([]*ethpb.ProposerSlashing, 20)
for i := 0; i < len(slashings); i++ { for i := 0; i < len(slashings); i++ {
sl, err := testutil.GenerateProposerSlashingForValidator(beaconState, privKeys[i], uint64(i)) sl, err := testutil.GenerateProposerSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i))
require.NoError(t, err) require.NoError(t, err)
slashings[i] = sl slashings[i] = sl
} }
@@ -395,7 +396,7 @@ func TestPool_PendingProposerSlashings_Slashed(t *testing.T) {
slashings2 := make([]*ethpb.ProposerSlashing, 32) slashings2 := make([]*ethpb.ProposerSlashing, 32)
result := make([]*ethpb.ProposerSlashing, 32) result := make([]*ethpb.ProposerSlashing, 32)
for i := 0; i < len(slashings); i++ { for i := 0; i < len(slashings); i++ {
sl, err := testutil.GenerateProposerSlashingForValidator(beaconState, privKeys[i], uint64(i)) sl, err := testutil.GenerateProposerSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i))
require.NoError(t, err) require.NoError(t, err)
slashings[i] = sl slashings[i] = sl
slashings2[i] = sl slashings2[i] = sl

View File

@@ -3,6 +3,7 @@ package slashings
import ( import (
"sync" "sync"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
) )
@@ -12,12 +13,12 @@ type Pool struct {
lock sync.RWMutex lock sync.RWMutex
pendingProposerSlashing []*ethpb.ProposerSlashing pendingProposerSlashing []*ethpb.ProposerSlashing
pendingAttesterSlashing []*PendingAttesterSlashing pendingAttesterSlashing []*PendingAttesterSlashing
included map[uint64]bool included map[types.ValidatorIndex]bool
} }
// PendingAttesterSlashing represents an attester slashing in the operation pool. // PendingAttesterSlashing represents an attester slashing in the operation pool.
// Allows for easy binary searching of included validator indexes. // Allows for easy binary searching of included validator indexes.
type PendingAttesterSlashing struct { type PendingAttesterSlashing struct {
attesterSlashing *ethpb.AttesterSlashing attesterSlashing *ethpb.AttesterSlashing
validatorToSlash uint64 validatorToSlash types.ValidatorIndex
} }

View File

@@ -107,7 +107,7 @@ func (p *Pool) MarkIncluded(exit *ethpb.SignedVoluntaryExit) {
} }
// Binary search to check if the index exists in the list of pending exits. // Binary search to check if the index exists in the list of pending exits.
func existsInList(pending []*ethpb.SignedVoluntaryExit, searchingFor uint64) (bool, int) { func existsInList(pending []*ethpb.SignedVoluntaryExit, searchingFor types.ValidatorIndex) (bool, int) {
i := sort.Search(len(pending), func(j int) bool { i := sort.Search(len(pending), func(j int) bool {
return pending[j].Exit.ValidatorIndex >= searchingFor return pending[j].Exit.ValidatorIndex >= searchingFor
}) })

View File

@@ -91,6 +91,7 @@ go_test(
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library", "@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_ethereum_go_ethereum//core/types:go_default_library", "@com_github_ethereum_go_ethereum//core/types:go_default_library",
"@com_github_ethereum_go_ethereum//trie:go_default_library", "@com_github_ethereum_go_ethereum//trie:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library",
"@com_github_sirupsen_logrus//hooks/test:go_default_library", "@com_github_sirupsen_logrus//hooks/test:go_default_library",

View File

@@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"testing" "testing"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
@@ -259,7 +260,7 @@ func TestProcessDeposit_AllDepositedSuccessfully(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, uint64(i+1), valCount, "Did not get correct active validator count") require.Equal(t, uint64(i+1), valCount, "Did not get correct active validator count")
val, err := web3Service.preGenesisState.ValidatorAtIndex(uint64(i)) val, err := web3Service.preGenesisState.ValidatorAtIndex(types.ValidatorIndex(i))
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, params.BeaconConfig().MaxEffectiveBalance, val.EffectiveBalance) assert.Equal(t, params.BeaconConfig().MaxEffectiveBalance, val.EffectiveBalance)
} }

View File

@@ -29,8 +29,8 @@ func (bs *Server) ListValidatorAssignments(
} }
var res []*ethpb.ValidatorAssignments_CommitteeAssignment var res []*ethpb.ValidatorAssignments_CommitteeAssignment
filtered := map[uint64]bool{} // track filtered validators to prevent duplication in the response. filtered := map[types.ValidatorIndex]bool{} // track filtered validators to prevent duplication in the response.
filteredIndices := make([]uint64, 0) filteredIndices := make([]types.ValidatorIndex, 0)
var requestedEpoch types.Epoch var requestedEpoch types.Epoch
switch q := req.QueryFilter.(type) { switch q := req.QueryFilter.(type) {
case *ethpb.ListValidatorAssignmentsRequest_Genesis: case *ethpb.ListValidatorAssignmentsRequest_Genesis:
@@ -105,7 +105,7 @@ func (bs *Server) ListValidatorAssignments(
} }
for _, index := range filteredIndices[start:end] { for _, index := range filteredIndices[start:end] {
if index >= uint64(requestedState.NumValidators()) { if uint64(index) >= uint64(requestedState.NumValidators()) {
return nil, status.Errorf(codes.OutOfRange, "Validator index %d >= validator count %d", return nil, status.Errorf(codes.OutOfRange, "Validator index %d >= validator count %d",
index, requestedState.NumValidators()) index, requestedState.NumValidators())
} }

View File

@@ -8,6 +8,7 @@ import (
"testing" "testing"
"github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/proto"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
@@ -267,7 +268,7 @@ func TestServer_ListAssignments_FilterPubkeysIndices_NoPagination(t *testing.T)
binary.LittleEndian.PutUint64(pubKey1, 1) binary.LittleEndian.PutUint64(pubKey1, 1)
pubKey2 := make([]byte, params.BeaconConfig().BLSPubkeyLength) pubKey2 := make([]byte, params.BeaconConfig().BLSPubkeyLength)
binary.LittleEndian.PutUint64(pubKey2, 2) binary.LittleEndian.PutUint64(pubKey2, 2)
req := &ethpb.ListValidatorAssignmentsRequest{PublicKeys: [][]byte{pubKey1, pubKey2}, Indices: []uint64{2, 3}} req := &ethpb.ListValidatorAssignmentsRequest{PublicKeys: [][]byte{pubKey1, pubKey2}, Indices: []types.ValidatorIndex{2, 3}}
res, err := bs.ListValidatorAssignments(context.Background(), req) res, err := bs.ListValidatorAssignments(context.Background(), req)
require.NoError(t, err) require.NoError(t, err)
@@ -332,7 +333,7 @@ func TestServer_ListAssignments_CanFilterPubkeysIndices_WithPagination(t *testin
StateGen: stategen.New(db), StateGen: stategen.New(db),
} }
req := &ethpb.ListValidatorAssignmentsRequest{Indices: []uint64{1, 2, 3, 4, 5, 6}, PageSize: 2, PageToken: "1"} req := &ethpb.ListValidatorAssignmentsRequest{Indices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}, PageSize: 2, PageToken: "1"}
res, err := bs.ListValidatorAssignments(context.Background(), req) res, err := bs.ListValidatorAssignments(context.Background(), req)
require.NoError(t, err) require.NoError(t, err)
@@ -366,7 +367,7 @@ func TestServer_ListAssignments_CanFilterPubkeysIndices_WithPagination(t *testin
// Test the wrap around scenario. // Test the wrap around scenario.
assignments = nil assignments = nil
req = &ethpb.ListValidatorAssignmentsRequest{Indices: []uint64{1, 2, 3, 4, 5, 6}, PageSize: 5, PageToken: "1"} req = &ethpb.ListValidatorAssignmentsRequest{Indices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}, PageSize: 5, PageToken: "1"}
res, err = bs.ListValidatorAssignments(context.Background(), req) res, err = bs.ListValidatorAssignments(context.Background(), req)
require.NoError(t, err) require.NoError(t, err)
cAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(s, 0) cAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(s, 0)

View File

@@ -874,7 +874,7 @@ func TestServer_StreamIndexedAttestations_OK(t *testing.T) {
var found bool var found bool
for comIndex, item := range comms { for comIndex, item := range comms {
for n, idx := range item.ValidatorIndices { for n, idx := range item.ValidatorIndices {
if uint64(j) == idx { if types.ValidatorIndex(j) == idx {
indexInCommittee = uint64(n) indexInCommittee = uint64(n)
committeeIndex = types.CommitteeIndex(comIndex) committeeIndex = types.CommitteeIndex(comIndex)
committeeLength = len(item.ValidatorIndices) committeeLength = len(item.ValidatorIndices)

View File

@@ -67,7 +67,7 @@ func (bs *Server) ListBeaconCommittees(
func (bs *Server) retrieveCommitteesForEpoch( func (bs *Server) retrieveCommitteesForEpoch(
ctx context.Context, ctx context.Context,
epoch types.Epoch, epoch types.Epoch,
) (SlotToCommiteesMap, []uint64, error) { ) (SlotToCommiteesMap, []types.ValidatorIndex, error) {
startSlot, err := helpers.StartSlot(epoch) startSlot, err := helpers.StartSlot(epoch)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
@@ -103,7 +103,7 @@ func (bs *Server) retrieveCommitteesForEpoch(
func (bs *Server) retrieveCommitteesForRoot( func (bs *Server) retrieveCommitteesForRoot(
ctx context.Context, ctx context.Context,
root []byte, root []byte,
) (SlotToCommiteesMap, []uint64, error) { ) (SlotToCommiteesMap, []types.ValidatorIndex, error) {
requestedState, err := bs.StateGen.StateByRoot(ctx, bytesutil.ToBytes32(root)) requestedState, err := bs.StateGen.StateByRoot(ctx, bytesutil.ToBytes32(root))
if err != nil { if err != nil {
return nil, nil, status.Error(codes.Internal, fmt.Sprintf("Could not get state: %v", err)) return nil, nil, status.Error(codes.Internal, fmt.Sprintf("Could not get state: %v", err))
@@ -138,7 +138,7 @@ func (bs *Server) retrieveCommitteesForRoot(
// the attester seeds value. // the attester seeds value.
func computeCommittees( func computeCommittees(
startSlot types.Slot, startSlot types.Slot,
activeIndices []uint64, activeIndices []types.ValidatorIndex,
attesterSeed [32]byte, attesterSeed [32]byte,
) (SlotToCommiteesMap, error) { ) (SlotToCommiteesMap, error) {
committeesListsBySlot := make(SlotToCommiteesMap, params.BeaconConfig().SlotsPerEpoch) committeesListsBySlot := make(SlotToCommiteesMap, params.BeaconConfig().SlotsPerEpoch)

View File

@@ -3,9 +3,9 @@ package beacon
import ( import (
"context" "context"
"github.com/prysmaticlabs/prysm/shared/featureconfig" types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/sliceutil" "github.com/prysmaticlabs/prysm/shared/sliceutil"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
@@ -32,7 +32,7 @@ func (bs *Server) SubmitProposerSlashing(
} }
return &ethpb.SubmitSlashingResponse{ return &ethpb.SubmitSlashingResponse{
SlashedIndices: []uint64{req.Header_1.Header.ProposerIndex}, SlashedIndices: []types.ValidatorIndex{req.Header_1.Header.ProposerIndex},
}, nil }, nil
} }
@@ -55,7 +55,11 @@ func (bs *Server) SubmitAttesterSlashing(
return nil, err return nil, err
} }
} }
slashedIndices := sliceutil.IntersectionUint64(req.Attestation_1.AttestingIndices, req.Attestation_2.AttestingIndices) indices := sliceutil.IntersectionUint64(req.Attestation_1.AttestingIndices, req.Attestation_2.AttestingIndices)
slashedIndices := make([]types.ValidatorIndex, len(indices))
for i, index := range indices {
slashedIndices[i] = types.ValidatorIndex(index)
}
return &ethpb.SubmitSlashingResponse{ return &ethpb.SubmitSlashingResponse{
SlashedIndices: slashedIndices, SlashedIndices: slashedIndices,
}, nil }, nil

View File

@@ -5,6 +5,7 @@ import (
"testing" "testing"
"github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/proto"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/shared/featureconfig" "github.com/prysmaticlabs/prysm/shared/featureconfig"
@@ -37,7 +38,7 @@ func TestServer_SubmitProposerSlashing(t *testing.T) {
// We want a proposer slashing for validator with index 2 to // We want a proposer slashing for validator with index 2 to
// be included in the pool. // be included in the pool.
slashing, err := testutil.GenerateProposerSlashingForValidator(st, privs[2], uint64(2)) slashing, err := testutil.GenerateProposerSlashingForValidator(st, privs[2], types.ValidatorIndex(2))
require.NoError(t, err) require.NoError(t, err)
_, err = bs.SubmitProposerSlashing(ctx, slashing) _, err = bs.SubmitProposerSlashing(ctx, slashing)
@@ -65,7 +66,7 @@ func TestServer_SubmitAttesterSlashing(t *testing.T) {
Broadcaster: mb, Broadcaster: mb,
} }
slashing, err := testutil.GenerateAttesterSlashingForValidator(st, privs[2], uint64(2)) slashing, err := testutil.GenerateAttesterSlashingForValidator(st, privs[2], types.ValidatorIndex(2))
require.NoError(t, err) require.NoError(t, err)
// We want the intersection of the slashing attesting indices // We want the intersection of the slashing attesting indices
@@ -99,9 +100,9 @@ func TestServer_SubmitProposerSlashing_DontBroadcast(t *testing.T) {
// We want a proposer slashing for validator with index 2 to // We want a proposer slashing for validator with index 2 to
// be included in the pool. // be included in the pool.
wanted := &ethpb.SubmitSlashingResponse{ wanted := &ethpb.SubmitSlashingResponse{
SlashedIndices: []uint64{2}, SlashedIndices: []types.ValidatorIndex{2},
} }
slashing, err := testutil.GenerateProposerSlashingForValidator(st, privs[2], uint64(2)) slashing, err := testutil.GenerateProposerSlashingForValidator(st, privs[2], types.ValidatorIndex(2))
require.NoError(t, err) require.NoError(t, err)
res, err := bs.SubmitProposerSlashing(ctx, slashing) res, err := bs.SubmitProposerSlashing(ctx, slashing)
@@ -112,7 +113,7 @@ func TestServer_SubmitProposerSlashing_DontBroadcast(t *testing.T) {
assert.Equal(t, false, mb.BroadcastCalled, "Expected broadcast not to be called by default") assert.Equal(t, false, mb.BroadcastCalled, "Expected broadcast not to be called by default")
slashing, err = testutil.GenerateProposerSlashingForValidator(st, privs[5], uint64(5)) slashing, err = testutil.GenerateProposerSlashingForValidator(st, privs[5], types.ValidatorIndex(5))
require.NoError(t, err) require.NoError(t, err)
// We do not want a proposer slashing for an already slashed validator // We do not want a proposer slashing for an already slashed validator
@@ -143,14 +144,14 @@ func TestServer_SubmitAttesterSlashing_DontBroadcast(t *testing.T) {
Broadcaster: mb, Broadcaster: mb,
} }
slashing, err := testutil.GenerateAttesterSlashingForValidator(st, privs[2], uint64(2)) slashing, err := testutil.GenerateAttesterSlashingForValidator(st, privs[2], types.ValidatorIndex(2))
require.NoError(t, err) require.NoError(t, err)
// We want the intersection of the slashing attesting indices // We want the intersection of the slashing attesting indices
// to be slashed, so we expect validators 2 and 3 to be in the response // to be slashed, so we expect validators 2 and 3 to be in the response
// slashed indices. // slashed indices.
wanted := &ethpb.SubmitSlashingResponse{ wanted := &ethpb.SubmitSlashingResponse{
SlashedIndices: []uint64{2}, SlashedIndices: []types.ValidatorIndex{2},
} }
res, err := bs.SubmitAttesterSlashing(ctx, slashing) res, err := bs.SubmitAttesterSlashing(ctx, slashing)
require.NoError(t, err) require.NoError(t, err)
@@ -159,7 +160,7 @@ func TestServer_SubmitAttesterSlashing_DontBroadcast(t *testing.T) {
} }
assert.Equal(t, false, mb.BroadcastCalled, "Expected broadcast not to be called by default") assert.Equal(t, false, mb.BroadcastCalled, "Expected broadcast not to be called by default")
slashing, err = testutil.GenerateAttesterSlashingForValidator(st, privs[5], uint64(5)) slashing, err = testutil.GenerateAttesterSlashingForValidator(st, privs[5], types.ValidatorIndex(5))
require.NoError(t, err) require.NoError(t, err)
// If any of the attesting indices in the slashing object have already // If any of the attesting indices in the slashing object have already
// been slashed, we should fail to insert properly into the attester slashing pool. // been slashed, we should fail to insert properly into the attester slashing pool.

View File

@@ -61,7 +61,7 @@ func (bs *Server) ListValidatorBalances(
) )
} }
res := make([]*ethpb.ValidatorBalances_Balance, 0) res := make([]*ethpb.ValidatorBalances_Balance, 0)
filtered := map[uint64]bool{} // Track filtered validators to prevent duplication in the response. filtered := map[types.ValidatorIndex]bool{} // Track filtered validators to prevent duplication in the response.
startSlot, err := helpers.StartSlot(requestedEpoch) startSlot, err := helpers.StartSlot(requestedEpoch)
if err != nil { if err != nil {
@@ -92,7 +92,7 @@ func (bs *Server) ListValidatorBalances(
} }
filtered[index] = true filtered[index] = true
if index >= uint64(len(balances)) { if uint64(index) >= uint64(len(balances)) {
return nil, status.Errorf(codes.OutOfRange, "Validator index %d >= balance list %d", return nil, status.Errorf(codes.OutOfRange, "Validator index %d >= balance list %d",
index, len(balances)) index, len(balances))
} }
@@ -109,7 +109,7 @@ func (bs *Server) ListValidatorBalances(
} }
for _, index := range req.Indices { for _, index := range req.Indices {
if index >= uint64(len(balances)) { if uint64(index) >= uint64(len(balances)) {
return nil, status.Errorf(codes.OutOfRange, "Validator index %d >= balance list %d", return nil, status.Errorf(codes.OutOfRange, "Validator index %d >= balance list %d",
index, len(balances)) index, len(balances))
} }
@@ -154,12 +154,12 @@ func (bs *Server) ListValidatorBalances(
if len(req.Indices) == 0 && len(req.PublicKeys) == 0 { if len(req.Indices) == 0 && len(req.PublicKeys) == 0 {
// Return everything. // Return everything.
for i := start; i < end; i++ { for i := start; i < end; i++ {
pubkey := requestedState.PubkeyAtIndex(uint64(i)) pubkey := requestedState.PubkeyAtIndex(types.ValidatorIndex(i))
val := vals[i] val := vals[i]
st := validatorStatus(val, requestedEpoch) st := validatorStatus(val, requestedEpoch)
res = append(res, &ethpb.ValidatorBalances_Balance{ res = append(res, &ethpb.ValidatorBalances_Balance{
PublicKey: pubkey[:], PublicKey: pubkey[:],
Index: uint64(i), Index: types.ValidatorIndex(i),
Balance: balances[i], Balance: balances[i],
Status: st.String(), Status: st.String(),
}) })
@@ -285,7 +285,7 @@ func (bs *Server) ListValidators(
}) })
if len(req.PublicKeys) == 0 && len(req.Indices) == 0 { if len(req.PublicKeys) == 0 && len(req.Indices) == 0 {
for i := uint64(0); i < uint64(reqState.NumValidators()); i++ { for i := types.ValidatorIndex(0); uint64(i) < uint64(reqState.NumValidators()); i++ {
val, err := reqState.ValidatorAtIndex(i) val, err := reqState.ValidatorAtIndex(i)
if err != nil { if err != nil {
return nil, status.Errorf(codes.Internal, "Could not get validator: %v", err) return nil, status.Errorf(codes.Internal, "Could not get validator: %v", err)
@@ -341,7 +341,7 @@ func (bs *Server) GetValidator(
ctx context.Context, req *ethpb.GetValidatorRequest, ctx context.Context, req *ethpb.GetValidatorRequest,
) (*ethpb.Validator, error) { ) (*ethpb.Validator, error) {
var requestingIndex bool var requestingIndex bool
var index uint64 var index types.ValidatorIndex
var pubKey []byte var pubKey []byte
switch q := req.QueryFilter.(type) { switch q := req.QueryFilter.(type) {
case *ethpb.GetValidatorRequest_Index: case *ethpb.GetValidatorRequest_Index:
@@ -360,7 +360,7 @@ func (bs *Server) GetValidator(
return nil, status.Errorf(codes.Internal, "Could not get head state: %v", err) return nil, status.Errorf(codes.Internal, "Could not get head state: %v", err)
} }
if requestingIndex { if requestingIndex {
if index >= uint64(headState.NumValidators()) { if uint64(index) >= uint64(headState.NumValidators()) {
return nil, status.Errorf( return nil, status.Errorf(
codes.OutOfRange, codes.OutOfRange,
"Requesting index %d, but there are only %d validators", "Requesting index %d, but there are only %d validators",
@@ -371,7 +371,7 @@ func (bs *Server) GetValidator(
return headState.ValidatorAtIndex(index) return headState.ValidatorAtIndex(index)
} }
pk48 := bytesutil.ToBytes48(pubKey) pk48 := bytesutil.ToBytes48(pubKey)
for i := uint64(0); i < uint64(headState.NumValidators()); i++ { for i := types.ValidatorIndex(0); uint64(i) < uint64(headState.NumValidators()); i++ {
keyFromState := headState.PubkeyAtIndex(i) keyFromState := headState.PubkeyAtIndex(i)
if keyFromState == pk48 { if keyFromState == pk48 {
return headState.ValidatorAtIndex(i) return headState.ValidatorAtIndex(i)
@@ -561,19 +561,19 @@ func (bs *Server) GetValidatorQueue(
} }
// Queue the validators whose eligible to activate and sort them by activation eligibility epoch number. // Queue the validators whose eligible to activate and sort them by activation eligibility epoch number.
// Additionally, determine those validators queued to exit // Additionally, determine those validators queued to exit
awaitingExit := make([]uint64, 0) awaitingExit := make([]types.ValidatorIndex, 0)
exitEpochs := make([]types.Epoch, 0) exitEpochs := make([]types.Epoch, 0)
activationQ := make([]uint64, 0) activationQ := make([]types.ValidatorIndex, 0)
vals := headState.Validators() vals := headState.Validators()
for idx, validator := range vals { for idx, validator := range vals {
eligibleActivated := validator.ActivationEligibilityEpoch != params.BeaconConfig().FarFutureEpoch eligibleActivated := validator.ActivationEligibilityEpoch != params.BeaconConfig().FarFutureEpoch
canBeActive := validator.ActivationEpoch >= helpers.ActivationExitEpoch(headState.FinalizedCheckpointEpoch()) canBeActive := validator.ActivationEpoch >= helpers.ActivationExitEpoch(headState.FinalizedCheckpointEpoch())
if eligibleActivated && canBeActive { if eligibleActivated && canBeActive {
activationQ = append(activationQ, uint64(idx)) activationQ = append(activationQ, types.ValidatorIndex(idx))
} }
if validator.ExitEpoch != params.BeaconConfig().FarFutureEpoch { if validator.ExitEpoch != params.BeaconConfig().FarFutureEpoch {
exitEpochs = append(exitEpochs, validator.ExitEpoch) exitEpochs = append(exitEpochs, validator.ExitEpoch)
awaitingExit = append(awaitingExit, uint64(idx)) awaitingExit = append(awaitingExit, types.ValidatorIndex(idx))
} }
} }
sort.Slice(activationQ, func(i, j int) bool { sort.Slice(activationQ, func(i, j int) bool {
@@ -613,7 +613,7 @@ func (bs *Server) GetValidatorQueue(
// We use the exit queue churn to determine if we have passed a churn limit. // We use the exit queue churn to determine if we have passed a churn limit.
minEpoch := exitQueueEpoch + params.BeaconConfig().MinValidatorWithdrawabilityDelay minEpoch := exitQueueEpoch + params.BeaconConfig().MinValidatorWithdrawabilityDelay
exitQueueIndices := make([]uint64, 0) exitQueueIndices := make([]types.ValidatorIndex, 0)
for _, valIdx := range awaitingExit { for _, valIdx := range awaitingExit {
val := vals[valIdx] val := vals[valIdx]
// Ensure the validator has not yet exited before adding its index to the exit queue. // Ensure the validator has not yet exited before adding its index to the exit queue.
@@ -676,10 +676,10 @@ func (bs *Server) GetValidatorPerformance(
validatorSummary := vp validatorSummary := vp
responseCap := len(req.Indices) + len(req.PublicKeys) responseCap := len(req.Indices) + len(req.PublicKeys)
validatorIndices := make([]uint64, 0, responseCap) validatorIndices := make([]types.ValidatorIndex, 0, responseCap)
missingValidators := make([][]byte, 0, responseCap) missingValidators := make([][]byte, 0, responseCap)
filtered := map[uint64]bool{} // Track filtered validators to prevent duplication in the response. filtered := map[types.ValidatorIndex]bool{} // Track filtered validators to prevent duplication in the response.
// Convert the list of validator public keys to validator indices and add to the indices set. // Convert the list of validator public keys to validator indices and add to the indices set.
for _, pubKey := range req.PublicKeys { for _, pubKey := range req.PublicKeys {
// Skip empty public key. // Skip empty public key.
@@ -729,7 +729,7 @@ func (bs *Server) GetValidatorPerformance(
return nil, status.Errorf(codes.Internal, "could not get validator: %v", err) return nil, status.Errorf(codes.Internal, "could not get validator: %v", err)
} }
pubKey := val.PublicKey() pubKey := val.PublicKey()
if idx >= uint64(len(validatorSummary)) { if uint64(idx) >= uint64(len(validatorSummary)) {
// Not listed in validator summary yet; treat it as missing. // Not listed in validator summary yet; treat it as missing.
missingValidators = append(missingValidators, pubKey[:]) missingValidators = append(missingValidators, pubKey[:])
continue continue
@@ -790,14 +790,14 @@ func (bs *Server) GetIndividualVotes(
return nil, status.Errorf(codes.Internal, "Could not retrieve archived state for epoch %d: %v", req.Epoch, err) return nil, status.Errorf(codes.Internal, "Could not retrieve archived state for epoch %d: %v", req.Epoch, err)
} }
// Track filtered validators to prevent duplication in the response. // Track filtered validators to prevent duplication in the response.
filtered := map[uint64]bool{} filtered := map[types.ValidatorIndex]bool{}
filteredIndices := make([]uint64, 0) filteredIndices := make([]types.ValidatorIndex, 0)
votes := make([]*ethpb.IndividualVotesRespond_IndividualVote, 0, len(req.Indices)+len(req.PublicKeys)) votes := make([]*ethpb.IndividualVotesRespond_IndividualVote, 0, len(req.Indices)+len(req.PublicKeys))
// Filter out assignments by public keys. // Filter out assignments by public keys.
for _, pubKey := range req.PublicKeys { for _, pubKey := range req.PublicKeys {
index, ok := requestedState.ValidatorIndexByPubkey(bytesutil.ToBytes48(pubKey)) index, ok := requestedState.ValidatorIndexByPubkey(bytesutil.ToBytes48(pubKey))
if !ok { if !ok {
votes = append(votes, &ethpb.IndividualVotesRespond_IndividualVote{PublicKey: pubKey, ValidatorIndex: ^uint64(0)}) votes = append(votes, &ethpb.IndividualVotesRespond_IndividualVote{PublicKey: pubKey, ValidatorIndex: types.ValidatorIndex(^uint64(0))})
continue continue
} }
filtered[index] = true filtered[index] = true
@@ -822,7 +822,7 @@ func (bs *Server) GetIndividualVotes(
return nil, status.Errorf(codes.Internal, "Could not pre compute attestations: %v", err) return nil, status.Errorf(codes.Internal, "Could not pre compute attestations: %v", err)
} }
for _, index := range filteredIndices { for _, index := range filteredIndices {
if index >= uint64(len(v)) { if uint64(index) >= uint64(len(v)) {
votes = append(votes, &ethpb.IndividualVotesRespond_IndividualVote{ValidatorIndex: index}) votes = append(votes, &ethpb.IndividualVotesRespond_IndividualVote{ValidatorIndex: index})
continue continue
} }

View File

@@ -383,7 +383,7 @@ func (is *infostream) calculateActivationTimeForPendingValidators(res []*ethpb.V
// Fetch the list of pending validators; count the number of attesting validators. // Fetch the list of pending validators; count the number of attesting validators.
numAttestingValidators := uint64(0) numAttestingValidators := uint64(0)
pendingValidators := make([]uint64, 0, headState.NumValidators()) pendingValidators := make([]types.ValidatorIndex, 0, headState.NumValidators())
err := headState.ReadFromEveryValidator(func(idx int, val state.ReadOnlyValidator) error { err := headState.ReadFromEveryValidator(func(idx int, val state.ReadOnlyValidator) error {
if val.IsNil() { if val.IsNil() {
@@ -462,7 +462,7 @@ func (is *infostream) handleBlockProcessed() {
} }
type indicesSorter struct { type indicesSorter struct {
indices []uint64 indices []types.ValidatorIndex
} }
func (s indicesSorter) Len() int { return len(s.indices) } func (s indicesSorter) Len() int { return len(s.indices) }

View File

@@ -141,7 +141,7 @@ func TestServer_ListValidatorBalances_DefaultResponse_NoArchive(t *testing.T) {
balances[i] = params.BeaconConfig().MaxEffectiveBalance balances[i] = params.BeaconConfig().MaxEffectiveBalance
balancesResponse[i] = &ethpb.ValidatorBalances_Balance{ balancesResponse[i] = &ethpb.ValidatorBalances_Balance{
PublicKey: pubKey(uint64(i)), PublicKey: pubKey(uint64(i)),
Index: uint64(i), Index: types.ValidatorIndex(i),
Balance: params.BeaconConfig().MaxEffectiveBalance, Balance: params.BeaconConfig().MaxEffectiveBalance,
Status: "EXITED", Status: "EXITED",
} }
@@ -254,7 +254,7 @@ func TestServer_ListValidatorBalances_Pagination_Default(t *testing.T) {
TotalSize: 1, TotalSize: 1,
}, },
}, },
{req: &ethpb.ListValidatorBalancesRequest{Indices: []uint64{1, 2, 3}, QueryFilter: &ethpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, {req: &ethpb.ListValidatorBalancesRequest{Indices: []types.ValidatorIndex{1, 2, 3}, QueryFilter: &ethpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}},
res: &ethpb.ValidatorBalances{ res: &ethpb.ValidatorBalances{
Balances: []*ethpb.ValidatorBalances_Balance{ Balances: []*ethpb.ValidatorBalances_Balance{
{Index: 1, PublicKey: pubKey(1), Balance: 1, Status: "EXITED"}, {Index: 1, PublicKey: pubKey(1), Balance: 1, Status: "EXITED"},
@@ -275,7 +275,7 @@ func TestServer_ListValidatorBalances_Pagination_Default(t *testing.T) {
NextPageToken: "", NextPageToken: "",
TotalSize: 3, TotalSize: 3,
}}, }},
{req: &ethpb.ListValidatorBalancesRequest{PublicKeys: [][]byte{pubKey(2), pubKey(3)}, Indices: []uint64{3, 4}, QueryFilter: &ethpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, // Duplication {req: &ethpb.ListValidatorBalancesRequest{PublicKeys: [][]byte{pubKey(2), pubKey(3)}, Indices: []types.ValidatorIndex{3, 4}, QueryFilter: &ethpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, // Duplication
res: &ethpb.ValidatorBalances{ res: &ethpb.ValidatorBalances{
Balances: []*ethpb.ValidatorBalances_Balance{ Balances: []*ethpb.ValidatorBalances_Balance{
{Index: 2, PublicKey: pubKey(2), Balance: 2, Status: "EXITED"}, {Index: 2, PublicKey: pubKey(2), Balance: 2, Status: "EXITED"},
@@ -285,7 +285,7 @@ func TestServer_ListValidatorBalances_Pagination_Default(t *testing.T) {
NextPageToken: "", NextPageToken: "",
TotalSize: 3, TotalSize: 3,
}}, }},
{req: &ethpb.ListValidatorBalancesRequest{PublicKeys: [][]byte{{}}, Indices: []uint64{3, 4}, QueryFilter: &ethpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, // Public key has a blank value {req: &ethpb.ListValidatorBalancesRequest{PublicKeys: [][]byte{{}}, Indices: []types.ValidatorIndex{3, 4}, QueryFilter: &ethpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, // Public key has a blank value
res: &ethpb.ValidatorBalances{ res: &ethpb.ValidatorBalances{
Balances: []*ethpb.ValidatorBalances_Balance{ Balances: []*ethpb.ValidatorBalances_Balance{
{Index: 3, PublicKey: pubKey(3), Balance: 3, Status: "EXITED"}, {Index: 3, PublicKey: pubKey(3), Balance: 3, Status: "EXITED"},
@@ -391,7 +391,7 @@ func TestServer_ListValidatorBalances_OutOfRange(t *testing.T) {
}, },
} }
req := &ethpb.ListValidatorBalancesRequest{Indices: []uint64{uint64(1)}, QueryFilter: &ethpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}} req := &ethpb.ListValidatorBalancesRequest{Indices: []types.ValidatorIndex{types.ValidatorIndex(1)}, QueryFilter: &ethpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}
wanted := "Validator index 1 >= balance list 1" wanted := "Validator index 1 >= balance list 1"
_, err = bs.ListValidatorBalances(context.Background(), req) _, err = bs.ListValidatorBalances(context.Background(), req)
assert.ErrorContains(t, wanted, err) assert.ErrorContains(t, wanted, err)
@@ -488,7 +488,7 @@ func TestServer_ListValidators_OnlyActiveValidators(t *testing.T) {
} }
validators[i] = val validators[i] = val
activeValidators = append(activeValidators, &ethpb.Validators_ValidatorContainer{ activeValidators = append(activeValidators, &ethpb.Validators_ValidatorContainer{
Index: uint64(i), Index: types.ValidatorIndex(i),
Validator: val, Validator: val,
}) })
} else { } else {
@@ -551,7 +551,7 @@ func TestServer_ListValidators_InactiveInTheMiddle(t *testing.T) {
} }
validators[i] = val validators[i] = val
activeValidators = append(activeValidators, &ethpb.Validators_ValidatorContainer{ activeValidators = append(activeValidators, &ethpb.Validators_ValidatorContainer{
Index: uint64(i), Index: types.ValidatorIndex(i),
Validator: val, Validator: val,
}) })
} else { } else {
@@ -652,7 +652,7 @@ func TestServer_ListValidators_NoPagination(t *testing.T) {
want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) want := make([]*ethpb.Validators_ValidatorContainer, len(validators))
for i := 0; i < len(validators); i++ { for i := 0; i < len(validators); i++ {
want[i] = &ethpb.Validators_ValidatorContainer{ want[i] = &ethpb.Validators_ValidatorContainer{
Index: uint64(i), Index: types.ValidatorIndex(i),
Validator: validators[i], Validator: validators[i],
} }
} }
@@ -685,7 +685,7 @@ func TestServer_ListValidators_StategenNotUsed(t *testing.T) {
want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) want := make([]*ethpb.Validators_ValidatorContainer, len(validators))
for i := 0; i < len(validators); i++ { for i := 0; i < len(validators); i++ {
want[i] = &ethpb.Validators_ValidatorContainer{ want[i] = &ethpb.Validators_ValidatorContainer{
Index: uint64(i), Index: types.ValidatorIndex(i),
Validator: validators[i], Validator: validators[i],
} }
} }
@@ -709,8 +709,8 @@ func TestServer_ListValidators_IndicesPubKeys(t *testing.T) {
beaconDB := dbTest.SetupDB(t) beaconDB := dbTest.SetupDB(t)
validators, _, headState := setupValidators(t, beaconDB, 100) validators, _, headState := setupValidators(t, beaconDB, 100)
indicesWanted := []uint64{2, 7, 11, 17} indicesWanted := []types.ValidatorIndex{2, 7, 11, 17}
pubkeyIndicesWanted := []uint64{3, 5, 9, 15} pubkeyIndicesWanted := []types.ValidatorIndex{3, 5, 9, 15}
allIndicesWanted := append(indicesWanted, pubkeyIndicesWanted...) allIndicesWanted := append(indicesWanted, pubkeyIndicesWanted...)
want := make([]*ethpb.Validators_ValidatorContainer, len(allIndicesWanted)) want := make([]*ethpb.Validators_ValidatorContainer, len(allIndicesWanted))
for i, idx := range allIndicesWanted { for i, idx := range allIndicesWanted {
@@ -741,7 +741,7 @@ func TestServer_ListValidators_IndicesPubKeys(t *testing.T) {
pubKeysWanted := make([][]byte, len(pubkeyIndicesWanted)) pubKeysWanted := make([][]byte, len(pubkeyIndicesWanted))
for i, indice := range pubkeyIndicesWanted { for i, indice := range pubkeyIndicesWanted {
pubKeysWanted[i] = pubKey(indice) pubKeysWanted[i] = pubKey(uint64(indice))
} }
req := &ethpb.ListValidatorsRequest{ req := &ethpb.ListValidatorsRequest{
Indices: indicesWanted, Indices: indicesWanted,
@@ -935,7 +935,7 @@ func TestServer_ListValidators_DefaultPageSize(t *testing.T) {
want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) want := make([]*ethpb.Validators_ValidatorContainer, len(validators))
for i := 0; i < len(validators); i++ { for i := 0; i < len(validators); i++ {
want[i] = &ethpb.Validators_ValidatorContainer{ want[i] = &ethpb.Validators_ValidatorContainer{
Index: uint64(i), Index: types.ValidatorIndex(i),
Validator: validators[i], Validator: validators[i],
} }
} }
@@ -981,7 +981,7 @@ func TestServer_ListValidators_FromOldEpoch(t *testing.T) {
want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) want := make([]*ethpb.Validators_ValidatorContainer, len(validators))
for i := 0; i < len(validators); i++ { for i := 0; i < len(validators); i++ {
want[i] = &ethpb.Validators_ValidatorContainer{ want[i] = &ethpb.Validators_ValidatorContainer{
Index: uint64(i), Index: types.ValidatorIndex(i),
Validator: validators[i], Validator: validators[i],
} }
} }
@@ -1049,7 +1049,7 @@ func TestServer_ListValidators_ProcessHeadStateSlots(t *testing.T) {
want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) want := make([]*ethpb.Validators_ValidatorContainer, len(validators))
for i := 0; i < len(validators); i++ { for i := 0; i < len(validators); i++ {
want[i] = &ethpb.Validators_ValidatorContainer{ want[i] = &ethpb.Validators_ValidatorContainer{
Index: uint64(i), Index: types.ValidatorIndex(i),
Validator: validators[i], Validator: validators[i],
} }
} }
@@ -1126,7 +1126,7 @@ func TestServer_GetValidator(t *testing.T) {
{ {
req: &ethpb.GetValidatorRequest{ req: &ethpb.GetValidatorRequest{
QueryFilter: &ethpb.GetValidatorRequest_Index{ QueryFilter: &ethpb.GetValidatorRequest_Index{
Index: uint64(count - 1), Index: types.ValidatorIndex(count - 1),
}, },
}, },
res: validators[count-1], res: validators[count-1],
@@ -1151,7 +1151,7 @@ func TestServer_GetValidator(t *testing.T) {
{ {
req: &ethpb.GetValidatorRequest{ req: &ethpb.GetValidatorRequest{
QueryFilter: &ethpb.GetValidatorRequest_Index{ QueryFilter: &ethpb.GetValidatorRequest_Index{
Index: uint64(len(validators)), Index: types.ValidatorIndex(len(validators)),
}, },
}, },
res: nil, res: nil,
@@ -1202,7 +1202,7 @@ func TestServer_GetValidatorActiveSetChanges(t *testing.T) {
withdrawableEpoch = params.BeaconConfig().MinValidatorWithdrawabilityDelay withdrawableEpoch = params.BeaconConfig().MinValidatorWithdrawabilityDelay
balance = params.BeaconConfig().EjectionBalance balance = params.BeaconConfig().EjectionBalance
} }
err := headState.UpdateValidatorAtIndex(uint64(i), &ethpb.Validator{ err := headState.UpdateValidatorAtIndex(types.ValidatorIndex(i), &ethpb.Validator{
ActivationEpoch: activationEpoch, ActivationEpoch: activationEpoch,
PublicKey: pubKey(uint64(i)), PublicKey: pubKey(uint64(i)),
EffectiveBalance: balance, EffectiveBalance: balance,
@@ -1238,19 +1238,19 @@ func TestServer_GetValidatorActiveSetChanges(t *testing.T) {
pubKey(4), pubKey(4),
pubKey(6), pubKey(6),
} }
wantedActiveIndices := []uint64{0, 2, 4, 6} wantedActiveIndices := []types.ValidatorIndex{0, 2, 4, 6}
wantedExited := [][]byte{ wantedExited := [][]byte{
pubKey(5), pubKey(5),
} }
wantedExitedIndices := []uint64{5} wantedExitedIndices := []types.ValidatorIndex{5}
wantedSlashed := [][]byte{ wantedSlashed := [][]byte{
pubKey(3), pubKey(3),
} }
wantedSlashedIndices := []uint64{3} wantedSlashedIndices := []types.ValidatorIndex{3}
wantedEjected := [][]byte{ wantedEjected := [][]byte{
pubKey(7), pubKey(7),
} }
wantedEjectedIndices := []uint64{7} wantedEjectedIndices := []types.ValidatorIndex{7}
wanted := &ethpb.ActiveSetChanges{ wanted := &ethpb.ActiveSetChanges{
Epoch: 0, Epoch: 0,
ActivatedPublicKeys: wantedActive, ActivatedPublicKeys: wantedActive,
@@ -1313,7 +1313,7 @@ func TestServer_GetValidatorQueue_PendingActivation(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, wantChurn, res.ChurnLimit) assert.Equal(t, wantChurn, res.ChurnLimit)
assert.DeepEqual(t, wanted, res.ActivationPublicKeys) assert.DeepEqual(t, wanted, res.ActivationPublicKeys)
wantedActiveIndices := []uint64{2, 1, 0} wantedActiveIndices := []types.ValidatorIndex{2, 1, 0}
assert.DeepEqual(t, wantedActiveIndices, res.ActivationValidatorIndices) assert.DeepEqual(t, wantedActiveIndices, res.ActivationValidatorIndices)
} }
@@ -1355,7 +1355,7 @@ func TestServer_GetValidatorQueue_ExitedValidatorLeavesQueue(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, wantChurn, res.ChurnLimit) assert.Equal(t, wantChurn, res.ChurnLimit)
assert.DeepEqual(t, wanted, res.ExitPublicKeys) assert.DeepEqual(t, wanted, res.ExitPublicKeys)
wantedExitIndices := []uint64{1} wantedExitIndices := []types.ValidatorIndex{1}
assert.DeepEqual(t, wantedExitIndices, res.ExitValidatorIndices) assert.DeepEqual(t, wantedExitIndices, res.ExitValidatorIndices)
// Now, we move the state.slot past the exit epoch of the validator, and now // Now, we move the state.slot past the exit epoch of the validator, and now
@@ -1784,7 +1784,7 @@ func TestGetValidatorPerformance_Indices(t *testing.T) {
} }
res, err := bs.GetValidatorPerformance(ctx, &ethpb.ValidatorPerformanceRequest{ res, err := bs.GetValidatorPerformance(ctx, &ethpb.ValidatorPerformanceRequest{
Indices: []uint64{2, 1, 0}, Indices: []types.ValidatorIndex{2, 1, 0},
}) })
require.NoError(t, err) require.NoError(t, err)
if !proto.Equal(want, res) { if !proto.Equal(want, res) {
@@ -1858,7 +1858,7 @@ func TestGetValidatorPerformance_IndicesPubkeys(t *testing.T) {
// Index 2 and publicKey3 points to the same validator. // Index 2 and publicKey3 points to the same validator.
// Should not return duplicates. // Should not return duplicates.
res, err := bs.GetValidatorPerformance(ctx, &ethpb.ValidatorPerformanceRequest{ res, err := bs.GetValidatorPerformance(ctx, &ethpb.ValidatorPerformanceRequest{
PublicKeys: [][]byte{publicKey1[:], publicKey3[:]}, Indices: []uint64{1, 2}, PublicKeys: [][]byte{publicKey1[:], publicKey3[:]}, Indices: []types.ValidatorIndex{1, 2},
}) })
require.NoError(t, err) require.NoError(t, err)
if !proto.Equal(want, res) { if !proto.Equal(want, res) {
@@ -1951,14 +1951,14 @@ func TestServer_GetIndividualVotes_ValidatorsDontExist(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
wanted := &ethpb.IndividualVotesRespond{ wanted := &ethpb.IndividualVotesRespond{
IndividualVotes: []*ethpb.IndividualVotesRespond_IndividualVote{ IndividualVotes: []*ethpb.IndividualVotesRespond_IndividualVote{
{PublicKey: []byte{'a'}, ValidatorIndex: ^uint64(0)}, {PublicKey: []byte{'a'}, ValidatorIndex: types.ValidatorIndex(^uint64(0))},
}, },
} }
assert.DeepEqual(t, wanted, res, "Unexpected response") assert.DeepEqual(t, wanted, res, "Unexpected response")
// Test non-existent validator index. // Test non-existent validator index.
res, err = bs.GetIndividualVotes(ctx, &ethpb.IndividualVotesRequest{ res, err = bs.GetIndividualVotes(ctx, &ethpb.IndividualVotesRequest{
Indices: []uint64{100}, Indices: []types.ValidatorIndex{100},
Epoch: 0, Epoch: 0,
}) })
require.NoError(t, err) require.NoError(t, err)
@@ -1972,14 +1972,14 @@ func TestServer_GetIndividualVotes_ValidatorsDontExist(t *testing.T) {
// Test both. // Test both.
res, err = bs.GetIndividualVotes(ctx, &ethpb.IndividualVotesRequest{ res, err = bs.GetIndividualVotes(ctx, &ethpb.IndividualVotesRequest{
PublicKeys: [][]byte{{'a'}, {'b'}}, PublicKeys: [][]byte{{'a'}, {'b'}},
Indices: []uint64{100, 101}, Indices: []types.ValidatorIndex{100, 101},
Epoch: 0, Epoch: 0,
}) })
require.NoError(t, err) require.NoError(t, err)
wanted = &ethpb.IndividualVotesRespond{ wanted = &ethpb.IndividualVotesRespond{
IndividualVotes: []*ethpb.IndividualVotesRespond_IndividualVote{ IndividualVotes: []*ethpb.IndividualVotesRespond_IndividualVote{
{PublicKey: []byte{'a'}, ValidatorIndex: ^uint64(0)}, {PublicKey: []byte{'a'}, ValidatorIndex: types.ValidatorIndex(^uint64(0))},
{PublicKey: []byte{'b'}, ValidatorIndex: ^uint64(0)}, {PublicKey: []byte{'b'}, ValidatorIndex: types.ValidatorIndex(^uint64(0))},
{ValidatorIndex: 100}, {ValidatorIndex: 100},
{ValidatorIndex: 101}, {ValidatorIndex: 101},
}, },
@@ -2040,7 +2040,7 @@ func TestServer_GetIndividualVotes_Working(t *testing.T) {
} }
res, err := bs.GetIndividualVotes(ctx, &ethpb.IndividualVotesRequest{ res, err := bs.GetIndividualVotes(ctx, &ethpb.IndividualVotesRequest{
Indices: []uint64{0, 1}, Indices: []types.ValidatorIndex{0, 1},
Epoch: 0, Epoch: 0,
}) })
require.NoError(t, err) require.NoError(t, err)

View File

@@ -77,7 +77,7 @@ func TestServer_GetAttestationInclusionSlot(t *testing.T) {
b.Block.Slot = 2 b.Block.Slot = 2
b.Block.Body.Attestations = []*ethpb.Attestation{a} b.Block.Body.Attestations = []*ethpb.Attestation{a}
require.NoError(t, bs.BeaconDB.SaveBlock(ctx, b)) require.NoError(t, bs.BeaconDB.SaveBlock(ctx, b))
res, err := bs.GetInclusionSlot(ctx, &pbrpc.InclusionSlotRequest{Slot: 1, Id: c[0]}) res, err := bs.GetInclusionSlot(ctx, &pbrpc.InclusionSlotRequest{Slot: 1, Id: uint64(c[0])})
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, b.Block.Slot, res.Slot) require.Equal(t, b.Block.Slot, res.Slot)
res, err = bs.GetInclusionSlot(ctx, &pbrpc.InclusionSlotRequest{Slot: 1, Id: 9999999}) res, err = bs.GetInclusionSlot(ctx, &pbrpc.InclusionSlotRequest{Slot: 1, Id: 9999999})

View File

@@ -98,7 +98,7 @@ func TestGetDuties_OK(t *testing.T) {
res, err = vs.GetDuties(context.Background(), req) res, err = vs.GetDuties(context.Background(), req)
require.NoError(t, err, "Could not call epoch committee assignment") require.NoError(t, err, "Could not call epoch committee assignment")
for i := 0; i < len(res.CurrentEpochDuties); i++ { for i := 0; i < len(res.CurrentEpochDuties); i++ {
assert.Equal(t, uint64(i), res.CurrentEpochDuties[i].ValidatorIndex) assert.Equal(t, types.ValidatorIndex(i), res.CurrentEpochDuties[i].ValidatorIndex)
} }
} }

View File

@@ -559,12 +559,12 @@ func TestServer_SubscribeCommitteeSubnets_DifferentLengthSlots(t *testing.T) {
} }
var slots []types.Slot var slots []types.Slot
var comIdxs []uint64 var comIdxs []types.CommitteeIndex
var isAggregator []bool var isAggregator []bool
for i := types.Slot(100); i < 200; i++ { for i := types.Slot(100); i < 200; i++ {
slots = append(slots, i) slots = append(slots, i)
comIdxs = append(comIdxs, uint64(randGen.Int63n(64))) comIdxs = append(comIdxs, types.CommitteeIndex(randGen.Int63n(64)))
boolVal := randGen.Uint64()%2 == 0 boolVal := randGen.Uint64()%2 == 0
isAggregator = append(isAggregator, boolVal) isAggregator = append(isAggregator, boolVal)
} }
@@ -607,12 +607,12 @@ func TestServer_SubscribeCommitteeSubnets_MultipleSlots(t *testing.T) {
} }
var slots []types.Slot var slots []types.Slot
var comIdxs []uint64 var comIdxs []types.CommitteeIndex
var isAggregator []bool var isAggregator []bool
for i := types.Slot(100); i < 200; i++ { for i := types.Slot(100); i < 200; i++ {
slots = append(slots, i) slots = append(slots, i)
comIdxs = append(comIdxs, uint64(randGen.Int63n(64))) comIdxs = append(comIdxs, types.CommitteeIndex(randGen.Int63n(64)))
boolVal := randGen.Uint64()%2 == 0 boolVal := randGen.Uint64()%2 == 0
isAggregator = append(isAggregator, boolVal) isAggregator = append(isAggregator, boolVal)
} }

View File

@@ -59,7 +59,7 @@ func TestProposeExit_Notification(t *testing.T) {
defer opSub.Unsubscribe() defer opSub.Unsubscribe()
// Send the request, expect a result on the state feed. // Send the request, expect a result on the state feed.
validatorIndex := uint64(0) validatorIndex := types.ValidatorIndex(0)
req := &ethpb.SignedVoluntaryExit{ req := &ethpb.SignedVoluntaryExit{
Exit: &ethpb.VoluntaryExit{ Exit: &ethpb.VoluntaryExit{
Epoch: epoch, Epoch: epoch,
@@ -134,7 +134,7 @@ func TestProposeExit_NoPanic(t *testing.T) {
require.ErrorContains(t, "voluntary exit does not exist", err, "Expected error for no exit existing") require.ErrorContains(t, "voluntary exit does not exist", err, "Expected error for no exit existing")
// Send the request, expect a result on the state feed. // Send the request, expect a result on the state feed.
validatorIndex := uint64(0) validatorIndex := types.ValidatorIndex(0)
req = &ethpb.SignedVoluntaryExit{ req = &ethpb.SignedVoluntaryExit{
Exit: &ethpb.VoluntaryExit{ Exit: &ethpb.VoluntaryExit{
Epoch: epoch, Epoch: epoch,

View File

@@ -81,7 +81,7 @@ func TestProposer_GetBlock_OK(t *testing.T) {
} }
proposerSlashings := make([]*ethpb.ProposerSlashing, params.BeaconConfig().MaxProposerSlashings) proposerSlashings := make([]*ethpb.ProposerSlashing, params.BeaconConfig().MaxProposerSlashings)
for i := uint64(0); i < params.BeaconConfig().MaxProposerSlashings; i++ { for i := types.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ {
proposerSlashing, err := testutil.GenerateProposerSlashingForValidator( proposerSlashing, err := testutil.GenerateProposerSlashingForValidator(
beaconState, beaconState,
privKeys[i], privKeys[i],
@@ -98,7 +98,7 @@ func TestProposer_GetBlock_OK(t *testing.T) {
attesterSlashing, err := testutil.GenerateAttesterSlashingForValidator( attesterSlashing, err := testutil.GenerateAttesterSlashingForValidator(
beaconState, beaconState,
privKeys[i+params.BeaconConfig().MaxProposerSlashings], privKeys[i+params.BeaconConfig().MaxProposerSlashings],
i+params.BeaconConfig().MaxProposerSlashings, /* validator index */ types.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */
) )
require.NoError(t, err) require.NoError(t, err)
attSlashings[i] = attesterSlashing attSlashings[i] = attesterSlashing

View File

@@ -4,6 +4,7 @@ import (
"context" "context"
"errors" "errors"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
@@ -17,7 +18,7 @@ import (
) )
var errPubkeyDoesNotExist = errors.New("pubkey does not exist") var errPubkeyDoesNotExist = errors.New("pubkey does not exist")
var nonExistentIndex = ^uint64(0) var nonExistentIndex = types.ValidatorIndex(^uint64(0))
// ValidatorStatus returns the validator status of the current epoch. // ValidatorStatus returns the validator status of the current epoch.
// The status response can be one of the following: // The status response can be one of the following:
@@ -67,7 +68,7 @@ func (vs *Server) MultipleValidatorStatus(
} }
// Convert indices to public keys. // Convert indices to public keys.
for _, idx := range req.Indices { for _, idx := range req.Indices {
pubkeyBytes := headState.PubkeyAtIndex(uint64(idx)) pubkeyBytes := headState.PubkeyAtIndex(types.ValidatorIndex(idx))
if !filtered[pubkeyBytes] { if !filtered[pubkeyBytes] {
pubKeys = append(pubKeys, pubkeyBytes[:]) pubKeys = append(pubKeys, pubkeyBytes[:])
filtered[pubkeyBytes] = true filtered[pubkeyBytes] = true
@@ -75,7 +76,7 @@ func (vs *Server) MultipleValidatorStatus(
} }
// Fetch statuses from beacon state. // Fetch statuses from beacon state.
statuses := make([]*ethpb.ValidatorStatusResponse, len(pubKeys)) statuses := make([]*ethpb.ValidatorStatusResponse, len(pubKeys))
indices := make([]uint64, len(pubKeys)) indices := make([]types.ValidatorIndex, len(pubKeys))
for i, pubKey := range pubKeys { for i, pubKey := range pubKeys {
statuses[i], indices[i] = vs.validatorStatus(ctx, headState, pubKey) statuses[i], indices[i] = vs.validatorStatus(ctx, headState, pubKey)
} }
@@ -126,7 +127,7 @@ func (vs *Server) validatorStatus(
ctx context.Context, ctx context.Context,
headState *stateTrie.BeaconState, headState *stateTrie.BeaconState,
pubKey []byte, pubKey []byte,
) (*ethpb.ValidatorStatusResponse, uint64) { ) (*ethpb.ValidatorStatusResponse, types.ValidatorIndex) {
ctx, span := trace.StartSpan(ctx, "ValidatorServer.validatorStatus") ctx, span := trace.StartSpan(ctx, "ValidatorServer.validatorStatus")
defer span.End() defer span.End()
@@ -196,20 +197,20 @@ func (vs *Server) validatorStatus(
} }
} }
var lastActivatedValidatorIdx uint64 var lastActivatedValidatorIdx types.ValidatorIndex
for j := headState.NumValidators() - 1; j >= 0; j-- { for j := headState.NumValidators() - 1; j >= 0; j-- {
val, err := headState.ValidatorAtIndexReadOnly(uint64(j)) val, err := headState.ValidatorAtIndexReadOnly(types.ValidatorIndex(j))
if err != nil { if err != nil {
return resp, idx return resp, idx
} }
if helpers.IsActiveValidatorUsingTrie(val, helpers.CurrentEpoch(headState)) { if helpers.IsActiveValidatorUsingTrie(val, helpers.CurrentEpoch(headState)) {
lastActivatedValidatorIdx = uint64(j) lastActivatedValidatorIdx = types.ValidatorIndex(j)
break break
} }
} }
// Our position in the activation queue is the above index - our validator index. // Our position in the activation queue is the above index - our validator index.
if lastActivatedValidatorIdx < idx { if lastActivatedValidatorIdx < idx {
resp.PositionInActivationQueue = idx - lastActivatedValidatorIdx resp.PositionInActivationQueue = uint64(idx - lastActivatedValidatorIdx)
} }
return resp, idx return resp, idx
default: default:
@@ -217,18 +218,18 @@ func (vs *Server) validatorStatus(
} }
} }
func statusForPubKey(headState *stateTrie.BeaconState, pubKey []byte) (ethpb.ValidatorStatus, uint64, error) { func statusForPubKey(headState *stateTrie.BeaconState, pubKey []byte) (ethpb.ValidatorStatus, types.ValidatorIndex, error) {
if headState == nil { if headState == nil {
return ethpb.ValidatorStatus_UNKNOWN_STATUS, 0, errors.New("head state does not exist") return ethpb.ValidatorStatus_UNKNOWN_STATUS, 0, errors.New("head state does not exist")
} }
idx, ok := headState.ValidatorIndexByPubkey(bytesutil.ToBytes48(pubKey)) idx, ok := headState.ValidatorIndexByPubkey(bytesutil.ToBytes48(pubKey))
if !ok || idx >= uint64(headState.NumValidators()) { if !ok || uint64(idx) >= uint64(headState.NumValidators()) {
return ethpb.ValidatorStatus_UNKNOWN_STATUS, 0, errPubkeyDoesNotExist return ethpb.ValidatorStatus_UNKNOWN_STATUS, 0, errPubkeyDoesNotExist
} }
return assignmentStatus(headState, idx), idx, nil return assignmentStatus(headState, idx), idx, nil
} }
func assignmentStatus(beaconState *stateTrie.BeaconState, validatorIdx uint64) ethpb.ValidatorStatus { func assignmentStatus(beaconState *stateTrie.BeaconState, validatorIdx types.ValidatorIndex) ethpb.ValidatorStatus {
validator, err := beaconState.ValidatorAtIndexReadOnly(validatorIdx) validator, err := beaconState.ValidatorAtIndexReadOnly(validatorIdx)
if err != nil { if err != nil {
return ethpb.ValidatorStatus_UNKNOWN_STATUS return ethpb.ValidatorStatus_UNKNOWN_STATUS

View File

@@ -595,7 +595,7 @@ func TestActivationStatus_OK(t *testing.T) {
t.Errorf("Validator with pubkey %#x is not unknown and instead has this status: %s", t.Errorf("Validator with pubkey %#x is not unknown and instead has this status: %s",
response[2].PublicKey, response[2].Status.Status.String()) response[2].PublicKey, response[2].Status.Status.String())
} }
if response[2].Index != uint64(params.BeaconConfig().FarFutureEpoch) { if uint64(response[2].Index) != uint64(params.BeaconConfig().FarFutureEpoch) {
t.Errorf("Validator with pubkey %#x is expected to have index %d, received %d", response[2].PublicKey, params.BeaconConfig().FarFutureEpoch, response[2].Index) t.Errorf("Validator with pubkey %#x is expected to have index %d, received %d", response[2].PublicKey, params.BeaconConfig().FarFutureEpoch, response[2].Index)
} }

View File

@@ -3,6 +3,7 @@ package state_test
import ( import (
"testing" "testing"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil" "github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
@@ -43,8 +44,8 @@ func TestFieldTrie_RecomputeTrie(t *testing.T) {
val2.ExitEpoch = 40 val2.ExitEpoch = 40
changedVals := []*ethpb.Validator{val1, val2} changedVals := []*ethpb.Validator{val1, val2}
require.NoError(t, newState.UpdateValidatorAtIndex(changedIdx[0], changedVals[0])) require.NoError(t, newState.UpdateValidatorAtIndex(types.ValidatorIndex(changedIdx[0]), changedVals[0]))
require.NoError(t, newState.UpdateValidatorAtIndex(changedIdx[1], changedVals[1])) require.NoError(t, newState.UpdateValidatorAtIndex(types.ValidatorIndex(changedIdx[1]), changedVals[1]))
expectedRoot, err := stateutil.ValidatorRegistryRoot(newState.Validators()) expectedRoot, err := stateutil.ValidatorRegistryRoot(newState.Validators())
require.NoError(t, err) require.NoError(t, err)

View File

@@ -616,14 +616,14 @@ func (b *BeaconState) validatorsReferences() []*ethpb.Validator {
} }
// ValidatorAtIndex is the validator at the provided index. // ValidatorAtIndex is the validator at the provided index.
func (b *BeaconState) ValidatorAtIndex(idx uint64) (*ethpb.Validator, error) { func (b *BeaconState) ValidatorAtIndex(idx types.ValidatorIndex) (*ethpb.Validator, error) {
if !b.HasInnerState() { if !b.HasInnerState() {
return nil, ErrNilInnerState return nil, ErrNilInnerState
} }
if b.state.Validators == nil { if b.state.Validators == nil {
return &ethpb.Validator{}, nil return &ethpb.Validator{}, nil
} }
if uint64(len(b.state.Validators)) <= idx { if uint64(len(b.state.Validators)) <= uint64(idx) {
return nil, fmt.Errorf("index %d out of range", idx) return nil, fmt.Errorf("index %d out of range", idx)
} }
@@ -636,14 +636,14 @@ func (b *BeaconState) ValidatorAtIndex(idx uint64) (*ethpb.Validator, error) {
// ValidatorAtIndexReadOnly is the validator at the provided index. This method // ValidatorAtIndexReadOnly is the validator at the provided index. This method
// doesn't clone the validator. // doesn't clone the validator.
func (b *BeaconState) ValidatorAtIndexReadOnly(idx uint64) (ReadOnlyValidator, error) { func (b *BeaconState) ValidatorAtIndexReadOnly(idx types.ValidatorIndex) (ReadOnlyValidator, error) {
if !b.HasInnerState() { if !b.HasInnerState() {
return ReadOnlyValidator{}, ErrNilInnerState return ReadOnlyValidator{}, ErrNilInnerState
} }
if b.state.Validators == nil { if b.state.Validators == nil {
return ReadOnlyValidator{}, nil return ReadOnlyValidator{}, nil
} }
if uint64(len(b.state.Validators)) <= idx { if uint64(len(b.state.Validators)) <= uint64(idx) {
return ReadOnlyValidator{}, fmt.Errorf("index %d out of range", idx) return ReadOnlyValidator{}, fmt.Errorf("index %d out of range", idx)
} }
@@ -654,7 +654,7 @@ func (b *BeaconState) ValidatorAtIndexReadOnly(idx uint64) (ReadOnlyValidator, e
} }
// ValidatorIndexByPubkey returns a given validator by its 48-byte public key. // ValidatorIndexByPubkey returns a given validator by its 48-byte public key.
func (b *BeaconState) ValidatorIndexByPubkey(key [48]byte) (uint64, bool) { func (b *BeaconState) ValidatorIndexByPubkey(key [48]byte) (types.ValidatorIndex, bool) {
if b == nil || b.valMapHandler == nil || b.valMapHandler.valIdxMap == nil { if b == nil || b.valMapHandler == nil || b.valMapHandler.valIdxMap == nil {
return 0, false return 0, false
} }
@@ -664,9 +664,9 @@ func (b *BeaconState) ValidatorIndexByPubkey(key [48]byte) (uint64, bool) {
return idx, ok return idx, ok
} }
func (b *BeaconState) validatorIndexMap() map[[48]byte]uint64 { func (b *BeaconState) validatorIndexMap() map[[48]byte]types.ValidatorIndex {
if b == nil || b.valMapHandler == nil || b.valMapHandler.valIdxMap == nil { if b == nil || b.valMapHandler == nil || b.valMapHandler.valIdxMap == nil {
return map[[48]byte]uint64{} return map[[48]byte]types.ValidatorIndex{}
} }
b.lock.RLock() b.lock.RLock()
defer b.lock.RUnlock() defer b.lock.RUnlock()
@@ -676,11 +676,11 @@ func (b *BeaconState) validatorIndexMap() map[[48]byte]uint64 {
// PubkeyAtIndex returns the pubkey at the given // PubkeyAtIndex returns the pubkey at the given
// validator index. // validator index.
func (b *BeaconState) PubkeyAtIndex(idx uint64) [48]byte { func (b *BeaconState) PubkeyAtIndex(idx types.ValidatorIndex) [48]byte {
if !b.HasInnerState() { if !b.HasInnerState() {
return [48]byte{} return [48]byte{}
} }
if idx >= uint64(len(b.state.Validators)) { if uint64(idx) >= uint64(len(b.state.Validators)) {
return [48]byte{} return [48]byte{}
} }
b.lock.RLock() b.lock.RLock()
@@ -756,7 +756,7 @@ func (b *BeaconState) balances() []uint64 {
} }
// BalanceAtIndex of validator with the provided index. // BalanceAtIndex of validator with the provided index.
func (b *BeaconState) BalanceAtIndex(idx uint64) (uint64, error) { func (b *BeaconState) BalanceAtIndex(idx types.ValidatorIndex) (uint64, error) {
if !b.HasInnerState() { if !b.HasInnerState() {
return 0, ErrNilInnerState return 0, ErrNilInnerState
} }
@@ -767,7 +767,7 @@ func (b *BeaconState) BalanceAtIndex(idx uint64) (uint64, error) {
b.lock.RLock() b.lock.RLock()
defer b.lock.RUnlock() defer b.lock.RUnlock()
if uint64(len(b.state.Balances)) <= idx { if uint64(len(b.state.Balances)) <= uint64(idx) {
return 0, fmt.Errorf("index of %d does not exist", idx) return 0, fmt.Errorf("index of %d does not exist", idx)
} }
return b.state.Balances[idx], nil return b.state.Balances[idx], nil

View File

@@ -341,11 +341,11 @@ func (b *BeaconState) ApplyToEveryValidator(f func(idx int, val *ethpb.Validator
// UpdateValidatorAtIndex for the beacon state. Updates the validator // UpdateValidatorAtIndex for the beacon state. Updates the validator
// at a specific index to a new value. // at a specific index to a new value.
func (b *BeaconState) UpdateValidatorAtIndex(idx uint64, val *ethpb.Validator) error { func (b *BeaconState) UpdateValidatorAtIndex(idx types.ValidatorIndex, val *ethpb.Validator) error {
if !b.HasInnerState() { if !b.HasInnerState() {
return ErrNilInnerState return ErrNilInnerState
} }
if uint64(len(b.state.Validators)) <= idx { if uint64(len(b.state.Validators)) <= uint64(idx) {
return errors.Errorf("invalid index provided %d", idx) return errors.Errorf("invalid index provided %d", idx)
} }
b.lock.Lock() b.lock.Lock()
@@ -361,14 +361,14 @@ func (b *BeaconState) UpdateValidatorAtIndex(idx uint64, val *ethpb.Validator) e
v[idx] = val v[idx] = val
b.state.Validators = v b.state.Validators = v
b.markFieldAsDirty(validators) b.markFieldAsDirty(validators)
b.addDirtyIndices(validators, []uint64{idx}) b.addDirtyIndices(validators, []uint64{uint64(idx)})
return nil return nil
} }
// SetValidatorIndexByPubkey updates the validator index mapping maintained internally to // SetValidatorIndexByPubkey updates the validator index mapping maintained internally to
// a given input 48-byte, public key. // a given input 48-byte, public key.
func (b *BeaconState) SetValidatorIndexByPubkey(pubKey [48]byte, validatorIdx uint64) { func (b *BeaconState) SetValidatorIndexByPubkey(pubKey [48]byte, validatorIdx types.ValidatorIndex) {
b.lock.Lock() b.lock.Lock()
defer b.lock.Unlock() defer b.lock.Unlock()
@@ -399,11 +399,11 @@ func (b *BeaconState) SetBalances(val []uint64) error {
// UpdateBalancesAtIndex for the beacon state. This method updates the balance // UpdateBalancesAtIndex for the beacon state. This method updates the balance
// at a specific index to a new value. // at a specific index to a new value.
func (b *BeaconState) UpdateBalancesAtIndex(idx, val uint64) error { func (b *BeaconState) UpdateBalancesAtIndex(idx types.ValidatorIndex, val uint64) error {
if !b.HasInnerState() { if !b.HasInnerState() {
return ErrNilInnerState return ErrNilInnerState
} }
if uint64(len(b.state.Balances)) <= idx { if uint64(len(b.state.Balances)) <= uint64(idx) {
return errors.Errorf("invalid index provided %d", idx) return errors.Errorf("invalid index provided %d", idx)
} }
b.lock.Lock() b.lock.Lock()
@@ -637,7 +637,7 @@ func (b *BeaconState) AppendValidator(val *ethpb.Validator) error {
// append validator to slice // append validator to slice
b.state.Validators = append(vals, val) b.state.Validators = append(vals, val)
valIdx := uint64(len(b.state.Validators) - 1) valIdx := types.ValidatorIndex(len(b.state.Validators) - 1)
// Copy if this is a shared validator map // Copy if this is a shared validator map
if ref := b.valMapHandler.mapRef; ref.Refs() > 1 { if ref := b.valMapHandler.mapRef; ref.Refs() > 1 {
@@ -648,7 +648,7 @@ func (b *BeaconState) AppendValidator(val *ethpb.Validator) error {
b.valMapHandler.valIdxMap[bytesutil.ToBytes48(val.PublicKey)] = valIdx b.valMapHandler.valIdxMap[bytesutil.ToBytes48(val.PublicKey)] = valIdx
b.markFieldAsDirty(validators) b.markFieldAsDirty(validators)
b.addDirtyIndices(validators, []uint64{valIdx}) b.addDirtyIndices(validators, []uint64{uint64(valIdx)})
return nil return nil
} }

View File

@@ -59,6 +59,7 @@ go_test(
"//shared/testutil:go_default_library", "//shared/testutil:go_default_library",
"//shared/testutil/assert:go_default_library", "//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
], ],
) )

View File

@@ -34,7 +34,7 @@ func PendingAttestationRoot(hasher htrutils.HashFn, att *pb.PendingAttestation)
inclusionRoot := bytesutil.ToBytes32(inclusionBuf) inclusionRoot := bytesutil.ToBytes32(inclusionBuf)
proposerBuf := make([]byte, 8) proposerBuf := make([]byte, 8)
binary.LittleEndian.PutUint64(proposerBuf, att.ProposerIndex) binary.LittleEndian.PutUint64(proposerBuf, uint64(att.ProposerIndex))
// Proposer index. // Proposer index.
proposerRoot := bytesutil.ToBytes32(proposerBuf) proposerRoot := bytesutil.ToBytes32(proposerBuf)
@@ -138,7 +138,7 @@ func (h *stateRootHasher) pendingAttestationRoot(hasher htrutils.HashFn, att *pb
copy(enc[2056:2184], attDataBuf) copy(enc[2056:2184], attDataBuf)
proposerBuf := make([]byte, 8) proposerBuf := make([]byte, 8)
binary.LittleEndian.PutUint64(proposerBuf, att.ProposerIndex) binary.LittleEndian.PutUint64(proposerBuf, uint64(att.ProposerIndex))
copy(enc[2184:2192], proposerBuf) copy(enc[2184:2192], proposerBuf)
// Check if it exists in cache: // Check if it exists in cache:

View File

@@ -24,7 +24,7 @@ func BlockHeaderRoot(header *ethpb.BeaconBlockHeader) ([32]byte, error) {
headerSlotRoot := bytesutil.ToBytes32(headerSlotBuf) headerSlotRoot := bytesutil.ToBytes32(headerSlotBuf)
fieldRoots[0] = headerSlotRoot[:] fieldRoots[0] = headerSlotRoot[:]
proposerIdxBuf := make([]byte, 8) proposerIdxBuf := make([]byte, 8)
binary.LittleEndian.PutUint64(proposerIdxBuf, header.ProposerIndex) binary.LittleEndian.PutUint64(proposerIdxBuf, uint64(header.ProposerIndex))
proposerIndexRoot := bytesutil.ToBytes32(proposerIdxBuf) proposerIndexRoot := bytesutil.ToBytes32(proposerIdxBuf)
fieldRoots[1] = proposerIndexRoot[:] fieldRoots[1] = proposerIndexRoot[:]
parentRoot := bytesutil.ToBytes32(header.ParentRoot) parentRoot := bytesutil.ToBytes32(header.ParentRoot)

View File

@@ -3,15 +3,15 @@ package stateutil_test
import ( import (
"testing" "testing"
"github.com/prysmaticlabs/prysm/shared/hashutil" types "github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil" "github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
"github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/hashutil"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
func TestReturnTrieLayer_OK(t *testing.T) { func TestReturnTrieLayer_OK(t *testing.T) {
@@ -92,8 +92,8 @@ func TestRecomputeFromLayer_VariableSizedArray(t *testing.T) {
val2.ExitEpoch = 40 val2.ExitEpoch = 40
changedVals := []*ethpb.Validator{val1, val2} changedVals := []*ethpb.Validator{val1, val2}
require.NoError(t, newState.UpdateValidatorAtIndex(changedIdx[0], changedVals[0])) require.NoError(t, newState.UpdateValidatorAtIndex(types.ValidatorIndex(changedIdx[0]), changedVals[0]))
require.NoError(t, newState.UpdateValidatorAtIndex(changedIdx[1], changedVals[1])) require.NoError(t, newState.UpdateValidatorAtIndex(types.ValidatorIndex(changedIdx[1]), changedVals[1]))
expectedRoot, err := stateutil.ValidatorRegistryRoot(newState.Validators()) expectedRoot, err := stateutil.ValidatorRegistryRoot(newState.Validators())
require.NoError(t, err) require.NoError(t, err)

View File

@@ -4,6 +4,7 @@ import (
"sync" "sync"
"github.com/pkg/errors" "github.com/pkg/errors"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
coreutils "github.com/prysmaticlabs/prysm/beacon-chain/core/state/stateutils" coreutils "github.com/prysmaticlabs/prysm/beacon-chain/core/state/stateutils"
pbp2p "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" pbp2p "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
@@ -178,7 +179,7 @@ func (r *reference) MinusRef() {
// a container to hold the map and a reference tracker for how many // a container to hold the map and a reference tracker for how many
// states shared this. // states shared this.
type validatorMapHandler struct { type validatorMapHandler struct {
valIdxMap map[[48]byte]uint64 valIdxMap map[[48]byte]types.ValidatorIndex
mapRef *reference mapRef *reference
} }
@@ -193,9 +194,9 @@ func newValHandler(vals []*ethpb.Validator) *validatorMapHandler {
// copies the whole map and returns a map handler with the copied map. // copies the whole map and returns a map handler with the copied map.
func (v *validatorMapHandler) copy() *validatorMapHandler { func (v *validatorMapHandler) copy() *validatorMapHandler {
if v == nil || v.valIdxMap == nil { if v == nil || v.valIdxMap == nil {
return &validatorMapHandler{valIdxMap: map[[48]byte]uint64{}, mapRef: new(reference)} return &validatorMapHandler{valIdxMap: map[[48]byte]types.ValidatorIndex{}, mapRef: new(reference)}
} }
m := make(map[[48]byte]uint64, len(v.valIdxMap)) m := make(map[[48]byte]types.ValidatorIndex, len(v.valIdxMap))
for k, v := range v.valIdxMap { for k, v := range v.valIdxMap {
m[k] = v m[k] = v
} }

View File

@@ -348,17 +348,17 @@ func TestValidatePendingAtts_CanPruneOldAtts(t *testing.T) {
for i := types.Slot(0); i < 100; i++ { for i := types.Slot(0); i < 100; i++ {
s.savePendingAtt(&ethpb.SignedAggregateAttestationAndProof{ s.savePendingAtt(&ethpb.SignedAggregateAttestationAndProof{
Message: &ethpb.AggregateAttestationAndProof{ Message: &ethpb.AggregateAttestationAndProof{
AggregatorIndex: uint64(i), AggregatorIndex: types.ValidatorIndex(i),
Aggregate: &ethpb.Attestation{ Aggregate: &ethpb.Attestation{
Data: &ethpb.AttestationData{Slot: i, BeaconBlockRoot: r1[:]}}}}) Data: &ethpb.AttestationData{Slot: i, BeaconBlockRoot: r1[:]}}}})
s.savePendingAtt(&ethpb.SignedAggregateAttestationAndProof{ s.savePendingAtt(&ethpb.SignedAggregateAttestationAndProof{
Message: &ethpb.AggregateAttestationAndProof{ Message: &ethpb.AggregateAttestationAndProof{
AggregatorIndex: uint64(i*2 + i), AggregatorIndex: types.ValidatorIndex(i*2 + i),
Aggregate: &ethpb.Attestation{ Aggregate: &ethpb.Attestation{
Data: &ethpb.AttestationData{Slot: i, BeaconBlockRoot: r2[:]}}}}) Data: &ethpb.AttestationData{Slot: i, BeaconBlockRoot: r2[:]}}}})
s.savePendingAtt(&ethpb.SignedAggregateAttestationAndProof{ s.savePendingAtt(&ethpb.SignedAggregateAttestationAndProof{
Message: &ethpb.AggregateAttestationAndProof{ Message: &ethpb.AggregateAttestationAndProof{
AggregatorIndex: uint64(i*3 + i), AggregatorIndex: types.ValidatorIndex(i*3 + i),
Aggregate: &ethpb.Attestation{ Aggregate: &ethpb.Attestation{
Data: &ethpb.AttestationData{Slot: i, BeaconBlockRoot: r3[:]}}}}) Data: &ethpb.AttestationData{Slot: i, BeaconBlockRoot: r3[:]}}}})
} }

View File

@@ -190,24 +190,24 @@ func (s *Service) validateBlockInAttestation(ctx context.Context, satt *ethpb.Si
} }
// Returns true if the node has received aggregate for the aggregator with index and target epoch. // Returns true if the node has received aggregate for the aggregator with index and target epoch.
func (s *Service) hasSeenAggregatorIndexEpoch(epoch types.Epoch, aggregatorIndex uint64) bool { func (s *Service) hasSeenAggregatorIndexEpoch(epoch types.Epoch, aggregatorIndex types.ValidatorIndex) bool {
s.seenAttestationLock.RLock() s.seenAttestationLock.RLock()
defer s.seenAttestationLock.RUnlock() defer s.seenAttestationLock.RUnlock()
b := append(bytesutil.Bytes32(uint64(epoch)), bytesutil.Bytes32(aggregatorIndex)...) b := append(bytesutil.Bytes32(uint64(epoch)), bytesutil.Bytes32(uint64(aggregatorIndex))...)
_, seen := s.seenAttestationCache.Get(string(b)) _, seen := s.seenAttestationCache.Get(string(b))
return seen return seen
} }
// Set aggregate's aggregator index target epoch as seen. // Set aggregate's aggregator index target epoch as seen.
func (s *Service) setAggregatorIndexEpochSeen(epoch types.Epoch, aggregatorIndex uint64) { func (s *Service) setAggregatorIndexEpochSeen(epoch types.Epoch, aggregatorIndex types.ValidatorIndex) {
s.seenAttestationLock.Lock() s.seenAttestationLock.Lock()
defer s.seenAttestationLock.Unlock() defer s.seenAttestationLock.Unlock()
b := append(bytesutil.Bytes32(uint64(epoch)), bytesutil.Bytes32(aggregatorIndex)...) b := append(bytesutil.Bytes32(uint64(epoch)), bytesutil.Bytes32(uint64(aggregatorIndex))...)
s.seenAttestationCache.Add(string(b), true) s.seenAttestationCache.Add(string(b), true)
} }
// This validates the aggregator's index in state is within the beacon committee. // This validates the aggregator's index in state is within the beacon committee.
func validateIndexInCommittee(ctx context.Context, bs *stateTrie.BeaconState, a *ethpb.Attestation, validatorIndex uint64) error { func validateIndexInCommittee(ctx context.Context, bs *stateTrie.BeaconState, a *ethpb.Attestation, validatorIndex types.ValidatorIndex) error {
ctx, span := trace.StartSpan(ctx, "sync.validateIndexInCommittee") ctx, span := trace.StartSpan(ctx, "sync.validateIndexInCommittee")
defer span.End() defer span.End()
@@ -231,7 +231,7 @@ func validateIndexInCommittee(ctx context.Context, bs *stateTrie.BeaconState, a
// This validates selection proof by validating it's from the correct validator index of the slot. // This validates selection proof by validating it's from the correct validator index of the slot.
// It does not verify the selection proof, it returns the signature set of selection proof which can be used for batch verify. // It does not verify the selection proof, it returns the signature set of selection proof which can be used for batch verify.
func validateSelectionIndex(ctx context.Context, bs *stateTrie.BeaconState, data *ethpb.AttestationData, validatorIndex uint64, proof []byte) (*bls.SignatureSet, error) { func validateSelectionIndex(ctx context.Context, bs *stateTrie.BeaconState, data *ethpb.AttestationData, validatorIndex types.ValidatorIndex, proof []byte) (*bls.SignatureSet, error) {
_, span := trace.StartSpan(ctx, "sync.validateSelectionIndex") _, span := trace.StartSpan(ctx, "sync.validateSelectionIndex")
defer span.End() defer span.End()

View File

@@ -10,6 +10,7 @@ import (
lru "github.com/hashicorp/golang-lru" lru "github.com/hashicorp/golang-lru"
pubsub "github.com/libp2p/go-libp2p-pubsub" pubsub "github.com/libp2p/go-libp2p-pubsub"
pubsubpb "github.com/libp2p/go-libp2p-pubsub/pb" pubsubpb "github.com/libp2p/go-libp2p-pubsub/pb"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/go-bitfield"
mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing"
@@ -48,7 +49,7 @@ func TestVerifyIndexInCommittee_CanVerify(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
indices, err := attestationutil.AttestingIndices(att.AggregationBits, committee) indices, err := attestationutil.AttestingIndices(att.AggregationBits, committee)
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, validateIndexInCommittee(ctx, s, att, indices[0])) require.NoError(t, validateIndexInCommittee(ctx, s, att, types.ValidatorIndex(indices[0])))
wanted := "validator index 1000 is not within the committee" wanted := "validator index 1000 is not within the committee"
assert.ErrorContains(t, wanted, validateIndexInCommittee(ctx, s, att, 1000)) assert.ErrorContains(t, wanted, validateIndexInCommittee(ctx, s, att, 1000))

View File

@@ -202,19 +202,19 @@ func (s *Service) validateBeaconBlock(ctx context.Context, blk *ethpb.SignedBeac
} }
// Returns true if the block is not the first block proposed for the proposer for the slot. // Returns true if the block is not the first block proposed for the proposer for the slot.
func (s *Service) hasSeenBlockIndexSlot(slot types.Slot, proposerIdx uint64) bool { func (s *Service) hasSeenBlockIndexSlot(slot types.Slot, proposerIdx types.ValidatorIndex) bool {
s.seenBlockLock.RLock() s.seenBlockLock.RLock()
defer s.seenBlockLock.RUnlock() defer s.seenBlockLock.RUnlock()
b := append(bytesutil.Bytes32(uint64(slot)), bytesutil.Bytes32(proposerIdx)...) b := append(bytesutil.Bytes32(uint64(slot)), bytesutil.Bytes32(uint64(proposerIdx))...)
_, seen := s.seenBlockCache.Get(string(b)) _, seen := s.seenBlockCache.Get(string(b))
return seen return seen
} }
// Set block proposer index and slot as seen for incoming blocks. // Set block proposer index and slot as seen for incoming blocks.
func (s *Service) setSeenBlockIndexSlot(slot types.Slot, proposerIdx uint64) { func (s *Service) setSeenBlockIndexSlot(slot types.Slot, proposerIdx types.ValidatorIndex) {
s.seenBlockLock.Lock() s.seenBlockLock.Lock()
defer s.seenBlockLock.Unlock() defer s.seenBlockLock.Unlock()
b := append(bytesutil.Bytes32(uint64(slot)), bytesutil.Bytes32(proposerIdx)...) b := append(bytesutil.Bytes32(uint64(slot)), bytesutil.Bytes32(uint64(proposerIdx))...)
s.seenBlockCache.Add(string(b), true) s.seenBlockCache.Add(string(b), true)
} }

View File

@@ -5,6 +5,7 @@ import (
"github.com/libp2p/go-libp2p-core/peer" "github.com/libp2p/go-libp2p-core/peer"
pubsub "github.com/libp2p/go-libp2p-pubsub" pubsub "github.com/libp2p/go-libp2p-pubsub"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/shared/traceutil" "github.com/prysmaticlabs/prysm/shared/traceutil"
@@ -60,7 +61,7 @@ func (s *Service) validateProposerSlashing(ctx context.Context, pid peer.ID, msg
} }
// Returns true if the node has already received a valid proposer slashing received for the proposer with index // Returns true if the node has already received a valid proposer slashing received for the proposer with index
func (s *Service) hasSeenProposerSlashingIndex(i uint64) bool { func (s *Service) hasSeenProposerSlashingIndex(i types.ValidatorIndex) bool {
s.seenProposerSlashingLock.RLock() s.seenProposerSlashingLock.RLock()
defer s.seenProposerSlashingLock.RUnlock() defer s.seenProposerSlashingLock.RUnlock()
_, seen := s.seenProposerSlashingCache.Get(i) _, seen := s.seenProposerSlashingCache.Get(i)
@@ -68,7 +69,7 @@ func (s *Service) hasSeenProposerSlashingIndex(i uint64) bool {
} }
// Set proposer slashing index in proposer slashing cache. // Set proposer slashing index in proposer slashing cache.
func (s *Service) setProposerSlashingIndexSeen(i uint64) { func (s *Service) setProposerSlashingIndexSeen(i types.ValidatorIndex) {
s.seenProposerSlashingLock.Lock() s.seenProposerSlashingLock.Lock()
defer s.seenProposerSlashingLock.Unlock() defer s.seenProposerSlashingLock.Unlock()
s.seenProposerSlashingCache.Add(i, true) s.seenProposerSlashingCache.Add(i, true)

View File

@@ -5,6 +5,7 @@ import (
"github.com/libp2p/go-libp2p-core/peer" "github.com/libp2p/go-libp2p-core/peer"
pubsub "github.com/libp2p/go-libp2p-pubsub" pubsub "github.com/libp2p/go-libp2p-pubsub"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/shared/traceutil" "github.com/prysmaticlabs/prysm/shared/traceutil"
@@ -52,7 +53,7 @@ func (s *Service) validateVoluntaryExit(ctx context.Context, pid peer.ID, msg *p
return pubsub.ValidationIgnore return pubsub.ValidationIgnore
} }
if exit.Exit.ValidatorIndex >= uint64(headState.NumValidators()) { if uint64(exit.Exit.ValidatorIndex) >= uint64(headState.NumValidators()) {
return pubsub.ValidationReject return pubsub.ValidationReject
} }
val, err := headState.ValidatorAtIndexReadOnly(exit.Exit.ValidatorIndex) val, err := headState.ValidatorAtIndexReadOnly(exit.Exit.ValidatorIndex)
@@ -69,7 +70,7 @@ func (s *Service) validateVoluntaryExit(ctx context.Context, pid peer.ID, msg *p
} }
// Returns true if the node has already received a valid exit request for the validator with index `i`. // Returns true if the node has already received a valid exit request for the validator with index `i`.
func (s *Service) hasSeenExitIndex(i uint64) bool { func (s *Service) hasSeenExitIndex(i types.ValidatorIndex) bool {
s.seenExitLock.RLock() s.seenExitLock.RLock()
defer s.seenExitLock.RUnlock() defer s.seenExitLock.RUnlock()
_, seen := s.seenExitCache.Get(i) _, seen := s.seenExitCache.Get(i)
@@ -77,7 +78,7 @@ func (s *Service) hasSeenExitIndex(i uint64) bool {
} }
// Set exit request index `i` in seen exit request cache. // Set exit request index `i` in seen exit request cache.
func (s *Service) setExitIndexSeen(i uint64) { func (s *Service) setExitIndexSeen(i types.ValidatorIndex) {
s.seenExitLock.Lock() s.seenExitLock.Lock()
defer s.seenExitLock.Unlock() defer s.seenExitLock.Unlock()
s.seenExitCache.Add(i, true) s.seenExitCache.Add(i, true)

View File

@@ -2578,8 +2578,8 @@ def prysm_deps():
name = "com_github_prysmaticlabs_ethereumapis", name = "com_github_prysmaticlabs_ethereumapis",
build_file_generation = "off", build_file_generation = "off",
importpath = "github.com/prysmaticlabs/ethereumapis", importpath = "github.com/prysmaticlabs/ethereumapis",
sum = "h1:c6x9r/6CYbuBsEF0BNJ5f0WhIq7guAGtxB9Mbxp/8Ok=", sum = "h1:GhzZ3sO2ZiuJxxm3dyBps+tDaVu3q7xMdJD2yJXyuDs=",
version = "v0.0.0-20210218172602-3f05f78bea9d", version = "v0.0.0-20210218195742-a393edb60549",
) )
go_repository( go_repository(
name = "com_github_prysmaticlabs_go_bitfield", name = "com_github_prysmaticlabs_go_bitfield",

View File

@@ -22,11 +22,11 @@ import (
"google.golang.org/grpc" "google.golang.org/grpc"
) )
// exitedIndice holds the exited indice from ProposeVoluntaryExit in memory so other functions don't confuse it // exitedIndex holds the exited index from ProposeVoluntaryExit in memory so other functions don't confuse it
// for a normal validator. // for a normal validator.
var exitedIndice uint64 var exitedIndex types.ValidatorIndex
// valExited is used to know if exitedIndice is set, since default value is 0. // valExited is used to know if exitedIndex is set, since default value is 0.
var valExited bool var valExited bool
// churnLimit is normally 4 unless the validator set is extremely large. // churnLimit is normally 4 unless the validator set is extremely large.
@@ -274,12 +274,12 @@ func proposeVoluntaryExit(conns ...*grpc.ClientConn) error {
return err return err
} }
exitedIndice = rand.Uint64() % params.BeaconConfig().MinGenesisActiveValidatorCount exitedIndex = types.ValidatorIndex(rand.Uint64() % params.BeaconConfig().MinGenesisActiveValidatorCount)
valExited = true valExited = true
voluntaryExit := &eth.VoluntaryExit{ voluntaryExit := &eth.VoluntaryExit{
Epoch: chainHead.HeadEpoch, Epoch: chainHead.HeadEpoch,
ValidatorIndex: exitedIndice, ValidatorIndex: exitedIndex,
} }
req := &eth.DomainRequest{ req := &eth.DomainRequest{
Epoch: chainHead.HeadEpoch, Epoch: chainHead.HeadEpoch,
@@ -293,7 +293,7 @@ func proposeVoluntaryExit(conns ...*grpc.ClientConn) error {
if err != nil { if err != nil {
return err return err
} }
signature := privKeys[exitedIndice].Sign(signingData[:]) signature := privKeys[exitedIndex].Sign(signingData[:])
signedExit := &eth.SignedVoluntaryExit{ signedExit := &eth.SignedVoluntaryExit{
Exit: voluntaryExit, Exit: voluntaryExit,
Signature: signature.Marshal(), Signature: signature.Marshal(),
@@ -310,7 +310,7 @@ func validatorIsExited(conns ...*grpc.ClientConn) error {
client := eth.NewBeaconChainClient(conn) client := eth.NewBeaconChainClient(conn)
validatorRequest := &eth.GetValidatorRequest{ validatorRequest := &eth.GetValidatorRequest{
QueryFilter: &eth.GetValidatorRequest_Index{ QueryFilter: &eth.GetValidatorRequest_Index{
Index: exitedIndice, Index: exitedIndex,
}, },
} }
validator, err := client.GetValidator(context.Background(), validatorRequest) validator, err := client.GetValidator(context.Background(), validatorRequest)
@@ -318,7 +318,7 @@ func validatorIsExited(conns ...*grpc.ClientConn) error {
return errors.Wrap(err, "failed to get validators") return errors.Wrap(err, "failed to get validators")
} }
if validator.ExitEpoch == params.BeaconConfig().FarFutureEpoch { if validator.ExitEpoch == params.BeaconConfig().FarFutureEpoch {
return fmt.Errorf("expected validator %d to be submitted for exit", exitedIndice) return fmt.Errorf("expected validator %d to be submitted for exit", exitedIndex)
} }
return nil return nil
} }

View File

@@ -6,12 +6,12 @@ import (
ptypes "github.com/gogo/protobuf/types" ptypes "github.com/gogo/protobuf/types"
"github.com/pkg/errors" "github.com/pkg/errors"
ethTypes "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/eth2-types"
eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/go-bitfield"
corehelpers "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" corehelpers "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/endtoend/policies" "github.com/prysmaticlabs/prysm/endtoend/policies"
"github.com/prysmaticlabs/prysm/endtoend/types" e2eTypes "github.com/prysmaticlabs/prysm/endtoend/types"
"github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/sliceutil" "github.com/prysmaticlabs/prysm/shared/sliceutil"
@@ -20,28 +20,28 @@ import (
) )
// InjectDoubleVote broadcasts a double vote into the beacon node pool for the slasher to detect. // InjectDoubleVote broadcasts a double vote into the beacon node pool for the slasher to detect.
var InjectDoubleVote = types.Evaluator{ var InjectDoubleVote = e2eTypes.Evaluator{
Name: "inject_double_vote_%d", Name: "inject_double_vote_%d",
Policy: policies.OnEpoch(1), Policy: policies.OnEpoch(1),
Evaluation: insertDoubleAttestationIntoPool, Evaluation: insertDoubleAttestationIntoPool,
} }
// ProposeDoubleBlock broadcasts a double block to the beacon node for the slasher to detect. // ProposeDoubleBlock broadcasts a double block to the beacon node for the slasher to detect.
var ProposeDoubleBlock = types.Evaluator{ var ProposeDoubleBlock = e2eTypes.Evaluator{
Name: "propose_double_block_%d", Name: "propose_double_block_%d",
Policy: policies.OnEpoch(1), Policy: policies.OnEpoch(1),
Evaluation: proposeDoubleBlock, Evaluation: proposeDoubleBlock,
} }
// ValidatorsSlashed ensures the expected amount of validators are slashed. // ValidatorsSlashed ensures the expected amount of validators are slashed.
var ValidatorsSlashed = types.Evaluator{ var ValidatorsSlashed = e2eTypes.Evaluator{
Name: "validators_slashed_epoch_%d", Name: "validators_slashed_epoch_%d",
Policy: policies.AfterNthEpoch(1), Policy: policies.AfterNthEpoch(1),
Evaluation: validatorsSlashed, Evaluation: validatorsSlashed,
} }
// SlashedValidatorsLoseBalance checks if the validators slashed lose the right balance. // SlashedValidatorsLoseBalance checks if the validators slashed lose the right balance.
var SlashedValidatorsLoseBalance = types.Evaluator{ var SlashedValidatorsLoseBalance = e2eTypes.Evaluator{
Name: "slashed_validators_lose_valance_epoch_%d", Name: "slashed_validators_lose_valance_epoch_%d",
Policy: policies.AfterNthEpoch(1), Policy: policies.AfterNthEpoch(1),
Evaluation: validatorsLoseBalance, Evaluation: validatorsLoseBalance,
@@ -69,10 +69,10 @@ func validatorsLoseBalance(conns ...*grpc.ClientConn) error {
ctx := context.Background() ctx := context.Background()
client := eth.NewBeaconChainClient(conn) client := eth.NewBeaconChainClient(conn)
for i, indice := range slashedIndices { for i, slashedIndex := range slashedIndices {
req := &eth.GetValidatorRequest{ req := &eth.GetValidatorRequest{
QueryFilter: &eth.GetValidatorRequest_Index{ QueryFilter: &eth.GetValidatorRequest_Index{
Index: indice, Index: types.ValidatorIndex(slashedIndex),
}, },
} }
valResp, err := client.GetValidator(ctx, req) valResp, err := client.GetValidator(ctx, req)
@@ -122,8 +122,8 @@ func insertDoubleAttestationIntoPool(conns ...*grpc.ClientConn) error {
return errors.Wrap(err, "could not get duties") return errors.Wrap(err, "could not get duties")
} }
var committeeIndex ethTypes.CommitteeIndex var committeeIndex types.CommitteeIndex
var committee []uint64 var committee []types.ValidatorIndex
for _, duty := range duties.Duties { for _, duty := range duties.Duties {
if duty.AttesterSlot == chainHead.HeadSlot-1 { if duty.AttesterSlot == chainHead.HeadSlot-1 {
committeeIndex = duty.CommitteeIndex committeeIndex = duty.CommitteeIndex
@@ -159,7 +159,7 @@ func insertDoubleAttestationIntoPool(conns ...*grpc.ClientConn) error {
valsToSlash := uint64(2) valsToSlash := uint64(2)
for i := uint64(0); i < valsToSlash && i < uint64(len(committee)); i++ { for i := uint64(0); i < valsToSlash && i < uint64(len(committee)); i++ {
if len(sliceutil.IntersectionUint64(slashedIndices, []uint64{committee[i]})) > 0 { if len(sliceutil.IntersectionUint64(slashedIndices, []uint64{uint64(committee[i])})) > 0 {
valsToSlash++ valsToSlash++
continue continue
} }
@@ -178,7 +178,7 @@ func insertDoubleAttestationIntoPool(conns ...*grpc.ClientConn) error {
if _, err = client.ProposeAttestation(ctx, att); err != nil { if _, err = client.ProposeAttestation(ctx, att); err != nil {
return errors.Wrap(err, "could not propose attestation") return errors.Wrap(err, "could not propose attestation")
} }
slashedIndices = append(slashedIndices, committee[i]) slashedIndices = append(slashedIndices, uint64(committee[i]))
} }
return nil return nil
} }
@@ -210,10 +210,10 @@ func proposeDoubleBlock(conns ...*grpc.ClientConn) error {
return errors.Wrap(err, "could not get duties") return errors.Wrap(err, "could not get duties")
} }
var proposerIndex uint64 var proposerIndex types.ValidatorIndex
for i, duty := range duties.CurrentEpochDuties { for i, duty := range duties.CurrentEpochDuties {
if sliceutil.IsInSlots(chainHead.HeadSlot-1, duty.ProposerSlots) { if sliceutil.IsInSlots(chainHead.HeadSlot-1, duty.ProposerSlots) {
proposerIndex = uint64(i) proposerIndex = types.ValidatorIndex(i)
break break
} }
} }
@@ -264,6 +264,6 @@ func proposeDoubleBlock(conns ...*grpc.ClientConn) error {
if _, err = client.ProposeBlock(ctx, signedBlk); err == nil { if _, err = client.ProposeBlock(ctx, signedBlk); err == nil {
return errors.New("expected block to fail processing") return errors.New("expected block to fail processing")
} }
slashedIndices = append(slashedIndices, proposerIndex) slashedIndices = append(slashedIndices, uint64(proposerIndex))
return nil return nil
} }

View File

@@ -51,7 +51,7 @@ func validatorsAreActive(conns ...*grpc.ClientConn) error {
exitEpochWrongCount := 0 exitEpochWrongCount := 0
withdrawEpochWrongCount := 0 withdrawEpochWrongCount := 0
for _, item := range validators.ValidatorList { for _, item := range validators.ValidatorList {
if valExited && item.Index == exitedIndice { if valExited && item.Index == exitedIndex {
continue continue
} }
if item.Validator.EffectiveBalance < params.BeaconConfig().MaxEffectiveBalance { if item.Validator.EffectiveBalance < params.BeaconConfig().MaxEffectiveBalance {

2
go.mod
View File

@@ -84,7 +84,7 @@ require (
github.com/prometheus/procfs v0.3.0 // indirect github.com/prometheus/procfs v0.3.0 // indirect
github.com/prometheus/tsdb v0.10.0 // indirect github.com/prometheus/tsdb v0.10.0 // indirect
github.com/prysmaticlabs/eth2-types v0.0.0-20210210115503-cf4ec6600a2d github.com/prysmaticlabs/eth2-types v0.0.0-20210210115503-cf4ec6600a2d
github.com/prysmaticlabs/ethereumapis v0.0.0-20210218172602-3f05f78bea9d github.com/prysmaticlabs/ethereumapis v0.0.0-20210218195742-a393edb60549
github.com/prysmaticlabs/go-bitfield v0.0.0-20210202205921-7fcea7c45dc8 github.com/prysmaticlabs/go-bitfield v0.0.0-20210202205921-7fcea7c45dc8
github.com/prysmaticlabs/prombbolt v0.0.0-20210126082820-9b7adba6db7c github.com/prysmaticlabs/prombbolt v0.0.0-20210126082820-9b7adba6db7c
github.com/rs/cors v1.7.0 github.com/rs/cors v1.7.0

4
go.sum
View File

@@ -1028,8 +1028,8 @@ github.com/prysmaticlabs/bazel-go-ethereum v0.0.0-20210222122116-71d15f72c132/go
github.com/prysmaticlabs/eth2-types v0.0.0-20210127031309-22cbe426eba6/go.mod h1:kOmQ/zdobQf7HUohDTifDNFEZfNaSCIY5fkONPL+dWU= github.com/prysmaticlabs/eth2-types v0.0.0-20210127031309-22cbe426eba6/go.mod h1:kOmQ/zdobQf7HUohDTifDNFEZfNaSCIY5fkONPL+dWU=
github.com/prysmaticlabs/eth2-types v0.0.0-20210210115503-cf4ec6600a2d h1:6ooFkN9g9oAJq+VZWseIpj/tQqyVU0DuLFs66Ro43BQ= github.com/prysmaticlabs/eth2-types v0.0.0-20210210115503-cf4ec6600a2d h1:6ooFkN9g9oAJq+VZWseIpj/tQqyVU0DuLFs66Ro43BQ=
github.com/prysmaticlabs/eth2-types v0.0.0-20210210115503-cf4ec6600a2d/go.mod h1:kOmQ/zdobQf7HUohDTifDNFEZfNaSCIY5fkONPL+dWU= github.com/prysmaticlabs/eth2-types v0.0.0-20210210115503-cf4ec6600a2d/go.mod h1:kOmQ/zdobQf7HUohDTifDNFEZfNaSCIY5fkONPL+dWU=
github.com/prysmaticlabs/ethereumapis v0.0.0-20210218172602-3f05f78bea9d h1:c6x9r/6CYbuBsEF0BNJ5f0WhIq7guAGtxB9Mbxp/8Ok= github.com/prysmaticlabs/ethereumapis v0.0.0-20210218195742-a393edb60549 h1:GhzZ3sO2ZiuJxxm3dyBps+tDaVu3q7xMdJD2yJXyuDs=
github.com/prysmaticlabs/ethereumapis v0.0.0-20210218172602-3f05f78bea9d/go.mod h1:YS3iOCGE+iVDE007GHWtj+UoPK9hyYA7Fo4mSDNTtiY= github.com/prysmaticlabs/ethereumapis v0.0.0-20210218195742-a393edb60549/go.mod h1:YS3iOCGE+iVDE007GHWtj+UoPK9hyYA7Fo4mSDNTtiY=
github.com/prysmaticlabs/go-bitfield v0.0.0-20200322041314-62c2aee71669/go.mod h1:hCwmef+4qXWjv0jLDbQdWnL0Ol7cS7/lCSS26WR+u6s= github.com/prysmaticlabs/go-bitfield v0.0.0-20200322041314-62c2aee71669/go.mod h1:hCwmef+4qXWjv0jLDbQdWnL0Ol7cS7/lCSS26WR+u6s=
github.com/prysmaticlabs/go-bitfield v0.0.0-20210202205921-7fcea7c45dc8 h1:18+Qqobq3HAUY0hgIhPGSqmLFnaLLocemmU7+Sj2aYQ= github.com/prysmaticlabs/go-bitfield v0.0.0-20210202205921-7fcea7c45dc8 h1:18+Qqobq3HAUY0hgIhPGSqmLFnaLLocemmU7+Sj2aYQ=
github.com/prysmaticlabs/go-bitfield v0.0.0-20210202205921-7fcea7c45dc8/go.mod h1:hCwmef+4qXWjv0jLDbQdWnL0Ol7cS7/lCSS26WR+u6s= github.com/prysmaticlabs/go-bitfield v0.0.0-20210202205921-7fcea7c45dc8/go.mod h1:hCwmef+4qXWjv0jLDbQdWnL0Ol7cS7/lCSS26WR+u6s=

View File

@@ -1229,7 +1229,7 @@ func (p *PendingAttestation) MarshalSSZTo(buf []byte) (dst []byte, err error) {
dst = ssz.MarshalUint64(dst, uint64(p.InclusionDelay)) dst = ssz.MarshalUint64(dst, uint64(p.InclusionDelay))
// Field (3) 'ProposerIndex' // Field (3) 'ProposerIndex'
dst = ssz.MarshalUint64(dst, p.ProposerIndex) dst = ssz.MarshalUint64(dst, uint64(p.ProposerIndex))
// Field (0) 'AggregationBits' // Field (0) 'AggregationBits'
if len(p.AggregationBits) > 2048 { if len(p.AggregationBits) > 2048 {
@@ -1269,7 +1269,7 @@ func (p *PendingAttestation) UnmarshalSSZ(buf []byte) error {
p.InclusionDelay = github_com_prysmaticlabs_eth2_types.Slot(ssz.UnmarshallUint64(buf[132:140])) p.InclusionDelay = github_com_prysmaticlabs_eth2_types.Slot(ssz.UnmarshallUint64(buf[132:140]))
// Field (3) 'ProposerIndex' // Field (3) 'ProposerIndex'
p.ProposerIndex = ssz.UnmarshallUint64(buf[140:148]) p.ProposerIndex = github_com_prysmaticlabs_eth2_types.ValidatorIndex(ssz.UnmarshallUint64(buf[140:148]))
// Field (0) 'AggregationBits' // Field (0) 'AggregationBits'
{ {
@@ -1320,7 +1320,7 @@ func (p *PendingAttestation) HashTreeRootWith(hh *ssz.Hasher) (err error) {
hh.PutUint64(uint64(p.InclusionDelay)) hh.PutUint64(uint64(p.InclusionDelay))
// Field (3) 'ProposerIndex' // Field (3) 'ProposerIndex'
hh.PutUint64(p.ProposerIndex) hh.PutUint64(uint64(p.ProposerIndex))
hh.Merkleize(indx) hh.Merkleize(indx)
return return

View File

@@ -297,13 +297,13 @@ func (m *Fork) GetEpoch() github_com_prysmaticlabs_eth2_types.Epoch {
} }
type PendingAttestation struct { type PendingAttestation struct {
AggregationBits github_com_prysmaticlabs_go_bitfield.Bitlist `protobuf:"bytes,1,opt,name=aggregation_bits,json=aggregationBits,proto3,casttype=github.com/prysmaticlabs/go-bitfield.Bitlist" json:"aggregation_bits,omitempty" ssz-max:"2048"` AggregationBits github_com_prysmaticlabs_go_bitfield.Bitlist `protobuf:"bytes,1,opt,name=aggregation_bits,json=aggregationBits,proto3,casttype=github.com/prysmaticlabs/go-bitfield.Bitlist" json:"aggregation_bits,omitempty" ssz-max:"2048"`
Data *v1alpha1.AttestationData `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` Data *v1alpha1.AttestationData `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
InclusionDelay github_com_prysmaticlabs_eth2_types.Slot `protobuf:"varint,3,opt,name=inclusion_delay,json=inclusionDelay,proto3,casttype=github.com/prysmaticlabs/eth2-types.Slot" json:"inclusion_delay,omitempty"` InclusionDelay github_com_prysmaticlabs_eth2_types.Slot `protobuf:"varint,3,opt,name=inclusion_delay,json=inclusionDelay,proto3,casttype=github.com/prysmaticlabs/eth2-types.Slot" json:"inclusion_delay,omitempty"`
ProposerIndex uint64 `protobuf:"varint,4,opt,name=proposer_index,json=proposerIndex,proto3" json:"proposer_index,omitempty"` ProposerIndex github_com_prysmaticlabs_eth2_types.ValidatorIndex `protobuf:"varint,4,opt,name=proposer_index,json=proposerIndex,proto3,casttype=github.com/prysmaticlabs/eth2-types.ValidatorIndex" json:"proposer_index,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"` XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"` XXX_sizecache int32 `json:"-"`
} }
func (m *PendingAttestation) Reset() { *m = PendingAttestation{} } func (m *PendingAttestation) Reset() { *m = PendingAttestation{} }
@@ -360,7 +360,7 @@ func (m *PendingAttestation) GetInclusionDelay() github_com_prysmaticlabs_eth2_t
return 0 return 0
} }
func (m *PendingAttestation) GetProposerIndex() uint64 { func (m *PendingAttestation) GetProposerIndex() github_com_prysmaticlabs_eth2_types.ValidatorIndex {
if m != nil { if m != nil {
return m.ProposerIndex return m.ProposerIndex
} }
@@ -744,93 +744,94 @@ func init() {
func init() { proto.RegisterFile("proto/beacon/p2p/v1/types.proto", fileDescriptor_e719e7d82cfa7b0d) } func init() { proto.RegisterFile("proto/beacon/p2p/v1/types.proto", fileDescriptor_e719e7d82cfa7b0d) }
var fileDescriptor_e719e7d82cfa7b0d = []byte{ var fileDescriptor_e719e7d82cfa7b0d = []byte{
// 1375 bytes of a gzipped FileDescriptorProto // 1386 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x57, 0x4d, 0x6f, 0x1b, 0x45, 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x57, 0x4d, 0x6f, 0x1b, 0x45,
0x18, 0x96, 0x13, 0xb7, 0x4d, 0xc7, 0x49, 0x9c, 0x4e, 0x20, 0xd9, 0x7e, 0x90, 0x75, 0x57, 0xb4, 0x18, 0x96, 0x13, 0xb7, 0x4d, 0xc7, 0x49, 0x9c, 0x4e, 0x20, 0xd9, 0x7e, 0x90, 0x4d, 0x57, 0x50,
0xa4, 0xa8, 0xb6, 0x63, 0x37, 0xb5, 0x93, 0x54, 0x14, 0xea, 0xb4, 0xa8, 0x69, 0x55, 0xa9, 0xda, 0x52, 0xd4, 0xd8, 0xb1, 0x9b, 0xda, 0x49, 0x2a, 0x0a, 0x75, 0x5a, 0xd4, 0xb4, 0xaa, 0x54, 0x6d,
0xd0, 0x4a, 0x48, 0x88, 0xd5, 0xec, 0xee, 0xd8, 0x3b, 0xcd, 0x7a, 0x67, 0xb5, 0x33, 0x76, 0xeb, 0x68, 0x25, 0x24, 0x60, 0x35, 0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xe0, 0xb4, 0xe3, 0xf1, 0xe8, 0xda, 0xeb, 0xf1, 0x5b, 0x63, 0xfa, 0x9b, 0x47, 0x4b, 0xb9, 0x6f, 0x1f,
0xc2, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x3b, 0x1f, 0x6b, 0xc9, 0xcf, 0x0c, 0x00, 0x00, 0x2d, 0xe5, 0x7e, 0x79, 0xb4, 0x94, 0x33, 0x0f, 0xcb, 0xbf, 0x0f, 0xe7, 0xff, 0x0e, 0x00, 0x00,
0xff, 0xff, 0x5b, 0x65, 0xa3, 0x88, 0x07, 0x0d, 0x00, 0x00,
} }
func (m *BeaconState) Marshal() (dAtA []byte, err error) { func (m *BeaconState) Marshal() (dAtA []byte, err error) {
@@ -2953,7 +2954,7 @@ func (m *PendingAttestation) Unmarshal(dAtA []byte) error {
} }
b := dAtA[iNdEx] b := dAtA[iNdEx]
iNdEx++ iNdEx++
m.ProposerIndex |= uint64(b&0x7F) << shift m.ProposerIndex |= github_com_prysmaticlabs_eth2_types.ValidatorIndex(b&0x7F) << shift
if b < 0x80 { if b < 0x80 {
break break
} }

View File

@@ -60,7 +60,7 @@ message PendingAttestation {
// The difference of when attestation gets created and get included on chain. // The difference of when attestation gets created and get included on chain.
uint64 inclusion_delay = 3 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Slot"]; uint64 inclusion_delay = 3 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Slot"];
// The proposer who included the attestation in the block. // The proposer who included the attestation in the block.
uint64 proposer_index = 4; uint64 proposer_index = 4 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.ValidatorIndex"];
} }
message HistoricalBatch { message HistoricalBatch {

View File

@@ -11,6 +11,7 @@ go_library(
"//shared/bls:go_default_library", "//shared/bls:go_default_library",
"//shared/params:go_default_library", "//shared/params:go_default_library",
"@com_github_pkg_errors//:go_default_library", "@com_github_pkg_errors//:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library",
"@io_opencensus_go//trace:go_default_library", "@io_opencensus_go//trace:go_default_library",
@@ -25,6 +26,7 @@ go_test(
"//shared/params:go_default_library", "//shared/params:go_default_library",
"//shared/testutil/assert:go_default_library", "//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library",
], ],

View File

@@ -9,6 +9,7 @@ import (
"sort" "sort"
"github.com/pkg/errors" "github.com/pkg/errors"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
@@ -35,7 +36,7 @@ import (
// data=attestation.data, // data=attestation.data,
// signature=attestation.signature, // signature=attestation.signature,
// ) // )
func ConvertToIndexed(ctx context.Context, attestation *ethpb.Attestation, committee []uint64) (*ethpb.IndexedAttestation, error) { func ConvertToIndexed(ctx context.Context, attestation *ethpb.Attestation, committee []types.ValidatorIndex) (*ethpb.IndexedAttestation, error) {
ctx, span := trace.StartSpan(ctx, "attestationutil.ConvertToIndexed") ctx, span := trace.StartSpan(ctx, "attestationutil.ConvertToIndexed")
defer span.End() defer span.End()
@@ -68,14 +69,14 @@ func ConvertToIndexed(ctx context.Context, attestation *ethpb.Attestation, commi
// """ // """
// committee = get_beacon_committee(state, data.slot, data.index) // committee = get_beacon_committee(state, data.slot, data.index)
// return set(index for i, index in enumerate(committee) if bits[i]) // return set(index for i, index in enumerate(committee) if bits[i])
func AttestingIndices(bf bitfield.Bitfield, committee []uint64) ([]uint64, error) { func AttestingIndices(bf bitfield.Bitfield, committee []types.ValidatorIndex) ([]uint64, error) {
if bf.Len() != uint64(len(committee)) { if bf.Len() != uint64(len(committee)) {
return nil, fmt.Errorf("bitfield length %d is not equal to committee length %d", bf.Len(), len(committee)) return nil, fmt.Errorf("bitfield length %d is not equal to committee length %d", bf.Len(), len(committee))
} }
indices := make([]uint64, 0, bf.Count()) indices := make([]uint64, 0, bf.Count())
for _, idx := range bf.BitIndices() { for _, idx := range bf.BitIndices() {
if idx < len(committee) { if idx < len(committee) {
indices = append(indices, committee[idx]) indices = append(indices, uint64(committee[idx]))
} }
} }
return indices, nil return indices, nil

View File

@@ -4,6 +4,7 @@ import (
"context" "context"
"testing" "testing"
types "github.com/prysmaticlabs/eth2-types"
eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/shared/attestationutil" "github.com/prysmaticlabs/prysm/shared/attestationutil"
@@ -15,7 +16,7 @@ import (
func TestAttestingIndices(t *testing.T) { func TestAttestingIndices(t *testing.T) {
type args struct { type args struct {
bf bitfield.Bitfield bf bitfield.Bitfield
committee []uint64 committee []types.ValidatorIndex
} }
tests := []struct { tests := []struct {
name string name string
@@ -27,7 +28,7 @@ func TestAttestingIndices(t *testing.T) {
name: "Full committee attested", name: "Full committee attested",
args: args{ args: args{
bf: bitfield.Bitlist{0b1111}, bf: bitfield.Bitlist{0b1111},
committee: []uint64{0, 1, 2}, committee: []types.ValidatorIndex{0, 1, 2},
}, },
want: []uint64{0, 1, 2}, want: []uint64{0, 1, 2},
}, },
@@ -35,7 +36,7 @@ func TestAttestingIndices(t *testing.T) {
name: "Partial committee attested", name: "Partial committee attested",
args: args{ args: args{
bf: bitfield.Bitlist{0b1101}, bf: bitfield.Bitlist{0b1101},
committee: []uint64{0, 1, 2}, committee: []types.ValidatorIndex{0, 1, 2},
}, },
want: []uint64{0, 2}, want: []uint64{0, 2},
}, },
@@ -43,7 +44,7 @@ func TestAttestingIndices(t *testing.T) {
name: "Invalid bit length", name: "Invalid bit length",
args: args{ args: args{
bf: bitfield.Bitlist{0b11111}, bf: bitfield.Bitlist{0b11111},
committee: []uint64{0, 1, 2}, committee: []types.ValidatorIndex{0, 1, 2},
}, },
err: "bitfield length 4 is not equal to committee length 3", err: "bitfield length 4 is not equal to committee length 3",
}, },
@@ -155,7 +156,7 @@ func TestIsValidAttestationIndices(t *testing.T) {
func BenchmarkAttestingIndices_PartialCommittee(b *testing.B) { func BenchmarkAttestingIndices_PartialCommittee(b *testing.B) {
bf := bitfield.Bitlist{0b11111111, 0b11111111, 0b10000111, 0b11111111, 0b100} bf := bitfield.Bitlist{0b11111111, 0b11111111, 0b10000111, 0b11111111, 0b100}
committee := []uint64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34} committee := []types.ValidatorIndex{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34}
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {

View File

@@ -225,6 +225,8 @@ func deepValueBaseTypeEqual(v1, v2 reflect.Value) bool {
return v1.Interface().(types.Epoch) == v2.Interface().(types.Epoch) return v1.Interface().(types.Epoch) == v2.Interface().(types.Epoch)
case "Slot": case "Slot":
return v1.Interface().(types.Slot) == v2.Interface().(types.Slot) return v1.Interface().(types.Slot) == v2.Interface().(types.Slot)
case "ValidatorIndex":
return v1.Interface().(types.ValidatorIndex) == v2.Interface().(types.ValidatorIndex)
case "CommitteeIndex": case "CommitteeIndex":
return v1.Interface().(types.CommitteeIndex) == v2.Interface().(types.CommitteeIndex) return v1.Interface().(types.CommitteeIndex) == v2.Interface().(types.CommitteeIndex)
} }

View File

@@ -63,6 +63,7 @@ go_test(
"//shared/testutil/assert:go_default_library", "//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"@com_github_gogo_protobuf//proto:go_default_library", "@com_github_gogo_protobuf//proto:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
], ],
) )

View File

@@ -188,7 +188,7 @@ func GenerateFullBlock(
func GenerateProposerSlashingForValidator( func GenerateProposerSlashingForValidator(
bState *stateTrie.BeaconState, bState *stateTrie.BeaconState,
priv bls.SecretKey, priv bls.SecretKey,
idx uint64, idx types.ValidatorIndex,
) (*ethpb.ProposerSlashing, error) { ) (*ethpb.ProposerSlashing, error) {
header1 := HydrateSignedBeaconHeader(&ethpb.SignedBeaconBlockHeader{ header1 := HydrateSignedBeaconHeader(&ethpb.SignedBeaconBlockHeader{
Header: &ethpb.BeaconBlockHeader{ Header: &ethpb.BeaconBlockHeader{
@@ -248,7 +248,7 @@ func generateProposerSlashings(
func GenerateAttesterSlashingForValidator( func GenerateAttesterSlashingForValidator(
bState *stateTrie.BeaconState, bState *stateTrie.BeaconState,
priv bls.SecretKey, priv bls.SecretKey,
idx uint64, idx types.ValidatorIndex,
) (*ethpb.AttesterSlashing, error) { ) (*ethpb.AttesterSlashing, error) {
currentEpoch := helpers.CurrentEpoch(bState) currentEpoch := helpers.CurrentEpoch(bState)
@@ -266,7 +266,7 @@ func GenerateAttesterSlashingForValidator(
Root: params.BeaconConfig().ZeroHash[:], Root: params.BeaconConfig().ZeroHash[:],
}, },
}, },
AttestingIndices: []uint64{idx}, AttestingIndices: []uint64{uint64(idx)},
} }
var err error var err error
att1.Signature, err = helpers.ComputeDomainAndSign(bState, currentEpoch, att1.Data, params.BeaconConfig().DomainBeaconAttester, priv) att1.Signature, err = helpers.ComputeDomainAndSign(bState, currentEpoch, att1.Data, params.BeaconConfig().DomainBeaconAttester, priv)
@@ -288,7 +288,7 @@ func GenerateAttesterSlashingForValidator(
Root: params.BeaconConfig().ZeroHash[:], Root: params.BeaconConfig().ZeroHash[:],
}, },
}, },
AttestingIndices: []uint64{idx}, AttestingIndices: []uint64{uint64(idx)},
} }
att2.Signature, err = helpers.ComputeDomainAndSign(bState, currentEpoch, att2.Data, params.BeaconConfig().DomainBeaconAttester, priv) att2.Signature, err = helpers.ComputeDomainAndSign(bState, currentEpoch, att2.Data, params.BeaconConfig().DomainBeaconAttester, priv)
if err != nil { if err != nil {
@@ -373,12 +373,12 @@ func generateVoluntaryExits(
return voluntaryExits, nil return voluntaryExits, nil
} }
func randValIndex(bState *stateTrie.BeaconState) (uint64, error) { func randValIndex(bState *stateTrie.BeaconState) (types.ValidatorIndex, error) {
activeCount, err := helpers.ActiveValidatorCount(bState, helpers.CurrentEpoch(bState)) activeCount, err := helpers.ActiveValidatorCount(bState, helpers.CurrentEpoch(bState))
if err != nil { if err != nil {
return 0, err return 0, err
} }
return rand.NewGenerator().Uint64() % activeCount, nil return types.ValidatorIndex(rand.NewGenerator().Uint64() % activeCount), nil
} }
// HydrateSignedBeaconHeader hydrates a signed beacon block header with correct field length sizes // HydrateSignedBeaconHeader hydrates a signed beacon block header with correct field length sizes

View File

@@ -4,6 +4,7 @@ import (
"context" "context"
"testing" "testing"
types "github.com/prysmaticlabs/eth2-types"
eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/core/state" "github.com/prysmaticlabs/prysm/beacon-chain/core/state"
@@ -99,7 +100,7 @@ func TestGenerateFullBlock_ValidAttesterSlashings(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
slashableIndices := block.Block.Body.AttesterSlashings[0].Attestation_1.AttestingIndices slashableIndices := block.Block.Body.AttesterSlashings[0].Attestation_1.AttestingIndices
if val, err := beaconState.ValidatorAtIndexReadOnly(slashableIndices[0]); err != nil || !val.Slashed() { if val, err := beaconState.ValidatorAtIndexReadOnly(types.ValidatorIndex(slashableIndices[0])); err != nil || !val.Slashed() {
require.NoError(t, err) require.NoError(t, err)
t.Fatal("expected validator to be slashed") t.Fatal("expected validator to be slashed")
} }

View File

@@ -4,6 +4,7 @@ import (
"context" "context"
"github.com/pkg/errors" "github.com/pkg/errors"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"go.opencensus.io/trace" "go.opencensus.io/trace"
) )
@@ -12,12 +13,12 @@ import (
// keys from a beacon node via gRPC. // keys from a beacon node via gRPC.
func (s *Service) FindOrGetPublicKeys( func (s *Service) FindOrGetPublicKeys(
ctx context.Context, ctx context.Context,
validatorIndices []uint64, validatorIndices []types.ValidatorIndex,
) (map[uint64][]byte, error) { ) (map[types.ValidatorIndex][]byte, error) {
ctx, span := trace.StartSpan(ctx, "beaconclient.FindOrGetPublicKeys") ctx, span := trace.StartSpan(ctx, "beaconclient.FindOrGetPublicKeys")
defer span.End() defer span.End()
validators := make(map[uint64][]byte, len(validatorIndices)) validators := make(map[types.ValidatorIndex][]byte, len(validatorIndices))
notFound := 0 notFound := 0
for _, validatorIdx := range validatorIndices { for _, validatorIdx := range validatorIndices {
pub, exists := s.publicKeyCache.Get(validatorIdx) pub, exists := s.publicKeyCache.Get(validatorIdx)

View File

@@ -5,6 +5,7 @@ import (
"testing" "testing"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/shared/mock" "github.com/prysmaticlabs/prysm/shared/mock"
"github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/assert"
@@ -54,7 +55,7 @@ func TestService_RequestValidator(t *testing.T) {
).Return(wanted2, nil) ).Return(wanted2, nil)
// We request public key of validator id 0,1. // We request public key of validator id 0,1.
res, err := bs.FindOrGetPublicKeys(context.Background(), []uint64{0, 1}) res, err := bs.FindOrGetPublicKeys(context.Background(), []types.ValidatorIndex{0, 1})
require.NoError(t, err) require.NoError(t, err)
for i, v := range wanted.ValidatorList { for i, v := range wanted.ValidatorList {
assert.DeepEqual(t, wanted.ValidatorList[i].Validator.PublicKey, res[v.Index]) assert.DeepEqual(t, wanted.ValidatorList[i].Validator.PublicKey, res[v.Index])
@@ -63,7 +64,7 @@ func TestService_RequestValidator(t *testing.T) {
require.LogsContain(t, hook, "Retrieved validators id public key map:") require.LogsContain(t, hook, "Retrieved validators id public key map:")
require.LogsDoNotContain(t, hook, "Retrieved validators public keys from cache:") require.LogsDoNotContain(t, hook, "Retrieved validators public keys from cache:")
// We expect public key of validator id 0 to be in cache. // We expect public key of validator id 0 to be in cache.
res, err = bs.FindOrGetPublicKeys(context.Background(), []uint64{0, 3}) res, err = bs.FindOrGetPublicKeys(context.Background(), []types.ValidatorIndex{0, 3})
require.NoError(t, err) require.NoError(t, err)
for i, v := range wanted2.ValidatorList { for i, v := range wanted2.ValidatorList {

View File

@@ -4,6 +4,7 @@ import (
lru "github.com/hashicorp/golang-lru" lru "github.com/hashicorp/golang-lru"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto" "github.com/prometheus/client_golang/prometheus/promauto"
types "github.com/prysmaticlabs/eth2-types"
) )
var ( var (
@@ -38,7 +39,7 @@ func NewPublicKeyCache(size int, onEvicted func(key interface{}, value interface
} }
// Get returns an ok bool and the cached value for the requested validator id key, if any. // Get returns an ok bool and the cached value for the requested validator id key, if any.
func (c *PublicKeyCache) Get(validatorIdx uint64) ([]byte, bool) { func (c *PublicKeyCache) Get(validatorIdx types.ValidatorIndex) ([]byte, bool) {
item, exists := c.cache.Get(validatorIdx) item, exists := c.cache.Get(validatorIdx)
if exists && item != nil { if exists && item != nil {
validatorsCacheHit.Inc() validatorsCacheHit.Inc()
@@ -50,18 +51,18 @@ func (c *PublicKeyCache) Get(validatorIdx uint64) ([]byte, bool) {
} }
// Set the response in the cache. // Set the response in the cache.
func (c *PublicKeyCache) Set(validatorIdx uint64, publicKey []byte) { func (c *PublicKeyCache) Set(validatorIdx types.ValidatorIndex, publicKey []byte) {
_ = c.cache.Add(validatorIdx, publicKey) _ = c.cache.Add(validatorIdx, publicKey)
} }
// Delete removes a validator id from the cache and returns if it existed or not. // Delete removes a validator id from the cache and returns if it existed or not.
// Performs the onEviction function before removal. // Performs the onEviction function before removal.
func (c *PublicKeyCache) Delete(validatorIdx uint64) bool { func (c *PublicKeyCache) Delete(validatorIdx types.ValidatorIndex) bool {
return c.cache.Remove(validatorIdx) return c.cache.Remove(validatorIdx)
} }
// Has returns true if the key exists in the cache. // Has returns true if the key exists in the cache.
func (c *PublicKeyCache) Has(validatorIdx uint64) bool { func (c *PublicKeyCache) Has(validatorIdx types.ValidatorIndex) bool {
return c.cache.Contains(validatorIdx) return c.cache.Contains(validatorIdx)
} }

View File

@@ -37,6 +37,7 @@ go_test(
"//shared/testutil/assert:go_default_library", "//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"//slasher/db/kv:go_default_library", "//slasher/db/kv:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_sirupsen_logrus//hooks/test:go_default_library", "@com_github_sirupsen_logrus//hooks/test:go_default_library",
"@com_github_urfave_cli_v2//:go_default_library", "@com_github_urfave_cli_v2//:go_default_library",
], ],

Some files were not shown because too many files have changed in this diff Show More