ETH2 Types: Epoch (#8373)

* update deps

* update deps

* update protos/*

* update deps

* reset protos

* update protos

* update shared/params/config

* update protos

* update /shared

* update shared/slotutil and shared/testutil

* update beacon-chain/core/helpers

* updates beacon-chain/state

* update beacon-chain/forkchoice

* update beacon-chain/blockchain

* update beacon-chain/cache

* update beacon-chain/core

* update beacon-chain/db

* update beacon-chain/node

* update beacon-chain/p2p

* update beacon-chain/rpc

* update beacon-chain/sync

* go mod tidy

* make sure that beacon-chain build suceeds

* go fmt

* update e2e tests

* update slasher

* remove redundant alias

* update validator

* gazelle

* fix build errors in unit tests

* go fmt

* update deps

* update fuzz/BUILD.bazel

* fix unit tests

* more unit test fixes

* fix blockchain UTs

* more unit test fixes
This commit is contained in:
Victor Farazdagi
2021-02-09 13:05:22 +03:00
committed by GitHub
parent 5727d4eb8a
commit a8e501b3cf
231 changed files with 1595 additions and 1308 deletions

View File

@@ -59,6 +59,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",
"@io_opencensus_go//trace:go_default_library",

View File

@@ -4,15 +4,15 @@ import (
"context"
"time"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"go.opencensus.io/trace"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray"
"github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params"
"go.opencensus.io/trace"
)
// ChainInfoFetcher defines a common interface for methods in blockchain service which
@@ -42,8 +42,8 @@ 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 uint64) ([]uint64, error)
HeadSeed(ctx context.Context, epoch uint64) ([32]byte, error)
HeadValidatorsIndices(ctx context.Context, epoch types.Epoch) ([]uint64, error)
HeadSeed(ctx context.Context, epoch types.Epoch) ([32]byte, error)
HeadGenesisValidatorRoot() [32]byte
HeadETH1Data() *ethpb.Eth1Data
ProtoArrayStore() *protoarray.Store
@@ -167,7 +167,7 @@ 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 uint64) ([]uint64, error) {
func (s *Service) HeadValidatorsIndices(ctx context.Context, epoch types.Epoch) ([]uint64, error) {
s.headLock.RLock()
defer s.headLock.RUnlock()
@@ -178,7 +178,7 @@ func (s *Service) HeadValidatorsIndices(ctx context.Context, epoch uint64) ([]ui
}
// HeadSeed returns the seed from the head view of a given epoch.
func (s *Service) HeadSeed(ctx context.Context, epoch uint64) ([32]byte, error) {
func (s *Service) HeadSeed(ctx context.Context, epoch types.Epoch) ([32]byte, error) {
s.headLock.RLock()
defer s.headLock.RUnlock()

View File

@@ -5,6 +5,7 @@ import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
@@ -120,7 +121,7 @@ func reportSlotMetrics(stateSlot, headSlot, clockSlot uint64, finalizedCheckpoin
// reportEpochMetrics reports epoch related metrics.
func reportEpochMetrics(ctx context.Context, postState, headState *stateTrie.BeaconState) error {
currentEpoch := postState.Slot() / params.BeaconConfig().SlotsPerEpoch
currentEpoch := types.Epoch(postState.Slot() / params.BeaconConfig().SlotsPerEpoch)
// Validator instances
pendingInstances := 0

View File

@@ -6,6 +6,7 @@ import (
"strconv"
"github.com/pkg/errors"
"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/state"
@@ -20,7 +21,7 @@ import (
func (s *Service) getAttPreState(ctx context.Context, c *ethpb.Checkpoint) (*stateTrie.BeaconState, error) {
// Use a multilock to allow scoped holding of a mutex by a checkpoint root + epoch
// allowing us to behave smarter in terms of how this function is used concurrently.
epochKey := strconv.FormatUint(c.Epoch, 10 /* base 10 */)
epochKey := strconv.FormatUint(uint64(c.Epoch), 10 /* base 10 */)
lock := mputil.NewMultilock(string(c.Root) + epochKey)
lock.Lock()
defer lock.Unlock()
@@ -78,7 +79,7 @@ func (s *Service) getAttPreState(ctx context.Context, c *ethpb.Checkpoint) (*sta
func (s *Service) verifyAttTargetEpoch(_ context.Context, genesisTime, nowTime uint64, c *ethpb.Checkpoint) error {
currentSlot := (nowTime - genesisTime) / params.BeaconConfig().SecondsPerSlot
currentEpoch := helpers.SlotToEpoch(currentSlot)
var prevEpoch uint64
var prevEpoch types.Epoch
// Prevents previous epoch under flow
if currentEpoch > 1 {
prevEpoch = currentEpoch - 1

View File

@@ -5,6 +5,7 @@ import (
"testing"
"github.com/gogo/protobuf/proto"
"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/state"
@@ -234,19 +235,19 @@ func TestStore_UpdateCheckpointState(t *testing.T) {
service, err := New(ctx, cfg)
require.NoError(t, err)
epoch := uint64(1)
epoch := types.Epoch(1)
baseState, _ := testutil.DeterministicGenesisState(t, 1)
checkpoint := &ethpb.Checkpoint{Epoch: epoch, Root: bytesutil.PadTo([]byte("hi"), 32)}
require.NoError(t, service.beaconDB.SaveState(ctx, baseState, bytesutil.ToBytes32(checkpoint.Root)))
returned, err := service.getAttPreState(ctx, checkpoint)
require.NoError(t, err)
assert.Equal(t, returned.Slot(), checkpoint.Epoch*params.BeaconConfig().SlotsPerEpoch, "Incorrectly returned base state")
assert.Equal(t, uint64(checkpoint.Epoch.Mul(params.BeaconConfig().SlotsPerEpoch)), returned.Slot(), "Incorrectly returned base state")
cached, err := service.checkpointStateCache.StateByCheckpoint(checkpoint)
require.NoError(t, err)
assert.Equal(t, returned.Slot(), cached.Slot(), "State should have been cached")
epoch = uint64(2)
epoch = 2
newCheckpoint := &ethpb.Checkpoint{Epoch: epoch, Root: bytesutil.PadTo([]byte("bye"), 32)}
require.NoError(t, service.beaconDB.SaveState(ctx, baseState, bytesutil.ToBytes32(newCheckpoint.Root)))
returned, err = service.getAttPreState(ctx, newCheckpoint)

View File

@@ -7,6 +7,7 @@ import (
"time"
"github.com/pkg/errors"
"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"
@@ -77,7 +78,7 @@ func TestStore_OnBlock(t *testing.T) {
blk: func() *ethpb.SignedBeaconBlock {
b := testutil.NewBeaconBlock()
b.Block.ParentRoot = randomParentRoot2
b.Block.Slot = params.BeaconConfig().FarFutureEpoch
b.Block.Slot = uint64(params.BeaconConfig().FarFutureEpoch)
return b
}(),
s: st.Copy(),
@@ -336,7 +337,7 @@ func TestUpdateJustified_CouldUpdateBest(t *testing.T) {
service.bestJustifiedCheckpt.Epoch = 2
require.NoError(t, service.updateJustified(context.Background(), s))
assert.Equal(t, uint64(2), service.bestJustifiedCheckpt.Epoch, "Incorrect justified epoch in service")
assert.Equal(t, types.Epoch(2), service.bestJustifiedCheckpt.Epoch, "Incorrect justified epoch in service")
}
func TestFillForkChoiceMissingBlocks_CanSave(t *testing.T) {
@@ -944,6 +945,6 @@ func TestOnBlock_CanFinalize(t *testing.T) {
testState, err = service.stateGen.StateByRoot(ctx, r)
require.NoError(t, err)
}
require.Equal(t, uint64(3), service.CurrentJustifiedCheckpt().Epoch)
require.Equal(t, uint64(2), service.FinalizedCheckpt().Epoch)
require.Equal(t, types.Epoch(3), service.CurrentJustifiedCheckpt().Epoch)
require.Equal(t, types.Epoch(2), service.FinalizedCheckpt().Epoch)
}

View File

@@ -5,6 +5,7 @@ import (
"testing"
"time"
"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/state"
@@ -27,7 +28,7 @@ func TestAttestationCheckPtState_FarFutureSlot(t *testing.T) {
chainService := setupBeaconChain(t, beaconDB)
chainService.genesisTime = time.Now()
e := helpers.MaxSlotBuffer/params.BeaconConfig().SlotsPerEpoch + 1
e := types.Epoch(helpers.MaxSlotBuffer/params.BeaconConfig().SlotsPerEpoch + 1)
_, err := chainService.AttestationPreState(context.Background(), &ethpb.Attestation{Data: &ethpb.AttestationData{Target: &ethpb.Checkpoint{Epoch: e}}})
require.ErrorContains(t, "exceeds max allowed value relative to the local clock", err)
}

View File

@@ -4,6 +4,7 @@ import (
"context"
"github.com/pkg/errors"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state"
@@ -15,7 +16,7 @@ import (
)
// This defines how many epochs since finality the run time will begin to save hot state on to the DB.
var epochsSinceFinalitySaveHotStateDB = 100
var epochsSinceFinalitySaveHotStateDB = types.Epoch(100)
// BlockReceiver interface defines the methods of chain service receive and processing new blocks.
type BlockReceiver interface {
@@ -197,12 +198,12 @@ func (s *Service) handlePostBlockOperations(b *ethpb.BeaconBlock) error {
func (s *Service) checkSaveHotStateDB(ctx context.Context) error {
currentEpoch := helpers.SlotToEpoch(s.CurrentSlot())
// Prevent `sinceFinality` going underflow.
var sinceFinality uint64
var sinceFinality types.Epoch
if currentEpoch > s.finalizedCheckpt.Epoch {
sinceFinality = currentEpoch - s.finalizedCheckpt.Epoch
}
if sinceFinality >= uint64(epochsSinceFinalitySaveHotStateDB) {
if sinceFinality >= epochsSinceFinalitySaveHotStateDB {
s.stateGen.EnableSaveHotStateToDB(ctx)
return nil
}

View File

@@ -11,6 +11,7 @@ import (
"time"
"github.com/pkg/errors"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
"github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache"
@@ -75,7 +76,7 @@ type Service struct {
initSyncBlocksLock sync.RWMutex
justifiedBalances []uint64
justifiedBalancesLock sync.RWMutex
wsEpoch uint64
wsEpoch types.Epoch
wsRoot []byte
wsVerified bool
}
@@ -96,7 +97,7 @@ type Config struct {
OpsService *attestations.Service
StateGen *stategen.State
WspBlockRoot []byte
WspEpoch uint64
WspEpoch types.Epoch
}
// New instantiates a new block service instance that will
@@ -458,7 +459,7 @@ func (s *Service) initializeChainInfo(ctx context.Context) error {
return errors.Wrap(err, "could not retrieve head block")
}
headEpoch := helpers.SlotToEpoch(headBlock.Block.Slot)
var epochsSinceFinality uint64
var epochsSinceFinality types.Epoch
if headEpoch > finalized.Epoch {
epochsSinceFinality = headEpoch - finalized.Epoch
}

View File

@@ -23,6 +23,7 @@ go_library(
"//shared/event: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_sirupsen_logrus//:go_default_library",
],

View File

@@ -9,6 +9,7 @@ import (
"time"
"github.com/pkg/errors"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
@@ -290,7 +291,7 @@ func (s *ChainService) AttestationPreState(_ context.Context, _ *ethpb.Attestati
}
// HeadValidatorsIndices mocks the same method in the chain service.
func (s *ChainService) HeadValidatorsIndices(_ context.Context, epoch uint64) ([]uint64, error) {
func (s *ChainService) HeadValidatorsIndices(_ context.Context, epoch types.Epoch) ([]uint64, error) {
if s.State == nil {
return []uint64{}, nil
}
@@ -298,7 +299,7 @@ func (s *ChainService) HeadValidatorsIndices(_ context.Context, epoch uint64) ([
}
// HeadSeed mocks the same method in the chain service.
func (s *ChainService) HeadSeed(_ context.Context, epoch uint64) ([32]byte, error) {
func (s *ChainService) HeadSeed(_ context.Context, epoch types.Epoch) ([32]byte, error) {
return helpers.Seed(s.State, epoch, params.BeaconConfig().DomainBeaconAttester)
}

View File

@@ -4,6 +4,7 @@ import (
"context"
"testing"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
"github.com/prysmaticlabs/prysm/shared/testutil"
@@ -22,8 +23,8 @@ func TestService_VerifyWeakSubjectivityRoot(t *testing.T) {
wsVerified bool
wantErr bool
wsRoot [32]byte
wsEpoch uint64
finalizedEpoch uint64
wsEpoch types.Epoch
finalizedEpoch types.Epoch
errString string
name string
}{

View File

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

View File

@@ -4,6 +4,7 @@ import (
"testing"
"github.com/gogo/protobuf/proto"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
@@ -61,7 +62,7 @@ func TestCheckpointStateCache_MaxSize(t *testing.T) {
for i := uint64(0); i < uint64(maxCheckpointStateSize+100); i++ {
require.NoError(t, st.SetSlot(i))
require.NoError(t, c.AddCheckpointState(&ethpb.Checkpoint{Epoch: i, Root: make([]byte, 32)}, st))
require.NoError(t, c.AddCheckpointState(&ethpb.Checkpoint{Epoch: types.Epoch(i), Root: make([]byte, 32)}, st))
}
assert.Equal(t, maxCheckpointStateSize, len(c.cache.Keys()))

View File

@@ -40,6 +40,7 @@ go_library(
"//shared/trieutil:go_default_library",
"@com_github_gogo_protobuf//proto: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//trace:go_default_library",
@@ -84,6 +85,7 @@ go_test(
"//shared/trieutil:go_default_library",
"@com_github_gogo_protobuf//proto:go_default_library",
"@com_github_google_gofuzz//: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",
"@com_github_sirupsen_logrus//:go_default_library",

View File

@@ -6,6 +6,7 @@ import (
"fmt"
"github.com/pkg/errors"
"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"
@@ -113,7 +114,7 @@ func ProcessAttestationNoVerifySignature(
return nil, err
}
currEpoch := helpers.SlotToEpoch(beaconState.Slot())
var prevEpoch uint64
var prevEpoch types.Epoch
if currEpoch == 0 {
prevEpoch = 0
} else {
@@ -175,9 +176,9 @@ func ProcessAttestationNoVerifySignature(
ProposerIndex: proposerIndex,
}
var ffgSourceEpoch uint64
var ffgSourceEpoch types.Epoch
var ffgSourceRoot []byte
var ffgTargetEpoch uint64
var ffgTargetEpoch types.Epoch
if data.Target.Epoch == currEpoch {
ffgSourceEpoch = beaconState.CurrentJustifiedCheckpoint().Epoch
ffgSourceRoot = beaconState.CurrentJustifiedCheckpoint().Root

View File

@@ -5,6 +5,7 @@ import (
"fmt"
"testing"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
@@ -596,7 +597,7 @@ func TestValidateIndexedAttestation_AboveMaxLength(t *testing.T) {
indexedAtt1.AttestingIndices[i] = i
indexedAtt1.Data = &ethpb.AttestationData{
Target: &ethpb.Checkpoint{
Epoch: i,
Epoch: types.Epoch(i),
},
}
}

View File

@@ -4,6 +4,7 @@ import (
"context"
"testing"
"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"
@@ -98,7 +99,7 @@ func TestProcessAttesterSlashings_IndexedAttestationFailedToVerify(t *testing.T)
func TestProcessAttesterSlashings_AppliesCorrectStatus(t *testing.T) {
beaconState, privKeys := testutil.DeterministicGenesisState(t, 100)
for _, vv := range beaconState.Validators() {
vv.WithdrawableEpoch = 1 * params.BeaconConfig().SlotsPerEpoch
vv.WithdrawableEpoch = types.Epoch(1 * params.BeaconConfig().SlotsPerEpoch)
}
att1 := testutil.HydrateIndexedAttestation(&ethpb.IndexedAttestation{

View File

@@ -4,6 +4,7 @@ import (
"context"
"testing"
"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"
@@ -18,7 +19,7 @@ func TestProcessAttesterSlashings_RegressionSlashableIndices(t *testing.T) {
testutil.ResetCache()
beaconState, privKeys := testutil.DeterministicGenesisState(t, 5500)
for _, vv := range beaconState.Validators() {
vv.WithdrawableEpoch = 1 * params.BeaconConfig().SlotsPerEpoch
vv.WithdrawableEpoch = types.Epoch(1 * params.BeaconConfig().SlotsPerEpoch)
}
// This set of indices is very similar to the one from our sapphire testnet
// when close to 100 validators were incorrectly slashed. The set is from 0 -5500,

View File

@@ -4,6 +4,7 @@ import (
"context"
"testing"
"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"
@@ -319,8 +320,8 @@ func TestPreGenesisDeposits_SkipInvalidDeposit(t *testing.T) {
val, err := newState.ValidatorAtIndex(uint64(i))
require.NoError(t, err)
require.Equal(t, params.BeaconConfig().MaxEffectiveBalance, val.EffectiveBalance, "unequal effective balance")
require.Equal(t, uint64(0), val.ActivationEpoch)
require.Equal(t, uint64(0), val.ActivationEligibilityEpoch)
require.Equal(t, types.Epoch(0), val.ActivationEpoch)
require.Equal(t, types.Epoch(0), val.ActivationEligibilityEpoch)
}
if newState.Eth1DepositIndex() != 100 {
t.Errorf(

View File

@@ -71,6 +71,6 @@ func Eth1DataHasEnoughSupport(beaconState *stateTrie.BeaconState, data *ethpb.Et
// If 50+% majority converged on the same eth1data, then it has enough support to update the
// state.
support := params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch
return voteCount*2 > support, nil
support := params.BeaconConfig().EpochsPerEth1VotingPeriod.Mul(params.BeaconConfig().SlotsPerEpoch)
return voteCount*2 > uint64(support), nil
}

View File

@@ -6,6 +6,7 @@ import (
"testing"
"github.com/gogo/protobuf/proto"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state"
@@ -33,7 +34,7 @@ func TestEth1DataHasEnoughSupport(t *testing.T) {
stateVotes []*ethpb.Eth1Data
data *ethpb.Eth1Data
hasSupport bool
votingPeriodLength uint64
votingPeriodLength types.Epoch
}{
{
stateVotes: FakeDeposits(4 * params.BeaconConfig().SlotsPerEpoch),
@@ -174,7 +175,7 @@ func TestProcessEth1Data_SetsCorrectly(t *testing.T) {
},
}
period := params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch
period := uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod.Mul(params.BeaconConfig().SlotsPerEpoch))
for i := uint64(0); i < period; i++ {
beaconState, err = blocks.ProcessEth1DataInBlock(context.Background(), beaconState, b)
require.NoError(t, err)

View File

@@ -4,6 +4,7 @@ import (
"context"
"testing"
"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"
@@ -168,7 +169,7 @@ func TestProcessVoluntaryExits_AppliesCorrectStatus(t *testing.T) {
Slot: params.BeaconConfig().SlotsPerEpoch * 5,
})
require.NoError(t, err)
err = state.SetSlot(state.Slot() + (params.BeaconConfig().ShardCommitteePeriod * params.BeaconConfig().SlotsPerEpoch))
err = state.SetSlot(state.Slot() + uint64(params.BeaconConfig().ShardCommitteePeriod.Mul(params.BeaconConfig().SlotsPerEpoch)))
require.NoError(t, err)
priv, err := bls.RandKey()
@@ -192,17 +193,17 @@ func TestProcessVoluntaryExits_AppliesCorrectStatus(t *testing.T) {
newState, err := blocks.ProcessVoluntaryExits(context.Background(), state, b)
require.NoError(t, err, "Could not process exits")
newRegistry := newState.Validators()
if newRegistry[0].ExitEpoch != helpers.ActivationExitEpoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch) {
if newRegistry[0].ExitEpoch != helpers.ActivationExitEpoch(types.Epoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch)) {
t.Errorf("Expected validator exit epoch to be %d, got %d",
helpers.ActivationExitEpoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch), newRegistry[0].ExitEpoch)
helpers.ActivationExitEpoch(types.Epoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch)), newRegistry[0].ExitEpoch)
}
// Check conformance with NoVerify Exit Method.
newState, err = blocks.ProcessVoluntaryExitsNoVerifySignature(stateCopy, b.Block.Body)
require.NoError(t, err, "Could not process exits")
newRegistry = newState.Validators()
if newRegistry[0].ExitEpoch != helpers.ActivationExitEpoch(stateCopy.Slot()/params.BeaconConfig().SlotsPerEpoch) {
if newRegistry[0].ExitEpoch != helpers.ActivationExitEpoch(types.Epoch(stateCopy.Slot()/params.BeaconConfig().SlotsPerEpoch)) {
t.Errorf("Expected validator exit epoch to be %d, got %d",
helpers.ActivationExitEpoch(stateCopy.Slot()/params.BeaconConfig().SlotsPerEpoch), newRegistry[0].ExitEpoch)
helpers.ActivationExitEpoch(types.Epoch(stateCopy.Slot()/params.BeaconConfig().SlotsPerEpoch)), newRegistry[0].ExitEpoch)
}
}

View File

@@ -67,7 +67,7 @@ func ProcessRandaoNoVerify(
// If block randao passed verification, we XOR the state's latest randao mix with the block's
// randao and update the state's corresponding latest randao mix value.
latestMixesLength := params.BeaconConfig().EpochsPerHistoricalVector
latestMixSlice, err := beaconState.RandaoMixAtIndex(currentEpoch % latestMixesLength)
latestMixSlice, err := beaconState.RandaoMixAtIndex(uint64(currentEpoch % latestMixesLength))
if err != nil {
return nil, err
}
@@ -78,7 +78,7 @@ func ProcessRandaoNoVerify(
for i, x := range blockRandaoReveal {
latestMixSlice[i] ^= x
}
if err := beaconState.UpdateRandaoMixesAtIndex(currentEpoch%latestMixesLength, latestMixSlice); err != nil {
if err := beaconState.UpdateRandaoMixesAtIndex(uint64(currentEpoch%latestMixesLength), latestMixSlice); err != nil {
return nil, err
}
return beaconState, nil

View File

@@ -5,6 +5,7 @@ import (
"encoding/binary"
"testing"
"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"
@@ -20,9 +21,9 @@ func TestProcessRandao_IncorrectProposerFailsVerification(t *testing.T) {
// We fetch the proposer's index as that is whom the RANDAO will be verified against.
proposerIdx, err := helpers.BeaconProposerIndex(beaconState)
require.NoError(t, err)
epoch := uint64(0)
epoch := types.Epoch(0)
buf := make([]byte, 32)
binary.LittleEndian.PutUint64(buf, epoch)
binary.LittleEndian.PutUint64(buf, uint64(epoch))
domain, err := helpers.Domain(beaconState.Fork(), epoch, params.BeaconConfig().DomainRandao, beaconState.GenesisValidatorRoot())
require.NoError(t, err)
root, err := (&pb.SigningData{ObjectRoot: buf, Domain: domain}).HashTreeRoot()

View File

@@ -114,7 +114,7 @@ func randaoSigningData(beaconState *stateTrie.BeaconState) ([]byte, []byte, []by
currentEpoch := helpers.SlotToEpoch(beaconState.Slot())
buf := make([]byte, 32)
binary.LittleEndian.PutUint64(buf, currentEpoch)
binary.LittleEndian.PutUint64(buf, uint64(currentEpoch))
domain, err := helpers.Domain(beaconState.Fork(), currentEpoch, params.BeaconConfig().DomainRandao, beaconState.GenesisValidatorRoot())
if err != nil {

View File

@@ -37,6 +37,7 @@ go_test(
"//shared/testutil/require:go_default_library",
"@com_github_gogo_protobuf//proto:go_default_library",
"@com_github_google_gofuzz//: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",
],

View File

@@ -276,20 +276,20 @@ func ProcessFinalUpdates(state *stateTrie.BeaconState) (*stateTrie.BeaconState,
slashedExitLength := params.BeaconConfig().EpochsPerSlashingsVector
slashedEpoch := nextEpoch % slashedExitLength
slashings := state.Slashings()
if uint64(len(slashings)) != slashedExitLength {
if uint64(len(slashings)) != uint64(slashedExitLength) {
return nil, fmt.Errorf(
"state slashing length %d different than EpochsPerHistoricalVector %d",
len(slashings),
slashedExitLength,
)
}
if err := state.UpdateSlashingsAtIndex(slashedEpoch /* index */, 0 /* value */); err != nil {
if err := state.UpdateSlashingsAtIndex(uint64(slashedEpoch) /* index */, 0 /* value */); err != nil {
return nil, err
}
// Set RANDAO mix.
randaoMixLength := params.BeaconConfig().EpochsPerHistoricalVector
if uint64(state.RandaoMixesLength()) != randaoMixLength {
if uint64(state.RandaoMixesLength()) != uint64(randaoMixLength) {
return nil, fmt.Errorf(
"state randao length %d different than EpochsPerHistoricalVector %d",
state.RandaoMixesLength(),
@@ -300,13 +300,13 @@ func ProcessFinalUpdates(state *stateTrie.BeaconState) (*stateTrie.BeaconState,
if err != nil {
return nil, err
}
if err := state.UpdateRandaoMixesAtIndex(nextEpoch%randaoMixLength, mix); err != nil {
if err := state.UpdateRandaoMixesAtIndex(uint64(nextEpoch%randaoMixLength), mix); err != nil {
return nil, err
}
// Set historical root accumulator.
epochsPerHistoricalRoot := params.BeaconConfig().SlotsPerHistoricalRoot / params.BeaconConfig().SlotsPerEpoch
if nextEpoch%epochsPerHistoricalRoot == 0 {
if nextEpoch.Mod(epochsPerHistoricalRoot) == 0 {
historicalBatch := &pb.HistoricalBatch{
BlockRoots: state.BlockRoots(),
StateRoots: state.StateRoots(),

View File

@@ -5,6 +5,7 @@ import (
"testing"
"github.com/gogo/protobuf/proto"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch"
@@ -288,7 +289,7 @@ func TestProcessFinalUpdates_CanProcess(t *testing.T) {
assert.Equal(t, newS.Slashings()[ce], newS.Slashings()[ne], "Unexpected slashed balance")
// Verify randao is correctly updated in the right position.
mix, err := newS.RandaoMixAtIndex(ne)
mix, err := newS.RandaoMixAtIndex(uint64(ne))
assert.NoError(t, err)
assert.DeepNotEqual(t, params.BeaconConfig().ZeroHash[:], mix, "latest RANDAO still zero hashes")
@@ -396,11 +397,11 @@ func TestProcessRegistryUpdates_ValidatorsEjected(t *testing.T) {
}
func TestProcessRegistryUpdates_CanExits(t *testing.T) {
e := uint64(5)
e := types.Epoch(5)
exitEpoch := helpers.ActivationExitEpoch(e)
minWithdrawalDelay := params.BeaconConfig().MinValidatorWithdrawabilityDelay
base := &pb.BeaconState{
Slot: e * params.BeaconConfig().SlotsPerEpoch,
Slot: uint64(e) * params.BeaconConfig().SlotsPerEpoch,
Validators: []*ethpb.Validator{
{
ExitEpoch: exitEpoch,

View File

@@ -22,6 +22,7 @@ go_library(
"//shared/params:go_default_library",
"//shared/traceutil: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",
"@io_opencensus_go//trace:go_default_library",
],
@@ -49,6 +50,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",
"@com_github_prysmaticlabs_go_bitfield//:go_default_library",
],

View File

@@ -5,6 +5,7 @@ import (
"context"
"github.com/pkg/errors"
"github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
@@ -106,7 +107,7 @@ func AttestedPrevEpoch(s *stateTrie.BeaconState, a *pb.PendingAttestation) (bool
}
// SameTarget returns true if attestation `a` attested to the same target block in state.
func SameTarget(state *stateTrie.BeaconState, a *pb.PendingAttestation, e uint64) (bool, error) {
func SameTarget(state *stateTrie.BeaconState, a *pb.PendingAttestation, e types.Epoch) (bool, error) {
r, err := helpers.BlockRoot(state, e)
if err != nil {
return false, err

View File

@@ -17,7 +17,7 @@ import (
)
func TestUpdateValidator_Works(t *testing.T) {
e := params.BeaconConfig().FarFutureEpoch
e := uint64(params.BeaconConfig().FarFutureEpoch)
vp := []*precompute.Validator{{}, {InclusionSlot: e}, {}, {InclusionSlot: e}, {}, {InclusionSlot: e}}
record := &precompute.Validator{IsCurrentEpochAttester: true, IsCurrentEpochTargetAttester: true,
IsPrevEpochAttester: true, IsPrevEpochTargetAttester: true, IsPrevEpochHeadAttester: true}
@@ -34,7 +34,7 @@ func TestUpdateValidator_Works(t *testing.T) {
}
func TestUpdateValidator_InclusionOnlyCountsPrevEpoch(t *testing.T) {
e := params.BeaconConfig().FarFutureEpoch
e := uint64(params.BeaconConfig().FarFutureEpoch)
vp := []*precompute.Validator{{InclusionSlot: e}}
record := &precompute.Validator{IsCurrentEpochAttester: true, IsCurrentEpochTargetAttester: true}
a := &pb.PendingAttestation{InclusionDelay: 1, ProposerIndex: 2}

View File

@@ -3,6 +3,7 @@ package precompute_test
import (
"testing"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute"
@@ -38,16 +39,16 @@ func TestProcessJustificationAndFinalizationPreCompute_ConsecutiveEpochs(t *test
}
state, err := beaconstate.InitializeFromProto(base)
require.NoError(t, err)
attestedBalance := 4 * e * 3 / 2
attestedBalance := 4 * uint64(e) * 3 / 2
b := &precompute.Balance{PrevEpochTargetAttested: attestedBalance}
newState, err := precompute.ProcessJustificationAndFinalizationPreCompute(state, b)
require.NoError(t, err)
rt := [32]byte{byte(64)}
assert.DeepEqual(t, rt[:], newState.CurrentJustifiedCheckpoint().Root, "Unexpected justified root")
assert.Equal(t, uint64(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch")
assert.Equal(t, uint64(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch")
assert.Equal(t, types.Epoch(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch")
assert.Equal(t, types.Epoch(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch")
assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], newState.FinalizedCheckpoint().Root, "Unexpected finalized root")
assert.Equal(t, uint64(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch")
assert.Equal(t, types.Epoch(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch")
}
func TestProcessJustificationAndFinalizationPreCompute_JustifyCurrentEpoch(t *testing.T) {
@@ -75,16 +76,16 @@ func TestProcessJustificationAndFinalizationPreCompute_JustifyCurrentEpoch(t *te
}
state, err := beaconstate.InitializeFromProto(base)
require.NoError(t, err)
attestedBalance := 4 * e * 3 / 2
attestedBalance := 4 * uint64(e) * 3 / 2
b := &precompute.Balance{PrevEpochTargetAttested: attestedBalance}
newState, err := precompute.ProcessJustificationAndFinalizationPreCompute(state, b)
require.NoError(t, err)
rt := [32]byte{byte(64)}
assert.DeepEqual(t, rt[:], newState.CurrentJustifiedCheckpoint().Root, "Unexpected current justified root")
assert.Equal(t, uint64(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch")
assert.Equal(t, uint64(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch")
assert.Equal(t, types.Epoch(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch")
assert.Equal(t, types.Epoch(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch")
assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], newState.FinalizedCheckpoint().Root)
assert.Equal(t, uint64(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch")
assert.Equal(t, types.Epoch(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch")
}
func TestProcessJustificationAndFinalizationPreCompute_JustifyPrevEpoch(t *testing.T) {
@@ -111,14 +112,14 @@ func TestProcessJustificationAndFinalizationPreCompute_JustifyPrevEpoch(t *testi
}
state, err := beaconstate.InitializeFromProto(base)
require.NoError(t, err)
attestedBalance := 4 * e * 3 / 2
attestedBalance := 4 * uint64(e) * 3 / 2
b := &precompute.Balance{PrevEpochTargetAttested: attestedBalance}
newState, err := precompute.ProcessJustificationAndFinalizationPreCompute(state, b)
require.NoError(t, err)
rt := [32]byte{byte(64)}
assert.DeepEqual(t, rt[:], newState.CurrentJustifiedCheckpoint().Root, "Unexpected current justified root")
assert.Equal(t, uint64(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch")
assert.Equal(t, uint64(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch")
assert.Equal(t, types.Epoch(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch")
assert.Equal(t, types.Epoch(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch")
assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], newState.FinalizedCheckpoint().Root)
assert.Equal(t, uint64(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch")
assert.Equal(t, types.Epoch(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch")
}

View File

@@ -45,8 +45,8 @@ func New(ctx context.Context, state *stateTrie.BeaconState) ([]*Validator, *Bala
}
// Set inclusion slot and inclusion distance to be max, they will be compared and replaced
// with the lower values
pVal.InclusionSlot = params.BeaconConfig().FarFutureEpoch
pVal.InclusionDistance = params.BeaconConfig().FarFutureEpoch
pVal.InclusionSlot = uint64(params.BeaconConfig().FarFutureEpoch)
pVal.InclusionDistance = uint64(params.BeaconConfig().FarFutureEpoch)
pValidators[idx] = pVal
return nil

View File

@@ -29,7 +29,7 @@ func TestNew(t *testing.T) {
},
})
require.NoError(t, err)
e := params.BeaconConfig().FarFutureEpoch
e := uint64(params.BeaconConfig().FarFutureEpoch)
v, b, err := precompute.New(context.Background(), s)
require.NoError(t, err)
assert.DeepEqual(t, &precompute.Validator{

View File

@@ -2,6 +2,7 @@ package precompute
import (
"github.com/pkg/errors"
"github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/mathutil"
@@ -68,7 +69,7 @@ func AttestationsDelta(state *stateTrie.BeaconState, pBal *Balance, vp []*Valida
return rewards, penalties, nil
}
func attestationDelta(pBal *Balance, v *Validator, prevEpoch, finalizedEpoch uint64) (uint64, uint64) {
func attestationDelta(pBal *Balance, v *Validator, prevEpoch, finalizedEpoch types.Epoch) (uint64, uint64) {
eligible := v.IsActivePrevEpoch || (v.IsSlashed && !v.IsWithdrawableCurrentEpoch)
if !eligible || pBal.ActiveCurrentEpoch == 0 {
return 0, 0
@@ -139,7 +140,7 @@ func attestationDelta(pBal *Balance, v *Validator, prevEpoch, finalizedEpoch uin
// Equivalent to the following condition from the spec:
// `index not in get_unslashed_attesting_indices(state, matching_target_attestations)`
if !v.IsPrevEpochTargetAttester || v.IsSlashed {
p += vb * finalityDelay / params.BeaconConfig().InactivityPenaltyQuotient
p += vb * uint64(finalityDelay) / params.BeaconConfig().InactivityPenaltyQuotient
}
}
return r, p
@@ -182,7 +183,7 @@ func ProposersDelta(state *stateTrie.BeaconState, pBal *Balance, vp []*Validator
// Spec code:
// def is_in_inactivity_leak(state: BeaconState) -> bool:
// return get_finality_delay(state) > MIN_EPOCHS_TO_INACTIVITY_PENALTY
func isInInactivityLeak(prevEpoch, finalizedEpoch uint64) bool {
func isInInactivityLeak(prevEpoch, finalizedEpoch types.Epoch) bool {
return finalityDelay(prevEpoch, finalizedEpoch) > params.BeaconConfig().MinEpochsToInactivityPenalty
}
@@ -191,6 +192,6 @@ func isInInactivityLeak(prevEpoch, finalizedEpoch uint64) bool {
// Spec code:
// def get_finality_delay(state: BeaconState) -> uint64:
// return get_previous_epoch(state) - state.finalized_checkpoint.epoch
func finalityDelay(prevEpoch, finalizedEpoch uint64) uint64 {
func finalityDelay(prevEpoch, finalizedEpoch types.Epoch) types.Epoch {
return prevEpoch - finalizedEpoch
}

View File

@@ -4,6 +4,7 @@ import (
"context"
"testing"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch"
@@ -248,7 +249,7 @@ func TestProcessRewardsAndPenaltiesPrecompute_SlashedInactivePenalty(t *testing.
penalty := 3 * base
proposerReward := base / params.BeaconConfig().ProposerRewardQuotient
penalty += params.BeaconConfig().BaseRewardsPerEpoch*base - proposerReward
penalty += vp[i].CurrentEpochEffectiveBalance * finalityDelay / params.BeaconConfig().InactivityPenaltyQuotient
penalty += vp[i].CurrentEpochEffectiveBalance * uint64(finalityDelay) / params.BeaconConfig().InactivityPenaltyQuotient
assert.Equal(t, penalty, penalties[i], "Unexpected slashed indices penalty balance")
assert.Equal(t, uint64(0), rewards[i], "Unexpected slashed indices reward balance")
}
@@ -353,8 +354,8 @@ func TestFinalityDelay(t *testing.T) {
base.FinalizedCheckpoint = &ethpb.Checkpoint{Epoch: 3}
beaconState, err := state.InitializeFromProto(base)
require.NoError(t, err)
prevEpoch := uint64(0)
finalizedEpoch := uint64(0)
prevEpoch := types.Epoch(0)
finalizedEpoch := types.Epoch(0)
// Set values for each test case
setVal := func() {
prevEpoch = helpers.PrevEpoch(beaconState)
@@ -383,8 +384,8 @@ func TestIsInInactivityLeak(t *testing.T) {
base.FinalizedCheckpoint = &ethpb.Checkpoint{Epoch: 3}
beaconState, err := state.InitializeFromProto(base)
require.NoError(t, err)
prevEpoch := uint64(0)
finalizedEpoch := uint64(0)
prevEpoch := types.Epoch(0)
finalizedEpoch := types.Epoch(0)
// Set values for each test case
setVal := func() {
prevEpoch = helpers.PrevEpoch(beaconState)

View File

@@ -43,6 +43,7 @@ go_library(
"//shared/timeutils:go_default_library",
"@com_github_ferranbt_fastssz//: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",
],
@@ -78,6 +79,7 @@ go_test(
"//shared/testutil/require:go_default_library",
"//shared/timeutils:go_default_library",
"@com_github_google_gofuzz//: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",
],

View File

@@ -6,6 +6,7 @@ import (
"fmt"
"time"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/shared/bls"
"github.com/prysmaticlabs/prysm/shared/hashutil"
@@ -185,7 +186,7 @@ func VerifyCheckpointEpoch(c *ethpb.Checkpoint, genesis time.Time) bool {
currentSlot := (now - genesisTime) / params.BeaconConfig().SecondsPerSlot
currentEpoch := SlotToEpoch(currentSlot)
var prevEpoch uint64
var prevEpoch types.Epoch
if currentEpoch > 1 {
prevEpoch = currentEpoch - 1
}

View File

@@ -4,6 +4,7 @@ import (
"math"
"github.com/pkg/errors"
"github.com/prysmaticlabs/eth2-types"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/params"
)
@@ -45,7 +46,7 @@ func StateRootAtSlot(state *stateTrie.BeaconState, slot uint64) ([]byte, error)
// Return the block root at the start of a recent ``epoch``.
// """
// return get_block_root_at_slot(state, compute_start_slot_at_epoch(epoch))
func BlockRoot(state *stateTrie.BeaconState, epoch uint64) ([]byte, error) {
func BlockRoot(state *stateTrie.BeaconState, epoch types.Epoch) ([]byte, error) {
s, err := StartSlot(epoch)
if err != nil {
return nil, err

View File

@@ -8,6 +8,7 @@ import (
"sort"
"github.com/pkg/errors"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
@@ -167,7 +168,7 @@ type CommitteeAssignmentContainer struct {
// 4. Construct a map of validator indices pointing to the respective committees.
func CommitteeAssignments(
state *stateTrie.BeaconState,
epoch uint64,
epoch types.Epoch,
) (map[uint64]*CommitteeAssignmentContainer, map[uint64][]uint64, error) {
nextEpoch := NextEpoch(state)
if epoch > nextEpoch {
@@ -267,7 +268,7 @@ 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 uint64) ([]uint64, error) {
func ShuffledIndices(state *stateTrie.BeaconState, epoch types.Epoch) ([]uint64, 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)
@@ -289,8 +290,8 @@ func ShuffledIndices(state *stateTrie.BeaconState, epoch uint64) ([]uint64, erro
// UpdateCommitteeCache gets called at the beginning of every epoch to cache the committee shuffled indices
// list with committee index and epoch number. It caches the shuffled indices for current epoch and next epoch.
func UpdateCommitteeCache(state *stateTrie.BeaconState, epoch uint64) error {
for _, e := range []uint64{epoch, epoch + 1} {
func UpdateCommitteeCache(state *stateTrie.BeaconState, epoch types.Epoch) error {
for _, e := range []types.Epoch{epoch, epoch + 1} {
seed, err := Seed(state, e, params.BeaconConfig().DomainBeaconAttester)
if err != nil {
return err
@@ -330,7 +331,7 @@ func UpdateCommitteeCache(state *stateTrie.BeaconState, epoch uint64) error {
}
// UpdateProposerIndicesInCache updates proposer indices entry of the committee cache.
func UpdateProposerIndicesInCache(state *stateTrie.BeaconState, epoch uint64) error {
func UpdateProposerIndicesInCache(state *stateTrie.BeaconState, epoch types.Epoch) error {
// The cache uses the state root at the (current epoch - 2)'s slot as key. (e.g. for epoch 2, the key is root at slot 31)
// Which is the reason why we skip genesis epoch.
if epoch <= params.BeaconConfig().GenesisEpoch+params.BeaconConfig().MinSeedLookahead {

View File

@@ -6,6 +6,7 @@ import (
"strconv"
"testing"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield"
beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state"
@@ -89,7 +90,7 @@ func TestVerifyBitfieldLength_OK(t *testing.T) {
func TestCommitteeAssignments_CannotRetrieveFutureEpoch(t *testing.T) {
ClearCache()
epoch := uint64(1)
epoch := types.Epoch(1)
state, err := beaconstate.InitializeFromProto(&pb.BeaconState{
Slot: 0, // Epoch 0.
})
@@ -101,7 +102,7 @@ func TestCommitteeAssignments_CannotRetrieveFutureEpoch(t *testing.T) {
func TestCommitteeAssignments_NoProposerForSlot0(t *testing.T) {
validators := make([]*ethpb.Validator, 4*params.BeaconConfig().SlotsPerEpoch)
for i := 0; i < len(validators); i++ {
var activationEpoch uint64
var activationEpoch types.Epoch
if i >= len(validators)/2 {
activationEpoch = 3
}
@@ -131,7 +132,7 @@ func TestCommitteeAssignments_CanRetrieve(t *testing.T) {
validators := make([]*ethpb.Validator, 4*params.BeaconConfig().SlotsPerEpoch)
for i := 0; i < len(validators); i++ {
// First 2 epochs only half validators are activated.
var activationEpoch uint64
var activationEpoch types.Epoch
if i >= len(validators)/2 {
activationEpoch = 3
}
@@ -208,7 +209,7 @@ func TestCommitteeAssignments_CannotRetrieveFuture(t *testing.T) {
validators := make([]*ethpb.Validator, 4*params.BeaconConfig().SlotsPerEpoch)
for i := 0; i < len(validators); i++ {
// First 2 epochs only half validators are activated.
var activationEpoch uint64
var activationEpoch types.Epoch
if i >= len(validators)/2 {
activationEpoch = 3
}
@@ -249,7 +250,7 @@ func TestCommitteeAssignments_EverySlotHasMin1Proposer(t *testing.T) {
})
require.NoError(t, err)
ClearCache()
epoch := uint64(1)
epoch := types.Epoch(1)
_, proposerIndexToSlots, err := CommitteeAssignments(state, epoch)
require.NoError(t, err, "Failed to determine CommitteeAssignments")
@@ -417,12 +418,12 @@ func TestUpdateCommitteeCache_CanUpdate(t *testing.T) {
require.NoError(t, err)
require.NoError(t, UpdateCommitteeCache(state, CurrentEpoch(state)))
epoch := uint64(1)
epoch := types.Epoch(1)
idx := uint64(1)
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
require.NoError(t, err)
indices, err = committeeCache.Committee(epoch*params.BeaconConfig().SlotsPerEpoch, seed, idx)
indices, err = committeeCache.Committee(uint64(epoch.Mul(params.BeaconConfig().SlotsPerEpoch)), seed, idx)
require.NoError(t, err)
assert.Equal(t, params.BeaconConfig().TargetCommitteeSize, uint64(len(indices)), "Did not save correct indices lengths")
}

View File

@@ -1,6 +1,7 @@
package helpers
import (
"github.com/prysmaticlabs/eth2-types"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/bls"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
@@ -17,7 +18,7 @@ import (
// """
// mix = get_randao_mix(state, Epoch(epoch + EPOCHS_PER_HISTORICAL_VECTOR - MIN_SEED_LOOKAHEAD - 1)) # Avoid underflow
// return hash(domain_type + int_to_bytes(epoch, length=8) + mix)
func Seed(state *stateTrie.BeaconState, epoch uint64, domain [bls.DomainByteLength]byte) ([32]byte, error) {
func Seed(state *stateTrie.BeaconState, epoch types.Epoch, domain [bls.DomainByteLength]byte) ([32]byte, error) {
// See https://github.com/ethereum/eth2.0-specs/pull/1296 for
// rationale on why offset has to look down by 1.
lookAheadEpoch := epoch + params.BeaconConfig().EpochsPerHistoricalVector -
@@ -27,7 +28,7 @@ func Seed(state *stateTrie.BeaconState, epoch uint64, domain [bls.DomainByteLeng
if err != nil {
return [32]byte{}, err
}
seed := append(domain[:], bytesutil.Bytes8(epoch)...)
seed := append(domain[:], bytesutil.Bytes8(uint64(epoch))...)
seed = append(seed, randaoMix...)
seed32 := hashutil.Hash(seed)
@@ -44,6 +45,6 @@ func Seed(state *stateTrie.BeaconState, epoch uint64, domain [bls.DomainByteLeng
// Return the randao mix at a recent ``epoch``.
// """
// return state.randao_mixes[epoch % EPOCHS_PER_HISTORICAL_VECTOR]
func RandaoMix(state *stateTrie.BeaconState, epoch uint64) ([]byte, error) {
return state.RandaoMixAtIndex(epoch % params.BeaconConfig().EpochsPerHistoricalVector)
func RandaoMix(state *stateTrie.BeaconState, epoch types.Epoch) ([]byte, error) {
return state.RandaoMixAtIndex(uint64(epoch % params.BeaconConfig().EpochsPerHistoricalVector))
}

View File

@@ -4,6 +4,7 @@ import (
"encoding/binary"
"testing"
"github.com/prysmaticlabs/eth2-types"
beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
@@ -22,7 +23,7 @@ func TestRandaoMix_OK(t *testing.T) {
state, err := beaconstate.InitializeFromProto(&pb.BeaconState{RandaoMixes: randaoMixes})
require.NoError(t, err)
tests := []struct {
epoch uint64
epoch types.Epoch
randaoMix []byte
}{
{
@@ -39,7 +40,7 @@ func TestRandaoMix_OK(t *testing.T) {
},
}
for _, test := range tests {
require.NoError(t, state.SetSlot((test.epoch+1)*params.BeaconConfig().SlotsPerEpoch))
require.NoError(t, state.SetSlot(uint64(test.epoch.Add(1).Mul(params.BeaconConfig().SlotsPerEpoch))))
mix, err := RandaoMix(state, test.epoch)
require.NoError(t, err)
assert.DeepEqual(t, test.randaoMix, mix, "Incorrect randao mix")
@@ -56,7 +57,7 @@ func TestRandaoMix_CopyOK(t *testing.T) {
state, err := beaconstate.InitializeFromProto(&pb.BeaconState{RandaoMixes: randaoMixes})
require.NoError(t, err)
tests := []struct {
epoch uint64
epoch types.Epoch
randaoMix []byte
}{
{
@@ -73,10 +74,10 @@ func TestRandaoMix_CopyOK(t *testing.T) {
},
}
for _, test := range tests {
require.NoError(t, state.SetSlot((test.epoch+1)*params.BeaconConfig().SlotsPerEpoch))
require.NoError(t, state.SetSlot(uint64((test.epoch + 1).Mul(params.BeaconConfig().SlotsPerEpoch))))
mix, err := RandaoMix(state, test.epoch)
require.NoError(t, err)
uniqueNumber := params.BeaconConfig().EpochsPerHistoricalVector + 1000
uniqueNumber := uint64(params.BeaconConfig().EpochsPerHistoricalVector.Add(1000))
binary.LittleEndian.PutUint64(mix, uniqueNumber)
for _, mx := range randaoMixes {
@@ -93,7 +94,7 @@ func TestGenerateSeed_OK(t *testing.T) {
binary.LittleEndian.PutUint64(intInBytes, uint64(i))
randaoMixes[i] = intInBytes
}
slot := 10 * params.BeaconConfig().MinSeedLookahead * params.BeaconConfig().SlotsPerEpoch
slot := uint64(params.BeaconConfig().MinSeedLookahead.Mul(10 * params.BeaconConfig().SlotsPerEpoch))
state, err := beaconstate.InitializeFromProto(&pb.BeaconState{
RandaoMixes: randaoMixes,
Slot: slot,

View File

@@ -3,6 +3,7 @@ package helpers
import (
fssz "github.com/ferranbt/fastssz"
"github.com/pkg/errors"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
@@ -22,7 +23,7 @@ const DomainByteLength = 4
var ErrSigFailedToVerify = errors.New("signature did not verify")
// ComputeDomainAndSign computes the domain and signing root and sign it using the passed in private key.
func ComputeDomainAndSign(st *state.BeaconState, epoch uint64, obj fssz.HashRoot, domain [4]byte, key bls.SecretKey) ([]byte, error) {
func ComputeDomainAndSign(st *state.BeaconState, epoch types.Epoch, obj fssz.HashRoot, domain [4]byte, key bls.SecretKey) ([]byte, error) {
d, err := Domain(st.Fork(), epoch, domain, st.GenesisValidatorRoot())
if err != nil {
return nil, err
@@ -64,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, epoch uint64, obj fssz.HashRoot, domain [4]byte, sig []byte) error {
func ComputeDomainVerifySigningRoot(st *state.BeaconState, index uint64, epoch types.Epoch, obj fssz.HashRoot, domain [4]byte, sig []byte) error {
v, err := st.ValidatorAtIndex(index)
if err != nil {
return err

View File

@@ -6,6 +6,7 @@ import (
"time"
"github.com/pkg/errors"
"github.com/prysmaticlabs/eth2-types"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/mathutil"
"github.com/prysmaticlabs/prysm/shared/params"
@@ -24,8 +25,10 @@ const MaxSlotBuffer = uint64(1 << 7)
// Return the epoch number of ``slot``.
// """
// return Epoch(slot // SLOTS_PER_EPOCH)
func SlotToEpoch(slot uint64) uint64 {
return slot / params.BeaconConfig().SlotsPerEpoch
func SlotToEpoch(slot uint64) types.Epoch {
// TODO(#8205): Once types.Slot PR is ready, replace with
// return types.Epoch(slot.DivSlot(params.BeaconConfig().SlotsPerEpoch))
return types.Epoch(slot / params.BeaconConfig().SlotsPerEpoch)
}
// CurrentEpoch returns the current epoch number calculated from
@@ -37,7 +40,7 @@ func SlotToEpoch(slot uint64) uint64 {
// Return the current epoch.
// """
// return compute_epoch_of_slot(state.slot)
func CurrentEpoch(state *stateTrie.BeaconState) uint64 {
func CurrentEpoch(state *stateTrie.BeaconState) types.Epoch {
return SlotToEpoch(state.Slot())
}
@@ -52,7 +55,7 @@ func CurrentEpoch(state *stateTrie.BeaconState) uint64 {
// """
// current_epoch = get_current_epoch(state)
// return GENESIS_EPOCH if current_epoch == GENESIS_EPOCH else Epoch(current_epoch - 1)
func PrevEpoch(state *stateTrie.BeaconState) uint64 {
func PrevEpoch(state *stateTrie.BeaconState) types.Epoch {
currentEpoch := CurrentEpoch(state)
if currentEpoch == 0 {
return 0
@@ -62,7 +65,7 @@ func PrevEpoch(state *stateTrie.BeaconState) uint64 {
// NextEpoch returns the next epoch number calculated from
// the slot number stored in beacon state.
func NextEpoch(state *stateTrie.BeaconState) uint64 {
func NextEpoch(state *stateTrie.BeaconState) types.Epoch {
return SlotToEpoch(state.Slot()) + 1
}
@@ -75,8 +78,8 @@ func NextEpoch(state *stateTrie.BeaconState) uint64 {
// Return the start slot of ``epoch``.
// """
// return Slot(epoch * SLOTS_PER_EPOCH)
func StartSlot(epoch uint64) (uint64, error) {
slot, err := mathutil.Mul64(epoch, params.BeaconConfig().SlotsPerEpoch)
func StartSlot(epoch types.Epoch) (uint64, error) {
slot, err := mathutil.Mul64(uint64(epoch), params.BeaconConfig().SlotsPerEpoch)
if err != nil {
return slot, errors.Errorf("start slot calculation overflows: %v", err)
}
@@ -85,7 +88,7 @@ func StartSlot(epoch uint64) (uint64, error) {
// EndSlot returns the last slot number of the
// current epoch.
func EndSlot(epoch uint64) (uint64, error) {
func EndSlot(epoch types.Epoch) (uint64, error) {
if epoch == math.MaxUint64 {
return 0, errors.New("start slot calculation overflows")
}
@@ -199,7 +202,7 @@ func RoundUpToNearestEpoch(slot uint64) uint64 {
// else:
// weak_subjectivity_period += SAFETY_DECAY*val_count/(2*100*MIN_PER_EPOCH_CHURN_LIMIT)
// return weak_subjectivity_period
func WeakSubjectivityCheckptEpoch(valCount uint64) (uint64, error) {
func WeakSubjectivityCheckptEpoch(valCount uint64) (types.Epoch, error) {
wsp := params.BeaconConfig().MinValidatorWithdrawabilityDelay
m := params.BeaconConfig().MinPerEpochChurnLimit
@@ -207,14 +210,14 @@ func WeakSubjectivityCheckptEpoch(valCount uint64) (uint64, error) {
d := params.BeaconConfig().SafetyDecay
if valCount >= m*q {
v := d * q / (2 * 100)
wsp += v
wsp += types.Epoch(v)
} else {
v, err := mathutil.Mul64(d, valCount)
if err != nil {
return 0, err
}
v /= 2 * 100 * m
wsp += v
wsp += types.Epoch(v)
}
return wsp, nil
}
@@ -224,7 +227,7 @@ func WeakSubjectivityCheckptEpoch(valCount uint64) (uint64, error) {
func VotingPeriodStartTime(genesis, slot uint64) uint64 {
startTime := genesis
startTime +=
(slot - (slot % (params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch))) *
(slot - (slot % (uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod) * params.BeaconConfig().SlotsPerEpoch))) *
params.BeaconConfig().SecondsPerSlot
return startTime
}

View File

@@ -5,19 +5,19 @@ import (
"testing"
"time"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/prysmaticlabs/prysm/shared/timeutils"
"github.com/prysmaticlabs/eth2-types"
beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/prysmaticlabs/prysm/shared/timeutils"
)
func TestSlotToEpoch_OK(t *testing.T) {
tests := []struct {
slot uint64
epoch uint64
epoch types.Epoch
}{
{slot: 0, epoch: 0},
{slot: 50, epoch: 1},
@@ -33,7 +33,7 @@ func TestSlotToEpoch_OK(t *testing.T) {
func TestCurrentEpoch_OK(t *testing.T) {
tests := []struct {
slot uint64
epoch uint64
epoch types.Epoch
}{
{slot: 0, epoch: 0},
{slot: 50, epoch: 1},
@@ -51,7 +51,7 @@ func TestCurrentEpoch_OK(t *testing.T) {
func TestPrevEpoch_OK(t *testing.T) {
tests := []struct {
slot uint64
epoch uint64
epoch types.Epoch
}{
{slot: 0, epoch: 0},
{slot: 0 + params.BeaconConfig().SlotsPerEpoch + 1, epoch: 0},
@@ -67,13 +67,13 @@ func TestPrevEpoch_OK(t *testing.T) {
func TestNextEpoch_OK(t *testing.T) {
tests := []struct {
slot uint64
epoch uint64
epoch types.Epoch
}{
{slot: 0, epoch: 0/params.BeaconConfig().SlotsPerEpoch + 1},
{slot: 50, epoch: 0/params.BeaconConfig().SlotsPerEpoch + 2},
{slot: 64, epoch: 64/params.BeaconConfig().SlotsPerEpoch + 1},
{slot: 128, epoch: 128/params.BeaconConfig().SlotsPerEpoch + 1},
{slot: 200, epoch: 200/params.BeaconConfig().SlotsPerEpoch + 1},
{slot: 0, epoch: types.Epoch(0/params.BeaconConfig().SlotsPerEpoch + 1)},
{slot: 50, epoch: types.Epoch(0/params.BeaconConfig().SlotsPerEpoch + 2)},
{slot: 64, epoch: types.Epoch(64/params.BeaconConfig().SlotsPerEpoch + 1)},
{slot: 128, epoch: types.Epoch(128/params.BeaconConfig().SlotsPerEpoch + 1)},
{slot: 200, epoch: types.Epoch(200/params.BeaconConfig().SlotsPerEpoch + 1)},
}
for _, tt := range tests {
state, err := beaconstate.InitializeFromProto(&pb.BeaconState{Slot: tt.slot})
@@ -84,7 +84,7 @@ func TestNextEpoch_OK(t *testing.T) {
func TestEpochStartSlot_OK(t *testing.T) {
tests := []struct {
epoch uint64
epoch types.Epoch
startSlot uint64
error bool
}{
@@ -108,7 +108,7 @@ func TestEpochStartSlot_OK(t *testing.T) {
func TestEpochEndSlot_OK(t *testing.T) {
tests := []struct {
epoch uint64
epoch types.Epoch
startSlot uint64
error bool
}{
@@ -349,7 +349,7 @@ func TestValidateSlotClock_HandlesBadSlot(t *testing.T) {
func TestWeakSubjectivityCheckptEpoch(t *testing.T) {
tests := []struct {
valCount uint64
want uint64
want types.Epoch
}{
// Verifying these numbers aligned with the reference table defined:
// https://github.com/ethereum/eth2.0-specs/blob/weak-subjectivity-guide/specs/phase0/weak-subjectivity.md#calculating-the-weak-subjectivity-period

View File

@@ -4,6 +4,7 @@ import (
"bytes"
"github.com/pkg/errors"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
@@ -22,16 +23,16 @@ import (
// Check if ``validator`` is active.
// """
// return validator.activation_epoch <= epoch < validator.exit_epoch
func IsActiveValidator(validator *ethpb.Validator, epoch uint64) bool {
func IsActiveValidator(validator *ethpb.Validator, epoch types.Epoch) bool {
return checkValidatorActiveStatus(validator.ActivationEpoch, validator.ExitEpoch, epoch)
}
// IsActiveValidatorUsingTrie checks if a read only validator is active.
func IsActiveValidatorUsingTrie(validator stateTrie.ReadOnlyValidator, epoch uint64) bool {
func IsActiveValidatorUsingTrie(validator stateTrie.ReadOnlyValidator, epoch types.Epoch) bool {
return checkValidatorActiveStatus(validator.ActivationEpoch(), validator.ExitEpoch(), epoch)
}
func checkValidatorActiveStatus(activationEpoch, exitEpoch, epoch uint64) bool {
func checkValidatorActiveStatus(activationEpoch, exitEpoch, epoch types.Epoch) bool {
return activationEpoch <= epoch && epoch < exitEpoch
}
@@ -44,16 +45,16 @@ func checkValidatorActiveStatus(activationEpoch, exitEpoch, epoch uint64) bool {
// Check if ``validator`` is slashable.
// """
// return (not validator.slashed) and (validator.activation_epoch <= epoch < validator.withdrawable_epoch)
func IsSlashableValidator(activationEpoch, withdrawableEpoch uint64, slashed bool, epoch uint64) bool {
func IsSlashableValidator(activationEpoch, withdrawableEpoch types.Epoch, slashed bool, epoch types.Epoch) bool {
return checkValidatorSlashable(activationEpoch, withdrawableEpoch, slashed, epoch)
}
// IsSlashableValidatorUsingTrie checks if a read only validator is slashable.
func IsSlashableValidatorUsingTrie(val stateTrie.ReadOnlyValidator, epoch uint64) bool {
func IsSlashableValidatorUsingTrie(val stateTrie.ReadOnlyValidator, epoch types.Epoch) bool {
return checkValidatorSlashable(val.ActivationEpoch(), val.WithdrawableEpoch(), val.Slashed(), epoch)
}
func checkValidatorSlashable(activationEpoch, withdrawableEpoch uint64, slashed bool, epoch uint64) bool {
func checkValidatorSlashable(activationEpoch, withdrawableEpoch types.Epoch, slashed bool, epoch types.Epoch) bool {
active := activationEpoch <= epoch
beforeWithdrawable := epoch < withdrawableEpoch
return beforeWithdrawable && active && !slashed
@@ -72,7 +73,7 @@ func checkValidatorSlashable(activationEpoch, withdrawableEpoch uint64, slashed
// 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 uint64) ([]uint64, error) {
func ActiveValidatorIndices(state *stateTrie.BeaconState, epoch types.Epoch) ([]uint64, error) {
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
if err != nil {
return nil, errors.Wrap(err, "could not get seed")
@@ -103,7 +104,7 @@ func ActiveValidatorIndices(state *stateTrie.BeaconState, epoch uint64) ([]uint6
// ActiveValidatorCount returns the number of active validators in the state
// at the given epoch.
func ActiveValidatorCount(state *stateTrie.BeaconState, epoch uint64) (uint64, error) {
func ActiveValidatorCount(state *stateTrie.BeaconState, epoch types.Epoch) (uint64, error) {
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
if err != nil {
return 0, errors.Wrap(err, "could not get seed")
@@ -142,7 +143,7 @@ func ActiveValidatorCount(state *stateTrie.BeaconState, epoch uint64) (uint64, e
// Return the epoch during which validator activations and exits initiated in ``epoch`` take effect.
// """
// return Epoch(epoch + 1 + MAX_SEED_LOOKAHEAD)
func ActivationExitEpoch(epoch uint64) uint64 {
func ActivationExitEpoch(epoch types.Epoch) types.Epoch {
return epoch + 1 + params.BeaconConfig().MaxSeedLookahead
}
@@ -283,7 +284,7 @@ func ComputeProposerIndex(bState *stateTrie.BeaconState, activeIndices []uint64,
// epoch = get_current_epoch(state) if epoch is None else epoch
// fork_version = state.fork.previous_version if epoch < state.fork.epoch else state.fork.current_version
// return compute_domain(domain_type, fork_version, state.genesis_validators_root)
func Domain(fork *pb.Fork, epoch uint64, domainType [bls.DomainByteLength]byte, genesisRoot []byte) ([]byte, error) {
func Domain(fork *pb.Fork, epoch types.Epoch, domainType [bls.DomainByteLength]byte, genesisRoot []byte) ([]byte, error) {
if fork == nil {
return []byte{}, errors.New("nil fork or domain type")
}
@@ -324,7 +325,7 @@ func IsEligibleForActivationQueueUsingTrie(validator stateTrie.ReadOnlyValidator
}
// isEligibleForActivationQueue carries out the logic for IsEligibleForActivationQueue*
func isEligibileForActivationQueue(activationEligibilityEpoch, effectiveBalance uint64) bool {
func isEligibileForActivationQueue(activationEligibilityEpoch types.Epoch, effectiveBalance uint64) bool {
return activationEligibilityEpoch == params.BeaconConfig().FarFutureEpoch &&
effectiveBalance == params.BeaconConfig().MaxEffectiveBalance
}
@@ -357,7 +358,7 @@ func IsEligibleForActivationUsingTrie(state *stateTrie.BeaconState, validator st
}
// isEligibleForActivation carries out the logic for IsEligibleForActivation*
func isEligibleForActivation(activationEligibilityEpoch, activationEpoch, finalizedEpoch uint64) bool {
func isEligibleForActivation(activationEligibilityEpoch, activationEpoch, finalizedEpoch types.Epoch) bool {
return activationEligibilityEpoch <= finalizedEpoch &&
activationEpoch == params.BeaconConfig().FarFutureEpoch
}

View File

@@ -4,6 +4,7 @@ import (
"errors"
"testing"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state"
@@ -17,7 +18,7 @@ import (
func TestIsActiveValidator_OK(t *testing.T) {
tests := []struct {
a uint64
a types.Epoch
b bool
}{
{a: 0, b: false},
@@ -34,7 +35,7 @@ func TestIsActiveValidator_OK(t *testing.T) {
func TestIsActiveValidatorUsingTrie_OK(t *testing.T) {
tests := []struct {
a uint64
a types.Epoch
b bool
}{
{a: 0, b: false},
@@ -57,7 +58,7 @@ func TestIsSlashableValidator_OK(t *testing.T) {
tests := []struct {
name string
validator *ethpb.Validator
epoch uint64
epoch types.Epoch
slashable bool
}{
{
@@ -139,7 +140,7 @@ func TestIsSlashableValidatorUsingTrie_OK(t *testing.T) {
tests := []struct {
name string
validator *ethpb.Validator
epoch uint64
epoch types.Epoch
slashable bool
}{
{
@@ -350,7 +351,7 @@ func TestComputeProposerIndex_Compatibility(t *testing.T) {
}
func TestDelayedActivationExitEpoch_OK(t *testing.T) {
epoch := uint64(9999)
epoch := types.Epoch(9999)
wanted := epoch + 1 + params.BeaconConfig().MaxSeedLookahead
assert.Equal(t, wanted, ActivationExitEpoch(epoch))
}
@@ -422,7 +423,7 @@ func TestDomain_OK(t *testing.T) {
},
}
tests := []struct {
epoch uint64
epoch types.Epoch
domainType [4]byte
result []byte
}{
@@ -445,7 +446,7 @@ func TestActiveValidatorIndices(t *testing.T) {
farFutureEpoch := params.BeaconConfig().FarFutureEpoch
type args struct {
state *pb.BeaconState
epoch uint64
epoch types.Epoch
}
tests := []struct {
name string

View File

@@ -79,13 +79,13 @@ go_test(
"//shared/bytesutil:go_default_library",
"//shared/hashutil:go_default_library",
"//shared/params:go_default_library",
"//shared/sszutil:go_default_library",
"//shared/testutil:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
"//shared/trieutil:go_default_library",
"@com_github_gogo_protobuf//proto:go_default_library",
"@com_github_google_gofuzz//: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",
"@com_github_sirupsen_logrus//:go_default_library",

View File

@@ -8,7 +8,6 @@ import (
"github.com/prysmaticlabs/prysm/beacon-chain/core/state"
beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/sszutil"
"github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
@@ -34,9 +33,7 @@ func TestSkipSlotCache_OK(t *testing.T) {
bState, err = state.ExecuteStateTransition(context.Background(), bState, blk)
require.NoError(t, err, "Could not process state transition")
if !sszutil.DeepEqual(originalState.CloneInnerState(), bState.CloneInnerState()) {
t.Fatal("Skipped slots cache leads to different states")
}
assert.DeepEqual(t, originalState.CloneInnerState(), bState.CloneInnerState(), "Skipped slots cache leads to different states")
}
func TestSkipSlotCache_ConcurrentMixup(t *testing.T) {

View File

@@ -4,6 +4,7 @@ import (
"testing"
"github.com/gogo/protobuf/proto"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
@@ -15,19 +16,19 @@ import (
)
func TestGenesisBeaconState_OK(t *testing.T) {
genesisEpochNumber := uint64(0)
genesisEpoch := types.Epoch(0)
assert.DeepEqual(t, []byte{0, 0, 0, 0}, params.BeaconConfig().GenesisForkVersion, "GenesisSlot( should be {0,0,0,0} for these tests to pass")
genesisForkVersion := params.BeaconConfig().GenesisForkVersion
assert.Equal(t, [32]byte{}, params.BeaconConfig().ZeroHash, "ZeroHash should be all 0s for these tests to pass")
assert.Equal(t, uint64(65536), params.BeaconConfig().EpochsPerHistoricalVector, "EpochsPerHistoricalVector should be 8192 for these tests to pass")
assert.Equal(t, types.Epoch(65536), params.BeaconConfig().EpochsPerHistoricalVector, "EpochsPerHistoricalVector should be 8192 for these tests to pass")
latestRandaoMixesLength := params.BeaconConfig().EpochsPerHistoricalVector
assert.Equal(t, uint64(16777216), params.BeaconConfig().HistoricalRootsLimit, "HistoricalRootsLimit should be 16777216 for these tests to pass")
depositsForChainStart := 100
assert.Equal(t, uint64(8192), params.BeaconConfig().EpochsPerSlashingsVector, "EpochsPerSlashingsVector should be 8192 for these tests to pass")
assert.Equal(t, types.Epoch(8192), params.BeaconConfig().EpochsPerSlashingsVector, "EpochsPerSlashingsVector should be 8192 for these tests to pass")
genesisTime := uint64(99999)
deposits, _, err := testutil.DeterministicDepositsAndKeys(uint64(depositsForChainStart))
@@ -42,7 +43,7 @@ func TestGenesisBeaconState_OK(t *testing.T) {
if !proto.Equal(newState.Fork(), &pb.Fork{
PreviousVersion: genesisForkVersion,
CurrentVersion: genesisForkVersion,
Epoch: genesisEpochNumber,
Epoch: genesisEpoch,
}) {
t.Error("Fork was not correctly initialized")
}
@@ -51,22 +52,22 @@ func TestGenesisBeaconState_OK(t *testing.T) {
assert.Equal(t, depositsForChainStart, len(newState.Validators()), "Validators was not correctly initialized")
v, err := newState.ValidatorAtIndex(0)
require.NoError(t, err)
assert.Equal(t, uint64(0), v.ActivationEpoch, "Validators was not correctly initialized")
assert.Equal(t, types.Epoch(0), v.ActivationEpoch, "Validators was not correctly initialized")
v, err = newState.ValidatorAtIndex(0)
require.NoError(t, err)
assert.Equal(t, uint64(0), v.ActivationEligibilityEpoch, "Validators was not correctly initialized")
assert.Equal(t, types.Epoch(0), v.ActivationEligibilityEpoch, "Validators was not correctly initialized")
assert.Equal(t, depositsForChainStart, len(newState.Balances()), "Balances was not correctly initialized")
// Randomness and committees fields checks.
assert.Equal(t, latestRandaoMixesLength, uint64(len(newState.RandaoMixes())), "Length of RandaoMixes was not correctly initialized")
assert.Equal(t, latestRandaoMixesLength, types.Epoch(len(newState.RandaoMixes())), "Length of RandaoMixes was not correctly initialized")
mix, err := newState.RandaoMixAtIndex(0)
require.NoError(t, err)
assert.DeepEqual(t, eth1Data.BlockHash, mix, "RandaoMixes was not correctly initialized")
// Finality fields checks.
assert.Equal(t, genesisEpochNumber, newState.PreviousJustifiedCheckpoint().Epoch, "PreviousJustifiedCheckpoint.Epoch was not correctly initialized")
assert.Equal(t, genesisEpochNumber, newState.CurrentJustifiedCheckpoint().Epoch, "JustifiedEpoch was not correctly initialized")
assert.Equal(t, genesisEpochNumber, newState.FinalizedCheckpointEpoch(), "FinalizedSlot was not correctly initialized")
assert.Equal(t, genesisEpoch, newState.PreviousJustifiedCheckpoint().Epoch, "PreviousJustifiedCheckpoint.Epoch was not correctly initialized")
assert.Equal(t, genesisEpoch, newState.CurrentJustifiedCheckpoint().Epoch, "JustifiedEpoch was not correctly initialized")
assert.Equal(t, genesisEpoch, newState.FinalizedCheckpointEpoch(), "FinalizedSlot was not correctly initialized")
assert.Equal(t, uint8(0x00), newState.JustificationBits()[0], "JustificationBits was not correctly initialized")
// Recent state checks.

View File

@@ -6,6 +6,7 @@ import (
"fmt"
"testing"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
@@ -321,7 +322,7 @@ func createFullBlockWithOperations(t *testing.T) (*beaconstate.BeaconState,
proposerSlashIdx := uint64(3)
slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch
err = beaconState.SetSlot((params.BeaconConfig().ShardCommitteePeriod * slotsPerEpoch) + params.BeaconConfig().MinAttestationInclusionDelay)
err = beaconState.SetSlot(uint64(params.BeaconConfig().ShardCommitteePeriod.Mul(slotsPerEpoch)) + params.BeaconConfig().MinAttestationInclusionDelay)
require.NoError(t, err)
currentEpoch := helpers.CurrentEpoch(beaconState)
@@ -501,12 +502,12 @@ func TestProcessBlockNoVerify_PassesProcessingConditions(t *testing.T) {
}
func TestProcessEpochPrecompute_CanProcess(t *testing.T) {
epoch := uint64(1)
epoch := types.Epoch(1)
atts := []*pb.PendingAttestation{{Data: &ethpb.AttestationData{Target: &ethpb.Checkpoint{Root: make([]byte, 32)}}, InclusionDelay: 1}}
slashing := make([]uint64, params.BeaconConfig().EpochsPerSlashingsVector)
base := &pb.BeaconState{
Slot: epoch*params.BeaconConfig().SlotsPerEpoch + 1,
Slot: uint64(epoch.Mul(params.BeaconConfig().SlotsPerEpoch)) + 1,
BlockRoots: make([][]byte, 128),
Slashings: slashing,
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),

View File

@@ -9,9 +9,9 @@ go_library(
deps = [
"//beacon-chain/core/helpers:go_default_library",
"//beacon-chain/state:go_default_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",
],
)
@@ -28,6 +28,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",
],
)

View File

@@ -6,10 +6,10 @@ package validators
import (
"github.com/pkg/errors"
"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"
"github.com/prysmaticlabs/prysm/shared/mathutil"
"github.com/prysmaticlabs/prysm/shared/params"
)
@@ -44,7 +44,7 @@ func InitiateValidatorExit(state *stateTrie.BeaconState, idx uint64) (*stateTrie
if validator.ExitEpoch != params.BeaconConfig().FarFutureEpoch {
return state, nil
}
var exitEpochs []uint64
var exitEpochs []types.Epoch
err = state.ReadFromEveryValidator(func(idx int, val stateTrie.ReadOnlyValidator) error {
if val.ExitEpoch() != params.BeaconConfig().FarFutureEpoch {
exitEpochs = append(exitEpochs, val.ExitEpoch())
@@ -57,7 +57,7 @@ func InitiateValidatorExit(state *stateTrie.BeaconState, idx uint64) (*stateTrie
exitEpochs = append(exitEpochs, helpers.ActivationExitEpoch(helpers.CurrentEpoch(state)))
// Obtain the exit queue epoch as the maximum number in the exit epochs array.
exitQueueEpoch := uint64(0)
exitQueueEpoch := types.Epoch(0)
for _, i := range exitEpochs {
if exitQueueEpoch < i {
exitQueueEpoch = i
@@ -132,7 +132,7 @@ func SlashValidator(state *stateTrie.BeaconState, slashedIdx uint64) (*stateTrie
return nil, err
}
validator.Slashed = true
maxWithdrawableEpoch := mathutil.Max(validator.WithdrawableEpoch, currentEpoch+params.BeaconConfig().EpochsPerSlashingsVector)
maxWithdrawableEpoch := types.MaxEpoch(validator.WithdrawableEpoch, currentEpoch+params.BeaconConfig().EpochsPerSlashingsVector)
validator.WithdrawableEpoch = maxWithdrawableEpoch
if err := state.UpdateValidatorAtIndex(slashedIdx, validator); err != nil {
@@ -143,7 +143,7 @@ func SlashValidator(state *stateTrie.BeaconState, slashedIdx uint64) (*stateTrie
slashings := state.Slashings()
currentSlashing := slashings[currentEpoch%params.BeaconConfig().EpochsPerSlashingsVector]
if err := state.UpdateSlashingsAtIndex(
currentEpoch%params.BeaconConfig().EpochsPerSlashingsVector,
uint64(currentEpoch%params.BeaconConfig().EpochsPerSlashingsVector),
currentSlashing+validator.EffectiveBalance,
); err != nil {
return nil, err
@@ -172,7 +172,7 @@ func SlashValidator(state *stateTrie.BeaconState, slashedIdx uint64) (*stateTrie
}
// ActivatedValidatorIndices determines the indices activated during the given epoch.
func ActivatedValidatorIndices(epoch uint64, validators []*ethpb.Validator) []uint64 {
func ActivatedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []uint64 {
activations := make([]uint64, 0)
for i := 0; i < len(validators); i++ {
val := validators[i]
@@ -184,11 +184,11 @@ func ActivatedValidatorIndices(epoch uint64, validators []*ethpb.Validator) []ui
}
// SlashedValidatorIndices determines the indices slashed during the given epoch.
func SlashedValidatorIndices(epoch uint64, validators []*ethpb.Validator) []uint64 {
func SlashedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []uint64 {
slashed := make([]uint64, 0)
for i := 0; i < len(validators); i++ {
val := validators[i]
maxWithdrawableEpoch := mathutil.Max(val.WithdrawableEpoch, epoch+params.BeaconConfig().EpochsPerSlashingsVector)
maxWithdrawableEpoch := types.MaxEpoch(val.WithdrawableEpoch, epoch+params.BeaconConfig().EpochsPerSlashingsVector)
if val.WithdrawableEpoch == maxWithdrawableEpoch && val.Slashed {
slashed = append(slashed, uint64(i))
}
@@ -197,16 +197,16 @@ func SlashedValidatorIndices(epoch uint64, validators []*ethpb.Validator) []uint
}
// ExitedValidatorIndices determines the indices exited during the current epoch.
func ExitedValidatorIndices(epoch uint64, validators []*ethpb.Validator, activeValidatorCount uint64) ([]uint64, error) {
func ExitedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]uint64, error) {
exited := make([]uint64, 0)
exitEpochs := make([]uint64, 0)
exitEpochs := make([]types.Epoch, 0)
for i := 0; i < len(validators); i++ {
val := validators[i]
if val.ExitEpoch != params.BeaconConfig().FarFutureEpoch {
exitEpochs = append(exitEpochs, val.ExitEpoch)
}
}
exitQueueEpoch := uint64(0)
exitQueueEpoch := types.Epoch(0)
for _, i := range exitEpochs {
if exitQueueEpoch < i {
exitQueueEpoch = i
@@ -238,16 +238,16 @@ func ExitedValidatorIndices(epoch uint64, validators []*ethpb.Validator, activeV
}
// EjectedValidatorIndices determines the indices ejected during the given epoch.
func EjectedValidatorIndices(epoch uint64, validators []*ethpb.Validator, activeValidatorCount uint64) ([]uint64, error) {
func EjectedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]uint64, error) {
ejected := make([]uint64, 0)
exitEpochs := make([]uint64, 0)
exitEpochs := make([]types.Epoch, 0)
for i := 0; i < len(validators); i++ {
val := validators[i]
if val.ExitEpoch != params.BeaconConfig().FarFutureEpoch {
exitEpochs = append(exitEpochs, val.ExitEpoch)
}
}
exitQueueEpoch := uint64(0)
exitQueueEpoch := types.Epoch(0)
for _, i := range exitEpochs {
if exitQueueEpoch < i {
exitQueueEpoch = i

View File

@@ -3,6 +3,7 @@ package validators
import (
"testing"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state"
@@ -39,7 +40,7 @@ func TestHasVoted_OK(t *testing.T) {
}
func TestInitiateValidatorExit_AlreadyExited(t *testing.T) {
exitEpoch := uint64(199)
exitEpoch := types.Epoch(199)
base := &pb.BeaconState{Validators: []*ethpb.Validator{{
ExitEpoch: exitEpoch},
}}
@@ -53,7 +54,7 @@ func TestInitiateValidatorExit_AlreadyExited(t *testing.T) {
}
func TestInitiateValidatorExit_ProperExit(t *testing.T) {
exitedEpoch := uint64(100)
exitedEpoch := types.Epoch(100)
idx := uint64(3)
base := &pb.BeaconState{Validators: []*ethpb.Validator{
{ExitEpoch: exitedEpoch},
@@ -71,7 +72,7 @@ func TestInitiateValidatorExit_ProperExit(t *testing.T) {
}
func TestInitiateValidatorExit_ChurnOverflow(t *testing.T) {
exitedEpoch := uint64(100)
exitedEpoch := types.Epoch(100)
idx := uint64(4)
base := &pb.BeaconState{Validators: []*ethpb.Validator{
{ExitEpoch: exitedEpoch + 2},
@@ -133,7 +134,7 @@ func TestSlashValidator_OK(t *testing.T) {
assert.Equal(t, helpers.CurrentEpoch(state)+params.BeaconConfig().EpochsPerSlashingsVector, v.WithdrawableEpoch, "Withdrawable epoch not the expected value")
maxBalance := params.BeaconConfig().MaxEffectiveBalance
slashedBalance := state.Slashings()[state.Slot()%params.BeaconConfig().EpochsPerSlashingsVector]
slashedBalance := state.Slashings()[state.Slot()%uint64(params.BeaconConfig().EpochsPerSlashingsVector)]
assert.Equal(t, maxBalance, slashedBalance, "Slashed balance isnt the expected amount")
whistleblowerReward := slashedBalance / params.BeaconConfig().WhistleBlowerRewardQuotient

View File

@@ -9,6 +9,7 @@ go_library(
"//beacon-chain:__subpackages__",
"//tools:__subpackages__",
],
deps = ["@com_github_prysmaticlabs_eth2_types//:go_default_library"],
)
go_test(

View File

@@ -14,6 +14,8 @@
// }
package filters
import "github.com/prysmaticlabs/eth2-types"
// FilterType defines an enum which is used as the keys in a map that tracks
// set attribute filters for data as part of the `FilterQuery` struct type.
type FilterType uint8
@@ -89,13 +91,13 @@ func (q *QueryFilter) SetTargetRoot(val []byte) *QueryFilter {
}
// SetSourceEpoch enables filtering by the source epoch data attribute of an object.
func (q *QueryFilter) SetSourceEpoch(val uint64) *QueryFilter {
func (q *QueryFilter) SetSourceEpoch(val types.Epoch) *QueryFilter {
q.queries[SourceEpoch] = val
return q
}
// SetTargetEpoch enables filtering by the target epoch data attribute of an object.
func (q *QueryFilter) SetTargetEpoch(val uint64) *QueryFilter {
func (q *QueryFilter) SetTargetEpoch(val types.Epoch) *QueryFilter {
q.queries[TargetEpoch] = val
return q
}
@@ -113,13 +115,13 @@ func (q *QueryFilter) SetEndSlot(val uint64) *QueryFilter {
}
// SetStartEpoch enables filtering by the StartEpoch attribute of an object (inclusive).
func (q *QueryFilter) SetStartEpoch(val uint64) *QueryFilter {
func (q *QueryFilter) SetStartEpoch(val types.Epoch) *QueryFilter {
q.queries[StartEpoch] = val
return q
}
// SetEndEpoch enables filtering by the EndEpoch attribute of an object (inclusive).
func (q *QueryFilter) SetEndEpoch(val uint64) *QueryFilter {
func (q *QueryFilter) SetEndEpoch(val types.Epoch) *QueryFilter {
q.queries[EndEpoch] = val
return q
}

View File

@@ -46,6 +46,7 @@ go_library(
"@com_github_golang_snappy//:go_default_library",
"@com_github_pkg_errors//:go_default_library",
"@com_github_prometheus_client_golang//prometheus:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_prysmaticlabs_prombbolt//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
@@ -88,6 +89,7 @@ go_test(
"//shared/testutil/require:go_default_library",
"@com_github_ethereum_go_ethereum//common: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",
"@in_gopkg_d4l3k_messagediff_v1//:go_default_library",
"@io_etcd_go_bbolt//:go_default_library",

View File

@@ -6,6 +6,7 @@ import (
"fmt"
"github.com/pkg/errors"
"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/db/filters"
@@ -458,8 +459,8 @@ func blockRootsBySlotRange(
if step, ok = slotStepEncoded.(uint64); !ok || step == 0 {
step = 1
}
startEpoch, startEpochOk := startEpochEncoded.(uint64)
endEpoch, endEpochOk := endEpochEncoded.(uint64)
startEpoch, startEpochOk := startEpochEncoded.(types.Epoch)
endEpoch, endEpochOk := endEpochEncoded.(types.Epoch)
var err error
if startEpochOk && endEpochOk {
startSlot, err = helpers.StartSlot(startEpoch)

View File

@@ -6,6 +6,7 @@ import (
"testing"
"github.com/gogo/protobuf/proto"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
@@ -267,7 +268,10 @@ func TestStore_CleanUpDirtyStates_AboveThreshold(t *testing.T) {
require.NoError(t, db.SaveState(context.Background(), st, r))
}
require.NoError(t, db.SaveFinalizedCheckpoint(context.Background(), &ethpb.Checkpoint{Root: bRoots[len(bRoots)-1][:], Epoch: slotsPerArchivedPoint / params.BeaconConfig().SlotsPerEpoch}))
require.NoError(t, db.SaveFinalizedCheckpoint(context.Background(), &ethpb.Checkpoint{
Root: bRoots[len(bRoots)-1][:],
Epoch: types.Epoch(slotsPerArchivedPoint / params.BeaconConfig().SlotsPerEpoch),
}))
require.NoError(t, db.CleanUpDirtyStates(context.Background(), slotsPerArchivedPoint))
for i, root := range bRoots {

View File

@@ -8,5 +8,8 @@ go_library(
],
importpath = "github.com/prysmaticlabs/prysm/beacon-chain/forkchoice",
visibility = ["//beacon-chain:__subpackages__"],
deps = ["//beacon-chain/forkchoice/protoarray:go_default_library"],
deps = [
"//beacon-chain/forkchoice/protoarray:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
],
)

View File

@@ -3,6 +3,7 @@ package forkchoice
import (
"context"
"github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray"
)
@@ -17,17 +18,17 @@ type ForkChoicer interface {
// HeadRetriever retrieves head root of the current chain.
type HeadRetriever interface {
Head(context.Context, uint64, [32]byte, []uint64, uint64) ([32]byte, error)
Head(context.Context, types.Epoch, [32]byte, []uint64, types.Epoch) ([32]byte, error)
}
// BlockProcessor processes the block that's used for accounting fork choice.
type BlockProcessor interface {
ProcessBlock(context.Context, uint64, [32]byte, [32]byte, [32]byte, uint64, uint64) error
ProcessBlock(context.Context, uint64, [32]byte, [32]byte, [32]byte, types.Epoch, types.Epoch) error
}
// AttestationProcessor processes the attestation that's used for accounting fork choice.
type AttestationProcessor interface {
ProcessAttestation(context.Context, []uint64, [32]byte, uint64)
ProcessAttestation(context.Context, []uint64, [32]byte, types.Epoch)
}
// Pruner prunes the fork choice upon new finalization. This is used to keep fork choice sane.

View File

@@ -22,6 +22,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",
"@io_opencensus_go//trace:go_default_library",
],
)
@@ -43,5 +44,6 @@ 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",
],
)

View File

@@ -4,6 +4,7 @@ import (
"context"
"testing"
"github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
@@ -181,7 +182,7 @@ func TestFFGUpdates_TwoBranches(t *testing.T) {
assert.Equal(t, indexToHash(7), r, "Incorrect head with justified epoch at 0")
}
func setup(justifiedEpoch, finalizedEpoch uint64) *ForkChoice {
func setup(justifiedEpoch, finalizedEpoch types.Epoch) *ForkChoice {
f := New(0, 0, params.BeaconConfig().ZeroHash)
f.store.nodesIndices[params.BeaconConfig().ZeroHash] = 0
f.store.nodes = append(f.store.nodes, &Node{

View File

@@ -1,5 +1,7 @@
package protoarray
import "github.com/prysmaticlabs/eth2-types"
// Slot of the fork choice node.
func (n *Node) Slot() uint64 {
return n.slot
@@ -16,12 +18,12 @@ func (n *Node) Parent() uint64 {
}
// JustifiedEpoch of the fork choice node.
func (n *Node) JustifiedEpoch() uint64 {
func (n *Node) JustifiedEpoch() types.Epoch {
return n.justifiedEpoch
}
// FinalizedEpoch of the fork choice node.
func (n *Node) FinalizedEpoch() uint64 {
func (n *Node) FinalizedEpoch() types.Epoch {
return n.finalizedEpoch
}

View File

@@ -3,6 +3,7 @@ package protoarray
import (
"testing"
"github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
@@ -10,8 +11,8 @@ func TestNode_Getters(t *testing.T) {
slot := uint64(100)
root := [32]byte{'a'}
parent := uint64(10)
jEpoch := uint64(20)
fEpoch := uint64(30)
jEpoch := types.Epoch(20)
fEpoch := types.Epoch(30)
weight := uint64(10000)
bestChild := uint64(5)
bestDescendant := uint64(4)

View File

@@ -7,6 +7,7 @@ import (
"math"
"github.com/pkg/errors"
"github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/shared/params"
"go.opencensus.io/trace"
)
@@ -19,7 +20,7 @@ const defaultPruneThreshold = 256
var lastHeadRoot [32]byte
// New initializes a new fork choice store.
func New(justifiedEpoch, finalizedEpoch uint64, finalizedRoot [32]byte) *ForkChoice {
func New(justifiedEpoch, finalizedEpoch types.Epoch, finalizedRoot [32]byte) *ForkChoice {
s := &Store{
justifiedEpoch: justifiedEpoch,
finalizedEpoch: finalizedEpoch,
@@ -38,7 +39,7 @@ func New(justifiedEpoch, finalizedEpoch uint64, finalizedRoot [32]byte) *ForkCho
// Head returns the head root from fork choice store.
// It firsts computes validator's balance changes then recalculates block tree from leaves to root.
func (f *ForkChoice) Head(ctx context.Context, justifiedEpoch uint64, justifiedRoot [32]byte, justifiedStateBalances []uint64, finalizedEpoch uint64) ([32]byte, error) {
func (f *ForkChoice) Head(ctx context.Context, justifiedEpoch types.Epoch, justifiedRoot [32]byte, justifiedStateBalances []uint64, finalizedEpoch types.Epoch) ([32]byte, error) {
ctx, span := trace.StartSpan(ctx, "protoArrayForkChoice.Head")
defer span.End()
f.votesLock.Lock()
@@ -67,7 +68,7 @@ func (f *ForkChoice) Head(ctx context.Context, justifiedEpoch uint64, justifiedR
// ProcessAttestation processes attestation for vote accounting, it iterates around validator indices
// and update their votes accordingly.
func (f *ForkChoice) ProcessAttestation(ctx context.Context, validatorIndices []uint64, blockRoot [32]byte, targetEpoch uint64) {
func (f *ForkChoice) ProcessAttestation(ctx context.Context, validatorIndices []uint64, blockRoot [32]byte, targetEpoch types.Epoch) {
ctx, span := trace.StartSpan(ctx, "protoArrayForkChoice.ProcessAttestation")
defer span.End()
f.votesLock.Lock()
@@ -94,7 +95,7 @@ func (f *ForkChoice) ProcessAttestation(ctx context.Context, validatorIndices []
}
// ProcessBlock processes a new block by inserting it to the fork choice store.
func (f *ForkChoice) ProcessBlock(ctx context.Context, slot uint64, blockRoot, parentRoot, graffiti [32]byte, justifiedEpoch, finalizedEpoch uint64) error {
func (f *ForkChoice) ProcessBlock(ctx context.Context, slot uint64, blockRoot, parentRoot, graffiti [32]byte, justifiedEpoch, finalizedEpoch types.Epoch) error {
ctx, span := trace.StartSpan(ctx, "protoArrayForkChoice.ProcessBlock")
defer span.End()
@@ -206,12 +207,12 @@ func (s *Store) PruneThreshold() uint64 {
}
// JustifiedEpoch of fork choice store.
func (s *Store) JustifiedEpoch() uint64 {
func (s *Store) JustifiedEpoch() types.Epoch {
return s.justifiedEpoch
}
// FinalizedEpoch of fork choice store.
func (s *Store) FinalizedEpoch() uint64 {
func (s *Store) FinalizedEpoch() types.Epoch {
return s.finalizedEpoch
}
@@ -315,7 +316,7 @@ func (s *Store) updateCanonicalNodes(ctx context.Context, root [32]byte) error {
func (s *Store) insert(ctx context.Context,
slot uint64,
root, parent, graffiti [32]byte,
justifiedEpoch, finalizedEpoch uint64) error {
justifiedEpoch, finalizedEpoch types.Epoch) error {
ctx, span := trace.StartSpan(ctx, "protoArrayForkChoice.insert")
defer span.End()
@@ -367,7 +368,7 @@ func (s *Store) insert(ctx context.Context,
// and its best child. For each node, it updates the weight with input delta and
// back propagate the nodes delta to its parents delta. After scoring changes,
// the best child is then updated along with best descendant.
func (s *Store) applyWeightChanges(ctx context.Context, justifiedEpoch, finalizedEpoch uint64, delta []int) error {
func (s *Store) applyWeightChanges(ctx context.Context, justifiedEpoch, finalizedEpoch types.Epoch, delta []int) error {
ctx, span := trace.StartSpan(ctx, "protoArrayForkChoice.applyWeightChanges")
defer span.End()

View File

@@ -4,6 +4,7 @@ import (
"context"
"testing"
"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"
@@ -19,7 +20,7 @@ func TestStore_PruneThreshold(t *testing.T) {
}
func TestStore_JustifiedEpoch(t *testing.T) {
j := uint64(100)
j := types.Epoch(100)
s := &Store{
justifiedEpoch: j,
}
@@ -29,7 +30,7 @@ func TestStore_JustifiedEpoch(t *testing.T) {
}
func TestStore_FinalizedEpoch(t *testing.T) {
f := uint64(50)
f := types.Epoch(50)
s := &Store{
finalizedEpoch: f,
}
@@ -159,8 +160,8 @@ func TestStore_Insert_UnknownParent(t *testing.T) {
assert.Equal(t, 1, len(s.nodes), "Did not insert block")
assert.Equal(t, 1, len(s.nodesIndices), "Did not insert block")
assert.Equal(t, NonExistentNode, s.nodes[0].parent, "Incorrect parent")
assert.Equal(t, uint64(1), s.nodes[0].justifiedEpoch, "Incorrect justification")
assert.Equal(t, uint64(1), s.nodes[0].finalizedEpoch, "Incorrect finalization")
assert.Equal(t, types.Epoch(1), s.nodes[0].justifiedEpoch, "Incorrect justification")
assert.Equal(t, types.Epoch(1), s.nodes[0].finalizedEpoch, "Incorrect finalization")
assert.Equal(t, [32]byte{'A'}, s.nodes[0].root, "Incorrect root")
}
@@ -175,8 +176,8 @@ func TestStore_Insert_KnownParent(t *testing.T) {
assert.Equal(t, 2, len(s.nodes), "Did not insert block")
assert.Equal(t, 2, len(s.nodesIndices), "Did not insert block")
assert.Equal(t, uint64(0), s.nodes[1].parent, "Incorrect parent")
assert.Equal(t, uint64(1), s.nodes[1].justifiedEpoch, "Incorrect justification")
assert.Equal(t, uint64(1), s.nodes[1].finalizedEpoch, "Incorrect finalization")
assert.Equal(t, types.Epoch(1), s.nodes[1].justifiedEpoch, "Incorrect justification")
assert.Equal(t, types.Epoch(1), s.nodes[1].finalizedEpoch, "Incorrect finalization")
assert.Equal(t, [32]byte{'A'}, s.nodes[1].root, "Incorrect root")
}
@@ -193,8 +194,8 @@ func TestStore_ApplyScoreChanges_UpdateEpochs(t *testing.T) {
// The justified and finalized epochs in Store should be updated to 1 and 1 given the following input.
require.NoError(t, s.applyWeightChanges(context.Background(), 1, 1, []int{}))
assert.Equal(t, uint64(1), s.justifiedEpoch, "Did not update justified epoch")
assert.Equal(t, uint64(1), s.finalizedEpoch, "Did not update finalized epoch")
assert.Equal(t, types.Epoch(1), s.justifiedEpoch, "Did not update justified epoch")
assert.Equal(t, types.Epoch(1), s.finalizedEpoch, "Did not update finalized epoch")
}
func TestStore_ApplyScoreChanges_UpdateWeightsPositiveDelta(t *testing.T) {
@@ -419,8 +420,8 @@ func TestStore_Prune_MoreThanOnce(t *testing.T) {
func TestStore_LeadsToViableHead(t *testing.T) {
tests := []struct {
n *Node
justifiedEpoch uint64
finalizedEpoch uint64
justifiedEpoch types.Epoch
finalizedEpoch types.Epoch
want bool
}{
{&Node{}, 0, 0, true},
@@ -445,8 +446,8 @@ func TestStore_LeadsToViableHead(t *testing.T) {
func TestStore_ViableForHead(t *testing.T) {
tests := []struct {
n *Node
justifiedEpoch uint64
finalizedEpoch uint64
justifiedEpoch types.Epoch
finalizedEpoch types.Epoch
want bool
}{
{&Node{}, 0, 0, true},

View File

@@ -1,6 +1,10 @@
package protoarray
import "sync"
import (
"sync"
"github.com/prysmaticlabs/eth2-types"
)
// ForkChoice defines the overall fork choice store which includes all block nodes, validator's latest votes and balances.
type ForkChoice struct {
@@ -13,8 +17,8 @@ type ForkChoice struct {
// Store defines the fork choice store which includes block nodes and the last view of checkpoint information.
type Store struct {
pruneThreshold uint64 // do not prune tree unless threshold is reached.
justifiedEpoch uint64 // latest justified epoch in store.
finalizedEpoch uint64 // latest finalized epoch in store.
justifiedEpoch types.Epoch // latest justified epoch in store.
finalizedEpoch types.Epoch // latest finalized epoch in store.
finalizedRoot [32]byte // latest finalized root in store.
nodes []*Node // list of block nodes, each node is a representation of one block.
nodesIndices map[[32]byte]uint64 // the root of block node and the nodes index in the list.
@@ -25,22 +29,22 @@ type Store struct {
// Node defines the individual block which includes its block parent, ancestor and how much weight accounted for it.
// This is used as an array based stateful DAG for efficient fork choice look up.
type Node struct {
slot uint64 // slot of the block converted to the node.
root [32]byte // root of the block converted to the node.
parent uint64 // parent index of this node.
justifiedEpoch uint64 // justifiedEpoch of this node.
finalizedEpoch uint64 // finalizedEpoch of this node.
weight uint64 // weight of this node.
bestChild uint64 // bestChild index of this node.
bestDescendant uint64 // bestDescendant of this node.
graffiti [32]byte // graffiti of the block node.
slot uint64 // slot of the block converted to the node.
root [32]byte // root of the block converted to the node.
parent uint64 // parent index of this node.
justifiedEpoch types.Epoch // justifiedEpoch of this node.
finalizedEpoch types.Epoch // finalizedEpoch of this node.
weight uint64 // weight of this node.
bestChild uint64 // bestChild index of this node.
bestDescendant uint64 // bestDescendant of this node.
graffiti [32]byte // graffiti of the block node.
}
// Vote defines an individual validator's vote.
type Vote struct {
currentRoot [32]byte // current voting root.
nextRoot [32]byte // next voting root.
nextEpoch uint64 // epoch of next voting period.
currentRoot [32]byte // current voting root.
nextRoot [32]byte // next voting root.
nextEpoch types.Epoch // epoch of next voting period.
}
// NonExistentNode defines an unknown node which is used for the array based stateful DAG.

View File

@@ -43,6 +43,7 @@ go_library(
"//shared/version:go_default_library",
"@com_github_ethereum_go_ethereum//common:go_default_library",
"@com_github_pkg_errors//:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
"@com_github_urfave_cli_v2//:go_default_library",
"@in_gopkg_yaml_v2//:go_default_library",
@@ -62,6 +63,7 @@ go_test(
"//shared/cmd: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_sirupsen_logrus//hooks/test:go_default_library",
"@com_github_urfave_cli_v2//:go_default_library",
],

View File

@@ -6,11 +6,13 @@ import (
"fmt"
"strconv"
"strings"
"github.com/prysmaticlabs/eth2-types"
)
// Given input string `block_root:epoch_number`, this verifies the input string is valid, and
// returns the block root as bytes and epoch number as unsigned integers.
func convertWspInput(wsp string) ([]byte, uint64, error) {
func convertWspInput(wsp string) ([]byte, types.Epoch, error) {
if wsp == "" {
return nil, 0, nil
}
@@ -43,5 +45,5 @@ func convertWspInput(wsp string) ([]byte, uint64, error) {
return nil, 0, err
}
return bRoot, epoch, nil
return bRoot, types.Epoch(epoch), nil
}

View File

@@ -4,6 +4,7 @@ import (
"reflect"
"testing"
"github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
@@ -12,7 +13,7 @@ func TestConvertWspInput(t *testing.T) {
name string
input string
bRoot []byte
epoch uint64
epoch types.Epoch
wantErr bool
errStr string
}{

View File

@@ -159,6 +159,7 @@ go_test(
"@com_github_libp2p_go_libp2p_pubsub//pb:go_default_library",
"@com_github_libp2p_go_libp2p_swarm//testing:go_default_library",
"@com_github_multiformats_go_multiaddr//:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_prysmaticlabs_go_bitfield//:go_default_library",

View File

@@ -13,6 +13,7 @@ import (
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/enr"
ma "github.com/multiformats/go-multiaddr"
"github.com/prysmaticlabs/eth2-types"
mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
@@ -142,7 +143,7 @@ func TestStartDiscv5_SameForkDigests_DifferentNextForkData(t *testing.T) {
ipAddr, pkey := createAddrAndPrivKey(t)
c := params.BeaconConfig()
nextForkEpoch := uint64(i)
nextForkEpoch := types.Epoch(i)
c.NextForkEpoch = nextForkEpoch
params.OverrideBeaconConfig(c)
@@ -208,11 +209,11 @@ func TestStartDiscv5_SameForkDigests_DifferentNextForkData(t *testing.T) {
func TestDiscv5_AddRetrieveForkEntryENR(t *testing.T) {
params.SetupTestConfigCleanup(t)
c := params.BeaconConfig()
c.ForkVersionSchedule = map[uint64][]byte{
c.ForkVersionSchedule = map[types.Epoch][]byte{
0: params.BeaconConfig().GenesisForkVersion,
1: {0, 0, 0, 1},
}
nextForkEpoch := uint64(1)
nextForkEpoch := types.Epoch(1)
nextForkVersion := []byte{0, 0, 0, 1}
c.NextForkEpoch = nextForkEpoch
c.NextForkVersion = nextForkVersion

View File

@@ -19,6 +19,7 @@ go_library(
"@com_github_libp2p_go_libp2p_core//peer:go_default_library",
"@com_github_multiformats_go_multiaddr//:go_default_library",
"@com_github_multiformats_go_multiaddr//net:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_go_bitfield//:go_default_library",
],
)
@@ -44,6 +45,7 @@ go_test(
"@com_github_libp2p_go_libp2p_core//network:go_default_library",
"@com_github_libp2p_go_libp2p_core//peer:go_default_library",
"@com_github_multiformats_go_multiaddr//:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1:go_default_library",
"@com_github_prysmaticlabs_go_bitfield//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",

View File

@@ -33,6 +33,7 @@ import (
"github.com/libp2p/go-libp2p-core/peer"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr/net"
"github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers/peerdata"
@@ -545,10 +546,10 @@ func (p *Status) Prune() {
// Ideally, all peers would be reporting the same finalized epoch but some may be behind due to their
// own latency, or because of their finalized epoch at the time we queried them.
// Returns epoch number and list of peers that are at or beyond that epoch.
func (p *Status) BestFinalized(maxPeers int, ourFinalizedEpoch uint64) (uint64, []peer.ID) {
func (p *Status) BestFinalized(maxPeers int, ourFinalizedEpoch types.Epoch) (types.Epoch, []peer.ID) {
connected := p.Connected()
finalizedEpochVotes := make(map[uint64]uint64)
pidEpoch := make(map[peer.ID]uint64, len(connected))
finalizedEpochVotes := make(map[types.Epoch]uint64)
pidEpoch := make(map[peer.ID]types.Epoch, len(connected))
pidHead := make(map[peer.ID]uint64, len(connected))
potentialPIDs := make([]peer.ID, 0, len(connected))
for _, pid := range connected {
@@ -562,7 +563,7 @@ func (p *Status) BestFinalized(maxPeers int, ourFinalizedEpoch uint64) (uint64,
}
// Select the target epoch, which is the epoch most peers agree upon.
var targetEpoch uint64
var targetEpoch types.Epoch
var mostVotes uint64
for epoch, count := range finalizedEpochVotes {
if count > mostVotes || (count == mostVotes && epoch > targetEpoch) {
@@ -597,14 +598,14 @@ func (p *Status) BestFinalized(maxPeers int, ourFinalizedEpoch uint64) (uint64,
// BestNonFinalized returns the highest known epoch, higher than ours,
// and is shared by at least minPeers.
func (p *Status) BestNonFinalized(minPeers int, ourHeadEpoch uint64) (uint64, []peer.ID) {
func (p *Status) BestNonFinalized(minPeers int, ourHeadEpoch types.Epoch) (types.Epoch, []peer.ID) {
connected := p.Connected()
epochVotes := make(map[uint64]uint64)
pidEpoch := make(map[peer.ID]uint64, len(connected))
epochVotes := make(map[types.Epoch]uint64)
pidEpoch := make(map[peer.ID]types.Epoch, len(connected))
pidHead := make(map[peer.ID]uint64, len(connected))
potentialPIDs := make([]peer.ID, 0, len(connected))
ourHeadSlot := ourHeadEpoch * params.BeaconConfig().SlotsPerEpoch
ourHeadSlot := uint64(ourHeadEpoch.Mul(params.BeaconConfig().SlotsPerEpoch))
for _, pid := range connected {
peerChainState, err := p.ChainState(pid)
if err == nil && peerChainState != nil && peerChainState.HeadSlot > ourHeadSlot {
@@ -617,7 +618,7 @@ func (p *Status) BestNonFinalized(minPeers int, ourHeadEpoch uint64) (uint64, []
}
// Select the target epoch, which has enough peers' votes (>= minPeers).
var targetEpoch uint64
var targetEpoch types.Epoch
for epoch, votes := range epochVotes {
if votes >= uint64(minPeers) && targetEpoch < epoch {
targetEpoch = epoch
@@ -692,7 +693,7 @@ func (p *Status) PeersToPrune() []peer.ID {
}
// HighestEpoch returns the highest epoch reported epoch amongst peers.
func (p *Status) HighestEpoch() uint64 {
func (p *Status) HighestEpoch() types.Epoch {
p.store.RLock()
defer p.store.RUnlock()
var highestSlot uint64

View File

@@ -11,6 +11,7 @@ import (
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
ma "github.com/multiformats/go-multiaddr"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers"
@@ -286,7 +287,7 @@ func TestPeerChainState(t *testing.T) {
oldChainStartLastUpdated, err := p.ChainStateLastUpdated(id)
require.NoError(t, err)
finalizedEpoch := uint64(123)
finalizedEpoch := types.Epoch(123)
p.SetChainState(id, &pb.Status{FinalizedEpoch: finalizedEpoch})
resChainState, err := p.ChainState(id)
@@ -568,7 +569,7 @@ func TestTrimmedOrderedPeers(t *testing.T) {
},
})
expectedTarget := uint64(2)
expectedTarget := types.Epoch(2)
maxPeers := 3
mockroot2 := [32]byte{}
mockroot3 := [32]byte{}
@@ -721,14 +722,14 @@ func TestPrunePeers(t *testing.T) {
func TestStatus_BestPeer(t *testing.T) {
type peerConfig struct {
headSlot uint64
finalizedEpoch uint64
finalizedEpoch types.Epoch
}
tests := []struct {
name string
peers []*peerConfig
limitPeers int
ourFinalizedEpoch uint64
targetEpoch uint64
ourFinalizedEpoch types.Epoch
targetEpoch types.Epoch
// targetEpochSupport denotes how many peers support returned epoch.
targetEpochSupport int
}{
@@ -915,7 +916,7 @@ func TestStatus_BestNonFinalized(t *testing.T) {
})
}
expectedEpoch := uint64(8)
expectedEpoch := types.Epoch(8)
retEpoch, pids := p.BestNonFinalized(3, 5)
assert.Equal(t, expectedEpoch, retEpoch, "Incorrect Finalized epoch retrieved")
assert.Equal(t, 3, len(pids), "Unexpected number of peers")
@@ -947,7 +948,7 @@ func TestStatus_CurrentEpoch(t *testing.T) {
HeadSlot: params.BeaconConfig().SlotsPerEpoch * 4,
})
assert.Equal(t, uint64(5), p.HighestEpoch(), "Expected current epoch to be 5")
assert.Equal(t, types.Epoch(5), p.HighestEpoch(), "Expected current epoch to be 5")
}
func TestInbound(t *testing.T) {

View File

@@ -60,7 +60,7 @@ func (m *MockPeersProvider) Peers() *peers.Status {
}
m.peers.Add(createENR(), id0, ma0, network.DirInbound)
m.peers.SetConnectionState(id0, peers.PeerConnected)
m.peers.SetChainState(id0, &pb.Status{FinalizedEpoch: uint64(10)})
m.peers.SetChainState(id0, &pb.Status{FinalizedEpoch: 10})
id1, err := peer.Decode("16Uiu2HAm4HgJ9N1o222xK61o7LSgToYWoAy1wNTJRkh9gLZapVAy")
if err != nil {
log.WithError(err).Debug("Cannot decode")
@@ -71,7 +71,7 @@ func (m *MockPeersProvider) Peers() *peers.Status {
}
m.peers.Add(createENR(), id1, ma1, network.DirOutbound)
m.peers.SetConnectionState(id1, peers.PeerConnected)
m.peers.SetChainState(id1, &pb.Status{FinalizedEpoch: uint64(11)})
m.peers.SetChainState(id1, &pb.Status{FinalizedEpoch: 11})
}
return m.peers
}

View File

@@ -53,6 +53,7 @@ go_library(
"@com_github_patrickmn_go_cache//: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",
"@org_golang_google_grpc//codes:go_default_library",
@@ -107,6 +108,7 @@ go_test(
"@com_github_gogo_protobuf//proto:go_default_library",
"@com_github_gogo_protobuf//types:go_default_library",
"@com_github_golang_mock//gomock: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",
"@in_gopkg_d4l3k_messagediff_v1//:go_default_library",

View File

@@ -4,6 +4,7 @@ import (
"context"
"strconv"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
@@ -30,7 +31,7 @@ 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)
var requestedEpoch uint64
var requestedEpoch types.Epoch
switch q := req.QueryFilter.(type) {
case *ethpb.ListValidatorAssignmentsRequest_Genesis:
if q.Genesis {

View File

@@ -11,6 +11,7 @@ import (
"github.com/gogo/protobuf/proto"
ptypes "github.com/gogo/protobuf/types"
"github.com/golang/mock/gomock"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield"
chainMock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing"
@@ -150,9 +151,9 @@ func TestServer_ListAttestations_FiltersCorrectly(t *testing.T) {
someRoot := [32]byte{1, 2, 3}
sourceRoot := [32]byte{4, 5, 6}
sourceEpoch := uint64(5)
sourceEpoch := types.Epoch(5)
targetRoot := [32]byte{7, 8, 9}
targetEpoch := uint64(7)
targetEpoch := types.Epoch(7)
blocks := []*ethpb.SignedBeaconBlock{
testutil.HydrateSignedBeaconBlock(&ethpb.SignedBeaconBlock{
@@ -600,7 +601,7 @@ func TestServer_ListIndexedAttestations_OldEpoch(t *testing.T) {
blockRoot := bytesutil.ToBytes32([]byte("root"))
count := params.BeaconConfig().SlotsPerEpoch
atts := make([]*ethpb.Attestation, 0, count)
epoch := uint64(50)
epoch := types.Epoch(50)
startSlot, err := helpers.StartSlot(epoch)
require.NoError(t, err)
@@ -660,7 +661,7 @@ func TestServer_ListIndexedAttestations_OldEpoch(t *testing.T) {
}
err = db.SaveStateSummary(ctx, &pbp2p.StateSummary{
Root: blockRoot[:],
Slot: epoch * params.BeaconConfig().SlotsPerEpoch,
Slot: uint64(epoch) * params.BeaconConfig().SlotsPerEpoch,
})
require.NoError(t, err)
require.NoError(t, db.SaveState(ctx, state, bytesutil.ToBytes32([]byte("root"))))
@@ -857,10 +858,10 @@ func TestServer_StreamIndexedAttestations_OK(t *testing.T) {
activeIndices, err := helpers.ActiveValidatorIndices(headState, 0)
require.NoError(t, err)
epoch := uint64(0)
epoch := types.Epoch(0)
attesterSeed, err := helpers.Seed(headState, epoch, params.BeaconConfig().DomainBeaconAttester)
require.NoError(t, err)
committees, err := computeCommittees(epoch*params.BeaconConfig().SlotsPerEpoch, activeIndices, attesterSeed)
committees, err := computeCommittees(uint64(epoch)*params.BeaconConfig().SlotsPerEpoch, activeIndices, attesterSeed)
require.NoError(t, err)
count := params.BeaconConfig().SlotsPerEpoch

View File

@@ -9,6 +9,7 @@ import (
"github.com/gogo/protobuf/proto"
ptypes "github.com/gogo/protobuf/types"
"github.com/golang/mock/gomock"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
chainMock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
@@ -411,9 +412,9 @@ func TestServer_GetChainHead(t *testing.T) {
head, err := bs.GetChainHead(context.Background(), nil)
require.NoError(t, err)
assert.Equal(t, uint64(3), head.PreviousJustifiedEpoch, "Unexpected PreviousJustifiedEpoch")
assert.Equal(t, uint64(2), head.JustifiedEpoch, "Unexpected JustifiedEpoch")
assert.Equal(t, uint64(1), head.FinalizedEpoch, "Unexpected FinalizedEpoch")
assert.Equal(t, types.Epoch(3), head.PreviousJustifiedEpoch, "Unexpected PreviousJustifiedEpoch")
assert.Equal(t, types.Epoch(2), head.JustifiedEpoch, "Unexpected JustifiedEpoch")
assert.Equal(t, types.Epoch(1), head.FinalizedEpoch, "Unexpected FinalizedEpoch")
assert.Equal(t, uint64(24), head.PreviousJustifiedSlot, "Unexpected PreviousJustifiedSlot")
assert.Equal(t, uint64(16), head.JustifiedSlot, "Unexpected JustifiedSlot")
assert.Equal(t, uint64(8), head.FinalizedSlot, "Unexpected FinalizedSlot")
@@ -696,9 +697,9 @@ func TestServer_GetWeakSubjectivityCheckpoint(t *testing.T) {
c, err := server.GetWeakSubjectivityCheckpoint(ctx, &ptypes.Empty{})
require.NoError(t, err)
e := uint64(256)
e := types.Epoch(256)
require.Equal(t, e, c.Epoch)
wsState, err := server.StateGen.StateBySlot(ctx, e*params.BeaconConfig().SlotsPerEpoch)
wsState, err := server.StateGen.StateBySlot(ctx, uint64(e)*params.BeaconConfig().SlotsPerEpoch)
require.NoError(t, err)
sRoot, err := wsState.HashTreeRoot(ctx)
require.NoError(t, err)

View File

@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
@@ -65,7 +66,7 @@ func (bs *Server) ListBeaconCommittees(
func (bs *Server) retrieveCommitteesForEpoch(
ctx context.Context,
epoch uint64,
epoch types.Epoch,
) (map[uint64]*ethpb.BeaconCommittees_CommitteesList, []uint64, error) {
startSlot, err := helpers.StartSlot(epoch)
if err != nil {

View File

@@ -8,6 +8,7 @@ import (
"time"
ptypes "github.com/gogo/protobuf/types"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
@@ -388,7 +389,7 @@ func (bs *Server) GetValidatorActiveSetChanges(
) (*ethpb.ActiveSetChanges, error) {
currentEpoch := helpers.SlotToEpoch(bs.GenesisTimeFetcher.CurrentSlot())
var requestedEpoch uint64
var requestedEpoch types.Epoch
switch q := req.QueryFilter.(type) {
case *ethpb.GetValidatorActiveSetChangesRequest_Genesis:
requestedEpoch = 0
@@ -474,7 +475,7 @@ func (bs *Server) GetValidatorParticipation(
currentSlot := bs.GenesisTimeFetcher.CurrentSlot()
currentEpoch := helpers.SlotToEpoch(currentSlot)
var requestedEpoch uint64
var requestedEpoch types.Epoch
switch q := req.QueryFilter.(type) {
case *ethpb.GetValidatorParticipationRequest_Genesis:
requestedEpoch = 0
@@ -561,7 +562,7 @@ 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)
exitEpochs := make([]uint64, 0)
exitEpochs := make([]types.Epoch, 0)
activationQ := make([]uint64, 0)
vals := headState.Validators()
for idx, validator := range vals {
@@ -592,7 +593,7 @@ func (bs *Server) GetValidatorQueue(
return nil, status.Errorf(codes.Internal, "Could not compute churn limit: %v", err)
}
exitQueueEpoch := uint64(0)
exitQueueEpoch := types.Epoch(0)
for _, i := range exitEpochs {
if exitQueueEpoch < i {
exitQueueEpoch = i
@@ -877,7 +878,7 @@ func (bs *Server) isSlotCanonical(ctx context.Context, slot uint64) (bool, error
}
// Determines whether a validator has already exited.
func validatorHasExited(validator *ethpb.Validator, currentEpoch uint64) bool {
func validatorHasExited(validator *ethpb.Validator, currentEpoch types.Epoch) bool {
farFutureEpoch := params.BeaconConfig().FarFutureEpoch
if currentEpoch < validator.ActivationEligibilityEpoch {
return false
@@ -897,7 +898,7 @@ func validatorHasExited(validator *ethpb.Validator, currentEpoch uint64) bool {
return true
}
func validatorStatus(validator *ethpb.Validator, epoch uint64) ethpb.ValidatorStatus {
func validatorStatus(validator *ethpb.Validator, epoch types.Epoch) ethpb.ValidatorStatus {
farFutureEpoch := params.BeaconConfig().FarFutureEpoch
if validator == nil {
return ethpb.ValidatorStatus_UNKNOWN_STATUS

View File

@@ -13,6 +13,7 @@ import (
"github.com/patrickmn/go-cache"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/blockchain"
"github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache"
@@ -44,7 +45,7 @@ type infostream struct {
eth1DepositsMutex *sync.RWMutex
eth1Blocktimes *cache.Cache
eth1BlocktimesMutex *sync.RWMutex
currentEpoch uint64
currentEpoch types.Epoch
stream ethpb.BeaconChain_StreamValidatorsInfoServer
genesisTime uint64
}
@@ -117,7 +118,7 @@ func (bs *Server) StreamValidatorsInfo(stream ethpb.BeaconChain_StreamValidators
eth1DepositsMutex: &sync.RWMutex{},
eth1Blocktimes: cache.New(epochDuration*12, epochDuration*24),
eth1BlocktimesMutex: &sync.RWMutex{},
currentEpoch: headState.Slot() / params.BeaconConfig().SlotsPerEpoch,
currentEpoch: types.Epoch(headState.Slot() / params.BeaconConfig().SlotsPerEpoch),
stream: stream,
genesisTime: headState.GenesisTime(),
}
@@ -262,7 +263,7 @@ func (is *infostream) generateValidatorsInfo(pubKeys [][]byte) ([]*ethpb.Validat
if headState == nil {
return nil, status.Error(codes.Internal, "Not ready to serve information")
}
epoch := headState.Slot() / params.BeaconConfig().SlotsPerEpoch
epoch := types.Epoch(headState.Slot() / params.BeaconConfig().SlotsPerEpoch)
if epoch == 0 {
// Not reporting, but no error.
return nil, nil
@@ -297,7 +298,7 @@ func (is *infostream) generateValidatorsInfo(pubKeys [][]byte) ([]*ethpb.Validat
}
// generateValidatorInfo generates the validator info for a public key.
func (is *infostream) generateValidatorInfo(pubKey []byte, validator state.ReadOnlyValidator, headState *state.BeaconState, epoch uint64) (*ethpb.ValidatorInfo, error) {
func (is *infostream) generateValidatorInfo(pubKey []byte, validator state.ReadOnlyValidator, headState *state.BeaconState, epoch types.Epoch) (*ethpb.ValidatorInfo, error) {
info := &ethpb.ValidatorInfo{
PublicKey: pubKey,
Epoch: epoch,
@@ -367,7 +368,7 @@ func (is *infostream) generatePendingValidatorInfo(info *ethpb.ValidatorInfo) (*
return info, nil
}
func (is *infostream) calculateActivationTimeForPendingValidators(res []*ethpb.ValidatorInfo, headState *state.BeaconState, epoch uint64) error {
func (is *infostream) calculateActivationTimeForPendingValidators(res []*ethpb.ValidatorInfo, headState *state.BeaconState, epoch types.Epoch) error {
// pendingValidatorsMap is map from the validator pubkey to the index in our return array
pendingValidatorsMap := make(map[[48]byte]int)
for i, info := range res {
@@ -448,7 +449,7 @@ func (is *infostream) handleBlockProcessed() {
// We aren't ready to serve information
return
}
blockEpoch := headState.Slot() / params.BeaconConfig().SlotsPerEpoch
blockEpoch := types.Epoch(headState.Slot() / params.BeaconConfig().SlotsPerEpoch)
if blockEpoch == is.currentEpoch {
// Epoch hasn't changed, nothing to report yet.
return
@@ -470,7 +471,7 @@ func (s indicesSorter) Less(i, j int) bool {
return s.indices[i] < s.indices[j]
}
func (is *infostream) calculateStatusAndTransition(validator state.ReadOnlyValidator, currentEpoch uint64) (ethpb.ValidatorStatus, uint64) {
func (is *infostream) calculateStatusAndTransition(validator state.ReadOnlyValidator, currentEpoch types.Epoch) (ethpb.ValidatorStatus, uint64) {
farFutureEpoch := params.BeaconConfig().FarFutureEpoch
if validator.IsNil() {
@@ -499,8 +500,8 @@ func (is *infostream) calculateStatusAndTransition(validator state.ReadOnlyValid
}
// epochToTimestamp converts an epoch number to a timestamp.
func (is *infostream) epochToTimestamp(epoch uint64) uint64 {
return is.genesisTime + epoch*params.BeaconConfig().SecondsPerSlot*params.BeaconConfig().SlotsPerEpoch
func (is *infostream) epochToTimestamp(epoch types.Epoch) uint64 {
return is.genesisTime + uint64(epoch)*params.BeaconConfig().SecondsPerSlot*params.BeaconConfig().SlotsPerEpoch
}
// depositQueueTimestamp calculates the timestamp for exit of the validator from the deposit queue.
@@ -531,7 +532,7 @@ func (is *infostream) depositQueueTimestamp(eth1BlockNumber *big.Int) (uint64, e
followTime := time.Duration(params.BeaconConfig().Eth1FollowDistance*params.BeaconConfig().SecondsPerETH1Block) * time.Second
eth1UnixTime := time.Unix(int64(blockTimestamp), 0).Add(followTime)
period := params.BeaconConfig().SlotsPerEpoch * params.BeaconConfig().EpochsPerEth1VotingPeriod
period := uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod.Mul(params.BeaconConfig().SlotsPerEpoch))
votingPeriod := time.Duration(period*params.BeaconConfig().SecondsPerSlot) * time.Second
activationTime := eth1UnixTime.Add(votingPeriod)
eth2Genesis := time.Unix(int64(is.genesisTime), 0)

View File

@@ -4,6 +4,7 @@ import (
"sync"
"testing"
"github.com/prysmaticlabs/eth2-types"
mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil"
@@ -16,7 +17,7 @@ func TestInfostream_EpochToTimestamp(t *testing.T) {
params.OverrideBeaconConfig(params.MainnetConfig())
tests := []struct {
name string
epoch uint64
epoch types.Epoch
timestamp uint64
}{
{

View File

@@ -11,6 +11,7 @@ import (
"github.com/gogo/protobuf/proto"
ptypes "github.com/gogo/protobuf/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"
@@ -968,11 +969,11 @@ func TestServer_ListValidators_FromOldEpoch(t *testing.T) {
beaconDB := dbTest.SetupDB(t)
ctx := context.Background()
numEpochs := 30
numEpochs := types.Epoch(30)
validators := make([]*ethpb.Validator, numEpochs)
for i := 0; i < numEpochs; i++ {
for i := types.Epoch(0); i < numEpochs; i++ {
validators[i] = &ethpb.Validator{
ActivationEpoch: uint64(i),
ActivationEpoch: i,
PublicKey: make([]byte, 48),
WithdrawalCredentials: make([]byte, 32),
}
@@ -1089,11 +1090,11 @@ func TestServer_ListValidators_ProcessHeadStateSlots(t *testing.T) {
}
func TestServer_GetValidator(t *testing.T) {
count := 30
count := types.Epoch(30)
validators := make([]*ethpb.Validator, count)
for i := 0; i < count; i++ {
for i := types.Epoch(0); i < count; i++ {
validators[i] = &ethpb.Validator{
ActivationEpoch: uint64(i),
ActivationEpoch: i,
PublicKey: pubKey(uint64(i)),
WithdrawalCredentials: make([]byte, 32),
}
@@ -1359,7 +1360,7 @@ func TestServer_GetValidatorQueue_ExitedValidatorLeavesQueue(t *testing.T) {
// Now, we move the state.slot past the exit epoch of the validator, and now
// the validator should no longer exist in the queue.
require.NoError(t, headState.SetSlot((validators[1].ExitEpoch+1)*params.BeaconConfig().SlotsPerEpoch))
require.NoError(t, headState.SetSlot(uint64(validators[1].ExitEpoch+1)*params.BeaconConfig().SlotsPerEpoch))
res, err = bs.GetValidatorQueue(context.Background(), &ptypes.Empty{})
require.NoError(t, err)
assert.Equal(t, 0, len(res.ExitPublicKeys))
@@ -1451,8 +1452,8 @@ func TestServer_GetValidatorParticipation_UnknownState(t *testing.T) {
headState, err := testutil.NewBeaconState()
require.NoError(t, err)
require.NoError(t, headState.SetSlot(0))
epoch := uint64(50)
slots := epoch * params.BeaconConfig().SlotsPerEpoch
epoch := types.Epoch(50)
slots := uint64(epoch) * params.BeaconConfig().SlotsPerEpoch
bs := &Server{
BeaconDB: beaconDB,
HeadFetcher: &mock.ChainService{
@@ -1642,10 +1643,10 @@ func TestGetValidatorPerformance_Syncing(t *testing.T) {
func TestGetValidatorPerformance_OK(t *testing.T) {
ctx := context.Background()
epoch := uint64(1)
epoch := types.Epoch(1)
headState, err := testutil.NewBeaconState()
require.NoError(t, err)
require.NoError(t, headState.SetSlot((epoch+1)*params.BeaconConfig().SlotsPerEpoch))
require.NoError(t, headState.SetSlot(uint64(epoch+1)*params.BeaconConfig().SlotsPerEpoch))
atts := make([]*pb.PendingAttestation, 3)
for i := 0; i < len(atts); i++ {
atts[i] = &pb.PendingAttestation{
@@ -1693,7 +1694,7 @@ func TestGetValidatorPerformance_OK(t *testing.T) {
GenesisTimeFetcher: &mock.ChainService{Genesis: time.Now().Add(time.Duration(-1*int64(headState.Slot()*params.BeaconConfig().SecondsPerSlot)) * time.Second)},
SyncChecker: &mockSync.Sync{IsSyncing: false},
}
farFuture := params.BeaconConfig().FarFutureEpoch
farFuture := uint64(params.BeaconConfig().FarFutureEpoch)
want := &ethpb.ValidatorPerformanceResponse{
PublicKeys: [][]byte{publicKey2[:], publicKey3[:]},
CurrentEffectiveBalances: []uint64{params.BeaconConfig().MaxEffectiveBalance, params.BeaconConfig().MaxEffectiveBalance},
@@ -1718,12 +1719,12 @@ func TestGetValidatorPerformance_OK(t *testing.T) {
func TestGetValidatorPerformance_Indices(t *testing.T) {
ctx := context.Background()
epoch := uint64(1)
epoch := types.Epoch(1)
defaultBal := params.BeaconConfig().MaxEffectiveBalance
extraBal := params.BeaconConfig().MaxEffectiveBalance + params.BeaconConfig().GweiPerEth
headState, err := testutil.NewBeaconState()
require.NoError(t, err)
require.NoError(t, headState.SetSlot((epoch+1)*params.BeaconConfig().SlotsPerEpoch))
require.NoError(t, headState.SetSlot(uint64(epoch+1)*params.BeaconConfig().SlotsPerEpoch))
balances := []uint64{defaultBal, extraBal, extraBal + params.BeaconConfig().GweiPerEth}
require.NoError(t, headState.SetBalances(balances))
publicKey1 := bytesutil.ToBytes48([]byte{1})
@@ -1764,7 +1765,7 @@ func TestGetValidatorPerformance_Indices(t *testing.T) {
require.NoError(t, err)
_, err = precompute.ProcessRewardsAndPenaltiesPrecompute(c, bp, vp)
require.NoError(t, err)
farFuture := params.BeaconConfig().FarFutureEpoch
farFuture := uint64(params.BeaconConfig().FarFutureEpoch)
want := &ethpb.ValidatorPerformanceResponse{
PublicKeys: [][]byte{publicKey2[:], publicKey3[:]},
CurrentEffectiveBalances: []uint64{params.BeaconConfig().MaxEffectiveBalance, params.BeaconConfig().MaxEffectiveBalance},
@@ -1789,12 +1790,12 @@ func TestGetValidatorPerformance_Indices(t *testing.T) {
func TestGetValidatorPerformance_IndicesPubkeys(t *testing.T) {
ctx := context.Background()
epoch := uint64(1)
epoch := types.Epoch(1)
defaultBal := params.BeaconConfig().MaxEffectiveBalance
extraBal := params.BeaconConfig().MaxEffectiveBalance + params.BeaconConfig().GweiPerEth
headState, err := testutil.NewBeaconState()
require.NoError(t, err)
require.NoError(t, headState.SetSlot((epoch+1)*params.BeaconConfig().SlotsPerEpoch))
require.NoError(t, headState.SetSlot(uint64(epoch+1)*params.BeaconConfig().SlotsPerEpoch))
balances := []uint64{defaultBal, extraBal, extraBal + params.BeaconConfig().GweiPerEth}
require.NoError(t, headState.SetBalances(balances))
publicKey1 := bytesutil.ToBytes48([]byte{1})
@@ -1836,7 +1837,7 @@ func TestGetValidatorPerformance_IndicesPubkeys(t *testing.T) {
require.NoError(t, err)
_, err = precompute.ProcessRewardsAndPenaltiesPrecompute(c, bp, vp)
require.NoError(t, err)
farFuture := params.BeaconConfig().FarFutureEpoch
farFuture := uint64(params.BeaconConfig().FarFutureEpoch)
want := &ethpb.ValidatorPerformanceResponse{
PublicKeys: [][]byte{publicKey2[:], publicKey3[:]},
CurrentEffectiveBalances: []uint64{params.BeaconConfig().MaxEffectiveBalance, params.BeaconConfig().MaxEffectiveBalance},
@@ -2040,10 +2041,24 @@ func TestServer_GetIndividualVotes_Working(t *testing.T) {
require.NoError(t, err)
wanted := &ethpb.IndividualVotesRespond{
IndividualVotes: []*ethpb.IndividualVotesRespond_IndividualVote{
{ValidatorIndex: 0, PublicKey: beaconState.Validators()[0].PublicKey, IsActiveInCurrentEpoch: true, IsActiveInPreviousEpoch: true,
CurrentEpochEffectiveBalanceGwei: params.BeaconConfig().MaxEffectiveBalance, InclusionSlot: params.BeaconConfig().FarFutureEpoch, InclusionDistance: params.BeaconConfig().FarFutureEpoch},
{ValidatorIndex: 1, PublicKey: beaconState.Validators()[1].PublicKey, IsActiveInCurrentEpoch: true, IsActiveInPreviousEpoch: true,
CurrentEpochEffectiveBalanceGwei: params.BeaconConfig().MaxEffectiveBalance, InclusionSlot: params.BeaconConfig().FarFutureEpoch, InclusionDistance: params.BeaconConfig().FarFutureEpoch},
{
ValidatorIndex: 0,
PublicKey: beaconState.Validators()[0].PublicKey,
IsActiveInCurrentEpoch: true,
IsActiveInPreviousEpoch: true,
CurrentEpochEffectiveBalanceGwei: params.BeaconConfig().MaxEffectiveBalance,
InclusionSlot: uint64(params.BeaconConfig().FarFutureEpoch),
InclusionDistance: uint64(params.BeaconConfig().FarFutureEpoch),
},
{
ValidatorIndex: 1,
PublicKey: beaconState.Validators()[1].PublicKey,
IsActiveInCurrentEpoch: true,
IsActiveInPreviousEpoch: true,
CurrentEpochEffectiveBalanceGwei: params.BeaconConfig().MaxEffectiveBalance,
InclusionSlot: uint64(params.BeaconConfig().FarFutureEpoch),
InclusionDistance: uint64(params.BeaconConfig().FarFutureEpoch),
},
},
}
assert.DeepEqual(t, wanted, res, "Unexpected response")
@@ -2053,7 +2068,7 @@ func Test_validatorStatus(t *testing.T) {
tests := []struct {
name string
validator *ethpb.Validator
epoch uint64
epoch types.Epoch
want ethpb.ValidatorStatus
}{
{
@@ -2065,7 +2080,7 @@ func Test_validatorStatus(t *testing.T) {
{
name: "Deposited",
validator: &ethpb.Validator{
ActivationEligibilityEpoch: uint64(1),
ActivationEligibilityEpoch: 1,
},
epoch: 0,
want: ethpb.ValidatorStatus_DEPOSITED,
@@ -2073,8 +2088,8 @@ func Test_validatorStatus(t *testing.T) {
{
name: "Pending",
validator: &ethpb.Validator{
ActivationEligibilityEpoch: uint64(0),
ActivationEpoch: uint64(1),
ActivationEligibilityEpoch: 0,
ActivationEpoch: 1,
},
epoch: 0,
want: ethpb.ValidatorStatus_PENDING,
@@ -2082,8 +2097,8 @@ func Test_validatorStatus(t *testing.T) {
{
name: "Active",
validator: &ethpb.Validator{
ActivationEligibilityEpoch: uint64(0),
ActivationEpoch: uint64(0),
ActivationEligibilityEpoch: 0,
ActivationEpoch: 0,
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
},
epoch: 0,
@@ -2092,9 +2107,9 @@ func Test_validatorStatus(t *testing.T) {
{
name: "Slashed",
validator: &ethpb.Validator{
ActivationEligibilityEpoch: uint64(0),
ActivationEpoch: uint64(0),
ExitEpoch: uint64(5),
ActivationEligibilityEpoch: 0,
ActivationEpoch: 0,
ExitEpoch: 5,
Slashed: true,
},
epoch: 4,
@@ -2103,9 +2118,9 @@ func Test_validatorStatus(t *testing.T) {
{
name: "Exiting",
validator: &ethpb.Validator{
ActivationEligibilityEpoch: uint64(0),
ActivationEpoch: uint64(0),
ExitEpoch: uint64(5),
ActivationEligibilityEpoch: 0,
ActivationEpoch: 0,
ExitEpoch: 5,
Slashed: false,
},
epoch: 4,
@@ -2114,9 +2129,9 @@ func Test_validatorStatus(t *testing.T) {
{
name: "Exiting",
validator: &ethpb.Validator{
ActivationEligibilityEpoch: uint64(0),
ActivationEpoch: uint64(0),
ExitEpoch: uint64(3),
ActivationEligibilityEpoch: 0,
ActivationEpoch: 0,
ExitEpoch: 3,
Slashed: false,
},
epoch: 4,

View File

@@ -36,6 +36,7 @@ go_library(
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_gogo_protobuf//types:go_default_library",
"@com_github_pkg_errors//:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
@@ -68,6 +69,7 @@ go_test(
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
"@com_github_gogo_protobuf//types:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
],

View File

@@ -10,6 +10,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
ptypes "github.com/gogo/protobuf/types"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1"
"github.com/prysmaticlabs/prysm/shared/params"
"go.opencensus.io/trace"
@@ -79,8 +80,8 @@ func (bs *Server) GetDepositContract(ctx context.Context, _ *ptypes.Empty) (*eth
}, nil
}
func sortedEpochs(forkSchedule map[uint64][]byte) []uint64 {
sortedEpochs := make([]uint64, len(forkSchedule))
func sortedEpochs(forkSchedule map[types.Epoch][]byte) []types.Epoch {
sortedEpochs := make([]types.Epoch, len(forkSchedule))
i := 0
for k := range forkSchedule {
sortedEpochs[i] = k

View File

@@ -4,7 +4,8 @@ import (
"context"
"testing"
"github.com/gogo/protobuf/types"
pbtypes "github.com/gogo/protobuf/types"
"github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
@@ -93,7 +94,7 @@ func TestGetSpec(t *testing.T) {
params.OverrideBeaconConfig(config)
server := &Server{}
resp, err := server.GetSpec(context.Background(), &types.Empty{})
resp, err := server.GetSpec(context.Background(), &pbtypes.Empty{})
require.NoError(t, err)
assert.Equal(t, 60, len(resp.Data))
@@ -235,7 +236,7 @@ func TestGetDepositContract(t *testing.T) {
params.OverrideBeaconConfig(config)
s := Server{}
resp, err := s.GetDepositContract(context.Background(), &types.Empty{})
resp, err := s.GetDepositContract(context.Background(), &pbtypes.Empty{})
require.NoError(t, err)
assert.Equal(t, uint64(chainId), resp.Data.ChainId)
assert.Equal(t, address, resp.Data.Address)
@@ -243,15 +244,15 @@ func TestGetDepositContract(t *testing.T) {
func TestForkSchedule_Ok(t *testing.T) {
genesisForkVersion := []byte("Genesis")
firstForkVersion, firstForkEpoch := []byte("First"), uint64(100)
secondForkVersion, secondForkEpoch := []byte("Second"), uint64(200)
thirdForkVersion, thirdForkEpoch := []byte("Third"), uint64(300)
firstForkVersion, firstForkEpoch := []byte("First"), types.Epoch(100)
secondForkVersion, secondForkEpoch := []byte("Second"), types.Epoch(200)
thirdForkVersion, thirdForkEpoch := []byte("Third"), types.Epoch(300)
params.SetupTestConfigCleanup(t)
config := params.BeaconConfig()
config.GenesisForkVersion = genesisForkVersion
// Create fork schedule adding keys in non-sorted order.
schedule := make(map[uint64][]byte, 3)
schedule := make(map[types.Epoch][]byte, 3)
schedule[secondForkEpoch] = secondForkVersion
schedule[firstForkEpoch] = firstForkVersion
schedule[thirdForkEpoch] = thirdForkVersion
@@ -259,7 +260,7 @@ func TestForkSchedule_Ok(t *testing.T) {
params.OverrideBeaconConfig(config)
s := &Server{}
resp, err := s.GetForkSchedule(context.Background(), &types.Empty{})
resp, err := s.GetForkSchedule(context.Background(), &pbtypes.Empty{})
require.NoError(t, err)
require.Equal(t, 3, len(resp.Data))
fork := resp.Data[0]
@@ -278,7 +279,7 @@ func TestForkSchedule_Ok(t *testing.T) {
func TestForkSchedule_NoForks(t *testing.T) {
s := &Server{}
resp, err := s.GetForkSchedule(context.Background(), &types.Empty{})
resp, err := s.GetForkSchedule(context.Background(), &pbtypes.Empty{})
require.NoError(t, err)
assert.Equal(t, 0, len(resp.Data))
}

View File

@@ -29,12 +29,15 @@ func (bs *Server) GetGenesis(ctx context.Context, _ *ptypes.Empty) (*ethpb.Genes
forkVersion := params.BeaconConfig().GenesisForkVersion
return &ethpb.GenesisResponse{
GenesisTime: &ptypes.Timestamp{
Seconds: genesisTime.Unix(),
Nanos: 0,
Data: &ethpb.GenesisResponse_Genesis{
GenesisTime: &ptypes.Timestamp{
Seconds: genesisTime.Unix(),
Nanos: 0,
},
GenesisValidatorsRoot: validatorRoot[:],
GenesisForkVersion: forkVersion,
},
GenesisValidatorsRoot: validatorRoot[:],
GenesisForkVersion: forkVersion,
}, nil
}

View File

@@ -31,10 +31,10 @@ func TestGetGenesis(t *testing.T) {
}
resp, err := s.GetGenesis(context.Background(), &ptypes.Empty{})
require.NoError(t, err)
assert.Equal(t, genesis.Unix(), resp.GenesisTime.Seconds)
assert.Equal(t, int32(0), resp.GenesisTime.Nanos)
assert.DeepEqual(t, validatorsRoot[:], resp.GenesisValidatorsRoot)
assert.DeepEqual(t, []byte("genesis"), resp.GenesisForkVersion)
assert.Equal(t, genesis.Unix(), resp.Data.GenesisTime.Seconds)
assert.Equal(t, int32(0), resp.Data.GenesisTime.Nanos)
assert.DeepEqual(t, validatorsRoot[:], resp.Data.GenesisValidatorsRoot)
assert.DeepEqual(t, []byte("genesis"), resp.Data.GenesisForkVersion)
})
t.Run("No genesis time", func(t *testing.T) {

View File

@@ -82,5 +82,5 @@ func TestServer_GetAttestationInclusionSlot(t *testing.T) {
require.Equal(t, b.Block.Slot, res.Slot)
res, err = bs.GetInclusionSlot(ctx, &pbrpc.InclusionSlotRequest{Slot: 1, Id: 9999999})
require.NoError(t, err)
require.Equal(t, params.BeaconConfig().FarFutureEpoch, res.Slot)
require.Equal(t, uint64(params.BeaconConfig().FarFutureEpoch), res.Slot)
}

View File

@@ -54,6 +54,7 @@ go_library(
"@com_github_ferranbt_fastssz//:go_default_library",
"@com_github_gogo_protobuf//types: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//trace:go_default_library",
@@ -114,6 +115,7 @@ go_test(
"@com_github_gogo_protobuf//proto:go_default_library",
"@com_github_gogo_protobuf//types:go_default_library",
"@com_github_golang_mock//gomock: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",
"@com_github_sirupsen_logrus//:go_default_library",

View File

@@ -4,6 +4,7 @@ import (
"context"
"time"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
@@ -42,7 +43,7 @@ func (vs *Server) StreamDuties(req *ethpb.DutiesRequest, stream ethpb.BeaconNode
if genesisTime.IsZero() {
return status.Error(codes.Unavailable, "genesis time is not set")
}
var currentEpoch uint64
var currentEpoch types.Epoch
if genesisTime.Before(timeutils.Now()) {
currentEpoch = slotutil.EpochsSinceGenesis(vs.TimeFetcher.GenesisTime())
}
@@ -65,8 +66,8 @@ func (vs *Server) StreamDuties(req *ethpb.DutiesRequest, stream ethpb.BeaconNode
for {
select {
// Ticks every epoch to submit assignments to connected validator clients.
case epoch := <-epochTicker.C():
req.Epoch = epoch
case slot := <-epochTicker.C():
req.Epoch = types.Epoch(slot)
res, err := vs.duties(stream.Context(), req)
if err != nil {
return status.Errorf(codes.Internal, "Could not compute validator duties: %v", err)

View File

@@ -7,6 +7,7 @@ import (
"time"
"github.com/golang/mock/gomock"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
mockChain "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
@@ -109,7 +110,7 @@ func TestGetDuties_SlotOutOfUpperBound(t *testing.T) {
TimeFetcher: chain,
}
req := &ethpb.DutiesRequest{
Epoch: chain.CurrentSlot()/params.BeaconConfig().SlotsPerEpoch + 2,
Epoch: types.Epoch(chain.CurrentSlot()/params.BeaconConfig().SlotsPerEpoch + 2),
}
_, err := vs.duties(context.Background(), req)
require.ErrorContains(t, "can not be greater than next epoch", err)

View File

@@ -5,6 +5,7 @@ import (
"testing"
"time"
"github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
mockChain "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
@@ -30,8 +31,8 @@ func TestProposeExit_Notification(t *testing.T) {
require.NoError(t, err)
beaconState, err := state.GenesisBeaconState(deposits, 0, &ethpb.Eth1Data{BlockHash: make([]byte, 32)})
require.NoError(t, err)
epoch := uint64(2048)
require.NoError(t, beaconState.SetSlot(epoch*params.BeaconConfig().SlotsPerEpoch))
epoch := types.Epoch(2048)
require.NoError(t, beaconState.SetSlot(uint64(epoch)*params.BeaconConfig().SlotsPerEpoch))
block := testutil.NewBeaconBlock()
require.NoError(t, db.SaveBlock(ctx, block), "Could not save genesis block")
genesisRoot, err := block.Block.HashTreeRoot()
@@ -100,8 +101,8 @@ func TestProposeExit_NoPanic(t *testing.T) {
require.NoError(t, err)
beaconState, err := state.GenesisBeaconState(deposits, 0, &ethpb.Eth1Data{BlockHash: make([]byte, 32)})
require.NoError(t, err)
epoch := uint64(2048)
require.NoError(t, beaconState.SetSlot(epoch*params.BeaconConfig().SlotsPerEpoch))
epoch := types.Epoch(2048)
require.NoError(t, beaconState.SetSlot(uint64(epoch)*params.BeaconConfig().SlotsPerEpoch))
block := testutil.NewBeaconBlock()
require.NoError(t, db.SaveBlock(ctx, block), "Could not save genesis block")
genesisRoot, err := block.Block.HashTreeRoot()

View File

@@ -371,13 +371,13 @@ func (vs *Server) mockETH1DataVote(ctx context.Context, slot uint64) (*ethpb.Eth
// DepositCount = state.eth1_deposit_index,
// BlockHash = hash(hash(current_epoch + slot_in_voting_period)),
// )
slotInVotingPeriod := slot % (params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch)
slotInVotingPeriod := slot % (uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod) * params.BeaconConfig().SlotsPerEpoch)
headState, err := vs.HeadFetcher.HeadState(ctx)
if err != nil {
return nil, err
}
var enc []byte
enc = fastssz.MarshalUint64(enc, helpers.SlotToEpoch(slot)+slotInVotingPeriod)
enc = fastssz.MarshalUint64(enc, uint64(helpers.SlotToEpoch(slot))+slotInVotingPeriod)
depRoot := hashutil.Hash(enc)
blockHash := hashutil.Hash(depRoot[:])
return &ethpb.Eth1Data{

View File

@@ -309,7 +309,7 @@ func TestProposer_PendingDeposits_Eth1DataVoteOK(t *testing.T) {
BlockHash: blockHash,
DepositCount: 3,
}
period := params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch
period := uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod) * params.BeaconConfig().SlotsPerEpoch
for i := 0; i <= int(period/2); i++ {
votes = append(votes, vote)
}
@@ -501,7 +501,7 @@ func TestProposer_PendingDeposits_FollowsCorrectEth1Block(t *testing.T) {
DepositRoot: make([]byte, 32),
DepositCount: 7,
}
period := params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch
period := uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod) * params.BeaconConfig().SlotsPerEpoch
for i := 0; i <= int(period/2); i++ {
votes = append(votes, vote)
}
@@ -1217,11 +1217,11 @@ func TestProposer_Eth1Data_MockEnabled(t *testing.T) {
eth1Data, err := ps.eth1Data(ctx, 100)
require.NoError(t, err)
period := params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch
period := uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod) * params.BeaconConfig().SlotsPerEpoch
wantedSlot := 100 % period
currentEpoch := helpers.SlotToEpoch(100)
var enc []byte
enc = fastssz.MarshalUint64(enc, currentEpoch+wantedSlot)
enc = fastssz.MarshalUint64(enc, uint64(currentEpoch)+wantedSlot)
depRoot := hashutil.Hash(enc)
blockHash := hashutil.Hash(depRoot[:])
want := &ethpb.Eth1Data{
@@ -2086,7 +2086,7 @@ func TestProposer_DeleteAttsInPool_Aggregated(t *testing.T) {
func majorityVoteBoundaryTime(slot uint64) (uint64, uint64) {
slotStartTime := uint64(mockPOW.GenesisTime) +
(slot-(slot%(params.BeaconConfig().EpochsPerEth1VotingPeriod*params.BeaconConfig().SlotsPerEpoch)))*
(slot-(slot%(uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod)*params.BeaconConfig().SlotsPerEpoch)))*
params.BeaconConfig().SecondsPerSlot
earliestValidTime := slotStartTime - 2*params.BeaconConfig().SecondsPerETH1Block*params.BeaconConfig().Eth1FollowDistance
latestValidTime := slotStartTime - params.BeaconConfig().SecondsPerETH1Block*params.BeaconConfig().Eth1FollowDistance

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