diff --git a/beacon-chain/blockchain/chain_info.go b/beacon-chain/blockchain/chain_info.go index 2dd7c3b00c..174fe5423f 100644 --- a/beacon-chain/blockchain/chain_info.go +++ b/beacon-chain/blockchain/chain_info.go @@ -42,7 +42,7 @@ type HeadFetcher interface { HeadRoot(ctx context.Context) ([]byte, error) HeadBlock(ctx context.Context) (*ethpb.SignedBeaconBlock, 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) HeadGenesisValidatorRoot() [32]byte 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. -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() defer s.headLock.RUnlock() if !s.hasHeadState() { - return []uint64{}, nil + return []types.ValidatorIndex{}, nil } return helpers.ActiveValidatorIndices(s.headState(ctx), epoch) } diff --git a/beacon-chain/blockchain/metrics.go b/beacon-chain/blockchain/metrics.go index 1cdc4904aa..c2fca57486 100644 --- a/beacon-chain/blockchain/metrics.go +++ b/beacon-chain/blockchain/metrics.go @@ -140,7 +140,7 @@ func reportEpochMetrics(ctx context.Context, postState, headState *stateTrie.Bea slashingEffectiveBalance := uint64(0) for i, validator := range postState.Validators() { - bal, err := postState.BalanceAtIndex(uint64(i)) + bal, err := postState.BalanceAtIndex(types.ValidatorIndex(i)) if err != nil { log.Errorf("Could not load validator balance: %v", err) continue diff --git a/beacon-chain/blockchain/testing/mock.go b/beacon-chain/blockchain/testing/mock.go index ee8c13b18c..ca9615aba5 100644 --- a/beacon-chain/blockchain/testing/mock.go +++ b/beacon-chain/blockchain/testing/mock.go @@ -291,9 +291,9 @@ func (s *ChainService) AttestationPreState(_ context.Context, _ *ethpb.Attestati } // 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 { - return []uint64{}, nil + return []types.ValidatorIndex{}, nil } return helpers.ActiveValidatorIndices(s.State, epoch) } diff --git a/beacon-chain/cache/committee.go b/beacon-chain/cache/committee.go index 25f5a1f9f8..73922c4826 100644 --- a/beacon-chain/cache/committee.go +++ b/beacon-chain/cache/committee.go @@ -56,7 +56,7 @@ func NewCommitteesCache() *CommitteeCache { // 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. -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() 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. -func (c *CommitteeCache) ActiveIndices(seed [32]byte) ([]uint64, error) { +func (c *CommitteeCache) ActiveIndices(seed [32]byte) ([]types.ValidatorIndex, error) { c.lock.RLock() defer c.lock.RUnlock() obj, exists, err := c.CommitteeCache.GetByKey(key(seed)) diff --git a/beacon-chain/cache/committee_disabled.go b/beacon-chain/cache/committee_disabled.go index ce842fa3aa..f4dc21eb76 100644 --- a/beacon-chain/cache/committee_disabled.go +++ b/beacon-chain/cache/committee_disabled.go @@ -16,7 +16,7 @@ func NewCommitteesCache() *FakeCommitteeCache { // 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. -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 } @@ -27,12 +27,12 @@ func (c *FakeCommitteeCache) AddCommitteeShuffledList(committees *Committees) er } // 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 } // 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 } @@ -42,7 +42,7 @@ func (c *FakeCommitteeCache) ActiveIndicesCount(seed [32]byte) (int, error) { } // 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 } diff --git a/beacon-chain/cache/committee_test.go b/beacon-chain/cache/committee_test.go index 8b3e9478ac..8fe169ea6a 100644 --- a/beacon-chain/cache/committee_test.go +++ b/beacon-chain/cache/committee_test.go @@ -17,7 +17,7 @@ func TestCommitteeKeyFn_OK(t *testing.T) { item := &Committees{ CommitteeCount: 1, Seed: [32]byte{'A'}, - ShuffledIndices: []uint64{1, 2, 3, 4, 5}, + ShuffledIndices: []types.ValidatorIndex{1, 2, 3, 4, 5}, } k, err := committeeKeyFn(item) @@ -34,7 +34,7 @@ func TestCommitteeCache_CommitteesByEpoch(t *testing.T) { cache := NewCommitteesCache() item := &Committees{ - ShuffledIndices: []uint64{1, 2, 3, 4, 5, 6}, + ShuffledIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}, Seed: [32]byte{'A'}, CommitteeCount: 3, } @@ -59,7 +59,7 @@ func TestCommitteeCache_CommitteesByEpoch(t *testing.T) { func TestCommitteeCache_ActiveIndices(t *testing.T) { 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) require.NoError(t, err) if indices != nil { @@ -76,7 +76,7 @@ func TestCommitteeCache_ActiveIndices(t *testing.T) { func TestCommitteeCache_ActiveCount(t *testing.T) { 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) require.NoError(t, err) 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{ CommitteeCount: 1, Seed: seed, - ShuffledIndices: []uint64{0}, - SortedIndices: []uint64{}, + ShuffledIndices: []types.ValidatorIndex{0}, + SortedIndices: []types.ValidatorIndex{}, }) require.NoError(t, err) diff --git a/beacon-chain/cache/committees.go b/beacon-chain/cache/committees.go index 8bc06c1b1b..ba1bfb4887 100644 --- a/beacon-chain/cache/committees.go +++ b/beacon-chain/cache/committees.go @@ -1,6 +1,10 @@ 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 // a Committee struct. @@ -10,6 +14,6 @@ var ErrNotCommittee = errors.New("object is not a committee struct") type Committees struct { CommitteeCount uint64 Seed [32]byte - ShuffledIndices []uint64 - SortedIndices []uint64 + ShuffledIndices []types.ValidatorIndex + SortedIndices []types.ValidatorIndex } diff --git a/beacon-chain/cache/proposer_indices.go b/beacon-chain/cache/proposer_indices.go index 83bb3c824e..78583b2091 100644 --- a/beacon-chain/cache/proposer_indices.go +++ b/beacon-chain/cache/proposer_indices.go @@ -7,6 +7,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" + types "github.com/prysmaticlabs/eth2-types" "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. -func (c *ProposerIndicesCache) ProposerIndices(r [32]byte) ([]uint64, error) { +func (c *ProposerIndicesCache) ProposerIndices(r [32]byte) ([]types.ValidatorIndex, error) { c.lock.RLock() defer c.lock.RUnlock() obj, exists, err := c.ProposerIndicesCache.GetByKey(key(r)) diff --git a/beacon-chain/cache/proposer_indices_disabled.go b/beacon-chain/cache/proposer_indices_disabled.go index e002677b21..5e4ede6890 100644 --- a/beacon-chain/cache/proposer_indices_disabled.go +++ b/beacon-chain/cache/proposer_indices_disabled.go @@ -3,6 +3,8 @@ // This file is used in fuzzer builds to bypass proposer indices caches. package cache +import types "github.com/prysmaticlabs/eth2-types" + // FakeProposerIndicesCache is a struct with 1 queue for looking up proposer indices by root. type FakeProposerIndicesCache struct { } @@ -19,7 +21,7 @@ func (c *FakeProposerIndicesCache) AddProposerIndices(p *ProposerIndices) error } // 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 } diff --git a/beacon-chain/cache/proposer_indices_test.go b/beacon-chain/cache/proposer_indices_test.go index d21ad168a1..39154c0534 100644 --- a/beacon-chain/cache/proposer_indices_test.go +++ b/beacon-chain/cache/proposer_indices_test.go @@ -4,6 +4,7 @@ import ( "strconv" "testing" + types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/require" @@ -12,7 +13,7 @@ import ( func TestProposerKeyFn_OK(t *testing.T) { item := &ProposerIndices{ BlockRoot: [32]byte{'A'}, - ProposerIndices: []uint64{1, 2, 3, 4, 5}, + ProposerIndices: []types.ValidatorIndex{1, 2, 3, 4, 5}, } k, err := proposerIndicesKeyFn(item) @@ -48,7 +49,7 @@ func TestProposerCache_AddProposerIndicesList(t *testing.T) { require.NoError(t, err) 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)) received, err = cache.ProposerIndices(item.BlockRoot) diff --git a/beacon-chain/cache/proposer_indices_type.go b/beacon-chain/cache/proposer_indices_type.go index dd51a0f26a..06f003465f 100644 --- a/beacon-chain/cache/proposer_indices_type.go +++ b/beacon-chain/cache/proposer_indices_type.go @@ -1,6 +1,10 @@ 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 // 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. type ProposerIndices struct { BlockRoot [32]byte - ProposerIndices []uint64 + ProposerIndices []types.ValidatorIndex } diff --git a/beacon-chain/core/blocks/attestation.go b/beacon-chain/core/blocks/attestation.go index 980dea78dc..1a153dd23b 100644 --- a/beacon-chain/core/blocks/attestation.go +++ b/beacon-chain/core/blocks/attestation.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/pkg/errors" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -248,7 +249,7 @@ func VerifyIndexedAttestation(ctx context.Context, beaconState *stateTrie.Beacon indices := indexedAtt.AttestingIndices var pubkeys []bls.PublicKey for i := 0; i < len(indices); i++ { - pubkeyAtIdx := beaconState.PubkeyAtIndex(indices[i]) + pubkeyAtIdx := beaconState.PubkeyAtIndex(types.ValidatorIndex(indices[i])) pk, err := bls.PublicKeyFromBytes(pubkeyAtIdx[:]) if err != nil { return errors.Wrap(err, "could not deserialize validator public key") diff --git a/beacon-chain/core/blocks/attester_slashing.go b/beacon-chain/core/blocks/attester_slashing.go index a003d3acbf..752c70a5fd 100644 --- a/beacon-chain/core/blocks/attester_slashing.go +++ b/beacon-chain/core/blocks/attester_slashing.go @@ -5,6 +5,7 @@ import ( "sort" "github.com/pkg/errors" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" v "github.com/prysmaticlabs/prysm/beacon-chain/core/validators" @@ -56,12 +57,12 @@ func ProcessAttesterSlashings( var slashedAny bool var val stateTrie.ReadOnlyValidator for _, validatorIndex := range slashableIndices { - val, err = beaconState.ValidatorAtIndexReadOnly(validatorIndex) + val, err = beaconState.ValidatorAtIndexReadOnly(types.ValidatorIndex(validatorIndex)) if err != nil { return nil, err } 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 { return nil, errors.Wrapf(err, "could not slash validator index %d", validatorIndex) diff --git a/beacon-chain/core/blocks/deposit_test.go b/beacon-chain/core/blocks/deposit_test.go index e657ea9745..68789eab91 100644 --- a/beacon-chain/core/blocks/deposit_test.go +++ b/beacon-chain/core/blocks/deposit_test.go @@ -317,7 +317,7 @@ func TestPreGenesisDeposits_SkipInvalidDeposit(t *testing.T) { require.Equal(t, false, ok, "bad pubkey should not exist in state") 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.Equal(t, params.BeaconConfig().MaxEffectiveBalance, val.EffectiveBalance, "unequal effective balance") require.Equal(t, types.Epoch(0), val.ActivationEpoch) diff --git a/beacon-chain/core/blocks/proposer_slashing_test.go b/beacon-chain/core/blocks/proposer_slashing_test.go index f09a978557..33eb9d6ba5 100644 --- a/beacon-chain/core/blocks/proposer_slashing_test.go +++ b/beacon-chain/core/blocks/proposer_slashing_test.go @@ -139,7 +139,7 @@ func TestProcessProposerSlashings_AppliesCorrectStatus(t *testing.T) { // We test the case when data is correct and verify the validator // registry has been updated. beaconState, privKeys := testutil.DeterministicGenesisState(t, 100) - proposerIdx := uint64(1) + proposerIdx := types.ValidatorIndex(1) header1 := ðpb.SignedBeaconBlockHeader{ Header: testutil.HydrateBeaconHeader(ðpb.BeaconBlockHeader{ diff --git a/beacon-chain/core/blocks/signature.go b/beacon-chain/core/blocks/signature.go index 0a47170f33..b409b4c5af 100644 --- a/beacon-chain/core/blocks/signature.go +++ b/beacon-chain/core/blocks/signature.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "github.com/pkg/errors" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -148,7 +149,7 @@ func createAttestationSignatureSet(ctx context.Context, beaconState *stateTrie.B indices := ia.AttestingIndices pubkeys := make([][]byte, len(indices)) for i := 0; i < len(indices); i++ { - pubkeyAtIdx := beaconState.PubkeyAtIndex(indices[i]) + pubkeyAtIdx := beaconState.PubkeyAtIndex(types.ValidatorIndex(indices[i])) pubkeys[i] = pubkeyAtIdx[:] } aggP, err := bls.AggregatePublicKeys(pubkeys) diff --git a/beacon-chain/core/epoch/BUILD.bazel b/beacon-chain/core/epoch/BUILD.bazel index c35460d13d..796c44a18a 100644 --- a/beacon-chain/core/epoch/BUILD.bazel +++ b/beacon-chain/core/epoch/BUILD.bazel @@ -15,6 +15,7 @@ go_library( "//shared/mathutil:go_default_library", "//shared/params: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", ], ) diff --git a/beacon-chain/core/epoch/epoch_processing.go b/beacon-chain/core/epoch/epoch_processing.go index 9efbcc4402..c2257578bf 100644 --- a/beacon-chain/core/epoch/epoch_processing.go +++ b/beacon-chain/core/epoch/epoch_processing.go @@ -9,6 +9,7 @@ import ( "sort" "github.com/pkg/errors" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/validators" @@ -22,7 +23,7 @@ import ( // sortableIndices implements the Sort interface to sort newly activated validator indices // by activation epoch and by index number. type sortableIndices struct { - indices []uint64 + indices []types.ValidatorIndex validators []*ethpb.Validator } @@ -85,7 +86,7 @@ func ProcessRegistryUpdates(state *stateTrie.BeaconState) (*stateTrie.BeaconStat // Process the validators for activation eligibility. if helpers.IsEligibleForActivationQueue(validator) { 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 } } @@ -94,7 +95,7 @@ func ProcessRegistryUpdates(state *stateTrie.BeaconState) (*stateTrie.BeaconStat isActive := helpers.IsActiveValidator(validator, currentEpoch) belowEjectionBalance := validator.EffectiveBalance <= ejectionBal if isActive && belowEjectionBalance { - state, err = validators.InitiateValidatorExit(state, uint64(idx)) + state, err = validators.InitiateValidatorExit(state, types.ValidatorIndex(idx)) if err != nil { 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. - var activationQ []uint64 + var activationQ []types.ValidatorIndex for idx, validator := range vals { 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 { penaltyNumerator := val.EffectiveBalance / increment * minSlashing 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 true, val, nil @@ -341,8 +342,8 @@ func ProcessFinalUpdates(state *stateTrie.BeaconState) (*stateTrie.BeaconState, // for a in attestations: // output = output.union(get_attesting_indices(state, a.data, a.aggregation_bits)) // return set(filter(lambda index: not state.validators[index].slashed, output)) -func UnslashedAttestingIndices(state *stateTrie.BeaconState, atts []*pb.PendingAttestation) ([]uint64, error) { - var setIndices []uint64 +func UnslashedAttestingIndices(state *stateTrie.BeaconState, atts []*pb.PendingAttestation) ([]types.ValidatorIndex, error) { + var setIndices []types.ValidatorIndex seen := make(map[uint64]bool) for _, att := range atts { @@ -357,7 +358,7 @@ func UnslashedAttestingIndices(state *stateTrie.BeaconState, atts []*pb.PendingA // Create a set for attesting indices for _, index := range attestingIndices { if !seen[index] { - setIndices = append(setIndices, index) + setIndices = append(setIndices, types.ValidatorIndex(index)) } seen[index] = true } @@ -389,7 +390,7 @@ func UnslashedAttestingIndices(state *stateTrie.BeaconState, atts []*pb.PendingA // total_balance = get_total_active_balance(state) // effective_balance = state.validator_registry[index].effective_balance // 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) if err != nil { return 0, errors.Wrap(err, "could not calculate active balance") diff --git a/beacon-chain/core/epoch/precompute/reward_penalty.go b/beacon-chain/core/epoch/precompute/reward_penalty.go index d3d95d009c..d7b1802f9d 100644 --- a/beacon-chain/core/epoch/precompute/reward_penalty.go +++ b/beacon-chain/core/epoch/precompute/reward_penalty.go @@ -163,7 +163,7 @@ func ProposersDelta(state *stateTrie.BeaconState, pBal *Balance, vp []*Validator baseRewardsPerEpoch := params.BeaconConfig().BaseRewardsPerEpoch proposerRewardQuotient := params.BeaconConfig().ProposerRewardQuotient 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. return nil, errors.New("proposer index out of range") } diff --git a/beacon-chain/core/epoch/precompute/reward_penalty_test.go b/beacon-chain/core/epoch/precompute/reward_penalty_test.go index a0825cac41..e0bf877cf5 100644 --- a/beacon-chain/core/epoch/precompute/reward_penalty_test.go +++ b/beacon-chain/core/epoch/precompute/reward_penalty_test.go @@ -78,7 +78,7 @@ func TestAttestationDeltaPrecompute(t *testing.T) { base.PreviousEpochAttestations = atts beaconState, err := state.InitializeFromProto(base) require.NoError(t, err) - slashedAttestedIndices := []uint64{1413} + slashedAttestedIndices := []types.ValidatorIndex{1413} for _, i := range slashedAttestedIndices { vs := beaconState.Validators() vs[i].Slashed = true @@ -101,7 +101,7 @@ func TestAttestationDeltaPrecompute(t *testing.T) { totalBalance, err := helpers.TotalActiveBalance(beaconState) require.NoError(t, err) - attestedIndices := []uint64{55, 1339, 1746, 1811, 1569} + attestedIndices := []types.ValidatorIndex{55, 1339, 1746, 1811, 1569} for _, i := range attestedIndices { base, err := epoch.BaseReward(beaconState, i) 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") } - nonAttestedIndices := []uint64{434, 677, 872, 791} + nonAttestedIndices := []types.ValidatorIndex{434, 677, 872, 791} for _, i := range nonAttestedIndices { base, err := epoch.BaseReward(beaconState, i) 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, 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 { vs := beaconState.Validators() vs[i].Slashed = true @@ -301,7 +301,7 @@ func TestProposerDeltaPrecompute_HappyCase(t *testing.T) { beaconState, err := state.InitializeFromProto(base) require.NoError(t, err) - proposerIndex := uint64(1) + proposerIndex := types.ValidatorIndex(1) b := &Balance{ActiveCurrentEpoch: 1000} v := []*Validator{ {IsPrevEpochAttester: true, CurrentEpochEffectiveBalance: 32, ProposerIndex: proposerIndex}, @@ -323,7 +323,7 @@ func TestProposerDeltaPrecompute_ValidatorIndexOutOfRange(t *testing.T) { beaconState, err := state.InitializeFromProto(base) require.NoError(t, err) - proposerIndex := validatorCount + proposerIndex := types.ValidatorIndex(validatorCount) b := &Balance{ActiveCurrentEpoch: 1000} v := []*Validator{ {IsPrevEpochAttester: true, CurrentEpochEffectiveBalance: 32, ProposerIndex: proposerIndex}, @@ -339,7 +339,7 @@ func TestProposerDeltaPrecompute_SlashedCase(t *testing.T) { beaconState, err := state.InitializeFromProto(base) require.NoError(t, err) - proposerIndex := uint64(1) + proposerIndex := types.ValidatorIndex(1) b := &Balance{ActiveCurrentEpoch: 1000} v := []*Validator{ {IsPrevEpochAttester: true, CurrentEpochEffectiveBalance: 32, ProposerIndex: proposerIndex, IsSlashed: true}, diff --git a/beacon-chain/core/epoch/precompute/slashing.go b/beacon-chain/core/epoch/precompute/slashing.go index 9c60f3ff8c..357d4017f0 100644 --- a/beacon-chain/core/epoch/precompute/slashing.go +++ b/beacon-chain/core/epoch/precompute/slashing.go @@ -1,6 +1,7 @@ package precompute import ( + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -47,7 +48,7 @@ func ProcessSlashingsPrecompute(state *stateTrie.BeaconState, pBal *Balance) err if val.Slashed && correctEpoch { penaltyNumerator := val.EffectiveBalance / increment * minSlashing 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 true, val, nil diff --git a/beacon-chain/core/epoch/precompute/type.go b/beacon-chain/core/epoch/precompute/type.go index 82bef11a28..8305280ae3 100644 --- a/beacon-chain/core/epoch/precompute/type.go +++ b/beacon-chain/core/epoch/precompute/type.go @@ -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 types.Slot // 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 uint64 // AfterEpochTransitionBalance is the validator balance after epoch transition. diff --git a/beacon-chain/core/helpers/committee.go b/beacon-chain/core/helpers/committee.go index 4e16b1e5ff..263239535a 100644 --- a/beacon-chain/core/helpers/committee.go +++ b/beacon-chain/core/helpers/committee.go @@ -68,7 +68,7 @@ func SlotCommitteeCount(activeValidatorCount uint64) uint64 { // index=(slot % SLOTS_PER_EPOCH) * committees_per_slot + index, // 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) seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester) 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 // 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. -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) if err != nil { 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 // return [indices[compute_shuffled_index(ValidatorIndex(i), len(indices), seed)] for i in range(start, end) func ComputeCommittee( - indices []uint64, + indices []types.ValidatorIndex, seed [32]byte, index, count uint64, -) ([]uint64, error) { +) ([]types.ValidatorIndex, error) { validatorCount := uint64(len(indices)) start := sliceutil.SplitOffset(validatorCount, count, index) 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. - shuffledIndices := make([]uint64, len(indices)) + shuffledIndices := make([]types.ValidatorIndex, len(indices)) copy(shuffledIndices, indices) // UnshuffleList is used here as it is an optimized implementation created // for fast computation of committees. @@ -154,7 +154,7 @@ func ComputeCommittee( // CommitteeAssignmentContainer represents a committee, index, and attester slot for a given epoch. type CommitteeAssignmentContainer struct { - Committee []uint64 + Committee []types.ValidatorIndex AttesterSlot types.Slot CommitteeIndex types.CommitteeIndex } @@ -169,7 +169,7 @@ type CommitteeAssignmentContainer struct { func CommitteeAssignments( state *stateTrie.BeaconState, epoch types.Epoch, -) (map[uint64]*CommitteeAssignmentContainer, map[uint64][]types.Slot, error) { +) (map[types.ValidatorIndex]*CommitteeAssignmentContainer, map[types.ValidatorIndex][]types.Slot, error) { nextEpoch := NextEpoch(state) if epoch > nextEpoch { return nil, nil, fmt.Errorf( @@ -186,7 +186,7 @@ func CommitteeAssignments( if err != nil { 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. validProposalEpoch := epoch < nextEpoch 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 // active validator set, which does not change. 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. 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, // 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) if err != nil { 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 IsActiveValidatorUsingTrie(val, epoch) { - indices = append(indices, uint64(idx)) + indices = append(indices, types.ValidatorIndex(idx)) } return 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, // sorted indices is required to retrieve proposer index. This is also // used for failing verify signature fallback. - sortedIndices := make([]uint64, len(shuffledIndices)) + sortedIndices := make([]types.ValidatorIndex, len(shuffledIndices)) copy(sortedIndices, shuffledIndices) sort.Slice(sortedIndices, func(i, j int) bool { 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, // 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() - proposerIndices := make([]uint64, params.BeaconConfig().SlotsPerEpoch) + proposerIndices := make([]types.ValidatorIndex, params.BeaconConfig().SlotsPerEpoch) e := CurrentEpoch(state) seed, err := Seed(state, e, params.BeaconConfig().DomainBeaconProposer) diff --git a/beacon-chain/core/helpers/committee_test.go b/beacon-chain/core/helpers/committee_test.go index 33bd814220..8825a8f154 100644 --- a/beacon-chain/core/helpers/committee_test.go +++ b/beacon-chain/core/helpers/committee_test.go @@ -70,7 +70,7 @@ func TestComputeCommittee_WithoutCache(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} index := uint64(215) count := uint64(32) @@ -150,9 +150,9 @@ func TestCommitteeAssignments_CanRetrieve(t *testing.T) { require.NoError(t, err) tests := []struct { - index uint64 + index types.ValidatorIndex slot types.Slot - committee []uint64 + committee []types.ValidatorIndex committeeIndex types.CommitteeIndex isProposer bool proposerSlot types.Slot @@ -160,14 +160,14 @@ func TestCommitteeAssignments_CanRetrieve(t *testing.T) { { index: 0, slot: 78, - committee: []uint64{0, 38}, + committee: []types.ValidatorIndex{0, 38}, committeeIndex: 0, isProposer: false, }, { index: 1, slot: 71, - committee: []uint64{1, 4}, + committee: []types.ValidatorIndex{1, 4}, committeeIndex: 0, isProposer: true, proposerSlot: 79, @@ -175,13 +175,13 @@ func TestCommitteeAssignments_CanRetrieve(t *testing.T) { { index: 11, slot: 90, - committee: []uint64{31, 11}, + committee: []types.ValidatorIndex{31, 11}, committeeIndex: 0, isProposer: false, }, { index: 2, slot: 127, // 3rd epoch has more active validators - committee: []uint64{89, 2, 81, 5}, + committee: []types.ValidatorIndex{89, 2, 81, 5}, committeeIndex: 0, isProposer: false, }, @@ -404,8 +404,8 @@ func TestUpdateCommitteeCache_CanUpdate(t *testing.T) { ClearCache() validatorCount := params.BeaconConfig().MinGenesisActiveValidatorCount validators := make([]*ethpb.Validator, validatorCount) - indices := make([]uint64, validatorCount) - for i := uint64(0); i < validatorCount; i++ { + indices := make([]types.ValidatorIndex, validatorCount) + for i := types.ValidatorIndex(0); uint64(i) < validatorCount; i++ { validators[i] = ðpb.Validator{ ExitEpoch: params.BeaconConfig().FarFutureEpoch, } @@ -647,7 +647,7 @@ func TestPrecomputeProposerIndices_Ok(t *testing.T) { proposerIndices, err := precomputeProposerIndices(state, indices) require.NoError(t, err) - var wantedProposerIndices []uint64 + var wantedProposerIndices []types.ValidatorIndex seed, err := Seed(state, 0, params.BeaconConfig().DomainBeaconProposer) require.NoError(t, err) for i := uint64(0); i < uint64(params.BeaconConfig().SlotsPerEpoch); i++ { diff --git a/beacon-chain/core/helpers/rewards_penalties.go b/beacon-chain/core/helpers/rewards_penalties.go index 0158c4d3fd..a3ce41d508 100644 --- a/beacon-chain/core/helpers/rewards_penalties.go +++ b/beacon-chain/core/helpers/rewards_penalties.go @@ -1,6 +1,7 @@ package helpers import ( + types "github.com/prysmaticlabs/eth2-types" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/shared/params" ) @@ -15,7 +16,7 @@ import ( // ``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]))) -func TotalBalance(state *stateTrie.BeaconState, indices []uint64) uint64 { +func TotalBalance(state *stateTrie.BeaconState, indices []types.ValidatorIndex) uint64 { total := uint64(0) for _, idx := range indices { @@ -64,7 +65,7 @@ func TotalActiveBalance(state *stateTrie.BeaconState) (uint64, error) { // Increase the validator balance at index ``index`` by ``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) if err != nil { return err @@ -94,7 +95,7 @@ func IncreaseBalanceWithVal(currBalance, delta uint64) uint64 { // 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 -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) if err != nil { return err diff --git a/beacon-chain/core/helpers/rewards_penalties_test.go b/beacon-chain/core/helpers/rewards_penalties_test.go index 37b24873cd..993a09688a 100644 --- a/beacon-chain/core/helpers/rewards_penalties_test.go +++ b/beacon-chain/core/helpers/rewards_penalties_test.go @@ -3,6 +3,7 @@ package helpers import ( "testing" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state" pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" @@ -18,7 +19,7 @@ func TestTotalBalance_OK(t *testing.T) { }}) 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 + state.Validators()[2].EffectiveBalance + state.Validators()[3].EffectiveBalance 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{}}) require.NoError(t, err) - balance := TotalBalance(state, []uint64{}) + balance := TotalBalance(state, []types.ValidatorIndex{}) wanted := params.BeaconConfig().EffectiveBalanceIncrement assert.Equal(t, wanted, balance, "Incorrect TotalBalance") } @@ -81,7 +82,7 @@ func TestGetBalance_OK(t *testing.T) { func TestIncreaseBalance_OK(t *testing.T) { tests := []struct { - i uint64 + i types.ValidatorIndex b []uint64 nb uint64 eb uint64 @@ -104,7 +105,7 @@ func TestIncreaseBalance_OK(t *testing.T) { func TestDecreaseBalance_OK(t *testing.T) { tests := []struct { - i uint64 + i types.ValidatorIndex b []uint64 nb uint64 eb uint64 diff --git a/beacon-chain/core/helpers/shuffle.go b/beacon-chain/core/helpers/shuffle.go index ff70903970..d84cfa51d8 100644 --- a/beacon-chain/core/helpers/shuffle.go +++ b/beacon-chain/core/helpers/shuffle.go @@ -4,6 +4,7 @@ import ( "encoding/binary" "fmt" + types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/hashutil" "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 // 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 -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 */) } // UnShuffledIndex returns the inverse of ShuffledIndex. This implementation is based // 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 */) } @@ -64,11 +65,11 @@ func UnShuffledIndex(index, indexCount uint64, seed [32]byte) (uint64, error) { // index = flip if bit else 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 { return index, nil } - if index >= indexCount { + if uint64(index) >= indexCount { return 0, fmt.Errorf("input index %d out of bounds: %d", index, indexCount) } @@ -95,9 +96,9 @@ func ComputeShuffledIndex(index, indexCount uint64, seed [32]byte, shuffle bool) hash8 := hash[:8] hash8Int := bytesutil.FromBytes8(hash8) 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. - position := index + position := uint64(index) if flip > position { position = flip } @@ -113,7 +114,7 @@ func ComputeShuffledIndex(index, indexCount uint64, seed [32]byte, shuffle bool) bitV := (byteV >> (position & 0x7)) & 0x1 // index = flip if bit else index if bitV == 1 { - index = flip + index = types.ValidatorIndex(flip) } if shuffle { round++ @@ -144,17 +145,17 @@ func ComputeShuffledIndex(index, indexCount uint64, seed [32]byte, shuffle bool) // - change byteV every 8 iterations. // - 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). -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 */) } // 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 */) } // 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 { return input, nil } @@ -183,7 +184,7 @@ func innerShuffleList(input []uint64, seed [32]byte, shuffle bool) ([]uint64, er source := hashfunc(buf) byteV := source[(pivot&0xff)>>3] 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. mirror = (pivot + listSize + 1) >> 1 @@ -192,7 +193,7 @@ func innerShuffleList(input []uint64, seed [32]byte, shuffle bool) ([]uint64, er source = hashfunc(buf) byteV = source[(end&0xff)>>3] 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 { 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 // depending on if the conditions are met. -func swapOrNot(buf []byte, byteV byte, i uint64, input []uint64, - j uint64, source [32]byte, hashFunc func([]byte) [32]byte) (byte, [32]byte) { +func swapOrNot(buf []byte, byteV byte, i types.ValidatorIndex, input []types.ValidatorIndex, + j types.ValidatorIndex, source [32]byte, hashFunc func([]byte) [32]byte) (byte, [32]byte) { if j&0xff == 0xff { // just overwrite the last part of the buffer, reuse the start (seed, round) binary.LittleEndian.PutUint32(buf[pivotViewSize:], uint32(j>>8)) diff --git a/beacon-chain/core/helpers/shuffle_test.go b/beacon-chain/core/helpers/shuffle_test.go index 6eeedb1c25..f2216211c1 100644 --- a/beacon-chain/core/helpers/shuffle_test.go +++ b/beacon-chain/core/helpers/shuffle_test.go @@ -5,6 +5,7 @@ import ( "reflect" "testing" + types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/sliceutil" "github.com/prysmaticlabs/prysm/shared/testutil/assert" @@ -13,7 +14,7 @@ import ( func TestShuffleList_InvalidValidatorCount(t *testing.T) { maxShuffleListSize = 20 - list := make([]uint64, 21) + list := make([]types.ValidatorIndex, 21) if _, err := ShuffleList(list, [32]byte{123, 125}); err == nil { t.Error("Shuffle should have failed when validator count exceeds ModuloBias") maxShuffleListSize = 1 << 40 @@ -22,14 +23,14 @@ func TestShuffleList_InvalidValidatorCount(t *testing.T) { } func TestShuffleList_OK(t *testing.T) { - var list1 []uint64 + var list1 []types.ValidatorIndex seed1 := [32]byte{1, 128, 12} seed2 := [32]byte{2, 128, 12} 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) list1, err := ShuffleList(list1, seed1) @@ -41,8 +42,8 @@ func TestShuffleList_OK(t *testing.T) { if reflect.DeepEqual(list1, list2) { 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, []uint64{0, 5, 2, 1, 6, 8, 7, 3, 4, 9}, list2, "List 2 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, []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) { @@ -60,14 +61,14 @@ func TestSplitIndices_OK(t *testing.T) { } func TestShuffleList_Vs_ShuffleIndex(t *testing.T) { - var list []uint64 + var list []types.ValidatorIndex listSize := uint64(1000) 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) } - shuffledListByIndex := make([]uint64, listSize) - for i := uint64(0); i < listSize; i++ { + shuffledListByIndex := make([]types.ValidatorIndex, listSize) + for i := types.ValidatorIndex(0); uint64(i) < listSize; i++ { si, err := ShuffledIndex(i, listSize, seed) assert.NoError(t, err) shuffledListByIndex[si] = i @@ -83,7 +84,7 @@ func BenchmarkShuffledIndex(b *testing.B) { for _, listSize := range listSizes { b.Run(fmt.Sprintf("ShuffledIndex_%d", listSize), func(ib *testing.B) { 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) } }) @@ -97,7 +98,7 @@ func BenchmarkIndexComparison(b *testing.B) { b.Run(fmt.Sprintf("Indexwise_ShuffleList_%d", listSize), func(ib *testing.B) { for i := 0; i < ib.N; i++ { // 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) assert.NoError(b, err) } @@ -110,9 +111,9 @@ func BenchmarkShuffleList(b *testing.B) { listSizes := []uint64{400000, 40000, 400} seed := [32]byte{123, 42} for _, listSize := range listSizes { - testIndices := make([]uint64, listSize) + testIndices := make([]types.ValidatorIndex, listSize) 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) { for i := 0; i < ib.N; i++ { @@ -124,25 +125,25 @@ func BenchmarkShuffleList(b *testing.B) { } func TestShuffledIndex(t *testing.T) { - var list []uint64 + var list []types.ValidatorIndex listSize := uint64(399) - for i := uint64(0); i < listSize; i++ { + for i := types.ValidatorIndex(0); uint64(i) < listSize; i++ { list = append(list, i) } - shuffledList := make([]uint64, listSize) - unShuffledList := make([]uint64, listSize) + shuffledList := make([]types.ValidatorIndex, listSize) + unshuffledlist := make([]types.ValidatorIndex, listSize) 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) assert.NoError(t, err) 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) 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) { diff --git a/beacon-chain/core/helpers/signing_root.go b/beacon-chain/core/helpers/signing_root.go index bace84a8b3..014660589a 100644 --- a/beacon-chain/core/helpers/signing_root.go +++ b/beacon-chain/core/helpers/signing_root.go @@ -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. -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) if err != nil { return err diff --git a/beacon-chain/core/helpers/spectest/BUILD.bazel b/beacon-chain/core/helpers/spectest/BUILD.bazel index 23de55cb1d..58d299e1cd 100644 --- a/beacon-chain/core/helpers/spectest/BUILD.bazel +++ b/beacon-chain/core/helpers/spectest/BUILD.bazel @@ -6,6 +6,7 @@ go_library( srcs = ["shuffle_test_format.go"], importpath = "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers/spectest", visibility = ["//beacon-chain:__subpackages__"], + deps = ["@com_github_prysmaticlabs_eth2_types//:go_default_library"], ) go_test( @@ -25,5 +26,6 @@ go_test( "//shared/testutil/require:go_default_library", "@com_github_ethereum_go_ethereum//common:go_default_library", "@com_github_go_yaml_yaml//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", ], ) diff --git a/beacon-chain/core/helpers/spectest/shuffle_test_format.go b/beacon-chain/core/helpers/spectest/shuffle_test_format.go index 317cef77d3..d88b07f414 100644 --- a/beacon-chain/core/helpers/spectest/shuffle_test_format.go +++ b/beacon-chain/core/helpers/spectest/shuffle_test_format.go @@ -1,8 +1,10 @@ package spectest +import types "github.com/prysmaticlabs/eth2-types" + // ShuffleTestCase -- type ShuffleTestCase struct { - Seed string `yaml:"seed"` - Count uint64 `yaml:"count"` - Mapping []uint64 `yaml:"mapping"` + Seed string `yaml:"seed"` + Count uint64 `yaml:"count"` + Mapping []types.ValidatorIndex `yaml:"mapping"` } diff --git a/beacon-chain/core/helpers/spectest/shuffle_yaml_test.go b/beacon-chain/core/helpers/spectest/shuffle_yaml_test.go index cf71b097fb..46fb2516d1 100644 --- a/beacon-chain/core/helpers/spectest/shuffle_yaml_test.go +++ b/beacon-chain/core/helpers/spectest/shuffle_yaml_test.go @@ -4,13 +4,12 @@ package spectest import ( "encoding/hex" - "fmt" "path" - "reflect" "testing" "github.com/ethereum/go-ethereum/common" "github.com/go-yaml/yaml" + types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/shared/params/spectest" "github.com/prysmaticlabs/prysm/shared/testutil" @@ -36,34 +35,32 @@ func runShuffleTests(t *testing.T, config string) { testCase := &ShuffleTestCase{} 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 // 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:]) if err != nil { return err } seed := common.BytesToHash(baseSeed) - testIndices := make([]uint64, testCase.Count) - for i := uint64(0); i < testCase.Count; i++ { + testIndices := make([]types.ValidatorIndex, testCase.Count) + for i := types.ValidatorIndex(0); uint64(i) < testCase.Count; i++ { testIndices[i] = i } - shuffledList := make([]uint64, testCase.Count) - for i := uint64(0); i < testCase.Count; i++ { + shuffledList := make([]types.ValidatorIndex, testCase.Count) + for i := types.ValidatorIndex(0); uint64(i) < testCase.Count; i++ { si, err := helpers.ShuffledIndex(i, testCase.Count, seed) if err != nil { return err } shuffledList[i] = si } - if !reflect.DeepEqual(shuffledList, testCase.Mapping) { - return fmt.Errorf("shuffle result error: expected %v, actual %v", testCase.Mapping, shuffledList) - } + require.DeepSSZEqual(t, shuffledList, testCase.Mapping) return nil } diff --git a/beacon-chain/core/helpers/validators.go b/beacon-chain/core/helpers/validators.go index 46983d3c11..550f0ed87c 100644 --- a/beacon-chain/core/helpers/validators.go +++ b/beacon-chain/core/helpers/validators.go @@ -73,7 +73,7 @@ func checkValidatorSlashable(activationEpoch, withdrawableEpoch types.Epoch, sla // 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)] -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) if err != nil { return nil, errors.Wrap(err, "could not get seed") @@ -85,10 +85,10 @@ func ActiveValidatorIndices(state *stateTrie.BeaconState, epoch types.Epoch) ([] if activeIndices != nil { return activeIndices, nil } - var indices []uint64 + var indices []types.ValidatorIndex if err := state.ReadFromEveryValidator(func(idx int, val stateTrie.ReadOnlyValidator) error { if IsActiveValidatorUsingTrie(val, epoch) { - indices = append(indices, uint64(idx)) + indices = append(indices, types.ValidatorIndex(idx)) } return 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)) // indices = get_active_validator_indices(state, epoch) // 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) // 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. @@ -243,7 +243,7 @@ func BeaconProposerIndex(state *stateTrie.BeaconState) (uint64, error) { // if effective_balance * MAX_RANDOM_BYTE >= MAX_EFFECTIVE_BALANCE * random_byte: // return ValidatorIndex(candidate_index) // 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)) if length == 0 { return 0, errors.New("empty active indices list") @@ -252,12 +252,12 @@ func ComputeProposerIndex(bState *stateTrie.BeaconState, activeIndices []uint64, hashFunc := hashutil.CustomSHA256Hasher() 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 { return 0, err } candidateIndex = activeIndices[candidateIndex] - if candidateIndex >= uint64(bState.NumValidators()) { + if uint64(candidateIndex) >= uint64(bState.NumValidators()) { return 0, errors.New("active index out of range") } b := append(seed[:], bytesutil.Bytes8(i/32)...) diff --git a/beacon-chain/core/helpers/validators_test.go b/beacon-chain/core/helpers/validators_test.go index f2f03bf247..a375c0d71f 100644 --- a/beacon-chain/core/helpers/validators_test.go +++ b/beacon-chain/core/helpers/validators_test.go @@ -243,7 +243,7 @@ func TestBeaconProposerIndex_OK(t *testing.T) { tests := []struct { slot types.Slot - index uint64 + index types.ValidatorIndex }{ { slot: 1, @@ -326,7 +326,7 @@ func TestComputeProposerIndex_Compatibility(t *testing.T) { indices, err := ActiveValidatorIndices(state, 0) require.NoError(t, err) - var proposerIndices []uint64 + var proposerIndices []types.ValidatorIndex seed, err := Seed(state, 0, params.BeaconConfig().DomainBeaconProposer) require.NoError(t, err) for i := uint64(0); i < uint64(params.BeaconConfig().SlotsPerEpoch); i++ { @@ -337,7 +337,7 @@ func TestComputeProposerIndex_Compatibility(t *testing.T) { proposerIndices = append(proposerIndices, index) } - var wantedProposerIndices []uint64 + var wantedProposerIndices []types.ValidatorIndex seed, err = Seed(state, 0, params.BeaconConfig().DomainBeaconProposer) require.NoError(t, err) 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. seed, err := Seed(beaconState, 0, params.BeaconConfig().DomainBeaconAttester) 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)) require.NoError(t, err) assert.Equal(t, uint64(c), validatorCount, "Did not get the correct validator count") @@ -451,7 +451,7 @@ func TestActiveValidatorIndices(t *testing.T) { tests := []struct { name string args args - want []uint64 + want []types.ValidatorIndex wantedErr string }{ { @@ -476,7 +476,7 @@ func TestActiveValidatorIndices(t *testing.T) { }, epoch: 10, }, - want: []uint64{0, 1, 2}, + want: []types.ValidatorIndex{0, 1, 2}, }, { name: "some_active_epoch_10", @@ -500,7 +500,7 @@ func TestActiveValidatorIndices(t *testing.T) { }, epoch: 10, }, - want: []uint64{0, 1}, + want: []types.ValidatorIndex{0, 1}, }, { name: "some_active_with_recent_new_epoch_10", @@ -528,7 +528,7 @@ func TestActiveValidatorIndices(t *testing.T) { }, epoch: 10, }, - want: []uint64{0, 1, 3}, + want: []types.ValidatorIndex{0, 1, 3}, }, { name: "some_active_with_recent_new_epoch_10", @@ -556,7 +556,7 @@ func TestActiveValidatorIndices(t *testing.T) { }, epoch: 10, }, - want: []uint64{0, 1, 3}, + want: []types.ValidatorIndex{0, 1, 3}, }, { name: "some_active_with_recent_new_epoch_10", @@ -584,7 +584,7 @@ func TestActiveValidatorIndices(t *testing.T) { }, epoch: 10, }, - want: []uint64{0, 2, 3}, + want: []types.ValidatorIndex{0, 2, 3}, }, } for _, tt := range tests { @@ -606,13 +606,13 @@ func TestComputeProposerIndex(t *testing.T) { seed := bytesutil.ToBytes32([]byte("seed")) type args struct { validators []*ethpb.Validator - indices []uint64 + indices []types.ValidatorIndex seed [32]byte } tests := []struct { name string args args - want uint64 + want types.ValidatorIndex wantedErr string }{ { @@ -625,7 +625,7 @@ func TestComputeProposerIndex(t *testing.T) { {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, }, want: 2, @@ -640,7 +640,7 @@ func TestComputeProposerIndex(t *testing.T) { {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, }, - indices: []uint64{3}, + indices: []types.ValidatorIndex{3}, seed: seed, }, want: 3, @@ -655,7 +655,7 @@ func TestComputeProposerIndex(t *testing.T) { {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, }, - indices: []uint64{}, + indices: []types.ValidatorIndex{}, seed: seed, }, wantedErr: "empty active indices list", @@ -670,7 +670,7 @@ func TestComputeProposerIndex(t *testing.T) { {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, }, - indices: []uint64{100}, + indices: []types.ValidatorIndex{100}, seed: seed, }, wantedErr: "active index out of range", @@ -690,7 +690,7 @@ func TestComputeProposerIndex(t *testing.T) { {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, }, want: 7, @@ -705,7 +705,7 @@ func TestComputeProposerIndex(t *testing.T) { {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, }, 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)) if length == 0 { return 0, errors.New("empty active indices list") @@ -787,12 +787,12 @@ func computeProposerIndexWithValidators(validators []*ethpb.Validator, activeInd hashFunc := hashutil.CustomSHA256Hasher() 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 { return 0, err } candidateIndex = activeIndices[candidateIndex] - if candidateIndex >= uint64(len(validators)) { + if uint64(candidateIndex) >= uint64(len(validators)) { return 0, errors.New("active index out of range") } b := append(seed[:], bytesutil.Bytes8(i/32)...) diff --git a/beacon-chain/core/state/stateutils/BUILD.bazel b/beacon-chain/core/state/stateutils/BUILD.bazel index 5a3e649bdc..4beb3e02b8 100644 --- a/beacon-chain/core/state/stateutils/BUILD.bazel +++ b/beacon-chain/core/state/stateutils/BUILD.bazel @@ -11,6 +11,7 @@ go_library( ], deps = [ "//shared/bytesutil:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", ], ) @@ -26,6 +27,7 @@ go_test( "//shared/bytesutil:go_default_library", "//shared/testutil/assert: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", ], ) diff --git a/beacon-chain/core/state/stateutils/validator_index_map.go b/beacon-chain/core/state/stateutils/validator_index_map.go index 75cf32cf12..0b8e64bafc 100644 --- a/beacon-chain/core/state/stateutils/validator_index_map.go +++ b/beacon-chain/core/state/stateutils/validator_index_map.go @@ -4,14 +4,15 @@ package stateutils import ( + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/bytesutil" ) // ValidatorIndexMap builds a lookup map for quickly determining the index of // a validator by their public key. -func ValidatorIndexMap(validators []*ethpb.Validator) map[[48]byte]uint64 { - m := make(map[[48]byte]uint64, len(validators)) +func ValidatorIndexMap(validators []*ethpb.Validator) map[[48]byte]types.ValidatorIndex { + m := make(map[[48]byte]types.ValidatorIndex, len(validators)) if validators == nil { return m } @@ -20,7 +21,7 @@ func ValidatorIndexMap(validators []*ethpb.Validator) map[[48]byte]uint64 { continue } key := bytesutil.ToBytes48(record.PublicKey) - m[key] = uint64(idx) + m[key] = types.ValidatorIndex(idx) } return m } diff --git a/beacon-chain/core/state/stateutils/validator_index_map_test.go b/beacon-chain/core/state/stateutils/validator_index_map_test.go index 716ec9ee85..efd0a0eb26 100644 --- a/beacon-chain/core/state/stateutils/validator_index_map_test.go +++ b/beacon-chain/core/state/stateutils/validator_index_map_test.go @@ -3,6 +3,7 @@ package stateutils_test import ( "testing" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/state/stateutils" beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -28,7 +29,7 @@ func TestValidatorIndexMap_OK(t *testing.T) { tests := []struct { key [48]byte - val uint64 + val types.ValidatorIndex ok bool }{ { diff --git a/beacon-chain/core/state/transition_test.go b/beacon-chain/core/state/transition_test.go index 3422d986db..631272e985 100644 --- a/beacon-chain/core/state/transition_test.go +++ b/beacon-chain/core/state/transition_test.go @@ -320,7 +320,7 @@ func createFullBlockWithOperations(t *testing.T) (*beaconstate.BeaconState, require.NoError(t, beaconState.SetCurrentJustifiedCheckpoint(cp)) require.NoError(t, beaconState.SetCurrentEpochAttestations([]*pb.PendingAttestation{})) - proposerSlashIdx := uint64(3) + proposerSlashIdx := types.ValidatorIndex(3) slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch err = beaconState.SetSlot(slotsPerEpoch.Mul(uint64(params.BeaconConfig().ShardCommitteePeriod)) + params.BeaconConfig().MinAttestationInclusionDelay) require.NoError(t, err) diff --git a/beacon-chain/core/validators/validator.go b/beacon-chain/core/validators/validator.go index 017c2c3446..a04c3f4905 100644 --- a/beacon-chain/core/validators/validator.go +++ b/beacon-chain/core/validators/validator.go @@ -36,7 +36,7 @@ import ( // # Set validator exit epoch and withdrawable epoch // validator.exit_epoch = exit_queue_epoch // 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) if err != nil { return nil, err @@ -121,7 +121,7 @@ func InitiateValidatorExit(state *stateTrie.BeaconState, idx uint64) (*stateTrie // proposer_reward = Gwei(whistleblower_reward // PROPOSER_REWARD_QUOTIENT) // increase_balance(state, proposer_index, 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) if err != nil { 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. -func ActivatedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []uint64 { - activations := make([]uint64, 0) +func ActivatedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []types.ValidatorIndex { + activations := make([]types.ValidatorIndex, 0) for i := 0; i < len(validators); i++ { val := validators[i] if val.ActivationEpoch <= epoch && epoch < val.ExitEpoch { - activations = append(activations, uint64(i)) + activations = append(activations, types.ValidatorIndex(i)) } } return activations } // SlashedValidatorIndices determines the indices slashed during the given epoch. -func SlashedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []uint64 { - slashed := make([]uint64, 0) +func SlashedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []types.ValidatorIndex { + slashed := make([]types.ValidatorIndex, 0) for i := 0; i < len(validators); i++ { val := validators[i] maxWithdrawableEpoch := types.MaxEpoch(val.WithdrawableEpoch, epoch+params.BeaconConfig().EpochsPerSlashingsVector) if val.WithdrawableEpoch == maxWithdrawableEpoch && val.Slashed { - slashed = append(slashed, uint64(i)) + slashed = append(slashed, types.ValidatorIndex(i)) } } return slashed } // ExitedValidatorIndices determines the indices exited during the current epoch. -func ExitedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]uint64, error) { - exited := make([]uint64, 0) +func ExitedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]types.ValidatorIndex, error) { + exited := make([]types.ValidatorIndex, 0) exitEpochs := make([]types.Epoch, 0) for i := 0; i < len(validators); i++ { val := validators[i] @@ -231,15 +231,15 @@ func ExitedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, ac for i, val := range validators { if val.ExitEpoch == epoch && val.WithdrawableEpoch == withdrawableEpoch && val.EffectiveBalance > params.BeaconConfig().EjectionBalance { - exited = append(exited, uint64(i)) + exited = append(exited, types.ValidatorIndex(i)) } } return exited, nil } // EjectedValidatorIndices determines the indices ejected during the given epoch. -func EjectedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]uint64, error) { - ejected := make([]uint64, 0) +func EjectedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]types.ValidatorIndex, error) { + ejected := make([]types.ValidatorIndex, 0) exitEpochs := make([]types.Epoch, 0) for i := 0; i < len(validators); i++ { val := validators[i] @@ -272,7 +272,7 @@ func EjectedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, a for i, val := range validators { if val.ExitEpoch == epoch && val.WithdrawableEpoch == withdrawableEpoch && val.EffectiveBalance <= params.BeaconConfig().EjectionBalance { - ejected = append(ejected, uint64(i)) + ejected = append(ejected, types.ValidatorIndex(i)) } } return ejected, nil diff --git a/beacon-chain/core/validators/validator_test.go b/beacon-chain/core/validators/validator_test.go index 92f47842a7..b4e26fb19a 100644 --- a/beacon-chain/core/validators/validator_test.go +++ b/beacon-chain/core/validators/validator_test.go @@ -55,7 +55,7 @@ func TestInitiateValidatorExit_AlreadyExited(t *testing.T) { func TestInitiateValidatorExit_ProperExit(t *testing.T) { exitedEpoch := types.Epoch(100) - idx := uint64(3) + idx := types.ValidatorIndex(3) base := &pb.BeaconState{Validators: []*ethpb.Validator{ {ExitEpoch: exitedEpoch}, {ExitEpoch: exitedEpoch + 1}, @@ -73,7 +73,7 @@ func TestInitiateValidatorExit_ProperExit(t *testing.T) { func TestInitiateValidatorExit_ChurnOverflow(t *testing.T) { exitedEpoch := types.Epoch(100) - idx := uint64(4) + idx := types.ValidatorIndex(4) base := &pb.BeaconState{Validators: []*ethpb.Validator{ {ExitEpoch: exitedEpoch + 2}, {ExitEpoch: exitedEpoch + 2}, @@ -119,7 +119,7 @@ func TestSlashValidator_OK(t *testing.T) { state, err := beaconstate.InitializeFromProto(base) require.NoError(t, err) - slashedIdx := uint64(2) + slashedIdx := types.ValidatorIndex(2) proposer, err := helpers.BeaconProposerIndex(state) require.NoError(t, err, "Could not get proposer") @@ -152,7 +152,7 @@ func TestSlashValidator_OK(t *testing.T) { func TestActivatedValidatorIndices(t *testing.T) { tests := []struct { state *pb.BeaconState - wanted []uint64 + wanted []types.ValidatorIndex }{ { 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{ @@ -184,7 +184,7 @@ func TestActivatedValidatorIndices(t *testing.T) { }, }, }, - wanted: []uint64{}, + wanted: []types.ValidatorIndex{}, }, { state: &pb.BeaconState{ @@ -195,7 +195,7 @@ func TestActivatedValidatorIndices(t *testing.T) { }, }, }, - wanted: []uint64{0}, + wanted: []types.ValidatorIndex{0}, }, } for _, tt := range tests { @@ -209,7 +209,7 @@ func TestActivatedValidatorIndices(t *testing.T) { func TestSlashedValidatorIndices(t *testing.T) { tests := []struct { state *pb.BeaconState - wanted []uint64 + wanted []types.ValidatorIndex }{ { state: &pb.BeaconState{ @@ -228,7 +228,7 @@ func TestSlashedValidatorIndices(t *testing.T) { }, }, }, - wanted: []uint64{0, 2}, + wanted: []types.ValidatorIndex{0, 2}, }, { state: &pb.BeaconState{ @@ -238,7 +238,7 @@ func TestSlashedValidatorIndices(t *testing.T) { }, }, }, - wanted: []uint64{}, + wanted: []types.ValidatorIndex{}, }, { state: &pb.BeaconState{ @@ -249,7 +249,7 @@ func TestSlashedValidatorIndices(t *testing.T) { }, }, }, - wanted: []uint64{0}, + wanted: []types.ValidatorIndex{0}, }, } for _, tt := range tests { @@ -263,7 +263,7 @@ func TestSlashedValidatorIndices(t *testing.T) { func TestExitedValidatorIndices(t *testing.T) { tests := []struct { state *pb.BeaconState - wanted []uint64 + wanted []types.ValidatorIndex }{ { state: &pb.BeaconState{ @@ -285,7 +285,7 @@ func TestExitedValidatorIndices(t *testing.T) { }, }, }, - wanted: []uint64{0, 2}, + wanted: []types.ValidatorIndex{0, 2}, }, { state: &pb.BeaconState{ @@ -297,7 +297,7 @@ func TestExitedValidatorIndices(t *testing.T) { }, }, }, - wanted: []uint64{}, + wanted: []types.ValidatorIndex{}, }, { state: &pb.BeaconState{ @@ -309,7 +309,7 @@ func TestExitedValidatorIndices(t *testing.T) { }, }, }, - wanted: []uint64{0}, + wanted: []types.ValidatorIndex{0}, }, } for _, tt := range tests { diff --git a/beacon-chain/interop-cold-start/BUILD.bazel b/beacon-chain/interop-cold-start/BUILD.bazel index 7efbed959d..7cd9c7adfa 100644 --- a/beacon-chain/interop-cold-start/BUILD.bazel +++ b/beacon-chain/interop-cold-start/BUILD.bazel @@ -19,6 +19,7 @@ go_library( "//shared/interop:go_default_library", "//shared/slotutil: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_sirupsen_logrus//:go_default_library", ], diff --git a/beacon-chain/interop-cold-start/service.go b/beacon-chain/interop-cold-start/service.go index 0479a0b7f9..e8cd933c0c 100644 --- a/beacon-chain/interop-cold-start/service.go +++ b/beacon-chain/interop-cold-start/service.go @@ -10,6 +10,7 @@ import ( "time" "github.com/pkg/errors" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache" "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") } - for i := uint64(0); i < uint64(genesisState.NumValidators()); i++ { + for i := types.ValidatorIndex(0); uint64(i) < uint64(genesisState.NumValidators()); i++ { pk := genesisState.PubkeyAtIndex(i) s.chainStartDeposits[i] = ðpb.Deposit{ Data: ðpb.Deposit_Data{ diff --git a/beacon-chain/operations/slashings/BUILD.bazel b/beacon-chain/operations/slashings/BUILD.bazel index 295b1799f2..07ab86affa 100644 --- a/beacon-chain/operations/slashings/BUILD.bazel +++ b/beacon-chain/operations/slashings/BUILD.bazel @@ -24,6 +24,7 @@ go_library( "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus: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_sirupsen_logrus//:go_default_library", "@com_github_trailofbits_go_mutexasserts//:go_default_library", @@ -47,6 +48,7 @@ go_test( "//shared/testutil:go_default_library", "//shared/testutil/assert: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", ], ) diff --git a/beacon-chain/operations/slashings/service.go b/beacon-chain/operations/slashings/service.go index 67e5ecb998..594b933cf6 100644 --- a/beacon-chain/operations/slashings/service.go +++ b/beacon-chain/operations/slashings/service.go @@ -6,6 +6,7 @@ import ( "sort" "github.com/pkg/errors" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" @@ -21,7 +22,7 @@ func NewPool() *Pool { return &Pool{ pendingProposerSlashing: make([]*ethpb.ProposerSlashing, 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. 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. maxSlashings := params.BeaconConfig().MaxAttesterSlashings @@ -63,7 +64,7 @@ func (p *Pool) PendingAttesterSlashings(ctx context.Context, state *beaconstate. attSlashing := slashing.attesterSlashing slashedVal := sliceutil.IntersectionUint64(attSlashing.Attestation_1.AttestingIndices, attSlashing.Attestation_2.AttestingIndices) for _, idx := range slashedVal { - included[idx] = true + included[types.ValidatorIndex(idx)] = true } pending = append(pending, attSlashing) @@ -131,7 +132,7 @@ func (p *Pool) InsertAttesterSlashing( cantSlash := make([]uint64, 0, len(slashedVal)) for _, val := range slashedVal { // Has this validator index been included recently? - ok, err := p.validatorSlashingPreconditionCheck(state, val) + ok, err := p.validatorSlashingPreconditionCheck(state, types.ValidatorIndex(val)) if err != nil { return err } @@ -145,16 +146,16 @@ func (p *Pool) InsertAttesterSlashing( // Check if the validator already exists in the list of slashings. // Use binary search to find the answer. 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) continue } pendingSlashing := &PendingAttesterSlashing{ attesterSlashing: slashing, - validatorToSlash: val, + validatorToSlash: types.ValidatorIndex(val), } // Insert into pending list and sort again. 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) for _, val := range slashedVal { 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.included[val] = true + p.included[types.ValidatorIndex(val)] = true numAttesterSlashingsIncluded.Inc() } } @@ -258,7 +259,7 @@ func (p *Pool) MarkIncludedProposerSlashing(ps *ethpb.ProposerSlashing) { // Note: this method requires caller to hold the lock. func (p *Pool) validatorSlashingPreconditionCheck( state *beaconstate.BeaconState, - valIdx uint64, + valIdx types.ValidatorIndex, ) (bool, error) { if !mutexasserts.RWMutexLocked(&p.lock) && !mutexasserts.RWMutexRLocked(&p.lock) { return false, errors.New("pool.validatorSlashingPreconditionCheck: caller must hold read/write lock") diff --git a/beacon-chain/operations/slashings/service_attester_test.go b/beacon-chain/operations/slashings/service_attester_test.go index 9ad6ee91d7..5167a6c6d1 100644 --- a/beacon-chain/operations/slashings/service_attester_test.go +++ b/beacon-chain/operations/slashings/service_attester_test.go @@ -4,20 +4,20 @@ import ( "context" "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/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/testutil" + "github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/require" ) func validAttesterSlashingForValIdx(t *testing.T, beaconState *state.BeaconState, privs []bls.SecretKey, valIdx ...uint64) *ethpb.AttesterSlashing { var slashings []*ethpb.AttesterSlashing 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) slashings = append(slashings, slashing) } @@ -60,14 +60,14 @@ func attesterSlashingForValIdx(valIdx ...uint64) *ethpb.AttesterSlashing { func pendingSlashingForValIdx(valIdx ...uint64) *PendingAttesterSlashing { return &PendingAttesterSlashing{ attesterSlashing: attesterSlashingForValIdx(valIdx...), - validatorToSlash: valIdx[0], + validatorToSlash: types.ValidatorIndex(valIdx[0]), } } func TestPool_InsertAttesterSlashing(t *testing.T) { type fields struct { pending []*PendingAttesterSlashing - included map[uint64]bool + included map[types.ValidatorIndex]bool wantErr []bool } type args struct { @@ -78,33 +78,33 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { pendingSlashings := make([]*PendingAttesterSlashing, 20) slashings := make([]*ethpb.AttesterSlashing, 20) 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) pendingSlashings[i] = &PendingAttesterSlashing{ attesterSlashing: sl, - validatorToSlash: uint64(i), + validatorToSlash: types.ValidatorIndex(i), } slashings[i] = sl } require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch)) // 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) exitedVal.WithdrawableEpoch = 0 - require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(2), exitedVal)) - futureWithdrawVal, err := beaconState.ValidatorAtIndex(uint64(4)) + require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(2), exitedVal)) + futureWithdrawVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(4)) require.NoError(t, err) futureWithdrawVal.WithdrawableEpoch = 17 - require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(4), futureWithdrawVal)) - slashedVal, err := beaconState.ValidatorAtIndex(uint64(5)) + require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(4), futureWithdrawVal)) + slashedVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(5)) require.NoError(t, err) slashedVal.Slashed = true - require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(5), slashedVal)) - slashedVal2, err := beaconState.ValidatorAtIndex(uint64(21)) + require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(5), slashedVal)) + slashedVal2, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(21)) require.NoError(t, err) 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) aggSlashing2 := validAttesterSlashingForValIdx(t, beaconState, privKeys, 5, 9, 13) @@ -122,7 +122,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Empty list", fields: fields{ pending: make([]*PendingAttesterSlashing, 0), - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), wantErr: []bool{false}, }, args: args{ @@ -139,7 +139,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Empty list two validators slashed", fields: fields{ pending: make([]*PendingAttesterSlashing, 0), - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), wantErr: []bool{false, false}, }, args: args{ @@ -153,7 +153,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { pending: []*PendingAttesterSlashing{ pendingSlashings[1], }, - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), wantErr: []bool{true}, }, args: args{ @@ -165,7 +165,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Slashing for already exit validator", fields: fields{ pending: []*PendingAttesterSlashing{}, - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), wantErr: []bool{true}, }, args: args{ @@ -177,7 +177,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Slashing for withdrawable validator", fields: fields{ pending: []*PendingAttesterSlashing{}, - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), wantErr: []bool{true}, }, args: args{ @@ -189,7 +189,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Slashing for slashed validator", fields: fields{ pending: []*PendingAttesterSlashing{}, - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), wantErr: []bool{false}, }, args: args{ @@ -201,7 +201,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Already included", fields: fields{ pending: []*PendingAttesterSlashing{}, - included: map[uint64]bool{ + included: map[types.ValidatorIndex]bool{ 1: true, }, wantErr: []bool{true}, @@ -218,7 +218,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { pendingSlashings[0], pendingSlashings[2], }, - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), wantErr: []bool{false}, }, args: args{ @@ -230,7 +230,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Doesn't reject partially slashed slashings", fields: fields{ pending: []*PendingAttesterSlashing{}, - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), wantErr: []bool{false, false, false, true}, }, args: args{ @@ -303,11 +303,11 @@ func TestPool_InsertAttesterSlashing_SigFailsVerify_ClearPool(t *testing.T) { pendingSlashings := make([]*PendingAttesterSlashing, 2) slashings := make([]*ethpb.AttesterSlashing, 2) 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) pendingSlashings[i] = &PendingAttesterSlashing{ attesterSlashing: sl, - validatorToSlash: uint64(i), + validatorToSlash: types.ValidatorIndex(i), } slashings[i] = sl } @@ -328,7 +328,7 @@ func TestPool_InsertAttesterSlashing_SigFailsVerify_ClearPool(t *testing.T) { func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { type fields struct { pending []*PendingAttesterSlashing - included map[uint64]bool + included map[types.ValidatorIndex]bool } type args struct { slashing *ethpb.AttesterSlashing @@ -348,7 +348,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { validatorToSlash: 1, }, }, - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), }, args: args{ slashing: attesterSlashingForValIdx(3), @@ -357,7 +357,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { pending: []*PendingAttesterSlashing{ pendingSlashingForValIdx(1), }, - included: map[uint64]bool{ + included: map[types.ValidatorIndex]bool{ 3: true, }, }, @@ -370,7 +370,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { pendingSlashingForValIdx(2), pendingSlashingForValIdx(3), }, - included: map[uint64]bool{ + included: map[types.ValidatorIndex]bool{ 0: true, }, }, @@ -382,7 +382,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { pendingSlashingForValIdx(1), pendingSlashingForValIdx(3), }, - included: map[uint64]bool{ + included: map[types.ValidatorIndex]bool{ 0: true, 2: true, }, @@ -404,7 +404,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { pendingSlashingForValIdx(10), pendingSlashingForValIdx(11), }, - included: map[uint64]bool{ + included: map[types.ValidatorIndex]bool{ 0: true, }, }, @@ -424,7 +424,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { pendingSlashingForValIdx(10), pendingSlashingForValIdx(11), }, - included: map[uint64]bool{ + included: map[types.ValidatorIndex]bool{ 0: true, 6: true, }, @@ -457,11 +457,11 @@ func TestPool_PendingAttesterSlashings(t *testing.T) { pendingSlashings := make([]*PendingAttesterSlashing, 20) slashings := make([]*ethpb.AttesterSlashing, 20) 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) pendingSlashings[i] = &PendingAttesterSlashing{ attesterSlashing: sl, - validatorToSlash: uint64(i), + validatorToSlash: types.ValidatorIndex(i), } slashings[i] = sl } @@ -532,15 +532,15 @@ func TestPool_PendingAttesterSlashings_Slashed(t *testing.T) { pendingSlashings2 := make([]*PendingAttesterSlashing, 20) slashings := make([]*ethpb.AttesterSlashing, 20) 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) pendingSlashings[i] = &PendingAttesterSlashing{ attesterSlashing: sl, - validatorToSlash: uint64(i), + validatorToSlash: types.ValidatorIndex(i), } pendingSlashings2[i] = &PendingAttesterSlashing{ attesterSlashing: sl, - validatorToSlash: uint64(i), + validatorToSlash: types.ValidatorIndex(i), } slashings[i] = sl } @@ -590,11 +590,11 @@ func TestPool_PendingAttesterSlashings_NoDuplicates(t *testing.T) { pendingSlashings := make([]*PendingAttesterSlashing, 3) slashings := make([]*ethpb.AttesterSlashing, 3) 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) pendingSlashings[i] = &PendingAttesterSlashing{ attesterSlashing: sl, - validatorToSlash: uint64(i), + validatorToSlash: types.ValidatorIndex(i), } slashings[i] = sl } diff --git a/beacon-chain/operations/slashings/service_proposer_test.go b/beacon-chain/operations/slashings/service_proposer_test.go index 772d26bcbc..91fd0bb6a3 100644 --- a/beacon-chain/operations/slashings/service_proposer_test.go +++ b/beacon-chain/operations/slashings/service_proposer_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/testutil" @@ -11,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/shared/testutil/require" ) -func proposerSlashingForValIdx(valIdx uint64) *ethpb.ProposerSlashing { +func proposerSlashingForValIdx(valIdx types.ValidatorIndex) *ethpb.ProposerSlashing { return ðpb.ProposerSlashing{ Header_1: ðpb.SignedBeaconBlockHeader{ Header: ðpb.BeaconBlockHeader{ProposerIndex: valIdx}, @@ -26,7 +27,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { type fields struct { wantedErr string pending []*ethpb.ProposerSlashing - included map[uint64]bool + included map[types.ValidatorIndex]bool } type args struct { slashings []*ethpb.ProposerSlashing @@ -35,7 +36,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { beaconState, privKeys := testutil.DeterministicGenesisState(t, 64) slashings := make([]*ethpb.ProposerSlashing, 20) 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) slashings[i] = sl } @@ -43,18 +44,18 @@ func TestPool_InsertProposerSlashing(t *testing.T) { require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch)) // 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) exitedVal.WithdrawableEpoch = 0 - futureExitedVal, err := beaconState.ValidatorAtIndex(uint64(4)) + futureExitedVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(4)) require.NoError(t, err) futureExitedVal.WithdrawableEpoch = 17 - slashedVal, err := beaconState.ValidatorAtIndex(uint64(5)) + slashedVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(5)) require.NoError(t, err) slashedVal.Slashed = true - require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(2), exitedVal)) - require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(4), futureExitedVal)) - require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(5), slashedVal)) + require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(2), exitedVal)) + require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(4), futureExitedVal)) + require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(5), slashedVal)) tests := []struct { name string @@ -66,7 +67,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { name: "Empty list", fields: fields{ pending: make([]*ethpb.ProposerSlashing, 0), - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), }, args: args{ slashings: slashings[0:1], @@ -77,7 +78,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { name: "Duplicate identical slashing", fields: fields{ pending: slashings[0:1], - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), wantedErr: "slashing object already exists in pending proposer slashings", }, args: args{ @@ -89,7 +90,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { name: "Slashing for exited validator", fields: fields{ pending: []*ethpb.ProposerSlashing{}, - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), wantedErr: "is not slashable", }, args: args{ @@ -101,7 +102,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { name: "Slashing for exiting validator", fields: fields{ pending: []*ethpb.ProposerSlashing{}, - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), }, args: args{ slashings: slashings[4:5], @@ -112,7 +113,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { name: "Slashing for slashed validator", fields: fields{ pending: []*ethpb.ProposerSlashing{}, - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), wantedErr: "not slashable", }, args: args{ @@ -124,7 +125,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { name: "Already included", fields: fields{ pending: []*ethpb.ProposerSlashing{}, - included: map[uint64]bool{ + included: map[types.ValidatorIndex]bool{ 1: true, }, wantedErr: "cannot be slashed", @@ -141,7 +142,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { slashings[0], slashings[2], }, - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), }, args: args{ slashings: slashings[1:2], @@ -185,7 +186,7 @@ func TestPool_InsertProposerSlashing_SigFailsVerify_ClearPool(t *testing.T) { beaconState, privKeys := testutil.DeterministicGenesisState(t, 64) slashings := make([]*ethpb.ProposerSlashing, 2) 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) slashings[i] = sl } @@ -206,7 +207,7 @@ func TestPool_InsertProposerSlashing_SigFailsVerify_ClearPool(t *testing.T) { func TestPool_MarkIncludedProposerSlashing(t *testing.T) { type fields struct { pending []*ethpb.ProposerSlashing - included map[uint64]bool + included map[types.ValidatorIndex]bool } type args struct { slashing *ethpb.ProposerSlashing @@ -223,7 +224,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) { pending: []*ethpb.ProposerSlashing{ proposerSlashingForValIdx(1), }, - included: make(map[uint64]bool), + included: make(map[types.ValidatorIndex]bool), }, args: args{ slashing: proposerSlashingForValIdx(3), @@ -232,7 +233,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) { pending: []*ethpb.ProposerSlashing{ proposerSlashingForValIdx(1), }, - included: map[uint64]bool{ + included: map[types.ValidatorIndex]bool{ 3: true, }, }, @@ -245,7 +246,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) { proposerSlashingForValIdx(2), proposerSlashingForValIdx(3), }, - included: map[uint64]bool{ + included: map[types.ValidatorIndex]bool{ 0: true, }, }, @@ -257,7 +258,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) { proposerSlashingForValIdx(1), proposerSlashingForValIdx(3), }, - included: map[uint64]bool{ + included: map[types.ValidatorIndex]bool{ 0: true, 2: true, }, @@ -278,7 +279,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) { proposerSlashingForValIdx(9), proposerSlashingForValIdx(10), }, - included: map[uint64]bool{ + included: map[types.ValidatorIndex]bool{ 0: true, }, }, @@ -297,7 +298,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) { proposerSlashingForValIdx(9), proposerSlashingForValIdx(10), }, - included: map[uint64]bool{ + included: map[types.ValidatorIndex]bool{ 0: true, 7: true, }, @@ -328,7 +329,7 @@ func TestPool_PendingProposerSlashings(t *testing.T) { beaconState, privKeys := testutil.DeterministicGenesisState(t, 64) slashings := make([]*ethpb.ProposerSlashing, 20) 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) slashings[i] = sl } @@ -395,7 +396,7 @@ func TestPool_PendingProposerSlashings_Slashed(t *testing.T) { slashings2 := make([]*ethpb.ProposerSlashing, 32) result := make([]*ethpb.ProposerSlashing, 32) 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) slashings[i] = sl slashings2[i] = sl diff --git a/beacon-chain/operations/slashings/types.go b/beacon-chain/operations/slashings/types.go index bc79634f04..893de20fbf 100644 --- a/beacon-chain/operations/slashings/types.go +++ b/beacon-chain/operations/slashings/types.go @@ -3,6 +3,7 @@ package slashings import ( "sync" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ) @@ -12,12 +13,12 @@ type Pool struct { lock sync.RWMutex pendingProposerSlashing []*ethpb.ProposerSlashing pendingAttesterSlashing []*PendingAttesterSlashing - included map[uint64]bool + included map[types.ValidatorIndex]bool } // PendingAttesterSlashing represents an attester slashing in the operation pool. // Allows for easy binary searching of included validator indexes. type PendingAttesterSlashing struct { attesterSlashing *ethpb.AttesterSlashing - validatorToSlash uint64 + validatorToSlash types.ValidatorIndex } diff --git a/beacon-chain/operations/voluntaryexits/service.go b/beacon-chain/operations/voluntaryexits/service.go index 21c1a11fd6..4cf3666525 100644 --- a/beacon-chain/operations/voluntaryexits/service.go +++ b/beacon-chain/operations/voluntaryexits/service.go @@ -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. -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 { return pending[j].Exit.ValidatorIndex >= searchingFor }) diff --git a/beacon-chain/powchain/BUILD.bazel b/beacon-chain/powchain/BUILD.bazel index 77d8fbbe74..e1bbc86d1a 100644 --- a/beacon-chain/powchain/BUILD.bazel +++ b/beacon-chain/powchain/BUILD.bazel @@ -91,6 +91,7 @@ go_test( "@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//trie:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@com_github_sirupsen_logrus//hooks/test:go_default_library", diff --git a/beacon-chain/powchain/deposit_test.go b/beacon-chain/powchain/deposit_test.go index dafd973a08..7d12a019cb 100644 --- a/beacon-chain/powchain/deposit_test.go +++ b/beacon-chain/powchain/deposit_test.go @@ -5,6 +5,7 @@ import ( "fmt" "testing" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" @@ -259,7 +260,7 @@ func TestProcessDeposit_AllDepositedSuccessfully(t *testing.T) { require.NoError(t, err) 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) assert.Equal(t, params.BeaconConfig().MaxEffectiveBalance, val.EffectiveBalance) } diff --git a/beacon-chain/rpc/beacon/assignments.go b/beacon-chain/rpc/beacon/assignments.go index b633c42909..c4f0634281 100644 --- a/beacon-chain/rpc/beacon/assignments.go +++ b/beacon-chain/rpc/beacon/assignments.go @@ -29,8 +29,8 @@ func (bs *Server) ListValidatorAssignments( } var res []*ethpb.ValidatorAssignments_CommitteeAssignment - filtered := map[uint64]bool{} // track filtered validators to prevent duplication in the response. - filteredIndices := make([]uint64, 0) + filtered := map[types.ValidatorIndex]bool{} // track filtered validators to prevent duplication in the response. + filteredIndices := make([]types.ValidatorIndex, 0) var requestedEpoch types.Epoch switch q := req.QueryFilter.(type) { case *ethpb.ListValidatorAssignmentsRequest_Genesis: @@ -105,7 +105,7 @@ func (bs *Server) ListValidatorAssignments( } 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", index, requestedState.NumValidators()) } diff --git a/beacon-chain/rpc/beacon/assignments_test.go b/beacon-chain/rpc/beacon/assignments_test.go index aaa10b7b07..673f6cb163 100644 --- a/beacon-chain/rpc/beacon/assignments_test.go +++ b/beacon-chain/rpc/beacon/assignments_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/gogo/protobuf/proto" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "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) pubKey2 := make([]byte, params.BeaconConfig().BLSPubkeyLength) binary.LittleEndian.PutUint64(pubKey2, 2) - req := ðpb.ListValidatorAssignmentsRequest{PublicKeys: [][]byte{pubKey1, pubKey2}, Indices: []uint64{2, 3}} + req := ðpb.ListValidatorAssignmentsRequest{PublicKeys: [][]byte{pubKey1, pubKey2}, Indices: []types.ValidatorIndex{2, 3}} res, err := bs.ListValidatorAssignments(context.Background(), req) require.NoError(t, err) @@ -332,7 +333,7 @@ func TestServer_ListAssignments_CanFilterPubkeysIndices_WithPagination(t *testin StateGen: stategen.New(db), } - req := ðpb.ListValidatorAssignmentsRequest{Indices: []uint64{1, 2, 3, 4, 5, 6}, PageSize: 2, PageToken: "1"} + req := ðpb.ListValidatorAssignmentsRequest{Indices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}, PageSize: 2, PageToken: "1"} res, err := bs.ListValidatorAssignments(context.Background(), req) require.NoError(t, err) @@ -366,7 +367,7 @@ func TestServer_ListAssignments_CanFilterPubkeysIndices_WithPagination(t *testin // Test the wrap around scenario. assignments = nil - req = ðpb.ListValidatorAssignmentsRequest{Indices: []uint64{1, 2, 3, 4, 5, 6}, PageSize: 5, PageToken: "1"} + req = ðpb.ListValidatorAssignmentsRequest{Indices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}, PageSize: 5, PageToken: "1"} res, err = bs.ListValidatorAssignments(context.Background(), req) require.NoError(t, err) cAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(s, 0) diff --git a/beacon-chain/rpc/beacon/attestations_test.go b/beacon-chain/rpc/beacon/attestations_test.go index cd94385e80..4c69c8ef2a 100644 --- a/beacon-chain/rpc/beacon/attestations_test.go +++ b/beacon-chain/rpc/beacon/attestations_test.go @@ -874,7 +874,7 @@ func TestServer_StreamIndexedAttestations_OK(t *testing.T) { var found bool for comIndex, item := range comms { for n, idx := range item.ValidatorIndices { - if uint64(j) == idx { + if types.ValidatorIndex(j) == idx { indexInCommittee = uint64(n) committeeIndex = types.CommitteeIndex(comIndex) committeeLength = len(item.ValidatorIndices) diff --git a/beacon-chain/rpc/beacon/committees.go b/beacon-chain/rpc/beacon/committees.go index 04d120ddb8..2921a0ee49 100644 --- a/beacon-chain/rpc/beacon/committees.go +++ b/beacon-chain/rpc/beacon/committees.go @@ -67,7 +67,7 @@ func (bs *Server) ListBeaconCommittees( func (bs *Server) retrieveCommitteesForEpoch( ctx context.Context, epoch types.Epoch, -) (SlotToCommiteesMap, []uint64, error) { +) (SlotToCommiteesMap, []types.ValidatorIndex, error) { startSlot, err := helpers.StartSlot(epoch) if err != nil { return nil, nil, err @@ -103,7 +103,7 @@ func (bs *Server) retrieveCommitteesForEpoch( func (bs *Server) retrieveCommitteesForRoot( ctx context.Context, root []byte, -) (SlotToCommiteesMap, []uint64, error) { +) (SlotToCommiteesMap, []types.ValidatorIndex, error) { requestedState, err := bs.StateGen.StateByRoot(ctx, bytesutil.ToBytes32(root)) if err != nil { 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. func computeCommittees( startSlot types.Slot, - activeIndices []uint64, + activeIndices []types.ValidatorIndex, attesterSeed [32]byte, ) (SlotToCommiteesMap, error) { committeesListsBySlot := make(SlotToCommiteesMap, params.BeaconConfig().SlotsPerEpoch) diff --git a/beacon-chain/rpc/beacon/slashings.go b/beacon-chain/rpc/beacon/slashings.go index 5e5313010e..4b15ada59d 100644 --- a/beacon-chain/rpc/beacon/slashings.go +++ b/beacon-chain/rpc/beacon/slashings.go @@ -3,9 +3,9 @@ package beacon import ( "context" - "github.com/prysmaticlabs/prysm/shared/featureconfig" - + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" + "github.com/prysmaticlabs/prysm/shared/featureconfig" "github.com/prysmaticlabs/prysm/shared/sliceutil" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -32,7 +32,7 @@ func (bs *Server) SubmitProposerSlashing( } return ðpb.SubmitSlashingResponse{ - SlashedIndices: []uint64{req.Header_1.Header.ProposerIndex}, + SlashedIndices: []types.ValidatorIndex{req.Header_1.Header.ProposerIndex}, }, nil } @@ -55,7 +55,11 @@ func (bs *Server) SubmitAttesterSlashing( 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 ðpb.SubmitSlashingResponse{ SlashedIndices: slashedIndices, }, nil diff --git a/beacon-chain/rpc/beacon/slashings_test.go b/beacon-chain/rpc/beacon/slashings_test.go index e1b7642ab8..01fbc38499 100644 --- a/beacon-chain/rpc/beacon/slashings_test.go +++ b/beacon-chain/rpc/beacon/slashings_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/gogo/protobuf/proto" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "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 // 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) _, err = bs.SubmitProposerSlashing(ctx, slashing) @@ -65,7 +66,7 @@ func TestServer_SubmitAttesterSlashing(t *testing.T) { 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) // 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 // be included in the pool. wanted := ðpb.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) 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") - slashing, err = testutil.GenerateProposerSlashingForValidator(st, privs[5], uint64(5)) + slashing, err = testutil.GenerateProposerSlashingForValidator(st, privs[5], types.ValidatorIndex(5)) require.NoError(t, err) // 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, } - slashing, err := testutil.GenerateAttesterSlashingForValidator(st, privs[2], uint64(2)) + slashing, err := testutil.GenerateAttesterSlashingForValidator(st, privs[2], types.ValidatorIndex(2)) require.NoError(t, err) // We want the intersection of the slashing attesting indices // to be slashed, so we expect validators 2 and 3 to be in the response // slashed indices. wanted := ðpb.SubmitSlashingResponse{ - SlashedIndices: []uint64{2}, + SlashedIndices: []types.ValidatorIndex{2}, } res, err := bs.SubmitAttesterSlashing(ctx, slashing) 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") - slashing, err = testutil.GenerateAttesterSlashingForValidator(st, privs[5], uint64(5)) + slashing, err = testutil.GenerateAttesterSlashingForValidator(st, privs[5], types.ValidatorIndex(5)) require.NoError(t, err) // 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. diff --git a/beacon-chain/rpc/beacon/validators.go b/beacon-chain/rpc/beacon/validators.go index 950da5d110..df7ccdba3e 100644 --- a/beacon-chain/rpc/beacon/validators.go +++ b/beacon-chain/rpc/beacon/validators.go @@ -61,7 +61,7 @@ func (bs *Server) ListValidatorBalances( ) } 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) if err != nil { @@ -92,7 +92,7 @@ func (bs *Server) ListValidatorBalances( } 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", index, len(balances)) } @@ -109,7 +109,7 @@ func (bs *Server) ListValidatorBalances( } 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", index, len(balances)) } @@ -154,12 +154,12 @@ func (bs *Server) ListValidatorBalances( if len(req.Indices) == 0 && len(req.PublicKeys) == 0 { // Return everything. for i := start; i < end; i++ { - pubkey := requestedState.PubkeyAtIndex(uint64(i)) + pubkey := requestedState.PubkeyAtIndex(types.ValidatorIndex(i)) val := vals[i] st := validatorStatus(val, requestedEpoch) res = append(res, ðpb.ValidatorBalances_Balance{ PublicKey: pubkey[:], - Index: uint64(i), + Index: types.ValidatorIndex(i), Balance: balances[i], Status: st.String(), }) @@ -285,7 +285,7 @@ func (bs *Server) ListValidators( }) 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) if err != nil { 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, ) (*ethpb.Validator, error) { var requestingIndex bool - var index uint64 + var index types.ValidatorIndex var pubKey []byte switch q := req.QueryFilter.(type) { 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) } if requestingIndex { - if index >= uint64(headState.NumValidators()) { + if uint64(index) >= uint64(headState.NumValidators()) { return nil, status.Errorf( codes.OutOfRange, "Requesting index %d, but there are only %d validators", @@ -371,7 +371,7 @@ func (bs *Server) GetValidator( return headState.ValidatorAtIndex(index) } 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) if keyFromState == pk48 { 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. // Additionally, determine those validators queued to exit - awaitingExit := make([]uint64, 0) + awaitingExit := make([]types.ValidatorIndex, 0) exitEpochs := make([]types.Epoch, 0) - activationQ := make([]uint64, 0) + activationQ := make([]types.ValidatorIndex, 0) vals := headState.Validators() for idx, validator := range vals { eligibleActivated := validator.ActivationEligibilityEpoch != params.BeaconConfig().FarFutureEpoch canBeActive := validator.ActivationEpoch >= helpers.ActivationExitEpoch(headState.FinalizedCheckpointEpoch()) if eligibleActivated && canBeActive { - activationQ = append(activationQ, uint64(idx)) + activationQ = append(activationQ, types.ValidatorIndex(idx)) } if validator.ExitEpoch != params.BeaconConfig().FarFutureEpoch { exitEpochs = append(exitEpochs, validator.ExitEpoch) - awaitingExit = append(awaitingExit, uint64(idx)) + awaitingExit = append(awaitingExit, types.ValidatorIndex(idx)) } } 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. minEpoch := exitQueueEpoch + params.BeaconConfig().MinValidatorWithdrawabilityDelay - exitQueueIndices := make([]uint64, 0) + exitQueueIndices := make([]types.ValidatorIndex, 0) for _, valIdx := range awaitingExit { val := vals[valIdx] // 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 responseCap := len(req.Indices) + len(req.PublicKeys) - validatorIndices := make([]uint64, 0, responseCap) + validatorIndices := make([]types.ValidatorIndex, 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. for _, pubKey := range req.PublicKeys { // Skip empty public key. @@ -729,7 +729,7 @@ func (bs *Server) GetValidatorPerformance( return nil, status.Errorf(codes.Internal, "could not get validator: %v", err) } pubKey := val.PublicKey() - if idx >= uint64(len(validatorSummary)) { + if uint64(idx) >= uint64(len(validatorSummary)) { // Not listed in validator summary yet; treat it as missing. missingValidators = append(missingValidators, pubKey[:]) 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) } // Track filtered validators to prevent duplication in the response. - filtered := map[uint64]bool{} - filteredIndices := make([]uint64, 0) + filtered := map[types.ValidatorIndex]bool{} + filteredIndices := make([]types.ValidatorIndex, 0) votes := make([]*ethpb.IndividualVotesRespond_IndividualVote, 0, len(req.Indices)+len(req.PublicKeys)) // Filter out assignments by public keys. for _, pubKey := range req.PublicKeys { index, ok := requestedState.ValidatorIndexByPubkey(bytesutil.ToBytes48(pubKey)) if !ok { - votes = append(votes, ðpb.IndividualVotesRespond_IndividualVote{PublicKey: pubKey, ValidatorIndex: ^uint64(0)}) + votes = append(votes, ðpb.IndividualVotesRespond_IndividualVote{PublicKey: pubKey, ValidatorIndex: types.ValidatorIndex(^uint64(0))}) continue } filtered[index] = true @@ -822,7 +822,7 @@ func (bs *Server) GetIndividualVotes( return nil, status.Errorf(codes.Internal, "Could not pre compute attestations: %v", err) } for _, index := range filteredIndices { - if index >= uint64(len(v)) { + if uint64(index) >= uint64(len(v)) { votes = append(votes, ðpb.IndividualVotesRespond_IndividualVote{ValidatorIndex: index}) continue } diff --git a/beacon-chain/rpc/beacon/validators_stream.go b/beacon-chain/rpc/beacon/validators_stream.go index c9ab2a7724..18ab10c9d8 100644 --- a/beacon-chain/rpc/beacon/validators_stream.go +++ b/beacon-chain/rpc/beacon/validators_stream.go @@ -383,7 +383,7 @@ func (is *infostream) calculateActivationTimeForPendingValidators(res []*ethpb.V // Fetch the list of pending validators; count the number of attesting validators. 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 { if val.IsNil() { @@ -462,7 +462,7 @@ func (is *infostream) handleBlockProcessed() { } type indicesSorter struct { - indices []uint64 + indices []types.ValidatorIndex } func (s indicesSorter) Len() int { return len(s.indices) } diff --git a/beacon-chain/rpc/beacon/validators_test.go b/beacon-chain/rpc/beacon/validators_test.go index a398760dd8..92b1cf3c23 100644 --- a/beacon-chain/rpc/beacon/validators_test.go +++ b/beacon-chain/rpc/beacon/validators_test.go @@ -141,7 +141,7 @@ func TestServer_ListValidatorBalances_DefaultResponse_NoArchive(t *testing.T) { balances[i] = params.BeaconConfig().MaxEffectiveBalance balancesResponse[i] = ðpb.ValidatorBalances_Balance{ PublicKey: pubKey(uint64(i)), - Index: uint64(i), + Index: types.ValidatorIndex(i), Balance: params.BeaconConfig().MaxEffectiveBalance, Status: "EXITED", } @@ -254,7 +254,7 @@ func TestServer_ListValidatorBalances_Pagination_Default(t *testing.T) { TotalSize: 1, }, }, - {req: ðpb.ListValidatorBalancesRequest{Indices: []uint64{1, 2, 3}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, + {req: ðpb.ListValidatorBalancesRequest{Indices: []types.ValidatorIndex{1, 2, 3}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, res: ðpb.ValidatorBalances{ Balances: []*ethpb.ValidatorBalances_Balance{ {Index: 1, PublicKey: pubKey(1), Balance: 1, Status: "EXITED"}, @@ -275,7 +275,7 @@ func TestServer_ListValidatorBalances_Pagination_Default(t *testing.T) { NextPageToken: "", TotalSize: 3, }}, - {req: ðpb.ListValidatorBalancesRequest{PublicKeys: [][]byte{pubKey(2), pubKey(3)}, Indices: []uint64{3, 4}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, // Duplication + {req: ðpb.ListValidatorBalancesRequest{PublicKeys: [][]byte{pubKey(2), pubKey(3)}, Indices: []types.ValidatorIndex{3, 4}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, // Duplication res: ðpb.ValidatorBalances{ Balances: []*ethpb.ValidatorBalances_Balance{ {Index: 2, PublicKey: pubKey(2), Balance: 2, Status: "EXITED"}, @@ -285,7 +285,7 @@ func TestServer_ListValidatorBalances_Pagination_Default(t *testing.T) { NextPageToken: "", TotalSize: 3, }}, - {req: ðpb.ListValidatorBalancesRequest{PublicKeys: [][]byte{{}}, Indices: []uint64{3, 4}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, // Public key has a blank value + {req: ðpb.ListValidatorBalancesRequest{PublicKeys: [][]byte{{}}, Indices: []types.ValidatorIndex{3, 4}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, // Public key has a blank value res: ðpb.ValidatorBalances{ Balances: []*ethpb.ValidatorBalances_Balance{ {Index: 3, PublicKey: pubKey(3), Balance: 3, Status: "EXITED"}, @@ -391,7 +391,7 @@ func TestServer_ListValidatorBalances_OutOfRange(t *testing.T) { }, } - req := ðpb.ListValidatorBalancesRequest{Indices: []uint64{uint64(1)}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}} + req := ðpb.ListValidatorBalancesRequest{Indices: []types.ValidatorIndex{types.ValidatorIndex(1)}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}} wanted := "Validator index 1 >= balance list 1" _, err = bs.ListValidatorBalances(context.Background(), req) assert.ErrorContains(t, wanted, err) @@ -488,7 +488,7 @@ func TestServer_ListValidators_OnlyActiveValidators(t *testing.T) { } validators[i] = val activeValidators = append(activeValidators, ðpb.Validators_ValidatorContainer{ - Index: uint64(i), + Index: types.ValidatorIndex(i), Validator: val, }) } else { @@ -551,7 +551,7 @@ func TestServer_ListValidators_InactiveInTheMiddle(t *testing.T) { } validators[i] = val activeValidators = append(activeValidators, ðpb.Validators_ValidatorContainer{ - Index: uint64(i), + Index: types.ValidatorIndex(i), Validator: val, }) } else { @@ -652,7 +652,7 @@ func TestServer_ListValidators_NoPagination(t *testing.T) { want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) for i := 0; i < len(validators); i++ { want[i] = ðpb.Validators_ValidatorContainer{ - Index: uint64(i), + Index: types.ValidatorIndex(i), Validator: validators[i], } } @@ -685,7 +685,7 @@ func TestServer_ListValidators_StategenNotUsed(t *testing.T) { want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) for i := 0; i < len(validators); i++ { want[i] = ðpb.Validators_ValidatorContainer{ - Index: uint64(i), + Index: types.ValidatorIndex(i), Validator: validators[i], } } @@ -709,8 +709,8 @@ func TestServer_ListValidators_IndicesPubKeys(t *testing.T) { beaconDB := dbTest.SetupDB(t) validators, _, headState := setupValidators(t, beaconDB, 100) - indicesWanted := []uint64{2, 7, 11, 17} - pubkeyIndicesWanted := []uint64{3, 5, 9, 15} + indicesWanted := []types.ValidatorIndex{2, 7, 11, 17} + pubkeyIndicesWanted := []types.ValidatorIndex{3, 5, 9, 15} allIndicesWanted := append(indicesWanted, pubkeyIndicesWanted...) want := make([]*ethpb.Validators_ValidatorContainer, len(allIndicesWanted)) for i, idx := range allIndicesWanted { @@ -741,7 +741,7 @@ func TestServer_ListValidators_IndicesPubKeys(t *testing.T) { pubKeysWanted := make([][]byte, len(pubkeyIndicesWanted)) for i, indice := range pubkeyIndicesWanted { - pubKeysWanted[i] = pubKey(indice) + pubKeysWanted[i] = pubKey(uint64(indice)) } req := ðpb.ListValidatorsRequest{ Indices: indicesWanted, @@ -935,7 +935,7 @@ func TestServer_ListValidators_DefaultPageSize(t *testing.T) { want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) for i := 0; i < len(validators); i++ { want[i] = ðpb.Validators_ValidatorContainer{ - Index: uint64(i), + Index: types.ValidatorIndex(i), Validator: validators[i], } } @@ -981,7 +981,7 @@ func TestServer_ListValidators_FromOldEpoch(t *testing.T) { want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) for i := 0; i < len(validators); i++ { want[i] = ðpb.Validators_ValidatorContainer{ - Index: uint64(i), + Index: types.ValidatorIndex(i), Validator: validators[i], } } @@ -1049,7 +1049,7 @@ func TestServer_ListValidators_ProcessHeadStateSlots(t *testing.T) { want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) for i := 0; i < len(validators); i++ { want[i] = ðpb.Validators_ValidatorContainer{ - Index: uint64(i), + Index: types.ValidatorIndex(i), Validator: validators[i], } } @@ -1126,7 +1126,7 @@ func TestServer_GetValidator(t *testing.T) { { req: ðpb.GetValidatorRequest{ QueryFilter: ðpb.GetValidatorRequest_Index{ - Index: uint64(count - 1), + Index: types.ValidatorIndex(count - 1), }, }, res: validators[count-1], @@ -1151,7 +1151,7 @@ func TestServer_GetValidator(t *testing.T) { { req: ðpb.GetValidatorRequest{ QueryFilter: ðpb.GetValidatorRequest_Index{ - Index: uint64(len(validators)), + Index: types.ValidatorIndex(len(validators)), }, }, res: nil, @@ -1202,7 +1202,7 @@ func TestServer_GetValidatorActiveSetChanges(t *testing.T) { withdrawableEpoch = params.BeaconConfig().MinValidatorWithdrawabilityDelay balance = params.BeaconConfig().EjectionBalance } - err := headState.UpdateValidatorAtIndex(uint64(i), ðpb.Validator{ + err := headState.UpdateValidatorAtIndex(types.ValidatorIndex(i), ðpb.Validator{ ActivationEpoch: activationEpoch, PublicKey: pubKey(uint64(i)), EffectiveBalance: balance, @@ -1238,19 +1238,19 @@ func TestServer_GetValidatorActiveSetChanges(t *testing.T) { pubKey(4), pubKey(6), } - wantedActiveIndices := []uint64{0, 2, 4, 6} + wantedActiveIndices := []types.ValidatorIndex{0, 2, 4, 6} wantedExited := [][]byte{ pubKey(5), } - wantedExitedIndices := []uint64{5} + wantedExitedIndices := []types.ValidatorIndex{5} wantedSlashed := [][]byte{ pubKey(3), } - wantedSlashedIndices := []uint64{3} + wantedSlashedIndices := []types.ValidatorIndex{3} wantedEjected := [][]byte{ pubKey(7), } - wantedEjectedIndices := []uint64{7} + wantedEjectedIndices := []types.ValidatorIndex{7} wanted := ðpb.ActiveSetChanges{ Epoch: 0, ActivatedPublicKeys: wantedActive, @@ -1313,7 +1313,7 @@ func TestServer_GetValidatorQueue_PendingActivation(t *testing.T) { require.NoError(t, err) assert.Equal(t, wantChurn, res.ChurnLimit) assert.DeepEqual(t, wanted, res.ActivationPublicKeys) - wantedActiveIndices := []uint64{2, 1, 0} + wantedActiveIndices := []types.ValidatorIndex{2, 1, 0} assert.DeepEqual(t, wantedActiveIndices, res.ActivationValidatorIndices) } @@ -1355,7 +1355,7 @@ func TestServer_GetValidatorQueue_ExitedValidatorLeavesQueue(t *testing.T) { require.NoError(t, err) assert.Equal(t, wantChurn, res.ChurnLimit) assert.DeepEqual(t, wanted, res.ExitPublicKeys) - wantedExitIndices := []uint64{1} + wantedExitIndices := []types.ValidatorIndex{1} assert.DeepEqual(t, wantedExitIndices, res.ExitValidatorIndices) // 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, ðpb.ValidatorPerformanceRequest{ - Indices: []uint64{2, 1, 0}, + Indices: []types.ValidatorIndex{2, 1, 0}, }) require.NoError(t, err) if !proto.Equal(want, res) { @@ -1858,7 +1858,7 @@ func TestGetValidatorPerformance_IndicesPubkeys(t *testing.T) { // Index 2 and publicKey3 points to the same validator. // Should not return duplicates. res, err := bs.GetValidatorPerformance(ctx, ðpb.ValidatorPerformanceRequest{ - PublicKeys: [][]byte{publicKey1[:], publicKey3[:]}, Indices: []uint64{1, 2}, + PublicKeys: [][]byte{publicKey1[:], publicKey3[:]}, Indices: []types.ValidatorIndex{1, 2}, }) require.NoError(t, err) if !proto.Equal(want, res) { @@ -1951,14 +1951,14 @@ func TestServer_GetIndividualVotes_ValidatorsDontExist(t *testing.T) { require.NoError(t, err) wanted := ðpb.IndividualVotesRespond{ 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") // Test non-existent validator index. res, err = bs.GetIndividualVotes(ctx, ðpb.IndividualVotesRequest{ - Indices: []uint64{100}, + Indices: []types.ValidatorIndex{100}, Epoch: 0, }) require.NoError(t, err) @@ -1972,14 +1972,14 @@ func TestServer_GetIndividualVotes_ValidatorsDontExist(t *testing.T) { // Test both. res, err = bs.GetIndividualVotes(ctx, ðpb.IndividualVotesRequest{ PublicKeys: [][]byte{{'a'}, {'b'}}, - Indices: []uint64{100, 101}, + Indices: []types.ValidatorIndex{100, 101}, Epoch: 0, }) require.NoError(t, err) wanted = ðpb.IndividualVotesRespond{ IndividualVotes: []*ethpb.IndividualVotesRespond_IndividualVote{ - {PublicKey: []byte{'a'}, ValidatorIndex: ^uint64(0)}, - {PublicKey: []byte{'b'}, ValidatorIndex: ^uint64(0)}, + {PublicKey: []byte{'a'}, ValidatorIndex: types.ValidatorIndex(^uint64(0))}, + {PublicKey: []byte{'b'}, ValidatorIndex: types.ValidatorIndex(^uint64(0))}, {ValidatorIndex: 100}, {ValidatorIndex: 101}, }, @@ -2040,7 +2040,7 @@ func TestServer_GetIndividualVotes_Working(t *testing.T) { } res, err := bs.GetIndividualVotes(ctx, ðpb.IndividualVotesRequest{ - Indices: []uint64{0, 1}, + Indices: []types.ValidatorIndex{0, 1}, Epoch: 0, }) require.NoError(t, err) diff --git a/beacon-chain/rpc/debug/block_test.go b/beacon-chain/rpc/debug/block_test.go index 4570383eb1..cc9ea157a2 100644 --- a/beacon-chain/rpc/debug/block_test.go +++ b/beacon-chain/rpc/debug/block_test.go @@ -77,7 +77,7 @@ func TestServer_GetAttestationInclusionSlot(t *testing.T) { b.Block.Slot = 2 b.Block.Body.Attestations = []*ethpb.Attestation{a} 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.Equal(t, b.Block.Slot, res.Slot) res, err = bs.GetInclusionSlot(ctx, &pbrpc.InclusionSlotRequest{Slot: 1, Id: 9999999}) diff --git a/beacon-chain/rpc/validator/assignments_test.go b/beacon-chain/rpc/validator/assignments_test.go index 42fbaba328..6edb646eef 100644 --- a/beacon-chain/rpc/validator/assignments_test.go +++ b/beacon-chain/rpc/validator/assignments_test.go @@ -98,7 +98,7 @@ func TestGetDuties_OK(t *testing.T) { res, err = vs.GetDuties(context.Background(), req) require.NoError(t, err, "Could not call epoch committee assignment") 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) } } diff --git a/beacon-chain/rpc/validator/attester_test.go b/beacon-chain/rpc/validator/attester_test.go index 3184fa97f2..691658a53e 100644 --- a/beacon-chain/rpc/validator/attester_test.go +++ b/beacon-chain/rpc/validator/attester_test.go @@ -559,12 +559,12 @@ func TestServer_SubscribeCommitteeSubnets_DifferentLengthSlots(t *testing.T) { } var slots []types.Slot - var comIdxs []uint64 + var comIdxs []types.CommitteeIndex var isAggregator []bool for i := types.Slot(100); i < 200; 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 isAggregator = append(isAggregator, boolVal) } @@ -607,12 +607,12 @@ func TestServer_SubscribeCommitteeSubnets_MultipleSlots(t *testing.T) { } var slots []types.Slot - var comIdxs []uint64 + var comIdxs []types.CommitteeIndex var isAggregator []bool for i := types.Slot(100); i < 200; 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 isAggregator = append(isAggregator, boolVal) } diff --git a/beacon-chain/rpc/validator/exit_test.go b/beacon-chain/rpc/validator/exit_test.go index 81499079fc..55d06acf7d 100644 --- a/beacon-chain/rpc/validator/exit_test.go +++ b/beacon-chain/rpc/validator/exit_test.go @@ -59,7 +59,7 @@ func TestProposeExit_Notification(t *testing.T) { defer opSub.Unsubscribe() // Send the request, expect a result on the state feed. - validatorIndex := uint64(0) + validatorIndex := types.ValidatorIndex(0) req := ðpb.SignedVoluntaryExit{ Exit: ðpb.VoluntaryExit{ 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") // Send the request, expect a result on the state feed. - validatorIndex := uint64(0) + validatorIndex := types.ValidatorIndex(0) req = ðpb.SignedVoluntaryExit{ Exit: ðpb.VoluntaryExit{ Epoch: epoch, diff --git a/beacon-chain/rpc/validator/proposer_test.go b/beacon-chain/rpc/validator/proposer_test.go index e26f07565c..b0c6ab627f 100644 --- a/beacon-chain/rpc/validator/proposer_test.go +++ b/beacon-chain/rpc/validator/proposer_test.go @@ -81,7 +81,7 @@ func TestProposer_GetBlock_OK(t *testing.T) { } 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( beaconState, privKeys[i], @@ -98,7 +98,7 @@ func TestProposer_GetBlock_OK(t *testing.T) { attesterSlashing, err := testutil.GenerateAttesterSlashingForValidator( beaconState, privKeys[i+params.BeaconConfig().MaxProposerSlashings], - i+params.BeaconConfig().MaxProposerSlashings, /* validator index */ + types.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */ ) require.NoError(t, err) attSlashings[i] = attesterSlashing diff --git a/beacon-chain/rpc/validator/status.go b/beacon-chain/rpc/validator/status.go index 13ea8409d9..1407c5bce6 100644 --- a/beacon-chain/rpc/validator/status.go +++ b/beacon-chain/rpc/validator/status.go @@ -4,6 +4,7 @@ import ( "context" "errors" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -17,7 +18,7 @@ import ( ) 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. // The status response can be one of the following: @@ -67,7 +68,7 @@ func (vs *Server) MultipleValidatorStatus( } // Convert indices to public keys. for _, idx := range req.Indices { - pubkeyBytes := headState.PubkeyAtIndex(uint64(idx)) + pubkeyBytes := headState.PubkeyAtIndex(types.ValidatorIndex(idx)) if !filtered[pubkeyBytes] { pubKeys = append(pubKeys, pubkeyBytes[:]) filtered[pubkeyBytes] = true @@ -75,7 +76,7 @@ func (vs *Server) MultipleValidatorStatus( } // Fetch statuses from beacon state. statuses := make([]*ethpb.ValidatorStatusResponse, len(pubKeys)) - indices := make([]uint64, len(pubKeys)) + indices := make([]types.ValidatorIndex, len(pubKeys)) for i, pubKey := range pubKeys { statuses[i], indices[i] = vs.validatorStatus(ctx, headState, pubKey) } @@ -126,7 +127,7 @@ func (vs *Server) validatorStatus( ctx context.Context, headState *stateTrie.BeaconState, pubKey []byte, -) (*ethpb.ValidatorStatusResponse, uint64) { +) (*ethpb.ValidatorStatusResponse, types.ValidatorIndex) { ctx, span := trace.StartSpan(ctx, "ValidatorServer.validatorStatus") 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-- { - val, err := headState.ValidatorAtIndexReadOnly(uint64(j)) + val, err := headState.ValidatorAtIndexReadOnly(types.ValidatorIndex(j)) if err != nil { return resp, idx } if helpers.IsActiveValidatorUsingTrie(val, helpers.CurrentEpoch(headState)) { - lastActivatedValidatorIdx = uint64(j) + lastActivatedValidatorIdx = types.ValidatorIndex(j) break } } // Our position in the activation queue is the above index - our validator index. if lastActivatedValidatorIdx < idx { - resp.PositionInActivationQueue = idx - lastActivatedValidatorIdx + resp.PositionInActivationQueue = uint64(idx - lastActivatedValidatorIdx) } return resp, idx 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 { return ethpb.ValidatorStatus_UNKNOWN_STATUS, 0, errors.New("head state does not exist") } 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 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) if err != nil { return ethpb.ValidatorStatus_UNKNOWN_STATUS diff --git a/beacon-chain/rpc/validator/status_test.go b/beacon-chain/rpc/validator/status_test.go index 20ae284bf5..739fe937b7 100644 --- a/beacon-chain/rpc/validator/status_test.go +++ b/beacon-chain/rpc/validator/status_test.go @@ -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", 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) } diff --git a/beacon-chain/state/field_trie_test.go b/beacon-chain/state/field_trie_test.go index a85d43cbb3..67c736d1b0 100644 --- a/beacon-chain/state/field_trie_test.go +++ b/beacon-chain/state/field_trie_test.go @@ -3,6 +3,7 @@ package state_test import ( "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/stateutil" @@ -43,8 +44,8 @@ func TestFieldTrie_RecomputeTrie(t *testing.T) { val2.ExitEpoch = 40 changedVals := []*ethpb.Validator{val1, val2} - require.NoError(t, newState.UpdateValidatorAtIndex(changedIdx[0], changedVals[0])) - require.NoError(t, newState.UpdateValidatorAtIndex(changedIdx[1], changedVals[1])) + require.NoError(t, newState.UpdateValidatorAtIndex(types.ValidatorIndex(changedIdx[0]), changedVals[0])) + require.NoError(t, newState.UpdateValidatorAtIndex(types.ValidatorIndex(changedIdx[1]), changedVals[1])) expectedRoot, err := stateutil.ValidatorRegistryRoot(newState.Validators()) require.NoError(t, err) diff --git a/beacon-chain/state/getters.go b/beacon-chain/state/getters.go index 36ce3b5c2d..1f7b8c66cb 100644 --- a/beacon-chain/state/getters.go +++ b/beacon-chain/state/getters.go @@ -616,14 +616,14 @@ func (b *BeaconState) validatorsReferences() []*ethpb.Validator { } // 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() { return nil, ErrNilInnerState } if b.state.Validators == nil { return ðpb.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) } @@ -636,14 +636,14 @@ func (b *BeaconState) ValidatorAtIndex(idx uint64) (*ethpb.Validator, error) { // ValidatorAtIndexReadOnly is the validator at the provided index. This method // 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() { return ReadOnlyValidator{}, ErrNilInnerState } if b.state.Validators == 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) } @@ -654,7 +654,7 @@ func (b *BeaconState) ValidatorAtIndexReadOnly(idx uint64) (ReadOnlyValidator, e } // 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 { return 0, false } @@ -664,9 +664,9 @@ func (b *BeaconState) ValidatorIndexByPubkey(key [48]byte) (uint64, bool) { 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 { - return map[[48]byte]uint64{} + return map[[48]byte]types.ValidatorIndex{} } b.lock.RLock() defer b.lock.RUnlock() @@ -676,11 +676,11 @@ func (b *BeaconState) validatorIndexMap() map[[48]byte]uint64 { // PubkeyAtIndex returns the pubkey at the given // validator index. -func (b *BeaconState) PubkeyAtIndex(idx uint64) [48]byte { +func (b *BeaconState) PubkeyAtIndex(idx types.ValidatorIndex) [48]byte { if !b.HasInnerState() { return [48]byte{} } - if idx >= uint64(len(b.state.Validators)) { + if uint64(idx) >= uint64(len(b.state.Validators)) { return [48]byte{} } b.lock.RLock() @@ -756,7 +756,7 @@ func (b *BeaconState) balances() []uint64 { } // 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() { return 0, ErrNilInnerState } @@ -767,7 +767,7 @@ func (b *BeaconState) BalanceAtIndex(idx uint64) (uint64, error) { b.lock.RLock() 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 b.state.Balances[idx], nil diff --git a/beacon-chain/state/setters.go b/beacon-chain/state/setters.go index d129be772e..7850710651 100644 --- a/beacon-chain/state/setters.go +++ b/beacon-chain/state/setters.go @@ -341,11 +341,11 @@ func (b *BeaconState) ApplyToEveryValidator(f func(idx int, val *ethpb.Validator // UpdateValidatorAtIndex for the beacon state. Updates the validator // 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() { 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) } b.lock.Lock() @@ -361,14 +361,14 @@ func (b *BeaconState) UpdateValidatorAtIndex(idx uint64, val *ethpb.Validator) e v[idx] = val b.state.Validators = v b.markFieldAsDirty(validators) - b.addDirtyIndices(validators, []uint64{idx}) + b.addDirtyIndices(validators, []uint64{uint64(idx)}) return nil } // SetValidatorIndexByPubkey updates the validator index mapping maintained internally to // 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() 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 // 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() { 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) } b.lock.Lock() @@ -637,7 +637,7 @@ func (b *BeaconState) AppendValidator(val *ethpb.Validator) error { // append validator to slice 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 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.markFieldAsDirty(validators) - b.addDirtyIndices(validators, []uint64{valIdx}) + b.addDirtyIndices(validators, []uint64{uint64(valIdx)}) return nil } diff --git a/beacon-chain/state/stateutil/BUILD.bazel b/beacon-chain/state/stateutil/BUILD.bazel index 1b89e73247..5eb2ec4e9a 100644 --- a/beacon-chain/state/stateutil/BUILD.bazel +++ b/beacon-chain/state/stateutil/BUILD.bazel @@ -59,6 +59,7 @@ go_test( "//shared/testutil:go_default_library", "//shared/testutil/assert: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", ], ) diff --git a/beacon-chain/state/stateutil/attestations.go b/beacon-chain/state/stateutil/attestations.go index 52df686442..65987fe849 100644 --- a/beacon-chain/state/stateutil/attestations.go +++ b/beacon-chain/state/stateutil/attestations.go @@ -34,7 +34,7 @@ func PendingAttestationRoot(hasher htrutils.HashFn, att *pb.PendingAttestation) inclusionRoot := bytesutil.ToBytes32(inclusionBuf) proposerBuf := make([]byte, 8) - binary.LittleEndian.PutUint64(proposerBuf, att.ProposerIndex) + binary.LittleEndian.PutUint64(proposerBuf, uint64(att.ProposerIndex)) // Proposer index. proposerRoot := bytesutil.ToBytes32(proposerBuf) @@ -138,7 +138,7 @@ func (h *stateRootHasher) pendingAttestationRoot(hasher htrutils.HashFn, att *pb copy(enc[2056:2184], attDataBuf) proposerBuf := make([]byte, 8) - binary.LittleEndian.PutUint64(proposerBuf, att.ProposerIndex) + binary.LittleEndian.PutUint64(proposerBuf, uint64(att.ProposerIndex)) copy(enc[2184:2192], proposerBuf) // Check if it exists in cache: diff --git a/beacon-chain/state/stateutil/blocks.go b/beacon-chain/state/stateutil/blocks.go index f7ebcda46a..89f7daf456 100644 --- a/beacon-chain/state/stateutil/blocks.go +++ b/beacon-chain/state/stateutil/blocks.go @@ -24,7 +24,7 @@ func BlockHeaderRoot(header *ethpb.BeaconBlockHeader) ([32]byte, error) { headerSlotRoot := bytesutil.ToBytes32(headerSlotBuf) fieldRoots[0] = headerSlotRoot[:] proposerIdxBuf := make([]byte, 8) - binary.LittleEndian.PutUint64(proposerIdxBuf, header.ProposerIndex) + binary.LittleEndian.PutUint64(proposerIdxBuf, uint64(header.ProposerIndex)) proposerIndexRoot := bytesutil.ToBytes32(proposerIdxBuf) fieldRoots[1] = proposerIndexRoot[:] parentRoot := bytesutil.ToBytes32(header.ParentRoot) diff --git a/beacon-chain/state/stateutil/trie_helpers_test.go b/beacon-chain/state/stateutil/trie_helpers_test.go index 5381637bc5..c1c061fafd 100644 --- a/beacon-chain/state/stateutil/trie_helpers_test.go +++ b/beacon-chain/state/stateutil/trie_helpers_test.go @@ -3,15 +3,15 @@ package stateutil_test import ( "testing" - "github.com/prysmaticlabs/prysm/shared/hashutil" - "github.com/prysmaticlabs/prysm/shared/testutil/assert" - "github.com/prysmaticlabs/prysm/shared/testutil/require" - + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil" "github.com/prysmaticlabs/prysm/shared/bytesutil" + "github.com/prysmaticlabs/prysm/shared/hashutil" "github.com/prysmaticlabs/prysm/shared/params" "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) { @@ -92,8 +92,8 @@ func TestRecomputeFromLayer_VariableSizedArray(t *testing.T) { val2.ExitEpoch = 40 changedVals := []*ethpb.Validator{val1, val2} - require.NoError(t, newState.UpdateValidatorAtIndex(changedIdx[0], changedVals[0])) - require.NoError(t, newState.UpdateValidatorAtIndex(changedIdx[1], changedVals[1])) + require.NoError(t, newState.UpdateValidatorAtIndex(types.ValidatorIndex(changedIdx[0]), changedVals[0])) + require.NoError(t, newState.UpdateValidatorAtIndex(types.ValidatorIndex(changedIdx[1]), changedVals[1])) expectedRoot, err := stateutil.ValidatorRegistryRoot(newState.Validators()) require.NoError(t, err) diff --git a/beacon-chain/state/types.go b/beacon-chain/state/types.go index 500e4fa9d4..e6ac82fb56 100644 --- a/beacon-chain/state/types.go +++ b/beacon-chain/state/types.go @@ -4,6 +4,7 @@ import ( "sync" "github.com/pkg/errors" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" coreutils "github.com/prysmaticlabs/prysm/beacon-chain/core/state/stateutils" 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 // states shared this. type validatorMapHandler struct { - valIdxMap map[[48]byte]uint64 + valIdxMap map[[48]byte]types.ValidatorIndex 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. func (v *validatorMapHandler) copy() *validatorMapHandler { 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 { m[k] = v } diff --git a/beacon-chain/sync/pending_attestations_queue_test.go b/beacon-chain/sync/pending_attestations_queue_test.go index 81a526b108..72a9b1de8a 100644 --- a/beacon-chain/sync/pending_attestations_queue_test.go +++ b/beacon-chain/sync/pending_attestations_queue_test.go @@ -348,17 +348,17 @@ func TestValidatePendingAtts_CanPruneOldAtts(t *testing.T) { for i := types.Slot(0); i < 100; i++ { s.savePendingAtt(ðpb.SignedAggregateAttestationAndProof{ Message: ðpb.AggregateAttestationAndProof{ - AggregatorIndex: uint64(i), + AggregatorIndex: types.ValidatorIndex(i), Aggregate: ðpb.Attestation{ Data: ðpb.AttestationData{Slot: i, BeaconBlockRoot: r1[:]}}}}) s.savePendingAtt(ðpb.SignedAggregateAttestationAndProof{ Message: ðpb.AggregateAttestationAndProof{ - AggregatorIndex: uint64(i*2 + i), + AggregatorIndex: types.ValidatorIndex(i*2 + i), Aggregate: ðpb.Attestation{ Data: ðpb.AttestationData{Slot: i, BeaconBlockRoot: r2[:]}}}}) s.savePendingAtt(ðpb.SignedAggregateAttestationAndProof{ Message: ðpb.AggregateAttestationAndProof{ - AggregatorIndex: uint64(i*3 + i), + AggregatorIndex: types.ValidatorIndex(i*3 + i), Aggregate: ðpb.Attestation{ Data: ðpb.AttestationData{Slot: i, BeaconBlockRoot: r3[:]}}}}) } diff --git a/beacon-chain/sync/validate_aggregate_proof.go b/beacon-chain/sync/validate_aggregate_proof.go index c8920bede8..0e44f7670e 100644 --- a/beacon-chain/sync/validate_aggregate_proof.go +++ b/beacon-chain/sync/validate_aggregate_proof.go @@ -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. -func (s *Service) hasSeenAggregatorIndexEpoch(epoch types.Epoch, aggregatorIndex uint64) bool { +func (s *Service) hasSeenAggregatorIndexEpoch(epoch types.Epoch, aggregatorIndex types.ValidatorIndex) bool { s.seenAttestationLock.RLock() 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)) return 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() 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) } // 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") 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. // 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") defer span.End() diff --git a/beacon-chain/sync/validate_aggregate_proof_test.go b/beacon-chain/sync/validate_aggregate_proof_test.go index 8bda4528f9..a5414baf2a 100644 --- a/beacon-chain/sync/validate_aggregate_proof_test.go +++ b/beacon-chain/sync/validate_aggregate_proof_test.go @@ -10,6 +10,7 @@ import ( lru "github.com/hashicorp/golang-lru" pubsub "github.com/libp2p/go-libp2p-pubsub" pubsubpb "github.com/libp2p/go-libp2p-pubsub/pb" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" @@ -48,7 +49,7 @@ func TestVerifyIndexInCommittee_CanVerify(t *testing.T) { assert.NoError(t, err) indices, err := attestationutil.AttestingIndices(att.AggregationBits, committee) 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" assert.ErrorContains(t, wanted, validateIndexInCommittee(ctx, s, att, 1000)) diff --git a/beacon-chain/sync/validate_beacon_blocks.go b/beacon-chain/sync/validate_beacon_blocks.go index 4aa0182737..d8c59c7176 100644 --- a/beacon-chain/sync/validate_beacon_blocks.go +++ b/beacon-chain/sync/validate_beacon_blocks.go @@ -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. -func (s *Service) hasSeenBlockIndexSlot(slot types.Slot, proposerIdx uint64) bool { +func (s *Service) hasSeenBlockIndexSlot(slot types.Slot, proposerIdx types.ValidatorIndex) bool { s.seenBlockLock.RLock() 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)) return seen } // 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() 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) } diff --git a/beacon-chain/sync/validate_proposer_slashing.go b/beacon-chain/sync/validate_proposer_slashing.go index c2024e0e13..95ad682a8f 100644 --- a/beacon-chain/sync/validate_proposer_slashing.go +++ b/beacon-chain/sync/validate_proposer_slashing.go @@ -5,6 +5,7 @@ import ( "github.com/libp2p/go-libp2p-core/peer" pubsub "github.com/libp2p/go-libp2p-pubsub" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "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 -func (s *Service) hasSeenProposerSlashingIndex(i uint64) bool { +func (s *Service) hasSeenProposerSlashingIndex(i types.ValidatorIndex) bool { s.seenProposerSlashingLock.RLock() defer s.seenProposerSlashingLock.RUnlock() _, seen := s.seenProposerSlashingCache.Get(i) @@ -68,7 +69,7 @@ func (s *Service) hasSeenProposerSlashingIndex(i uint64) bool { } // Set proposer slashing index in proposer slashing cache. -func (s *Service) setProposerSlashingIndexSeen(i uint64) { +func (s *Service) setProposerSlashingIndexSeen(i types.ValidatorIndex) { s.seenProposerSlashingLock.Lock() defer s.seenProposerSlashingLock.Unlock() s.seenProposerSlashingCache.Add(i, true) diff --git a/beacon-chain/sync/validate_voluntary_exit.go b/beacon-chain/sync/validate_voluntary_exit.go index 510f5a1e6a..4ce256d778 100644 --- a/beacon-chain/sync/validate_voluntary_exit.go +++ b/beacon-chain/sync/validate_voluntary_exit.go @@ -5,6 +5,7 @@ import ( "github.com/libp2p/go-libp2p-core/peer" pubsub "github.com/libp2p/go-libp2p-pubsub" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "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 } - if exit.Exit.ValidatorIndex >= uint64(headState.NumValidators()) { + if uint64(exit.Exit.ValidatorIndex) >= uint64(headState.NumValidators()) { return pubsub.ValidationReject } 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`. -func (s *Service) hasSeenExitIndex(i uint64) bool { +func (s *Service) hasSeenExitIndex(i types.ValidatorIndex) bool { s.seenExitLock.RLock() defer s.seenExitLock.RUnlock() _, 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. -func (s *Service) setExitIndexSeen(i uint64) { +func (s *Service) setExitIndexSeen(i types.ValidatorIndex) { s.seenExitLock.Lock() defer s.seenExitLock.Unlock() s.seenExitCache.Add(i, true) diff --git a/deps.bzl b/deps.bzl index fd7e127f51..1d082ba90e 100644 --- a/deps.bzl +++ b/deps.bzl @@ -2578,8 +2578,8 @@ def prysm_deps(): name = "com_github_prysmaticlabs_ethereumapis", build_file_generation = "off", importpath = "github.com/prysmaticlabs/ethereumapis", - sum = "h1:c6x9r/6CYbuBsEF0BNJ5f0WhIq7guAGtxB9Mbxp/8Ok=", - version = "v0.0.0-20210218172602-3f05f78bea9d", + sum = "h1:GhzZ3sO2ZiuJxxm3dyBps+tDaVu3q7xMdJD2yJXyuDs=", + version = "v0.0.0-20210218195742-a393edb60549", ) go_repository( name = "com_github_prysmaticlabs_go_bitfield", diff --git a/endtoend/evaluators/operations.go b/endtoend/evaluators/operations.go index 045606ccc8..83abc6b1dc 100644 --- a/endtoend/evaluators/operations.go +++ b/endtoend/evaluators/operations.go @@ -22,11 +22,11 @@ import ( "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. -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 // churnLimit is normally 4 unless the validator set is extremely large. @@ -274,12 +274,12 @@ func proposeVoluntaryExit(conns ...*grpc.ClientConn) error { return err } - exitedIndice = rand.Uint64() % params.BeaconConfig().MinGenesisActiveValidatorCount + exitedIndex = types.ValidatorIndex(rand.Uint64() % params.BeaconConfig().MinGenesisActiveValidatorCount) valExited = true voluntaryExit := ð.VoluntaryExit{ Epoch: chainHead.HeadEpoch, - ValidatorIndex: exitedIndice, + ValidatorIndex: exitedIndex, } req := ð.DomainRequest{ Epoch: chainHead.HeadEpoch, @@ -293,7 +293,7 @@ func proposeVoluntaryExit(conns ...*grpc.ClientConn) error { if err != nil { return err } - signature := privKeys[exitedIndice].Sign(signingData[:]) + signature := privKeys[exitedIndex].Sign(signingData[:]) signedExit := ð.SignedVoluntaryExit{ Exit: voluntaryExit, Signature: signature.Marshal(), @@ -310,7 +310,7 @@ func validatorIsExited(conns ...*grpc.ClientConn) error { client := eth.NewBeaconChainClient(conn) validatorRequest := ð.GetValidatorRequest{ QueryFilter: ð.GetValidatorRequest_Index{ - Index: exitedIndice, + Index: exitedIndex, }, } 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") } 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 } diff --git a/endtoend/evaluators/slashing.go b/endtoend/evaluators/slashing.go index 8a5f3e86ce..222667f4a7 100644 --- a/endtoend/evaluators/slashing.go +++ b/endtoend/evaluators/slashing.go @@ -6,12 +6,12 @@ import ( ptypes "github.com/gogo/protobuf/types" "github.com/pkg/errors" - ethTypes "github.com/prysmaticlabs/eth2-types" + "github.com/prysmaticlabs/eth2-types" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" corehelpers "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "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/params" "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. -var InjectDoubleVote = types.Evaluator{ +var InjectDoubleVote = e2eTypes.Evaluator{ Name: "inject_double_vote_%d", Policy: policies.OnEpoch(1), Evaluation: insertDoubleAttestationIntoPool, } // 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", Policy: policies.OnEpoch(1), Evaluation: proposeDoubleBlock, } // ValidatorsSlashed ensures the expected amount of validators are slashed. -var ValidatorsSlashed = types.Evaluator{ +var ValidatorsSlashed = e2eTypes.Evaluator{ Name: "validators_slashed_epoch_%d", Policy: policies.AfterNthEpoch(1), Evaluation: validatorsSlashed, } // 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", Policy: policies.AfterNthEpoch(1), Evaluation: validatorsLoseBalance, @@ -69,10 +69,10 @@ func validatorsLoseBalance(conns ...*grpc.ClientConn) error { ctx := context.Background() client := eth.NewBeaconChainClient(conn) - for i, indice := range slashedIndices { + for i, slashedIndex := range slashedIndices { req := ð.GetValidatorRequest{ QueryFilter: ð.GetValidatorRequest_Index{ - Index: indice, + Index: types.ValidatorIndex(slashedIndex), }, } valResp, err := client.GetValidator(ctx, req) @@ -122,8 +122,8 @@ func insertDoubleAttestationIntoPool(conns ...*grpc.ClientConn) error { return errors.Wrap(err, "could not get duties") } - var committeeIndex ethTypes.CommitteeIndex - var committee []uint64 + var committeeIndex types.CommitteeIndex + var committee []types.ValidatorIndex for _, duty := range duties.Duties { if duty.AttesterSlot == chainHead.HeadSlot-1 { committeeIndex = duty.CommitteeIndex @@ -159,7 +159,7 @@ func insertDoubleAttestationIntoPool(conns ...*grpc.ClientConn) error { valsToSlash := uint64(2) 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++ continue } @@ -178,7 +178,7 @@ func insertDoubleAttestationIntoPool(conns ...*grpc.ClientConn) error { if _, err = client.ProposeAttestation(ctx, att); err != nil { return errors.Wrap(err, "could not propose attestation") } - slashedIndices = append(slashedIndices, committee[i]) + slashedIndices = append(slashedIndices, uint64(committee[i])) } return nil } @@ -210,10 +210,10 @@ func proposeDoubleBlock(conns ...*grpc.ClientConn) error { return errors.Wrap(err, "could not get duties") } - var proposerIndex uint64 + var proposerIndex types.ValidatorIndex for i, duty := range duties.CurrentEpochDuties { if sliceutil.IsInSlots(chainHead.HeadSlot-1, duty.ProposerSlots) { - proposerIndex = uint64(i) + proposerIndex = types.ValidatorIndex(i) break } } @@ -264,6 +264,6 @@ func proposeDoubleBlock(conns ...*grpc.ClientConn) error { if _, err = client.ProposeBlock(ctx, signedBlk); err == nil { return errors.New("expected block to fail processing") } - slashedIndices = append(slashedIndices, proposerIndex) + slashedIndices = append(slashedIndices, uint64(proposerIndex)) return nil } diff --git a/endtoend/evaluators/validator.go b/endtoend/evaluators/validator.go index 95fc765a9c..bf6acd3c4f 100644 --- a/endtoend/evaluators/validator.go +++ b/endtoend/evaluators/validator.go @@ -51,7 +51,7 @@ func validatorsAreActive(conns ...*grpc.ClientConn) error { exitEpochWrongCount := 0 withdrawEpochWrongCount := 0 for _, item := range validators.ValidatorList { - if valExited && item.Index == exitedIndice { + if valExited && item.Index == exitedIndex { continue } if item.Validator.EffectiveBalance < params.BeaconConfig().MaxEffectiveBalance { diff --git a/go.mod b/go.mod index e8ecfba8a3..a3f0920cfa 100644 --- a/go.mod +++ b/go.mod @@ -84,7 +84,7 @@ require ( github.com/prometheus/procfs v0.3.0 // indirect github.com/prometheus/tsdb v0.10.0 // indirect 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/prombbolt v0.0.0-20210126082820-9b7adba6db7c github.com/rs/cors v1.7.0 diff --git a/go.sum b/go.sum index 069f0375ed..5ae87d5870 100644 --- a/go.sum +++ b/go.sum @@ -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-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/ethereumapis v0.0.0-20210218172602-3f05f78bea9d h1:c6x9r/6CYbuBsEF0BNJ5f0WhIq7guAGtxB9Mbxp/8Ok= -github.com/prysmaticlabs/ethereumapis v0.0.0-20210218172602-3f05f78bea9d/go.mod h1:YS3iOCGE+iVDE007GHWtj+UoPK9hyYA7Fo4mSDNTtiY= +github.com/prysmaticlabs/ethereumapis v0.0.0-20210218195742-a393edb60549 h1:GhzZ3sO2ZiuJxxm3dyBps+tDaVu3q7xMdJD2yJXyuDs= +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-20210202205921-7fcea7c45dc8 h1:18+Qqobq3HAUY0hgIhPGSqmLFnaLLocemmU7+Sj2aYQ= github.com/prysmaticlabs/go-bitfield v0.0.0-20210202205921-7fcea7c45dc8/go.mod h1:hCwmef+4qXWjv0jLDbQdWnL0Ol7cS7/lCSS26WR+u6s= diff --git a/proto/beacon/p2p/v1/generated.ssz.go b/proto/beacon/p2p/v1/generated.ssz.go index a3722022b7..ac2c045479 100755 --- a/proto/beacon/p2p/v1/generated.ssz.go +++ b/proto/beacon/p2p/v1/generated.ssz.go @@ -1229,7 +1229,7 @@ func (p *PendingAttestation) MarshalSSZTo(buf []byte) (dst []byte, err error) { dst = ssz.MarshalUint64(dst, uint64(p.InclusionDelay)) // Field (3) 'ProposerIndex' - dst = ssz.MarshalUint64(dst, p.ProposerIndex) + dst = ssz.MarshalUint64(dst, uint64(p.ProposerIndex)) // Field (0) 'AggregationBits' 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])) // 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' { @@ -1320,7 +1320,7 @@ func (p *PendingAttestation) HashTreeRootWith(hh *ssz.Hasher) (err error) { hh.PutUint64(uint64(p.InclusionDelay)) // Field (3) 'ProposerIndex' - hh.PutUint64(p.ProposerIndex) + hh.PutUint64(uint64(p.ProposerIndex)) hh.Merkleize(indx) return diff --git a/proto/beacon/p2p/v1/types.pb.go b/proto/beacon/p2p/v1/types.pb.go index 4b07c7cbf0..faf14bf55f 100755 --- a/proto/beacon/p2p/v1/types.pb.go +++ b/proto/beacon/p2p/v1/types.pb.go @@ -297,13 +297,13 @@ func (m *Fork) GetEpoch() github_com_prysmaticlabs_eth2_types.Epoch { } 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"` - 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"` - ProposerIndex uint64 `protobuf:"varint,4,opt,name=proposer_index,json=proposerIndex,proto3" json:"proposer_index,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + 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"` + 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 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_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *PendingAttestation) Reset() { *m = PendingAttestation{} } @@ -360,7 +360,7 @@ func (m *PendingAttestation) GetInclusionDelay() github_com_prysmaticlabs_eth2_t return 0 } -func (m *PendingAttestation) GetProposerIndex() uint64 { +func (m *PendingAttestation) GetProposerIndex() github_com_prysmaticlabs_eth2_types.ValidatorIndex { if m != nil { return m.ProposerIndex } @@ -744,93 +744,94 @@ func init() { func init() { proto.RegisterFile("proto/beacon/p2p/v1/types.proto", fileDescriptor_e719e7d82cfa7b0d) } 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, - 0x18, 0x96, 0x13, 0xb7, 0x4d, 0xc7, 0x49, 0x9c, 0x4e, 0x20, 0xd9, 0x7e, 0x90, 0x75, 0x57, 0xb4, - 0xa4, 0xa8, 0xb6, 0x63, 0x37, 0xb5, 0x93, 0x54, 0x14, 0xea, 0xb4, 0xa8, 0x69, 0x55, 0xa9, 0xda, - 0xd0, 0x4a, 0x48, 0x88, 0xd5, 0xec, 0xee, 0xd8, 0x3b, 0xcd, 0x7a, 0x67, 0xb5, 0x33, 0x76, 0xeb, - 0x4a, 0x88, 0x03, 0x07, 0xc4, 0x8d, 0xbf, 0x00, 0x7f, 0x82, 0x2f, 0x71, 0x80, 0x72, 0xe0, 0xc8, - 0xd7, 0x05, 0x0e, 0x16, 0xea, 0x8d, 0x8f, 0x0b, 0x3e, 0xe6, 0x84, 0x66, 0xf6, 0xcb, 0xa6, 0x71, - 0x71, 0x11, 0xb7, 0xf5, 0xcc, 0xf3, 0x3c, 0xef, 0xee, 0x33, 0xef, 0xbc, 0xef, 0x6b, 0xa0, 0xfa, - 0x01, 0xe5, 0xb4, 0x6c, 0x62, 0x64, 0x51, 0xaf, 0xec, 0x57, 0xfd, 0x72, 0xb7, 0x52, 0xe6, 0x3d, - 0x1f, 0xb3, 0x92, 0xdc, 0x81, 0x4b, 0x98, 0x3b, 0x38, 0xc0, 0x9d, 0x76, 0x29, 0xc4, 0x94, 0xfc, - 0xaa, 0x5f, 0xea, 0x56, 0x4e, 0xac, 0x60, 0xee, 0x94, 0xbb, 0x15, 0xe4, 0xfa, 0x0e, 0xaa, 0x94, - 0x11, 0xe7, 0x98, 0x71, 0xc4, 0x89, 0x00, 0x08, 0xde, 0x09, 0x75, 0x64, 0x3f, 0xe4, 0x1a, 0xa6, - 0x4b, 0xad, 0xbd, 0x08, 0x70, 0x6a, 0x04, 0xd0, 0x45, 0x2e, 0xb1, 0x11, 0xa7, 0x41, 0xb4, 0x5b, - 0x6c, 0x11, 0xee, 0x74, 0xcc, 0x92, 0x45, 0xdb, 0xe5, 0x16, 0x6d, 0xd1, 0xb2, 0x5c, 0x36, 0x3b, - 0x4d, 0xf9, 0x2b, 0x7c, 0x69, 0xf1, 0x14, 0xc2, 0xb5, 0xf7, 0xe7, 0x40, 0xae, 0x21, 0x63, 0xec, - 0x72, 0xc4, 0x31, 0xd4, 0xc0, 0x6c, 0x0b, 0x7b, 0x98, 0x11, 0x66, 0x70, 0xd2, 0xc6, 0xca, 0x6f, - 0x47, 0x0a, 0x99, 0xd5, 0xac, 0x9e, 0x8b, 0x16, 0xdf, 0x20, 0x6d, 0x0c, 0x6f, 0x80, 0xe5, 0x18, - 0x93, 0x44, 0x67, 0x46, 0x40, 0x29, 0x57, 0x7e, 0x17, 0xf0, 0xd9, 0xc6, 0xb1, 0x41, 0x5f, 0x9d, - 0x63, 0xec, 0x61, 0x91, 0x91, 0x87, 0x78, 0x4b, 0xbb, 0x50, 0xd5, 0xf4, 0xe7, 0x23, 0xca, 0xdd, - 0x84, 0xa1, 0x53, 0xca, 0xe1, 0x15, 0x90, 0x65, 0x2e, 0xe5, 0xca, 0x1f, 0x32, 0x4e, 0xe3, 0xfc, - 0x7e, 0x5f, 0x5d, 0x1d, 0xfa, 0x02, 0x3f, 0xe8, 0xb1, 0x36, 0xe2, 0xc4, 0x72, 0x91, 0xc9, 0xca, - 0x98, 0x3b, 0xd5, 0x62, 0xe8, 0xf1, 0xae, 0x4b, 0xb9, 0x2e, 0xa9, 0xb0, 0x02, 0xb2, 0x4d, 0x1a, - 0xec, 0x29, 0x7f, 0x0a, 0x89, 0x5c, 0xf5, 0x54, 0xe9, 0x60, 0xe3, 0x4b, 0xaf, 0xd3, 0x60, 0x4f, - 0x97, 0x50, 0xf8, 0x26, 0x58, 0x74, 0x91, 0x30, 0x3e, 0x34, 0xd6, 0x70, 0x30, 0xb2, 0x71, 0xa0, - 0x7c, 0x9f, 0x97, 0x0a, 0xab, 0xa9, 0x02, 0xe6, 0x4e, 0x29, 0xb6, 0xba, 0x14, 0xfa, 0xd4, 0x10, - 0x8c, 0xeb, 0x92, 0xa0, 0x1f, 0x0b, 0x55, 0x86, 0x96, 0xe0, 0x06, 0xc8, 0x85, 0x9a, 0xc2, 0x0f, - 0xa6, 0xfc, 0x90, 0x2f, 0x4c, 0xaf, 0xce, 0x36, 0x96, 0x06, 0x7d, 0x15, 0xa6, 0x86, 0x6c, 0x54, - 0x36, 0xab, 0xe7, 0x85, 0x2b, 0x40, 0x62, 0x85, 0x13, 0x4c, 0x30, 0x45, 0x26, 0xe0, 0x88, 0xf9, - 0xe3, 0xbf, 0x30, 0x25, 0x36, 0x64, 0xea, 0x60, 0xc1, 0x21, 0x8c, 0xd3, 0x80, 0x58, 0xc8, 0x8d, - 0xe8, 0x3f, 0x85, 0xf4, 0xb3, 0x83, 0xbe, 0xaa, 0xa5, 0xf4, 0x57, 0x05, 0xb7, 0x20, 0x7e, 0xb7, - 0xd1, 0x83, 0x2d, 0xad, 0x52, 0xab, 0xd7, 0xeb, 0xd5, 0x4a, 0x4d, 0xd3, 0xf3, 0xa9, 0x40, 0xa8, - 0xf9, 0x0a, 0x38, 0x8a, 0xb9, 0x53, 0x31, 0x6c, 0xc4, 0x91, 0xf2, 0xd9, 0xb2, 0x34, 0x46, 0x1d, - 0x63, 0xcc, 0x35, 0xee, 0x54, 0xae, 0x22, 0x8e, 0xf4, 0x19, 0x1c, 0x3d, 0xc1, 0xb7, 0x40, 0x3e, - 0xa1, 0x1b, 0x5d, 0xca, 0x31, 0x53, 0x3e, 0x5f, 0x2e, 0x4c, 0x4f, 0x20, 0xd2, 0x80, 0x83, 0xbe, - 0x3a, 0x9f, 0xbc, 0x62, 0x75, 0x6d, 0x7d, 0x43, 0xd3, 0xe7, 0x62, 0xe1, 0xbb, 0x42, 0x0a, 0x16, - 0x01, 0x0c, 0xd5, 0xb1, 0x4f, 0x19, 0xe1, 0x06, 0xf1, 0x6c, 0xfc, 0x40, 0xf9, 0x62, 0x59, 0xe6, - 0xea, 0x82, 0xc4, 0x86, 0x3b, 0x3b, 0x62, 0x03, 0xbe, 0x0d, 0x40, 0x9a, 0xa8, 0xca, 0x47, 0xaa, - 0x7c, 0x8f, 0xc2, 0x98, 0xf7, 0x48, 0x12, 0xb4, 0x71, 0x72, 0xd0, 0x57, 0x97, 0x53, 0xaf, 0xd6, - 0x36, 0x37, 0x2f, 0x56, 0x2a, 0xb5, 0x6a, 0xbd, 0x5e, 0xaf, 0x69, 0xfa, 0x90, 0x22, 0xdc, 0x00, - 0x33, 0x26, 0x72, 0x91, 0x67, 0x61, 0xa6, 0x7c, 0x2c, 0xd4, 0xb3, 0x4f, 0xe7, 0x26, 0x68, 0x78, - 0x09, 0xcc, 0x06, 0xc8, 0xb3, 0x11, 0x35, 0xda, 0xe4, 0x01, 0x66, 0xca, 0x07, 0x2f, 0xc9, 0x53, - 0x5b, 0x1e, 0xf4, 0xd5, 0xc5, 0xf4, 0xd4, 0x6a, 0x17, 0x2f, 0x5e, 0xa8, 0xc9, 0x53, 0xcf, 0x85, - 0xe8, 0x5b, 0x02, 0x0c, 0xab, 0xe0, 0x28, 0x73, 0x11, 0x73, 0x88, 0xd7, 0x62, 0xca, 0x5f, 0x25, - 0x19, 0x77, 0x71, 0xd0, 0x57, 0xf3, 0xa3, 0xe9, 0xa2, 0xe9, 0x29, 0x0c, 0xbe, 0x0b, 0x4e, 0xfa, - 0x01, 0xee, 0x12, 0xda, 0x61, 0x06, 0xf6, 0xa9, 0xe5, 0x18, 0x43, 0x15, 0x88, 0x29, 0x3f, 0xd7, - 0xa4, 0x37, 0x2f, 0x8f, 0xbb, 0x43, 0xb7, 0xb1, 0x67, 0x13, 0xaf, 0x75, 0x25, 0xe5, 0xfc, 0xe3, - 0xb8, 0xd6, 0xd7, 0x36, 0x6b, 0x9a, 0x7e, 0x3c, 0x8e, 0x71, 0x4d, 0x84, 0x18, 0x42, 0x33, 0xf8, - 0x0e, 0x38, 0x61, 0x75, 0x82, 0x00, 0x7b, 0xfc, 0xa0, 0xf8, 0xbf, 0xfc, 0x3f, 0xf1, 0x95, 0x28, - 0xc4, 0x93, 0xe1, 0x19, 0x80, 0xf7, 0x3a, 0x8c, 0x93, 0x26, 0xb1, 0xe4, 0x8a, 0x61, 0x12, 0xce, - 0x94, 0xaf, 0x2e, 0xcb, 0xb2, 0xb5, 0x3d, 0xe8, 0xab, 0xb3, 0xa9, 0x79, 0x15, 0x6d, 0xbf, 0xaf, - 0x96, 0xc7, 0x56, 0xa3, 0x16, 0x2d, 0x9a, 0x84, 0x37, 0x09, 0x76, 0xed, 0x52, 0x83, 0xf0, 0x2e, - 0xb6, 0x38, 0x0d, 0xd6, 0xf5, 0x63, 0x23, 0xfa, 0x0d, 0xc2, 0x19, 0x6c, 0x82, 0x17, 0x12, 0xd3, - 0xa3, 0x5d, 0x6c, 0x1b, 0x96, 0x83, 0xad, 0x3d, 0x9f, 0x12, 0x8f, 0x2b, 0x5f, 0x5f, 0x96, 0xf7, - 0xeb, 0xf4, 0x98, 0x94, 0xdc, 0x4e, 0x90, 0x7a, 0x72, 0x7a, 0x37, 0x62, 0x9d, 0x74, 0x13, 0xda, - 0xe0, 0x54, 0xec, 0xed, 0x81, 0x61, 0x1e, 0x4d, 0x1c, 0x26, 0x3e, 0xa3, 0x83, 0xa2, 0xdc, 0x01, - 0xcf, 0x35, 0x89, 0x87, 0x5c, 0xf2, 0x70, 0x54, 0xfd, 0x9b, 0x89, 0xd5, 0x17, 0x13, 0x7e, 0xba, - 0xa8, 0x3d, 0xca, 0x80, 0xac, 0x28, 0xd1, 0xf0, 0x12, 0x58, 0x48, 0xdc, 0xea, 0xe2, 0x80, 0x11, - 0xea, 0x29, 0x19, 0x79, 0x3e, 0x0b, 0xa3, 0xe7, 0xb3, 0xae, 0xe9, 0xf9, 0x18, 0x79, 0x37, 0x04, - 0xc2, 0x4d, 0x90, 0x8f, 0x2d, 0x88, 0xb9, 0x53, 0x63, 0xb8, 0xf3, 0x11, 0x30, 0xa6, 0x6e, 0x83, - 0x43, 0x32, 0x23, 0x95, 0x69, 0xd9, 0x8a, 0x8a, 0xfb, 0x7d, 0xf5, 0xdc, 0x24, 0xad, 0x48, 0x26, - 0x99, 0x1e, 0x72, 0xb5, 0x2f, 0xa7, 0x00, 0x7c, 0x32, 0x49, 0x61, 0x1b, 0x2c, 0xa0, 0x56, 0x2b, - 0xc0, 0xad, 0xa1, 0xa4, 0x0b, 0xbf, 0xa9, 0xf1, 0x64, 0xb5, 0xdb, 0xef, 0xab, 0xe7, 0x27, 0xcd, - 0x3a, 0x97, 0x30, 0xae, 0xe7, 0x87, 0xb4, 0x65, 0xc2, 0x6d, 0x81, 0xac, 0xac, 0xdb, 0x53, 0xf2, - 0x44, 0xce, 0x8e, 0x39, 0x91, 0xa1, 0x17, 0x94, 0xd5, 0x5b, 0x72, 0xe0, 0x1d, 0x90, 0x27, 0x9e, - 0xe5, 0x76, 0x84, 0x27, 0x86, 0x8d, 0x5d, 0xd4, 0x8b, 0x0c, 0x79, 0xb6, 0xde, 0x3c, 0x9f, 0x88, - 0x5c, 0x15, 0x1a, 0xf0, 0x0c, 0x98, 0xf7, 0x03, 0xea, 0x53, 0x86, 0x83, 0xa8, 0x5c, 0x67, 0x65, - 0xb5, 0x9e, 0x8b, 0x57, 0x65, 0xa9, 0xd6, 0xde, 0xcb, 0x80, 0xfc, 0xf5, 0xa4, 0x15, 0x35, 0x10, - 0xb7, 0x1c, 0x58, 0x1f, 0x6d, 0xa9, 0x99, 0x89, 0x3b, 0x6a, 0x7d, 0xb4, 0xa3, 0x4e, 0x4d, 0xda, - 0x50, 0x35, 0x1b, 0xcc, 0xca, 0x71, 0x68, 0xb7, 0xd3, 0x6e, 0xa3, 0xa0, 0x07, 0x5f, 0x8b, 0xa6, - 0x94, 0xcc, 0x7f, 0x1e, 0x52, 0x20, 0xc8, 0xca, 0x01, 0x49, 0x26, 0xa3, 0x2e, 0x9f, 0x35, 0x17, - 0xe4, 0x76, 0x49, 0xcb, 0x23, 0x5e, 0x4b, 0xb6, 0xcc, 0x2a, 0xc8, 0x51, 0xf3, 0x1e, 0xb6, 0x78, - 0x38, 0x4a, 0x65, 0xc6, 0x4d, 0x52, 0x20, 0x44, 0xc9, 0xf1, 0xe9, 0x1c, 0x38, 0x6c, 0xd3, 0x36, - 0x22, 0x71, 0x96, 0x1f, 0x00, 0x8f, 0x00, 0xda, 0x87, 0x19, 0x30, 0x23, 0xee, 0x97, 0x8c, 0x75, - 0xc0, 0x35, 0xc9, 0x4e, 0x78, 0x4d, 0x76, 0xc6, 0x4f, 0x7f, 0x53, 0xcf, 0x36, 0xfc, 0x69, 0x9f, - 0x66, 0x40, 0x4e, 0x56, 0x80, 0xdb, 0x7c, 0xc7, 0x6b, 0x52, 0x61, 0x12, 0xc3, 0xd8, 0x0e, 0x3f, - 0x5d, 0x97, 0xcf, 0xf0, 0x74, 0x3a, 0x90, 0x0e, 0x19, 0x18, 0xcf, 0xa3, 0xd2, 0x84, 0x33, 0x60, - 0x1e, 0x59, 0x9c, 0x74, 0xb1, 0x48, 0x2c, 0x22, 0x9a, 0xf0, 0xb4, 0xe8, 0x85, 0xfa, 0x5c, 0xb8, - 0xba, 0x13, 0x2e, 0xc2, 0xe3, 0x60, 0xc6, 0xef, 0x98, 0xc6, 0x1e, 0xee, 0x31, 0x25, 0x2b, 0x52, - 0x41, 0x3f, 0xe2, 0x77, 0xcc, 0x9b, 0xb8, 0xc7, 0xe0, 0x5a, 0x34, 0x42, 0x1e, 0x9a, 0x74, 0x82, - 0xd4, 0x3e, 0xc9, 0x80, 0xf9, 0x68, 0xc6, 0xb8, 0x85, 0x19, 0x43, 0x2d, 0x0c, 0xb7, 0x01, 0xf0, - 0x3b, 0xa6, 0x4b, 0x2c, 0x11, 0x22, 0x3a, 0xbe, 0x17, 0x07, 0x7d, 0xb5, 0x30, 0x64, 0xe7, 0x86, - 0x56, 0x60, 0x3e, 0xb6, 0x8a, 0x1e, 0x6a, 0xe3, 0x2d, 0xcd, 0xef, 0x98, 0x7b, 0xb8, 0xa7, 0xe9, - 0x47, 0x43, 0xde, 0x4d, 0xdc, 0x83, 0xd7, 0xc1, 0xd2, 0x7d, 0xc2, 0x1d, 0x3b, 0x40, 0xf7, 0x91, - 0x6b, 0x58, 0x01, 0xb6, 0xb1, 0xc7, 0x09, 0x72, 0xd9, 0x53, 0xcc, 0x4d, 0x09, 0xdb, 0x29, 0x1e, - 0x2e, 0x81, 0xc3, 0xa8, 0x4d, 0x3b, 0x1e, 0x0f, 0xaf, 0xaf, 0x1e, 0xfd, 0x6a, 0xcc, 0x7e, 0xfb, - 0x78, 0x25, 0xf3, 0xdd, 0xe3, 0x95, 0xcc, 0xaf, 0x8f, 0x57, 0x32, 0xe6, 0x61, 0xf9, 0x37, 0xe0, - 0xc2, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x3b, 0x1f, 0x6b, 0xc9, 0xcf, 0x0c, 0x00, 0x00, + 0x18, 0x96, 0x13, 0xb7, 0x4d, 0xc7, 0x49, 0x9c, 0x4e, 0x20, 0xd9, 0x7e, 0x90, 0x4d, 0x57, 0x50, + 0x52, 0xd4, 0xd8, 0xb1, 0x9b, 0xda, 0x49, 0x2a, 0x0a, 0x75, 0x5a, 0xd4, 0xb4, 0xaa, 0x54, 0x6d, + 0x68, 0x25, 0x24, 0x60, 0x35, 0xbb, 0x3b, 0xf6, 0x4e, 0xb3, 0xde, 0x59, 0xed, 0x8c, 0xdd, 0xba, + 0x12, 0xe2, 0xc0, 0x01, 0x71, 0xe3, 0x2f, 0xc0, 0x9f, 0xe0, 0xeb, 0x04, 0xe5, 0xc0, 0x91, 0xaf, + 0x0b, 0x1c, 0x56, 0xa8, 0x37, 0x3e, 0x2e, 0x58, 0xe2, 0x92, 0x13, 0x9a, 0xd9, 0x2f, 0x9b, 0xc6, + 0xc5, 0x45, 0xdc, 0x76, 0x67, 0x9e, 0xe7, 0x79, 0xd7, 0xcf, 0xbc, 0xf3, 0xbe, 0xaf, 0x81, 0xea, + 0x07, 0x94, 0xd3, 0xb2, 0x89, 0x91, 0x45, 0xbd, 0xb2, 0x5f, 0xf5, 0xcb, 0xdd, 0x4a, 0x99, 0xf7, + 0x7c, 0xcc, 0x4a, 0x72, 0x07, 0x2e, 0x60, 0xee, 0xe0, 0x00, 0x77, 0xda, 0xa5, 0x08, 0x53, 0xf2, + 0xab, 0x7e, 0xa9, 0x5b, 0x39, 0xb1, 0x84, 0xb9, 0x53, 0xee, 0x56, 0x90, 0xeb, 0x3b, 0xa8, 0x52, + 0x46, 0x9c, 0x63, 0xc6, 0x11, 0x27, 0x02, 0x20, 0x78, 0x27, 0xd4, 0xa1, 0xfd, 0x88, 0x6b, 0x98, + 0x2e, 0xb5, 0xf6, 0x62, 0xc0, 0xa9, 0x21, 0x40, 0x17, 0xb9, 0xc4, 0x46, 0x9c, 0x06, 0xf1, 0xee, + 0x6a, 0x8b, 0x70, 0xa7, 0x63, 0x96, 0x2c, 0xda, 0x2e, 0xb7, 0x68, 0x8b, 0x96, 0xe5, 0xb2, 0xd9, + 0x69, 0xca, 0xb7, 0xe8, 0xa3, 0xc5, 0x53, 0x04, 0xd7, 0xde, 0x9f, 0x01, 0x85, 0x86, 0x8c, 0xb1, + 0xcb, 0x11, 0xc7, 0x50, 0x03, 0xd3, 0x2d, 0xec, 0x61, 0x46, 0x98, 0xc1, 0x49, 0x1b, 0x2b, 0xbf, + 0x1e, 0x59, 0xce, 0xad, 0xe4, 0xf5, 0x42, 0xbc, 0xf8, 0x3a, 0x69, 0x63, 0x78, 0x1d, 0x2c, 0x26, + 0x98, 0x34, 0x3a, 0x33, 0x02, 0x4a, 0xb9, 0xf2, 0x9b, 0x80, 0x4f, 0x37, 0x8e, 0xf5, 0x43, 0x75, + 0x86, 0xb1, 0x07, 0xab, 0x8c, 0x3c, 0xc0, 0x5b, 0xda, 0xf9, 0xaa, 0xa6, 0x3f, 0x1b, 0x53, 0xee, + 0xa4, 0x0c, 0x9d, 0x52, 0x0e, 0x2f, 0x83, 0x3c, 0x73, 0x29, 0x57, 0x7e, 0x97, 0x71, 0x1a, 0xe7, + 0xf6, 0x43, 0x75, 0x65, 0xe0, 0x17, 0xf8, 0x41, 0x8f, 0xb5, 0x11, 0x27, 0x96, 0x8b, 0x4c, 0x56, + 0xc6, 0xdc, 0xa9, 0xae, 0x46, 0x1e, 0xef, 0xba, 0x94, 0xeb, 0x92, 0x0a, 0x2b, 0x20, 0xdf, 0xa4, + 0xc1, 0x9e, 0xf2, 0x87, 0x90, 0x28, 0x54, 0x4f, 0x95, 0x0e, 0x36, 0xbe, 0xf4, 0x1a, 0x0d, 0xf6, + 0x74, 0x09, 0x85, 0x6f, 0x80, 0x79, 0x17, 0x09, 0xe3, 0x23, 0x63, 0x0d, 0x07, 0x23, 0x1b, 0x07, + 0xca, 0x77, 0x45, 0xa9, 0xb0, 0x92, 0x29, 0x60, 0xee, 0x94, 0x12, 0xab, 0x4b, 0x91, 0x4f, 0x0d, + 0xc1, 0xb8, 0x26, 0x09, 0xfa, 0xb1, 0x48, 0x65, 0x60, 0x09, 0x6e, 0x80, 0x42, 0xa4, 0x29, 0xfc, + 0x60, 0xca, 0xf7, 0xc5, 0xe5, 0xc9, 0x95, 0xe9, 0xc6, 0x42, 0x3f, 0x54, 0x61, 0x66, 0xc8, 0x46, + 0x65, 0xb3, 0x7a, 0x4e, 0xb8, 0x02, 0x24, 0x56, 0x38, 0xc1, 0x04, 0x53, 0x64, 0x02, 0x8e, 0x99, + 0x3f, 0xfc, 0x0b, 0x53, 0x62, 0x23, 0xa6, 0x0e, 0xe6, 0x1c, 0xc2, 0x38, 0x0d, 0x88, 0x85, 0xdc, + 0x98, 0xfe, 0x63, 0x44, 0x3f, 0xd3, 0x0f, 0x55, 0x2d, 0xa3, 0xbf, 0x22, 0xb8, 0xcb, 0xe2, 0xbd, + 0x8d, 0xee, 0x6f, 0x69, 0x95, 0x5a, 0xbd, 0x5e, 0xaf, 0x56, 0x6a, 0x9a, 0x5e, 0xcc, 0x04, 0x22, + 0xcd, 0x97, 0xc1, 0x51, 0xcc, 0x9d, 0x8a, 0x61, 0x23, 0x8e, 0x94, 0xcf, 0x16, 0xa5, 0x31, 0xea, + 0x08, 0x63, 0xae, 0x72, 0xa7, 0x72, 0x05, 0x71, 0xa4, 0x4f, 0xe1, 0xf8, 0x09, 0xbe, 0x09, 0x8a, + 0x29, 0xdd, 0xe8, 0x52, 0x8e, 0x99, 0xf2, 0xf9, 0xe2, 0xf2, 0xe4, 0x18, 0x22, 0x0d, 0xd8, 0x0f, + 0xd5, 0xd9, 0xf4, 0x13, 0xab, 0x6b, 0xeb, 0x1b, 0x9a, 0x3e, 0x93, 0x08, 0xdf, 0x11, 0x52, 0x70, + 0x15, 0xc0, 0x48, 0x1d, 0xfb, 0x94, 0x11, 0x6e, 0x10, 0xcf, 0xc6, 0xf7, 0x95, 0x2f, 0x16, 0x65, + 0xae, 0xce, 0x49, 0x6c, 0xb4, 0xb3, 0x23, 0x36, 0xe0, 0xdb, 0x00, 0x64, 0x89, 0xaa, 0x7c, 0xa4, + 0xca, 0xef, 0x58, 0x1e, 0xf1, 0x1d, 0x69, 0x82, 0x36, 0x4e, 0xf6, 0x43, 0x75, 0x31, 0xf3, 0x6a, + 0x6d, 0x73, 0xf3, 0x42, 0xa5, 0x52, 0xab, 0xd6, 0xeb, 0xf5, 0x9a, 0xa6, 0x0f, 0x28, 0xc2, 0x0d, + 0x30, 0x65, 0x22, 0x17, 0x79, 0x16, 0x66, 0xca, 0xc7, 0x42, 0x3d, 0xff, 0x64, 0x6e, 0x8a, 0x86, + 0x17, 0xc1, 0x74, 0x80, 0x3c, 0x1b, 0x51, 0xa3, 0x4d, 0xee, 0x63, 0xa6, 0x7c, 0xf0, 0xa2, 0x3c, + 0xb5, 0xc5, 0x7e, 0xa8, 0xce, 0x67, 0xa7, 0x56, 0xbb, 0x70, 0xe1, 0x7c, 0x4d, 0x9e, 0x7a, 0x21, + 0x42, 0xdf, 0x14, 0x60, 0x58, 0x05, 0x47, 0x99, 0x8b, 0x98, 0x43, 0xbc, 0x16, 0x53, 0xfe, 0x2c, + 0xc9, 0xb8, 0xf3, 0xfd, 0x50, 0x2d, 0x0e, 0xa7, 0x8b, 0xa6, 0x67, 0x30, 0xf8, 0x2e, 0x38, 0xe9, + 0x07, 0xb8, 0x4b, 0x68, 0x87, 0x19, 0xd8, 0xa7, 0x96, 0x63, 0x0c, 0x54, 0x20, 0xa6, 0xfc, 0x54, + 0x93, 0xde, 0xbc, 0x34, 0xea, 0x0e, 0xdd, 0xc2, 0x9e, 0x4d, 0xbc, 0xd6, 0xe5, 0x8c, 0xf3, 0x8f, + 0xe3, 0x5a, 0x5f, 0xdb, 0xac, 0x69, 0xfa, 0xf1, 0x24, 0xc6, 0x55, 0x11, 0x62, 0x00, 0xcd, 0xe0, + 0x3b, 0xe0, 0x84, 0xd5, 0x09, 0x02, 0xec, 0xf1, 0x83, 0xe2, 0xff, 0xfc, 0xff, 0xc4, 0x57, 0xe2, + 0x10, 0x8f, 0x87, 0x67, 0x00, 0xde, 0xed, 0x30, 0x4e, 0x9a, 0xc4, 0x92, 0x2b, 0x86, 0x49, 0x38, + 0x53, 0xbe, 0xbc, 0x24, 0xcb, 0xd6, 0x76, 0x3f, 0x54, 0xa7, 0x33, 0xf3, 0x2a, 0xda, 0x7e, 0xa8, + 0x96, 0x47, 0x56, 0xa3, 0x16, 0x5d, 0x35, 0x09, 0x6f, 0x12, 0xec, 0xda, 0xa5, 0x06, 0xe1, 0x5d, + 0x6c, 0x71, 0x1a, 0xac, 0xeb, 0xc7, 0x86, 0xf4, 0x1b, 0x84, 0x33, 0xd8, 0x04, 0xcf, 0xa5, 0xa6, + 0xc7, 0xbb, 0xd8, 0x36, 0x2c, 0x07, 0x5b, 0x7b, 0x3e, 0x25, 0x1e, 0x57, 0xbe, 0xba, 0x24, 0xef, + 0xd7, 0xe9, 0x11, 0x29, 0xb9, 0x9d, 0x22, 0xf5, 0xf4, 0xf4, 0xae, 0x27, 0x3a, 0xd9, 0x26, 0xb4, + 0xc1, 0xa9, 0xc4, 0xdb, 0x03, 0xc3, 0x3c, 0x1c, 0x3b, 0x4c, 0x72, 0x46, 0x07, 0x45, 0xb9, 0x0d, + 0x9e, 0x69, 0x12, 0x0f, 0xb9, 0xe4, 0xc1, 0xb0, 0xfa, 0xd7, 0x63, 0xab, 0xcf, 0xa7, 0xfc, 0x6c, + 0x51, 0x7b, 0x98, 0x03, 0x79, 0x51, 0xa2, 0xe1, 0x45, 0x30, 0x97, 0xba, 0xd5, 0xc5, 0x01, 0x23, + 0xd4, 0x53, 0x72, 0xf2, 0x7c, 0xe6, 0x86, 0xcf, 0x67, 0x5d, 0xd3, 0x8b, 0x09, 0xf2, 0x4e, 0x04, + 0x84, 0x9b, 0xa0, 0x98, 0x58, 0x90, 0x70, 0x27, 0x46, 0x70, 0x67, 0x63, 0x60, 0x42, 0xdd, 0x06, + 0x87, 0x64, 0x46, 0x2a, 0x93, 0xb2, 0x15, 0xad, 0xee, 0x87, 0xea, 0xd9, 0x71, 0x5a, 0x91, 0x4c, + 0x32, 0x3d, 0xe2, 0x6a, 0x7f, 0x4d, 0x00, 0xf8, 0x78, 0x92, 0xc2, 0x36, 0x98, 0x43, 0xad, 0x56, + 0x80, 0x5b, 0x03, 0x49, 0x17, 0xfd, 0xa6, 0xc6, 0xe3, 0xd5, 0x6e, 0x3f, 0x54, 0xcf, 0x8d, 0x9b, + 0x75, 0x2e, 0x61, 0x5c, 0x2f, 0x0e, 0x68, 0xcb, 0x84, 0xdb, 0x02, 0x79, 0x59, 0xb7, 0x27, 0xe4, + 0x89, 0x9c, 0x19, 0x71, 0x22, 0x03, 0x1f, 0x28, 0xab, 0xb7, 0xe4, 0xc0, 0xdb, 0xa0, 0x48, 0x3c, + 0xcb, 0xed, 0x08, 0x4f, 0x0c, 0x1b, 0xbb, 0xa8, 0x17, 0x1b, 0xf2, 0x74, 0xbd, 0x79, 0x36, 0x15, + 0xb9, 0x22, 0x34, 0xe0, 0x5b, 0x60, 0xd6, 0x0f, 0xa8, 0x4f, 0x19, 0x0e, 0xe2, 0x72, 0x9d, 0x97, + 0xaa, 0xb5, 0xfd, 0x50, 0xad, 0x8e, 0xa3, 0x9a, 0xd6, 0x65, 0x59, 0xd3, 0xf5, 0x99, 0x44, 0x4d, + 0xbe, 0x6a, 0xef, 0xe5, 0x40, 0xf1, 0x5a, 0xda, 0xc2, 0x1a, 0x88, 0x5b, 0x0e, 0xac, 0x0f, 0xb7, + 0xe2, 0xdc, 0xd8, 0x9d, 0xb8, 0x3e, 0xdc, 0x89, 0x27, 0xc6, 0x6d, 0xc4, 0x9a, 0x0d, 0xa6, 0xe5, + 0x18, 0xb5, 0xdb, 0x69, 0xb7, 0x51, 0xd0, 0x83, 0xaf, 0xc6, 0xd3, 0x4d, 0xee, 0x3f, 0x0f, 0x37, + 0x10, 0xe4, 0xe5, 0x60, 0x25, 0x93, 0x58, 0x97, 0xcf, 0x9a, 0x0b, 0x0a, 0xbb, 0xa4, 0xe5, 0x11, + 0xaf, 0x25, 0x5b, 0x6d, 0x15, 0x14, 0xa8, 0x79, 0x17, 0x5b, 0x3c, 0x1a, 0xc1, 0x72, 0xa3, 0x26, + 0x30, 0x10, 0xa1, 0xe4, 0xd8, 0x75, 0x16, 0x1c, 0xb6, 0x69, 0x1b, 0x91, 0xe4, 0x76, 0x1c, 0x00, + 0x8f, 0x01, 0xda, 0x87, 0x39, 0x30, 0x25, 0xee, 0xa5, 0x8c, 0x75, 0xc0, 0xf5, 0xca, 0x8f, 0x79, + 0xbd, 0x76, 0x46, 0x4f, 0x8d, 0x13, 0x4f, 0x37, 0x34, 0x6a, 0x9f, 0xe6, 0x40, 0x41, 0x56, 0x8e, + 0x5b, 0x7c, 0xc7, 0x6b, 0x52, 0x61, 0x12, 0xc3, 0xd8, 0x8e, 0x7e, 0xba, 0x2e, 0x9f, 0xe1, 0xe9, + 0x6c, 0x90, 0x1d, 0x30, 0x30, 0x99, 0x63, 0xa5, 0x09, 0x2f, 0x80, 0x59, 0x64, 0x71, 0xd2, 0xc5, + 0x22, 0x21, 0x89, 0x68, 0xde, 0x93, 0xa2, 0x87, 0xea, 0x33, 0xd1, 0xea, 0x4e, 0xb4, 0x08, 0x8f, + 0x83, 0x29, 0xbf, 0x63, 0x1a, 0x7b, 0xb8, 0xc7, 0x94, 0xbc, 0x48, 0x05, 0xfd, 0x88, 0xdf, 0x31, + 0x6f, 0xe0, 0x1e, 0x83, 0x6b, 0xf1, 0xe8, 0x79, 0x68, 0xdc, 0xc9, 0x53, 0xfb, 0x24, 0x07, 0x66, + 0xe3, 0xd9, 0xe4, 0x26, 0x66, 0x0c, 0xb5, 0x30, 0xdc, 0x06, 0xc0, 0xef, 0x98, 0x2e, 0xb1, 0x44, + 0x88, 0xf8, 0xf8, 0x9e, 0xef, 0x87, 0xea, 0xf2, 0x80, 0x9d, 0x1b, 0xda, 0x32, 0xf3, 0xb1, 0xb5, + 0xea, 0xa1, 0x36, 0xde, 0xd2, 0xfc, 0x8e, 0xb9, 0x87, 0x7b, 0x9a, 0x7e, 0x34, 0xe2, 0xdd, 0xc0, + 0x3d, 0x78, 0x0d, 0x2c, 0xdc, 0x23, 0xdc, 0xb1, 0x03, 0x74, 0x0f, 0xb9, 0x86, 0x15, 0x60, 0x1b, + 0x7b, 0x9c, 0x20, 0x97, 0x3d, 0xc1, 0xdc, 0x8c, 0xb0, 0x9d, 0xe1, 0xe1, 0x02, 0x38, 0x8c, 0xda, + 0xb4, 0xe3, 0xf1, 0xe8, 0xda, 0xeb, 0xf1, 0x5b, 0x63, 0xfa, 0x9b, 0x47, 0x4b, 0xb9, 0x6f, 0x1f, + 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) { @@ -2953,7 +2954,7 @@ func (m *PendingAttestation) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.ProposerIndex |= uint64(b&0x7F) << shift + m.ProposerIndex |= github_com_prysmaticlabs_eth2_types.ValidatorIndex(b&0x7F) << shift if b < 0x80 { break } diff --git a/proto/beacon/p2p/v1/types.proto b/proto/beacon/p2p/v1/types.proto index aea1d475b9..93ea877fea 100644 --- a/proto/beacon/p2p/v1/types.proto +++ b/proto/beacon/p2p/v1/types.proto @@ -60,7 +60,7 @@ message PendingAttestation { // The difference of when attestation gets created and get included on chain. uint64 inclusion_delay = 3 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Slot"]; // 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 { diff --git a/shared/attestationutil/BUILD.bazel b/shared/attestationutil/BUILD.bazel index eba30933ce..8e9893c5df 100644 --- a/shared/attestationutil/BUILD.bazel +++ b/shared/attestationutil/BUILD.bazel @@ -11,6 +11,7 @@ go_library( "//shared/bls:go_default_library", "//shared/params: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_go_bitfield//:go_default_library", "@io_opencensus_go//trace:go_default_library", @@ -25,6 +26,7 @@ go_test( "//shared/params:go_default_library", "//shared/testutil/assert: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_go_bitfield//:go_default_library", ], diff --git a/shared/attestationutil/attestation_utils.go b/shared/attestationutil/attestation_utils.go index e8135af753..cf9b0f9f24 100644 --- a/shared/attestationutil/attestation_utils.go +++ b/shared/attestationutil/attestation_utils.go @@ -9,6 +9,7 @@ import ( "sort" "github.com/pkg/errors" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" @@ -35,7 +36,7 @@ import ( // data=attestation.data, // 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") 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) // 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)) { return nil, fmt.Errorf("bitfield length %d is not equal to committee length %d", bf.Len(), len(committee)) } indices := make([]uint64, 0, bf.Count()) for _, idx := range bf.BitIndices() { if idx < len(committee) { - indices = append(indices, committee[idx]) + indices = append(indices, uint64(committee[idx])) } } return indices, nil diff --git a/shared/attestationutil/attestation_utils_test.go b/shared/attestationutil/attestation_utils_test.go index 88ccc012c9..1408635f29 100644 --- a/shared/attestationutil/attestation_utils_test.go +++ b/shared/attestationutil/attestation_utils_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + types "github.com/prysmaticlabs/eth2-types" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/shared/attestationutil" @@ -15,7 +16,7 @@ import ( func TestAttestingIndices(t *testing.T) { type args struct { bf bitfield.Bitfield - committee []uint64 + committee []types.ValidatorIndex } tests := []struct { name string @@ -27,7 +28,7 @@ func TestAttestingIndices(t *testing.T) { name: "Full committee attested", args: args{ bf: bitfield.Bitlist{0b1111}, - committee: []uint64{0, 1, 2}, + committee: []types.ValidatorIndex{0, 1, 2}, }, want: []uint64{0, 1, 2}, }, @@ -35,7 +36,7 @@ func TestAttestingIndices(t *testing.T) { name: "Partial committee attested", args: args{ bf: bitfield.Bitlist{0b1101}, - committee: []uint64{0, 1, 2}, + committee: []types.ValidatorIndex{0, 1, 2}, }, want: []uint64{0, 2}, }, @@ -43,7 +44,7 @@ func TestAttestingIndices(t *testing.T) { name: "Invalid bit length", args: args{ 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", }, @@ -155,7 +156,7 @@ func TestIsValidAttestationIndices(t *testing.T) { func BenchmarkAttestingIndices_PartialCommittee(b *testing.B) { 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() for i := 0; i < b.N; i++ { diff --git a/shared/sszutil/deep_equal.go b/shared/sszutil/deep_equal.go index bad8f4a751..b5938f8a2b 100644 --- a/shared/sszutil/deep_equal.go +++ b/shared/sszutil/deep_equal.go @@ -225,6 +225,8 @@ func deepValueBaseTypeEqual(v1, v2 reflect.Value) bool { return v1.Interface().(types.Epoch) == v2.Interface().(types.Epoch) case "Slot": return v1.Interface().(types.Slot) == v2.Interface().(types.Slot) + case "ValidatorIndex": + return v1.Interface().(types.ValidatorIndex) == v2.Interface().(types.ValidatorIndex) case "CommitteeIndex": return v1.Interface().(types.CommitteeIndex) == v2.Interface().(types.CommitteeIndex) } diff --git a/shared/testutil/BUILD.bazel b/shared/testutil/BUILD.bazel index 134d2283c2..9a5337b607 100644 --- a/shared/testutil/BUILD.bazel +++ b/shared/testutil/BUILD.bazel @@ -63,6 +63,7 @@ go_test( "//shared/testutil/assert:go_default_library", "//shared/testutil/require: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", ], ) diff --git a/shared/testutil/block.go b/shared/testutil/block.go index 97f460e8ce..09061ee223 100644 --- a/shared/testutil/block.go +++ b/shared/testutil/block.go @@ -188,7 +188,7 @@ func GenerateFullBlock( func GenerateProposerSlashingForValidator( bState *stateTrie.BeaconState, priv bls.SecretKey, - idx uint64, + idx types.ValidatorIndex, ) (*ethpb.ProposerSlashing, error) { header1 := HydrateSignedBeaconHeader(ðpb.SignedBeaconBlockHeader{ Header: ðpb.BeaconBlockHeader{ @@ -248,7 +248,7 @@ func generateProposerSlashings( func GenerateAttesterSlashingForValidator( bState *stateTrie.BeaconState, priv bls.SecretKey, - idx uint64, + idx types.ValidatorIndex, ) (*ethpb.AttesterSlashing, error) { currentEpoch := helpers.CurrentEpoch(bState) @@ -266,7 +266,7 @@ func GenerateAttesterSlashingForValidator( Root: params.BeaconConfig().ZeroHash[:], }, }, - AttestingIndices: []uint64{idx}, + AttestingIndices: []uint64{uint64(idx)}, } var err error att1.Signature, err = helpers.ComputeDomainAndSign(bState, currentEpoch, att1.Data, params.BeaconConfig().DomainBeaconAttester, priv) @@ -288,7 +288,7 @@ func GenerateAttesterSlashingForValidator( Root: params.BeaconConfig().ZeroHash[:], }, }, - AttestingIndices: []uint64{idx}, + AttestingIndices: []uint64{uint64(idx)}, } att2.Signature, err = helpers.ComputeDomainAndSign(bState, currentEpoch, att2.Data, params.BeaconConfig().DomainBeaconAttester, priv) if err != nil { @@ -373,12 +373,12 @@ func generateVoluntaryExits( 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)) if err != nil { 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 diff --git a/shared/testutil/block_test.go b/shared/testutil/block_test.go index 1c52728368..11d340fc7c 100644 --- a/shared/testutil/block_test.go +++ b/shared/testutil/block_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + types "github.com/prysmaticlabs/eth2-types" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/state" @@ -99,7 +100,7 @@ func TestGenerateFullBlock_ValidAttesterSlashings(t *testing.T) { require.NoError(t, err) 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) t.Fatal("expected validator to be slashed") } diff --git a/slasher/beaconclient/validator_retrieval.go b/slasher/beaconclient/validator_retrieval.go index d3a971be7c..0a6ab08f20 100644 --- a/slasher/beaconclient/validator_retrieval.go +++ b/slasher/beaconclient/validator_retrieval.go @@ -4,6 +4,7 @@ import ( "context" "github.com/pkg/errors" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "go.opencensus.io/trace" ) @@ -12,12 +13,12 @@ import ( // keys from a beacon node via gRPC. func (s *Service) FindOrGetPublicKeys( ctx context.Context, - validatorIndices []uint64, -) (map[uint64][]byte, error) { + validatorIndices []types.ValidatorIndex, +) (map[types.ValidatorIndex][]byte, error) { ctx, span := trace.StartSpan(ctx, "beaconclient.FindOrGetPublicKeys") defer span.End() - validators := make(map[uint64][]byte, len(validatorIndices)) + validators := make(map[types.ValidatorIndex][]byte, len(validatorIndices)) notFound := 0 for _, validatorIdx := range validatorIndices { pub, exists := s.publicKeyCache.Get(validatorIdx) diff --git a/slasher/beaconclient/validator_retrieval_test.go b/slasher/beaconclient/validator_retrieval_test.go index ba41772db4..a9aa1f2d8f 100644 --- a/slasher/beaconclient/validator_retrieval_test.go +++ b/slasher/beaconclient/validator_retrieval_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/golang/mock/gomock" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/mock" "github.com/prysmaticlabs/prysm/shared/testutil/assert" @@ -54,7 +55,7 @@ func TestService_RequestValidator(t *testing.T) { ).Return(wanted2, nil) // 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) for i, v := range wanted.ValidatorList { 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.LogsDoNotContain(t, hook, "Retrieved validators public keys from 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) for i, v := range wanted2.ValidatorList { diff --git a/slasher/cache/validators_cache.go b/slasher/cache/validators_cache.go index 9868e98a56..e9603d1bc3 100644 --- a/slasher/cache/validators_cache.go +++ b/slasher/cache/validators_cache.go @@ -4,6 +4,7 @@ import ( lru "github.com/hashicorp/golang-lru" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" + types "github.com/prysmaticlabs/eth2-types" ) 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. -func (c *PublicKeyCache) Get(validatorIdx uint64) ([]byte, bool) { +func (c *PublicKeyCache) Get(validatorIdx types.ValidatorIndex) ([]byte, bool) { item, exists := c.cache.Get(validatorIdx) if exists && item != nil { validatorsCacheHit.Inc() @@ -50,18 +51,18 @@ func (c *PublicKeyCache) Get(validatorIdx uint64) ([]byte, bool) { } // 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) } // Delete removes a validator id from the cache and returns if it existed or not. // 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) } // 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) } diff --git a/slasher/db/BUILD.bazel b/slasher/db/BUILD.bazel index be62df94d9..bf1456fcda 100644 --- a/slasher/db/BUILD.bazel +++ b/slasher/db/BUILD.bazel @@ -37,6 +37,7 @@ go_test( "//shared/testutil/assert:go_default_library", "//shared/testutil/require: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_urfave_cli_v2//:go_default_library", ], diff --git a/slasher/db/iface/interface.go b/slasher/db/iface/interface.go index c1987da3da..3eba94487b 100644 --- a/slasher/db/iface/interface.go +++ b/slasher/db/iface/interface.go @@ -24,8 +24,8 @@ type ReadOnlyDatabase interface { GetLatestEpochDetected(ctx context.Context) (types.Epoch, error) // BlockHeader related methods. - BlockHeaders(ctx context.Context, slot types.Slot, validatorID uint64) ([]*ethpb.SignedBeaconBlockHeader, error) - HasBlockHeader(ctx context.Context, slot types.Slot, validatorID uint64) bool + BlockHeaders(ctx context.Context, slot types.Slot, validatorID types.ValidatorIndex) ([]*ethpb.SignedBeaconBlockHeader, error) + HasBlockHeader(ctx context.Context, slot types.Slot, validatorID types.ValidatorIndex) bool // IndexedAttestations related methods. HasIndexedAttestation(ctx context.Context, att *ethpb.IndexedAttestation) (bool, error) @@ -44,7 +44,7 @@ type ReadOnlyDatabase interface { HasProposerSlashing(ctx context.Context, slashing *ethpb.ProposerSlashing) (bool, dbtypes.SlashingStatus, error) // Validator Index -> Pubkey related methods. - ValidatorPubKey(ctx context.Context, validatorID uint64) ([]byte, error) + ValidatorPubKey(ctx context.Context, validatorID types.ValidatorIndex) ([]byte, error) // Chain data related methods. ChainHead(ctx context.Context) (*ethpb.ChainHead, error) @@ -83,8 +83,8 @@ type WriteAccessDatabase interface { SaveProposerSlashings(ctx context.Context, status dbtypes.SlashingStatus, slashings []*ethpb.ProposerSlashing) error // Validator Index -> Pubkey related methods. - SavePubKey(ctx context.Context, validatorID uint64, pubKey []byte) error - DeletePubKey(ctx context.Context, validatorID uint64) error + SavePubKey(ctx context.Context, validatorID types.ValidatorIndex, pubKey []byte) error + DeletePubKey(ctx context.Context, validatorID types.ValidatorIndex) error // Chain data related methods. SaveChainHead(ctx context.Context, head *ethpb.ChainHead) error @@ -107,6 +107,6 @@ type Database interface { // EpochSpansStore represents a data access layer for marshaling and unmarshaling validator spans for each validator per epoch. type EpochSpansStore interface { - SetValidatorSpan(ctx context.Context, idx uint64, newSpan slashertypes.Span) error - GetValidatorSpan(ctx context.Context, idx uint64) (slashertypes.Span, error) + SetValidatorSpan(ctx context.Context, idx types.ValidatorIndex, newSpan slashertypes.Span) error + GetValidatorSpan(ctx context.Context, idx types.ValidatorIndex) (slashertypes.Span, error) } diff --git a/slasher/db/kv/backup_test.go b/slasher/db/kv/backup_test.go index b0d6abe2f5..bc1ed72051 100644 --- a/slasher/db/kv/backup_test.go +++ b/slasher/db/kv/backup_test.go @@ -7,6 +7,7 @@ import ( "path/filepath" "testing" + types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/testutil/require" ) @@ -14,7 +15,7 @@ func TestStore_Backup(t *testing.T) { db := setupDB(t) ctx := context.Background() pubKey := []byte("hello") - require.NoError(t, db.SavePubKey(ctx, uint64(1), pubKey)) + require.NoError(t, db.SavePubKey(ctx, types.ValidatorIndex(1), pubKey)) require.NoError(t, db.Backup(ctx, "")) backupsPath := filepath.Join(db.databasePath, backupsDirectoryName) @@ -33,7 +34,7 @@ func TestStore_Backup(t *testing.T) { t.Cleanup(func() { require.NoError(t, backedDB.Close(), "Failed to close database") }) - received, err := backedDB.ValidatorPubKey(ctx, uint64(1)) + received, err := backedDB.ValidatorPubKey(ctx, types.ValidatorIndex(1)) require.NoError(t, err) require.DeepEqual(t, pubKey, received) } diff --git a/slasher/db/kv/block_header.go b/slasher/db/kv/block_header.go index dfb354a892..b4178669be 100644 --- a/slasher/db/kv/block_header.go +++ b/slasher/db/kv/block_header.go @@ -28,7 +28,7 @@ func unmarshalBlockHeader(ctx context.Context, enc []byte) (*ethpb.SignedBeaconB // BlockHeaders accepts an slot and validator id and returns the corresponding block header array. // Returns nil if the block header for those values does not exist. -func (s *Store) BlockHeaders(ctx context.Context, slot types.Slot, validatorID uint64) ([]*ethpb.SignedBeaconBlockHeader, error) { +func (s *Store) BlockHeaders(ctx context.Context, slot types.Slot, validatorID types.ValidatorIndex) ([]*ethpb.SignedBeaconBlockHeader, error) { ctx, span := trace.StartSpan(ctx, "slasherDB.BlockHeaders") defer span.End() var blockHeaders []*ethpb.SignedBeaconBlockHeader @@ -48,7 +48,7 @@ func (s *Store) BlockHeaders(ctx context.Context, slot types.Slot, validatorID u } // HasBlockHeader accepts a slot and validator id and returns true if the block header exists. -func (s *Store) HasBlockHeader(ctx context.Context, slot types.Slot, validatorID uint64) bool { +func (s *Store) HasBlockHeader(ctx context.Context, slot types.Slot, validatorID types.ValidatorIndex) bool { ctx, span := trace.StartSpan(ctx, "slasherDB.HasBlockHeader") defer span.End() prefix := encodeSlotValidatorID(slot, validatorID) diff --git a/slasher/db/kv/block_header_test.go b/slasher/db/kv/block_header_test.go index 643b311ecd..45fd2a4930 100644 --- a/slasher/db/kv/block_header_test.go +++ b/slasher/db/kv/block_header_test.go @@ -18,7 +18,7 @@ func TestNilDBHistoryBlkHdr(t *testing.T) { ctx := context.Background() slot := types.Slot(1) - validatorID := uint64(1) + validatorID := types.ValidatorIndex(1) require.Equal(t, false, db.HasBlockHeader(ctx, slot, validatorID)) diff --git a/slasher/db/kv/schema.go b/slasher/db/kv/schema.go index c22f3c9ef4..5f4c36afaa 100644 --- a/slasher/db/kv/schema.go +++ b/slasher/db/kv/schema.go @@ -29,12 +29,12 @@ var ( validatorsMinMaxSpanBucketNew = []byte("validators-min-max-span-bucket-new") ) -func encodeSlotValidatorID(slot types.Slot, validatorID uint64) []byte { - return append(bytesutil.Bytes8(uint64(slot)), bytesutil.Bytes8(validatorID)...) +func encodeSlotValidatorID(slot types.Slot, validatorID types.ValidatorIndex) []byte { + return append(bytesutil.Bytes8(uint64(slot)), bytesutil.Bytes8(uint64(validatorID))...) } -func encodeSlotValidatorIDSig(slot types.Slot, validatorID uint64, sig []byte) []byte { - return append(append(bytesutil.Bytes8(uint64(slot)), bytesutil.Bytes8(validatorID)...), sig...) +func encodeSlotValidatorIDSig(slot types.Slot, validatorID types.ValidatorIndex, sig []byte) []byte { + return append(append(bytesutil.Bytes8(uint64(slot)), bytesutil.Bytes8(uint64(validatorID))...), sig...) } func encodeEpochSig(targetEpoch types.Epoch, sig []byte) []byte { diff --git a/slasher/db/kv/validator_id_pubkey.go b/slasher/db/kv/validator_id_pubkey.go index d28ec577e6..5db2ffb8a8 100644 --- a/slasher/db/kv/validator_id_pubkey.go +++ b/slasher/db/kv/validator_id_pubkey.go @@ -4,6 +4,7 @@ import ( "context" "github.com/pkg/errors" + types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bytesutil" bolt "go.etcd.io/bbolt" "go.opencensus.io/trace" @@ -11,25 +12,25 @@ import ( // ValidatorPubKey accepts validator id and returns the corresponding pubkey. // Returns nil if the pubkey for this validator id does not exist. -func (s *Store) ValidatorPubKey(ctx context.Context, validatorID uint64) ([]byte, error) { +func (s *Store) ValidatorPubKey(ctx context.Context, validatorID types.ValidatorIndex) ([]byte, error) { ctx, span := trace.StartSpan(ctx, "SlasherDB.ValidatorPubKey") defer span.End() var pk []byte err := s.view(func(tx *bolt.Tx) error { b := tx.Bucket(validatorsPublicKeysBucket) - pk = b.Get(bytesutil.Bytes4(validatorID)) + pk = b.Get(bytesutil.Bytes4(uint64(validatorID))) return nil }) return pk, err } // SavePubKey accepts a validator id and its public key and writes it to disk. -func (s *Store) SavePubKey(ctx context.Context, validatorID uint64, pubKey []byte) error { +func (s *Store) SavePubKey(ctx context.Context, validatorID types.ValidatorIndex, pubKey []byte) error { ctx, span := trace.StartSpan(ctx, "SlasherDB.SavePubKey") defer span.End() err := s.update(func(tx *bolt.Tx) error { bucket := tx.Bucket(validatorsPublicKeysBucket) - key := bytesutil.Bytes4(validatorID) + key := bytesutil.Bytes4(uint64(validatorID)) if err := bucket.Put(key, pubKey); err != nil { return errors.Wrap(err, "failed to add validator public key to slasher s.") } @@ -39,12 +40,12 @@ func (s *Store) SavePubKey(ctx context.Context, validatorID uint64, pubKey []byt } // DeletePubKey deletes a public key of a validator id. -func (s *Store) DeletePubKey(ctx context.Context, validatorID uint64) error { +func (s *Store) DeletePubKey(ctx context.Context, validatorID types.ValidatorIndex) error { ctx, span := trace.StartSpan(ctx, "SlasherDB.DeletePubKey") defer span.End() return s.update(func(tx *bolt.Tx) error { bucket := tx.Bucket(validatorsPublicKeysBucket) - key := bytesutil.Bytes4(validatorID) + key := bytesutil.Bytes4(uint64(validatorID)) if err := bucket.Delete(key); err != nil { return errors.Wrap(err, "failed to delete public key from validators public key bucket") } diff --git a/slasher/db/kv/validator_id_pubkey_test.go b/slasher/db/kv/validator_id_pubkey_test.go index 0a1278db4a..47d6da5978 100644 --- a/slasher/db/kv/validator_id_pubkey_test.go +++ b/slasher/db/kv/validator_id_pubkey_test.go @@ -4,11 +4,12 @@ import ( "context" "testing" + types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/testutil/require" ) type publicKeyTestStruct struct { - validatorID uint64 + validatorID types.ValidatorIndex pk []byte } @@ -36,7 +37,7 @@ func TestNilDBValidatorPublicKey(t *testing.T) { db := setupDB(t) ctx := context.Background() - validatorID := uint64(1) + validatorID := types.ValidatorIndex(1) pk, err := db.ValidatorPubKey(ctx, validatorID) require.NoError(t, err, "Nil ValidatorPubKey should not return error") diff --git a/slasher/db/restore_test.go b/slasher/db/restore_test.go index 426a2b22db..09419b6f36 100644 --- a/slasher/db/restore_test.go +++ b/slasher/db/restore_test.go @@ -8,6 +8,7 @@ import ( "path" "testing" + types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/cmd" "github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/require" @@ -26,7 +27,7 @@ func TestRestore(t *testing.T) { }() require.NoError(t, err) pubKey := []byte("hello") - require.NoError(t, backupDb.SavePubKey(ctx, uint64(1), pubKey)) + require.NoError(t, backupDb.SavePubKey(ctx, types.ValidatorIndex(1), pubKey)) require.NoError(t, backupDb.Close()) // We rename the backup file so that we can later verify // whether the restored db has been renamed correctly. @@ -54,7 +55,7 @@ func TestRestore(t *testing.T) { require.NoError(t, restoredDb.Close()) }() require.NoError(t, err) - received, err := restoredDb.ValidatorPubKey(ctx, uint64(1)) + received, err := restoredDb.ValidatorPubKey(ctx, types.ValidatorIndex(1)) require.NoError(t, err) require.DeepEqual(t, pubKey, received, "Restored database has incorrect data") assert.LogsContain(t, logHook, "Restore completed successfully") diff --git a/slasher/detection/testing/utils.go b/slasher/detection/testing/utils.go index e1a5afefde..cb5bccf831 100644 --- a/slasher/detection/testing/utils.go +++ b/slasher/detection/testing/utils.go @@ -10,7 +10,7 @@ import ( // SignedBlockHeader given slot, proposer index this function generates signed block header. // with random bytes as its signature. -func SignedBlockHeader(slot types.Slot, proposerIdx uint64) (*ethpb.SignedBeaconBlockHeader, error) { +func SignedBlockHeader(slot types.Slot, proposerIdx types.ValidatorIndex) (*ethpb.SignedBeaconBlockHeader, error) { sig, err := genRandomByteArray(96) if err != nil { return nil, err @@ -29,7 +29,7 @@ func SignedBlockHeader(slot types.Slot, proposerIdx uint64) (*ethpb.SignedBeacon } // BlockHeader given slot, proposer index this function generates block header. -func BlockHeader(slot types.Slot, proposerIdx uint64) (*ethpb.BeaconBlockHeader, error) { +func BlockHeader(slot types.Slot, proposerIdx types.ValidatorIndex) (*ethpb.BeaconBlockHeader, error) { root := [32]byte{1, 2, 3} return ðpb.BeaconBlockHeader{ ProposerIndex: proposerIdx, diff --git a/slasher/rpc/BUILD.bazel b/slasher/rpc/BUILD.bazel index 858c3309d7..422c73f44d 100644 --- a/slasher/rpc/BUILD.bazel +++ b/slasher/rpc/BUILD.bazel @@ -26,6 +26,7 @@ go_library( "@com_github_grpc_ecosystem_go_grpc_middleware//tracing/opentracing:go_default_library", "@com_github_grpc_ecosystem_go_grpc_prometheus//: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_sirupsen_logrus//:go_default_library", "@io_opencensus_go//plugin/ocgrpc:go_default_library", diff --git a/slasher/rpc/server.go b/slasher/rpc/server.go index 36e09768a2..4c11768868 100644 --- a/slasher/rpc/server.go +++ b/slasher/rpc/server.go @@ -5,6 +5,7 @@ import ( "sync" "github.com/pkg/errors" + types "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" slashpb "github.com/prysmaticlabs/prysm/proto/slashing" @@ -103,7 +104,10 @@ func (s *Server) IsSlashableAttestation(ctx context.Context, req *ethpb.IndexedA if err != nil { return nil, err } - indices := req.AttestingIndices + indices := make([]types.ValidatorIndex, len(req.AttestingIndices)) + for i, index := range req.AttestingIndices { + indices[i] = types.ValidatorIndex(index) + } pkMap, err := s.beaconClient.FindOrGetPublicKeys(ctx, indices) if err != nil { return nil, err @@ -178,7 +182,7 @@ func (s *Server) IsSlashableBlock(ctx context.Context, req *ethpb.SignedBeaconBl if err != nil { return nil, err } - pkMap, err := s.beaconClient.FindOrGetPublicKeys(ctx, []uint64{req.Header.ProposerIndex}) + pkMap, err := s.beaconClient.FindOrGetPublicKeys(ctx, []types.ValidatorIndex{req.Header.ProposerIndex}) if err != nil { return nil, err } diff --git a/validator/client/attest.go b/validator/client/attest.go index 3f8f96a313..98197be01e 100644 --- a/validator/client/attest.go +++ b/validator/client/attest.go @@ -83,7 +83,7 @@ func (v *validator) SubmitAttestation(ctx context.Context, slot types.Slot, pubK } indexedAtt := ðpb.IndexedAttestation{ - AttestingIndices: []uint64{duty.ValidatorIndex}, + AttestingIndices: []uint64{uint64(duty.ValidatorIndex)}, Data: data, } @@ -226,7 +226,7 @@ func (v *validator) getDomainAndSigningRoot(ctx context.Context, data *ethpb.Att // For logging, this saves the last submitted attester index to its attestation data. The purpose of this // is to enhance attesting logs to be readable when multiple validator keys ran in a single client. -func (v *validator) saveAttesterIndexToData(data *ethpb.AttestationData, index uint64) error { +func (v *validator) saveAttesterIndexToData(data *ethpb.AttestationData, index types.ValidatorIndex) error { v.attLogsLock.Lock() defer v.attLogsLock.Unlock() @@ -236,9 +236,9 @@ func (v *validator) saveAttesterIndexToData(data *ethpb.AttestationData, index u } if v.attLogs[h] == nil { - v.attLogs[h] = &attSubmitted{data, []uint64{}, []uint64{}} + v.attLogs[h] = &attSubmitted{data, []types.ValidatorIndex{}, []types.ValidatorIndex{}} } - v.attLogs[h] = &attSubmitted{data, append(v.attLogs[h].attesterIndices, index), []uint64{}} + v.attLogs[h] = &attSubmitted{data, append(v.attLogs[h].attesterIndices, index), []types.ValidatorIndex{}} return nil } diff --git a/validator/client/attest_test.go b/validator/client/attest_test.go index e87cbeb019..82b9bd28f6 100644 --- a/validator/client/attest_test.go +++ b/validator/client/attest_test.go @@ -52,7 +52,7 @@ func TestAttestToBlockHead_SubmitAttestation_EmptyCommittee(t *testing.T) { { PublicKey: validatorKey.PublicKey().Marshal(), CommitteeIndex: 0, - Committee: make([]uint64, 0), + Committee: make([]types.ValidatorIndex, 0), ValidatorIndex: 0, }}} validator.SubmitAttestation(context.Background(), 0, pubKey) @@ -68,7 +68,7 @@ func TestAttestToBlockHead_SubmitAttestation_RequestFailure(t *testing.T) { { PublicKey: validatorKey.PublicKey().Marshal(), CommitteeIndex: 5, - Committee: make([]uint64, 111), + Committee: make([]types.ValidatorIndex, 111), ValidatorIndex: 0, }}} m.validatorClient.EXPECT().GetAttestationData( @@ -98,8 +98,8 @@ func TestAttestToBlockHead_AttestsCorrectly(t *testing.T) { validator, m, validatorKey, finish := setup(t) defer finish() hook := logTest.NewGlobal() - validatorIndex := uint64(7) - committee := []uint64{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := types.ValidatorIndex(7) + committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} pubKey := [48]byte{} copy(pubKey[:], validatorKey.PublicKey().Marshal()) validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ @@ -171,8 +171,8 @@ func TestAttestToBlockHead_BlocksDoubleAtt(t *testing.T) { hook := logTest.NewGlobal() validator, m, validatorKey, finish := setup(t) defer finish() - validatorIndex := uint64(7) - committee := []uint64{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := types.ValidatorIndex(7) + committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} pubKey := [48]byte{} copy(pubKey[:], validatorKey.PublicKey().Marshal()) validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ @@ -223,8 +223,8 @@ func TestAttestToBlockHead_BlocksSurroundAtt(t *testing.T) { hook := logTest.NewGlobal() validator, m, validatorKey, finish := setup(t) defer finish() - validatorIndex := uint64(7) - committee := []uint64{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := types.ValidatorIndex(7) + committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} pubKey := [48]byte{} copy(pubKey[:], validatorKey.PublicKey().Marshal()) validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ @@ -275,10 +275,10 @@ func TestAttestToBlockHead_BlocksSurroundedAtt(t *testing.T) { hook := logTest.NewGlobal() validator, m, validatorKey, finish := setup(t) defer finish() - validatorIndex := uint64(7) + validatorIndex := types.ValidatorIndex(7) pubKey := [48]byte{} copy(pubKey[:], validatorKey.PublicKey().Marshal()) - committee := []uint64{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ { PublicKey: validatorKey.PublicKey().Marshal(), @@ -363,8 +363,8 @@ func TestAttestToBlockHead_DoesAttestAfterDelay(t *testing.T) { defer wg.Wait() validator.genesisTime = uint64(timeutils.Now().Unix()) - validatorIndex := uint64(5) - committee := []uint64{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := types.ValidatorIndex(5) + committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} pubKey := [48]byte{} copy(pubKey[:], validatorKey.PublicKey().Marshal()) validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ @@ -402,8 +402,8 @@ func TestAttestToBlockHead_DoesAttestAfterDelay(t *testing.T) { func TestAttestToBlockHead_CorrectBitfieldLength(t *testing.T) { validator, m, validatorKey, finish := setup(t) defer finish() - validatorIndex := uint64(2) - committee := []uint64{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := types.ValidatorIndex(2) + committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} pubKey := [48]byte{} copy(pubKey[:], validatorKey.PublicKey().Marshal()) validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ diff --git a/validator/client/log.go b/validator/client/log.go index 7fb425d307..7a34dfc6da 100644 --- a/validator/client/log.go +++ b/validator/client/log.go @@ -17,8 +17,8 @@ var log = logrus.WithField("prefix", "validator") type attSubmitted struct { data *ethpb.AttestationData - attesterIndices []uint64 - aggregatorIndices []uint64 + attesterIndices []types.ValidatorIndex + aggregatorIndices []types.ValidatorIndex } func (v *validator) LogAttestationsSubmitted() { diff --git a/validator/client/propose_test.go b/validator/client/propose_test.go index 021ad99a57..958229e0d1 100644 --- a/validator/client/propose_test.go +++ b/validator/client/propose_test.go @@ -8,9 +8,10 @@ import ( "testing" "time" - "github.com/gogo/protobuf/types" + ptypes "github.com/gogo/protobuf/types" "github.com/golang/mock/gomock" lru "github.com/hashicorp/golang-lru" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" validatorpb "github.com/prysmaticlabs/prysm/proto/validator/accounts/v2" "github.com/prysmaticlabs/prysm/shared/bls" @@ -501,7 +502,7 @@ func TestProposeExit_DomainDataFailed(t *testing.T) { Return(ðpb.ValidatorIndexResponse{Index: 1}, nil) // Any time in the past will suffice - genesisTime := &types.Timestamp{ + genesisTime := &ptypes.Timestamp{ Seconds: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC).Unix(), } @@ -535,7 +536,7 @@ func TestProposeExit_DomainDataIsNil(t *testing.T) { Return(ðpb.ValidatorIndexResponse{Index: 1}, nil) // Any time in the past will suffice - genesisTime := &types.Timestamp{ + genesisTime := &ptypes.Timestamp{ Seconds: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC).Unix(), } @@ -568,7 +569,7 @@ func TestProposeBlock_ProposeExitFailed(t *testing.T) { Return(ðpb.ValidatorIndexResponse{Index: 1}, nil) // Any time in the past will suffice - genesisTime := &types.Timestamp{ + genesisTime := &ptypes.Timestamp{ Seconds: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC).Unix(), } @@ -605,7 +606,7 @@ func TestProposeExit_BroadcastsBlock(t *testing.T) { Return(ðpb.ValidatorIndexResponse{Index: 1}, nil) // Any time in the past will suffice - genesisTime := &types.Timestamp{ + genesisTime := &ptypes.Timestamp{ Seconds: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC).Unix(), } @@ -680,7 +681,7 @@ func TestGetGraffiti_Ok(t *testing.T) { graffitiStruct: &graffiti.Graffiti{ Default: "c", Random: []string{"d", "e"}, - Specific: map[uint64]string{ + Specific: map[types.ValidatorIndex]string{ 1: "f", 2: "g", }, @@ -713,7 +714,7 @@ func TestGetGraffiti_Ok(t *testing.T) { graffitiStruct: &graffiti.Graffiti{ Random: []string{"d"}, Default: "c", - Specific: map[uint64]string{ + Specific: map[types.ValidatorIndex]string{ 1: "f", 2: "g", }, diff --git a/validator/client/validator.go b/validator/client/validator.go index 92306462c4..0443e739cc 100644 --- a/validator/client/validator.go +++ b/validator/client/validator.go @@ -280,7 +280,7 @@ func (v *validator) ReceiveBlocks(ctx context.Context, connectionErrorChannel ch } func (v *validator) checkAndLogValidatorStatus(validatorStatuses []*ethpb.ValidatorActivationResponse_Status) bool { - nonexistentIndex := ^uint64(0) + nonexistentIndex := types.ValidatorIndex(^uint64(0)) var validatorActivated bool for _, status := range validatorStatuses { fields := logrus.Fields{ @@ -420,7 +420,7 @@ func (v *validator) UpdateDuties(ctx context.Context, slot types.Slot) error { // to eagerly subscribe to subnets so that the aggregator has attestations to aggregate. func (v *validator) subscribeToSubnets(ctx context.Context, res *ethpb.DutiesResponse) error { subscribeSlots := make([]types.Slot, 0, len(res.CurrentEpochDuties)+len(res.NextEpochDuties)) - subscribeCommitteeIDs := make([]uint64, 0, len(res.CurrentEpochDuties)+len(res.NextEpochDuties)) + subscribeCommitteeIndices := make([]types.CommitteeIndex, 0, len(res.CurrentEpochDuties)+len(res.NextEpochDuties)) subscribeIsAggregator := make([]bool, 0, len(res.CurrentEpochDuties)+len(res.NextEpochDuties)) alreadySubscribed := make(map[[64]byte]bool) @@ -444,7 +444,7 @@ func (v *validator) subscribeToSubnets(ctx context.Context, res *ethpb.DutiesRes } subscribeSlots = append(subscribeSlots, attesterSlot) - subscribeCommitteeIDs = append(subscribeCommitteeIDs, uint64(committeeIndex)) + subscribeCommitteeIndices = append(subscribeCommitteeIndices, committeeIndex) subscribeIsAggregator = append(subscribeIsAggregator, aggregator) } } @@ -468,14 +468,14 @@ func (v *validator) subscribeToSubnets(ctx context.Context, res *ethpb.DutiesRes } subscribeSlots = append(subscribeSlots, attesterSlot) - subscribeCommitteeIDs = append(subscribeCommitteeIDs, uint64(committeeIndex)) + subscribeCommitteeIndices = append(subscribeCommitteeIndices, committeeIndex) subscribeIsAggregator = append(subscribeIsAggregator, aggregator) } } _, err := v.validatorClient.SubscribeCommitteeSubnets(ctx, ðpb.CommitteeSubnetsSubscribeRequest{ Slots: subscribeSlots, - CommitteeIds: subscribeCommitteeIDs, + CommitteeIds: subscribeCommitteeIndices, IsAggregator: subscribeIsAggregator, }) @@ -531,7 +531,7 @@ func (v *validator) GetKeymanager() keymanager.IKeymanager { // isAggregator checks if a validator is an aggregator of a given slot, it uses the selection algorithm outlined in: // https://github.com/ethereum/eth2.0-specs/blob/v0.9.3/specs/validator/0_beacon-chain-validator.md#aggregation-selection -func (v *validator) isAggregator(ctx context.Context, committee []uint64, slot types.Slot, pubKey [48]byte) (bool, error) { +func (v *validator) isAggregator(ctx context.Context, committee []types.ValidatorIndex, slot types.Slot, pubKey [48]byte) (bool, error) { modulo := uint64(1) if len(committee)/int(params.BeaconConfig().TargetAggregatorsPerCommittee) > 1 { modulo = uint64(len(committee)) / params.BeaconConfig().TargetAggregatorsPerCommittee diff --git a/validator/client/validator_test.go b/validator/client/validator_test.go index 794e998156..31c7b5509c 100644 --- a/validator/client/validator_test.go +++ b/validator/client/validator_test.go @@ -473,7 +473,7 @@ func TestUpdateDuties_DoesNothingWhenNotEpochStart_AlreadyExistingAssignments(t duties: ðpb.DutiesResponse{ Duties: []*ethpb.DutiesResponse_Duty{ { - Committee: []uint64{}, + Committee: []types.ValidatorIndex{}, AttesterSlot: 10, CommitteeIndex: 20, }, @@ -546,7 +546,7 @@ func TestUpdateDuties_OK(t *testing.T) { AttesterSlot: params.BeaconConfig().SlotsPerEpoch, ValidatorIndex: 200, CommitteeIndex: 100, - Committee: []uint64{0, 1, 2, 3}, + Committee: []types.ValidatorIndex{0, 1, 2, 3}, PublicKey: []byte("testPubKey_1"), ProposerSlots: []types.Slot{params.BeaconConfig().SlotsPerEpoch + 1}, }, @@ -688,7 +688,7 @@ func TestRolesAt_DoesNotAssignProposer_Slot0(t *testing.T) { } func TestCheckAndLogValidatorStatus_OK(t *testing.T) { - nonexistentIndex := ^uint64(0) + nonexistentIndex := types.ValidatorIndex(^uint64(0)) type statusTest struct { name string status *ethpb.ValidatorActivationResponse_Status diff --git a/validator/graffiti/BUILD.bazel b/validator/graffiti/BUILD.bazel index 6e54291785..4fb1d97ac2 100644 --- a/validator/graffiti/BUILD.bazel +++ b/validator/graffiti/BUILD.bazel @@ -6,12 +6,18 @@ go_library( srcs = ["parse_graffiti.go"], importpath = "github.com/prysmaticlabs/prysm/validator/graffiti", visibility = ["//validator:__subpackages__"], - deps = ["@in_gopkg_yaml_v2//:go_default_library"], + deps = [ + "@com_github_prysmaticlabs_eth2_types//:go_default_library", + "@in_gopkg_yaml_v2//:go_default_library", + ], ) go_test( name = "go_default_test", srcs = ["parse_graffiti_test.go"], embed = [":go_default_library"], - deps = ["//shared/testutil/require:go_default_library"], + deps = [ + "//shared/testutil/require:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", + ], ) diff --git a/validator/graffiti/parse_graffiti.go b/validator/graffiti/parse_graffiti.go index db3b89644d..b25de39d59 100644 --- a/validator/graffiti/parse_graffiti.go +++ b/validator/graffiti/parse_graffiti.go @@ -3,13 +3,14 @@ package graffiti import ( "io/ioutil" + types "github.com/prysmaticlabs/eth2-types" "gopkg.in/yaml.v2" ) type Graffiti struct { - Default string `yaml:"default,omitempty"` - Random []string `yaml:"random,omitempty"` - Specific map[uint64]string `yaml:"specific,omitempty"` + Default string `yaml:"default,omitempty"` + Random []string `yaml:"random,omitempty"` + Specific map[types.ValidatorIndex]string `yaml:"specific,omitempty"` } // ParseGraffitiFile parses the graffiti file and returns the graffiti struct. diff --git a/validator/graffiti/parse_graffiti_test.go b/validator/graffiti/parse_graffiti_test.go index f6bec538c1..e7d5bb4470 100644 --- a/validator/graffiti/parse_graffiti_test.go +++ b/validator/graffiti/parse_graffiti_test.go @@ -6,6 +6,7 @@ import ( "path/filepath" "testing" + types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/testutil/require" ) @@ -69,7 +70,7 @@ specific: require.NoError(t, err) wanted := &Graffiti{ - Specific: map[uint64]string{ + Specific: map[types.ValidatorIndex]string{ 1234: "Yolo", 555: "What's up", 703727: "Meow", @@ -107,7 +108,7 @@ specific: "Mr B was here", "Mr C was here", }, - Specific: map[uint64]string{ + Specific: map[types.ValidatorIndex]string{ 1234: "Yolo", 555: "What's up", 703727: "Meow",