From c21e43e4c508787a64931b4d6ff64dcf4d52f266 Mon Sep 17 00:00:00 2001 From: terence tsao Date: Fri, 1 Oct 2021 13:17:57 -0700 Subject: [PATCH] Refactor: move functions `beacon-chain/core/time` -> `time/slots` (#9719) * Move necessary functions beacon-chain/core/time -> time/slots * Fix fuzz * Fix build * Update slot_epoch.go --- beacon-chain/blockchain/head.go | 10 +- .../blockchain/head_sync_committee_info.go | 18 +- .../head_sync_committee_info_test.go | 8 +- beacon-chain/blockchain/head_test.go | 6 +- beacon-chain/blockchain/log.go | 6 +- .../blockchain/process_attestation.go | 4 +- .../blockchain/process_attestation_helpers.go | 6 +- .../blockchain/process_attestation_test.go | 4 +- beacon-chain/blockchain/process_block.go | 5 +- .../blockchain/process_block_helpers.go | 16 +- .../blockchain/receive_attestation.go | 11 +- .../blockchain/receive_attestation_test.go | 4 +- beacon-chain/blockchain/receive_block.go | 4 +- beacon-chain/blockchain/service.go | 5 +- beacon-chain/blockchain/service_test.go | 6 +- .../blockchain/weak_subjectivity_checks.go | 4 +- beacon-chain/core/altair/BUILD.bazel | 2 + beacon-chain/core/altair/block.go | 6 +- beacon-chain/core/altair/block_test.go | 9 +- beacon-chain/core/altair/sync_committee.go | 9 +- beacon-chain/core/blocks/BUILD.bazel | 2 + beacon-chain/core/blocks/attester_slashing.go | 4 +- beacon-chain/core/blocks/exit.go | 4 +- beacon-chain/core/blocks/proposer_slashing.go | 3 +- .../core/blocks/proposer_slashing_test.go | 4 +- beacon-chain/core/blocks/randao.go | 4 +- beacon-chain/core/blocks/signature.go | 14 +- .../core/epoch/precompute/BUILD.bazel | 1 + .../precompute/justification_finalization.go | 3 +- beacon-chain/core/helpers/BUILD.bazel | 2 + beacon-chain/core/helpers/attestation.go | 16 +- beacon-chain/core/helpers/attestation_test.go | 4 +- beacon-chain/core/helpers/beacon_committee.go | 9 +- .../core/helpers/beacon_committee_test.go | 7 +- beacon-chain/core/helpers/block.go | 4 +- .../core/helpers/rewards_penalties.go | 4 +- beacon-chain/core/helpers/sync_committee.go | 7 +- beacon-chain/core/helpers/validators.go | 3 +- .../core/helpers/weak_subjectivity.go | 7 +- beacon-chain/core/time/BUILD.bazel | 5 +- beacon-chain/core/time/slot_epoch.go | 187 +----------------- beacon-chain/core/time/slot_epoch_test.go | 41 ++-- beacon-chain/core/transition/BUILD.bazel | 1 + beacon-chain/core/transition/transition.go | 5 +- beacon-chain/core/validators/BUILD.bazel | 1 + beacon-chain/core/validators/validator.go | 3 +- beacon-chain/db/kv/BUILD.bazel | 2 +- beacon-chain/db/kv/blocks.go | 6 +- beacon-chain/db/kv/state.go | 4 +- beacon-chain/db/slasherkv/BUILD.bazel | 4 +- beacon-chain/db/slasherkv/pruning.go | 4 +- beacon-chain/db/slasherkv/pruning_test.go | 20 +- .../operations/voluntaryexits/BUILD.bazel | 2 +- .../operations/voluntaryexits/service.go | 4 +- beacon-chain/p2p/broadcaster.go | 4 +- beacon-chain/p2p/discovery.go | 4 +- beacon-chain/p2p/fork.go | 6 +- beacon-chain/p2p/fork_watcher.go | 3 +- beacon-chain/p2p/peers/BUILD.bazel | 2 +- beacon-chain/p2p/peers/status.go | 6 +- beacon-chain/powchain/BUILD.bazel | 4 +- beacon-chain/powchain/service.go | 6 +- beacon-chain/powchain/service_test.go | 4 +- beacon-chain/rpc/apimiddleware/BUILD.bazel | 4 +- .../rpc/apimiddleware/custom_hooks.go | 4 +- .../rpc/apimiddleware/custom_hooks_test.go | 4 +- beacon-chain/rpc/eth/beacon/BUILD.bazel | 4 +- beacon-chain/rpc/eth/beacon/pool.go | 4 +- beacon-chain/rpc/eth/beacon/pool_test.go | 8 +- beacon-chain/rpc/eth/beacon/state.go | 4 +- beacon-chain/rpc/eth/beacon/validator.go | 12 +- beacon-chain/rpc/eth/beacon/validator_test.go | 12 +- beacon-chain/rpc/eth/validator/BUILD.bazel | 3 +- beacon-chain/rpc/eth/validator/validator.go | 30 +-- .../rpc/eth/validator/validator_test.go | 7 +- .../rpc/prysm/v1alpha1/beacon/BUILD.bazel | 1 + .../rpc/prysm/v1alpha1/beacon/assignments.go | 6 +- .../prysm/v1alpha1/beacon/assignments_test.go | 4 +- .../rpc/prysm/v1alpha1/beacon/attestations.go | 3 +- .../v1alpha1/beacon/attestations_test.go | 4 +- .../rpc/prysm/v1alpha1/beacon/blocks.go | 12 +- .../rpc/prysm/v1alpha1/beacon/blocks_test.go | 8 +- .../rpc/prysm/v1alpha1/beacon/committees.go | 13 +- .../prysm/v1alpha1/beacon/committees_test.go | 4 +- .../rpc/prysm/v1alpha1/beacon/validators.go | 23 +-- .../prysm/v1alpha1/beacon/validators_test.go | 9 +- .../rpc/prysm/v1alpha1/validator/BUILD.bazel | 1 + .../prysm/v1alpha1/validator/aggregator.go | 4 +- .../prysm/v1alpha1/validator/assignments.go | 14 +- .../rpc/prysm/v1alpha1/validator/attester.go | 15 +- .../prysm/v1alpha1/validator/attester_test.go | 10 +- .../rpc/prysm/v1alpha1/validator/proposer.go | 8 +- .../prysm/v1alpha1/validator/proposer_test.go | 3 +- .../rpc/prysm/v1alpha1/validator/status.go | 3 +- .../prysm/v1alpha1/validator/status_test.go | 10 +- beacon-chain/slasher/BUILD.bazel | 2 - .../slasher/detect_attestations_test.go | 10 +- beacon-chain/slasher/receive.go | 8 +- beacon-chain/slasher/service.go | 2 +- beacon-chain/state/stategen/BUILD.bazel | 1 + beacon-chain/state/stategen/setter.go | 4 +- beacon-chain/sync/BUILD.bazel | 2 +- beacon-chain/sync/fork_watcher.go | 3 +- beacon-chain/sync/initial-sync/BUILD.bazel | 4 +- .../sync/initial-sync/blocks_fetcher_peers.go | 4 +- .../sync/initial-sync/blocks_fetcher_test.go | 14 +- .../sync/initial-sync/blocks_fetcher_utils.go | 18 +- .../initial-sync/blocks_fetcher_utils_test.go | 6 +- .../sync/initial-sync/blocks_queue.go | 14 +- .../sync/initial-sync/blocks_queue_test.go | 14 +- beacon-chain/sync/initial-sync/fsm.go | 4 +- .../sync/initial-sync/initial_sync_test.go | 6 +- beacon-chain/sync/initial-sync/round_robin.go | 24 +-- beacon-chain/sync/initial-sync/service.go | 8 +- .../sync/initial-sync/service_test.go | 6 +- beacon-chain/sync/metrics.go | 4 +- .../sync/pending_attestations_queue.go | 3 +- beacon-chain/sync/pending_blocks_queue.go | 3 +- beacon-chain/sync/rpc.go | 4 +- .../sync/rpc_beacon_blocks_by_range_test.go | 6 +- beacon-chain/sync/rpc_goodbye.go | 4 +- beacon-chain/sync/rpc_metadata.go | 6 +- beacon-chain/sync/rpc_ping.go | 4 +- beacon-chain/sync/rpc_send_request.go | 6 +- beacon-chain/sync/rpc_status.go | 15 +- beacon-chain/sync/service.go | 5 +- beacon-chain/sync/subscriber.go | 3 +- .../sync/subscriber_beacon_attestation.go | 6 +- beacon-chain/sync/subscriber_test.go | 4 +- beacon-chain/sync/validate_aggregate_proof.go | 10 +- .../sync/validate_beacon_attestation.go | 4 +- beacon-chain/sync/validate_beacon_blocks.go | 12 +- .../validate_sync_committee_message_test.go | 14 +- .../validate_sync_contribution_proof_test.go | 48 ++--- network/forks/BUILD.bazel | 2 +- network/forks/fork.go | 10 +- testing/endtoend/evaluators/BUILD.bazel | 1 - testing/endtoend/evaluators/fork.go | 4 +- testing/endtoend/evaluators/metrics.go | 2 +- testing/endtoend/evaluators/validator.go | 10 +- testing/fuzz/BUILD.bazel | 2 + testing/fuzz/state_fuzz.go | 6 +- testing/slasher/simulator/BUILD.bazel | 1 - .../simulator/attestation_generator.go | 4 +- testing/slasher/simulator/simulator.go | 5 +- testing/util/BUILD.bazel | 2 + testing/util/attestation.go | 4 +- testing/util/helpers_test.go | 3 +- testing/util/sync_aggregate.go | 10 +- time/slots/BUILD.bazel | 2 + time/slots/slottime.go | 185 ++++++++++++++++- time/slots/slottime_test.go | 4 +- validator/client/BUILD.bazel | 1 - validator/client/aggregate.go | 7 +- validator/client/attest.go | 2 +- validator/client/log.go | 4 +- validator/client/metrics.go | 18 +- validator/client/propose.go | 4 +- validator/client/runner.go | 4 +- validator/client/sync_committee.go | 8 +- validator/client/validator.go | 7 +- validator/db/kv/BUILD.bazel | 2 +- validator/db/kv/proposer_protection.go | 6 +- 163 files changed, 739 insertions(+), 720 deletions(-) diff --git a/beacon-chain/blockchain/head.go b/beacon-chain/blockchain/head.go index 53a53d7ab..ecef5485b 100644 --- a/beacon-chain/blockchain/head.go +++ b/beacon-chain/blockchain/head.go @@ -141,7 +141,7 @@ func (s *Service) saveHead(ctx context.Context, headRoot [32]byte) error { NewHeadBlock: headRoot[:], OldHeadState: oldStateRoot, NewHeadState: newStateRoot, - Epoch: time.SlotToEpoch(newHeadSlot), + Epoch: slots.ToEpoch(newHeadSlot), }, }) @@ -336,15 +336,15 @@ func (s *Service) notifyNewHeadEvent( currentDutyDependentRoot := s.genesisRoot[:] var previousDutyEpoch types.Epoch - currentDutyEpoch := time.SlotToEpoch(newHeadSlot) + currentDutyEpoch := slots.ToEpoch(newHeadSlot) if currentDutyEpoch > 0 { previousDutyEpoch = currentDutyEpoch.Sub(1) } - currentDutySlot, err := time.StartSlot(currentDutyEpoch) + currentDutySlot, err := slots.EpochStart(currentDutyEpoch) if err != nil { return errors.Wrap(err, "could not get duty slot") } - previousDutySlot, err := time.StartSlot(previousDutyEpoch) + previousDutySlot, err := slots.EpochStart(previousDutyEpoch) if err != nil { return errors.Wrap(err, "could not get duty slot") } @@ -366,7 +366,7 @@ func (s *Service) notifyNewHeadEvent( Slot: newHeadSlot, Block: newHeadRoot, State: newHeadStateRoot, - EpochTransition: time.IsEpochStart(newHeadSlot), + EpochTransition: slots.IsEpochStart(newHeadSlot), PreviousDutyDependentRoot: previousDutyDependentRoot, CurrentDutyDependentRoot: currentDutyDependentRoot, }, diff --git a/beacon-chain/blockchain/head_sync_committee_info.go b/beacon-chain/blockchain/head_sync_committee_info.go index 66fc04bb3..7d2e5266a 100644 --- a/beacon-chain/blockchain/head_sync_committee_info.go +++ b/beacon-chain/blockchain/head_sync_committee_info.go @@ -11,11 +11,11 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/core/altair" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" ) // Initialize the state cache for sync committees. @@ -62,14 +62,14 @@ func (s *Service) HeadSyncContributionProofDomain(ctx context.Context, slot type // rather than for the range // [compute_start_slot_at_epoch(epoch), compute_start_slot_at_epoch(epoch) + SLOTS_PER_EPOCH) func (s *Service) HeadSyncCommitteeIndices(ctx context.Context, index types.ValidatorIndex, slot types.Slot) ([]types.CommitteeIndex, error) { - nextSlotEpoch := time.SlotToEpoch(slot + 1) - currentEpoch := time.SlotToEpoch(slot) + nextSlotEpoch := slots.ToEpoch(slot + 1) + currentEpoch := slots.ToEpoch(slot) switch { - case time.SyncCommitteePeriod(nextSlotEpoch) == time.SyncCommitteePeriod(currentEpoch): + case slots.SyncCommitteePeriod(nextSlotEpoch) == slots.SyncCommitteePeriod(currentEpoch): return s.headCurrentSyncCommitteeIndices(ctx, index, slot) // At sync committee period boundary, validator should sample the next epoch sync committee. - case time.SyncCommitteePeriod(nextSlotEpoch) == time.SyncCommitteePeriod(currentEpoch)+1: + case slots.SyncCommitteePeriod(nextSlotEpoch) == slots.SyncCommitteePeriod(currentEpoch)+1: return s.headNextSyncCommitteeIndices(ctx, index, slot) default: // Impossible condition. @@ -105,11 +105,11 @@ func (s *Service) HeadSyncCommitteePubKeys(ctx context.Context, slot types.Slot, return nil, err } - nextSlotEpoch := time.SlotToEpoch(headState.Slot() + 1) - currEpoch := time.SlotToEpoch(headState.Slot()) + nextSlotEpoch := slots.ToEpoch(headState.Slot() + 1) + currEpoch := slots.ToEpoch(headState.Slot()) var syncCommittee *ethpb.SyncCommittee - if currEpoch == nextSlotEpoch || time.SyncCommitteePeriod(currEpoch) == time.SyncCommitteePeriod(nextSlotEpoch) { + if currEpoch == nextSlotEpoch || slots.SyncCommitteePeriod(currEpoch) == slots.SyncCommitteePeriod(nextSlotEpoch) { syncCommittee, err = headState.CurrentSyncCommittee() if err != nil { return nil, err @@ -130,7 +130,7 @@ func (s *Service) domainWithHeadState(ctx context.Context, slot types.Slot, doma if err != nil { return nil, err } - return signing.Domain(headState.Fork(), time.SlotToEpoch(headState.Slot()), domain, headState.GenesisValidatorRoot()) + return signing.Domain(headState.Fork(), slots.ToEpoch(headState.Slot()), domain, headState.GenesisValidatorRoot()) } // returns the head state that is advanced up to `slot`. It utilizes the cache `syncCommitteeHeadState` by retrieving using `slot` as key. diff --git a/beacon-chain/blockchain/head_sync_committee_info_test.go b/beacon-chain/blockchain/head_sync_committee_info_test.go index d3fb47ea3..3947b7e19 100644 --- a/beacon-chain/blockchain/head_sync_committee_info_test.go +++ b/beacon-chain/blockchain/head_sync_committee_info_test.go @@ -7,12 +7,12 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/cache" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" dbtest "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/state/stategen" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" ) func TestService_headSyncCommitteeFetcher_Errors(t *testing.T) { @@ -122,7 +122,7 @@ func TestService_HeadSyncCommitteeDomain(t *testing.T) { c := &Service{} c.head = &head{state: s} - wanted, err := signing.Domain(s.Fork(), time.SlotToEpoch(s.Slot()), params.BeaconConfig().DomainSyncCommittee, s.GenesisValidatorRoot()) + wanted, err := signing.Domain(s.Fork(), slots.ToEpoch(s.Slot()), params.BeaconConfig().DomainSyncCommittee, s.GenesisValidatorRoot()) require.NoError(t, err) d, err := c.HeadSyncCommitteeDomain(context.Background(), 0) @@ -136,7 +136,7 @@ func TestService_HeadSyncContributionProofDomain(t *testing.T) { c := &Service{} c.head = &head{state: s} - wanted, err := signing.Domain(s.Fork(), time.SlotToEpoch(s.Slot()), params.BeaconConfig().DomainContributionAndProof, s.GenesisValidatorRoot()) + wanted, err := signing.Domain(s.Fork(), slots.ToEpoch(s.Slot()), params.BeaconConfig().DomainContributionAndProof, s.GenesisValidatorRoot()) require.NoError(t, err) d, err := c.HeadSyncContributionProofDomain(context.Background(), 0) @@ -150,7 +150,7 @@ func TestService_HeadSyncSelectionProofDomain(t *testing.T) { c := &Service{} c.head = &head{state: s} - wanted, err := signing.Domain(s.Fork(), time.SlotToEpoch(s.Slot()), params.BeaconConfig().DomainSyncCommitteeSelectionProof, s.GenesisValidatorRoot()) + wanted, err := signing.Domain(s.Fork(), slots.ToEpoch(s.Slot()), params.BeaconConfig().DomainSyncCommitteeSelectionProof, s.GenesisValidatorRoot()) require.NoError(t, err) d, err := c.HeadSyncSelectionProofDomain(context.Background(), 0) diff --git a/beacon-chain/blockchain/head_test.go b/beacon-chain/blockchain/head_test.go index ec3e94238..e29952b86 100644 --- a/beacon-chain/blockchain/head_test.go +++ b/beacon-chain/blockchain/head_test.go @@ -8,7 +8,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/config/features" "github.com/prysmaticlabs/prysm/config/params" @@ -18,6 +17,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" logTest "github.com/sirupsen/logrus/hooks/test" ) @@ -187,9 +187,9 @@ func Test_notifyNewHeadEvent(t *testing.T) { }, genesisRoot: genesisRoot, } - epoch1Start, err := coreTime.StartSlot(1) + epoch1Start, err := slots.EpochStart(1) require.NoError(t, err) - epoch2Start, err := coreTime.StartSlot(1) + epoch2Start, err := slots.EpochStart(1) require.NoError(t, err) require.NoError(t, bState.SetSlot(epoch1Start)) diff --git a/beacon-chain/blockchain/log.go b/beacon-chain/blockchain/log.go index fe803a947..34ded537b 100644 --- a/beacon-chain/blockchain/log.go +++ b/beacon-chain/blockchain/log.go @@ -5,12 +5,12 @@ import ( "fmt" "time" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" "github.com/prysmaticlabs/prysm/runtime/version" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" ) @@ -44,7 +44,7 @@ func logStateTransitionData(b block.BeaconBlock) { } func logBlockSyncStatus(block block.BeaconBlock, blockRoot [32]byte, finalized *ethpb.Checkpoint, receivedTime time.Time, genesisTime uint64) error { - startTime, err := coreTime.SlotToTime(genesisTime, block.Slot()) + startTime, err := slots.ToTime(genesisTime, block.Slot()) if err != nil { return err } @@ -52,7 +52,7 @@ func logBlockSyncStatus(block block.BeaconBlock, blockRoot [32]byte, finalized * "slot": block.Slot(), "slotInEpoch": block.Slot() % params.BeaconConfig().SlotsPerEpoch, "block": fmt.Sprintf("0x%s...", hex.EncodeToString(blockRoot[:])[:8]), - "epoch": coreTime.SlotToEpoch(block.Slot()), + "epoch": slots.ToEpoch(block.Slot()), "finalizedEpoch": finalized.Epoch, "finalizedRoot": fmt.Sprintf("0x%s...", hex.EncodeToString(finalized.Root)[:8]), }).Info("Synced new block") diff --git a/beacon-chain/blockchain/process_attestation.go b/beacon-chain/blockchain/process_attestation.go index 14998a74a..992a4ca60 100644 --- a/beacon-chain/blockchain/process_attestation.go +++ b/beacon-chain/blockchain/process_attestation.go @@ -5,12 +5,12 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/attestation" "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" ) @@ -75,7 +75,7 @@ func (s *Service) onAttestation(ctx context.Context, a *ethpb.Attestation) error // validate_aggregate_proof.go and validate_beacon_attestation.go // Verify attestations can only affect the fork choice of subsequent slots. - if err := coreTime.VerifySlotTime(genesisTime, a.Data.Slot+1, params.BeaconNetworkConfig().MaximumGossipClockDisparity); err != nil { + if err := slots.VerifyTime(genesisTime, a.Data.Slot+1, params.BeaconNetworkConfig().MaximumGossipClockDisparity); err != nil { return err } diff --git a/beacon-chain/blockchain/process_attestation_helpers.go b/beacon-chain/blockchain/process_attestation_helpers.go index ccaa79b17..90b082fbd 100644 --- a/beacon-chain/blockchain/process_attestation_helpers.go +++ b/beacon-chain/blockchain/process_attestation_helpers.go @@ -9,12 +9,12 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/async" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" ) // getAttPreState retrieves the att pre state by either from the cache or the DB. @@ -38,7 +38,7 @@ func (s *Service) getAttPreState(ctx context.Context, c *ethpb.Checkpoint) (stat return nil, errors.Wrapf(err, "could not get pre state for epoch %d", c.Epoch) } - epochStartSlot, err := time.StartSlot(c.Epoch) + epochStartSlot, err := slots.EpochStart(c.Epoch) if err != nil { return nil, err } @@ -63,7 +63,7 @@ func (s *Service) getAttPreState(ctx context.Context, c *ethpb.Checkpoint) (stat // verifyAttTargetEpoch validates attestation is from the current or previous epoch. func (s *Service) verifyAttTargetEpoch(_ context.Context, genesisTime, nowTime uint64, c *ethpb.Checkpoint) error { currentSlot := types.Slot((nowTime - genesisTime) / params.BeaconConfig().SecondsPerSlot) - currentEpoch := time.SlotToEpoch(currentSlot) + currentEpoch := slots.ToEpoch(currentSlot) var prevEpoch types.Epoch // Prevents previous epoch under flow if currentEpoch > 1 { diff --git a/beacon-chain/blockchain/process_attestation_test.go b/beacon-chain/blockchain/process_attestation_test.go index 5d80bd441..541aecd7e 100644 --- a/beacon-chain/blockchain/process_attestation_test.go +++ b/beacon-chain/blockchain/process_attestation_test.go @@ -5,7 +5,6 @@ import ( "testing" types "github.com/prysmaticlabs/eth2-types" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray" @@ -18,6 +17,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" ) func TestStore_OnAttestation_ErrorConditions(t *testing.T) { @@ -251,7 +251,7 @@ func TestStore_UpdateCheckpointState(t *testing.T) { require.NoError(t, service.cfg.BeaconDB.SaveState(ctx, baseState, bytesutil.ToBytes32(newCheckpoint.Root))) returned, err = service.getAttPreState(ctx, newCheckpoint) require.NoError(t, err) - s, err := coreTime.StartSlot(newCheckpoint.Epoch) + s, err := slots.EpochStart(newCheckpoint.Epoch) require.NoError(t, err) baseState, err = transition.ProcessSlots(ctx, baseState, s) require.NoError(t, err) diff --git a/beacon-chain/blockchain/process_block.go b/beacon-chain/blockchain/process_block.go index f6dab7a17..e4a66a2b3 100644 --- a/beacon-chain/blockchain/process_block.go +++ b/beacon-chain/blockchain/process_block.go @@ -21,6 +21,7 @@ import ( ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/attestation" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" ) @@ -268,7 +269,7 @@ func (s *Service) onBlockBatch(ctx context.Context, blks []block.SignedBeaconBlo return nil, nil, err } // Save potential boundary states. - if coreTime.IsEpochStart(preState.Slot()) { + if slots.IsEpochStart(preState.Slot()) { boundaries[blockRoots[i]] = preState.Copy() if err := s.handleEpochBoundary(ctx, preState); err != nil { return nil, nil, errors.Wrap(err, "could not handle epoch boundary state") @@ -367,7 +368,7 @@ func (s *Service) handleEpochBoundary(ctx context.Context, postState state.Beaco return err } var err error - s.nextEpochBoundarySlot, err = coreTime.StartSlot(coreTime.NextEpoch(postState)) + s.nextEpochBoundarySlot, err = slots.EpochStart(coreTime.NextEpoch(postState)) if err != nil { return err } diff --git a/beacon-chain/blockchain/process_block_helpers.go b/beacon-chain/blockchain/process_block_helpers.go index c82d2bbd8..bd89fa598 100644 --- a/beacon-chain/blockchain/process_block_helpers.go +++ b/beacon-chain/blockchain/process_block_helpers.go @@ -8,7 +8,6 @@ import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" @@ -16,12 +15,13 @@ import ( ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/attestation" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" ) // CurrentSlot returns the current slot based on time. func (s *Service) CurrentSlot() types.Slot { - return time.CurrentSlot(uint64(s.genesisTime.Unix())) + return slots.CurrentSlot(uint64(s.genesisTime.Unix())) } // getBlockPreState returns the pre state of an incoming block. It uses the parent root of the block @@ -45,7 +45,7 @@ func (s *Service) getBlockPreState(ctx context.Context, b block.BeaconBlock) (st } // Verify block slot time is not from the future. - if err := time.VerifySlotTime(preState.GenesisTime(), b.Slot(), params.BeaconNetworkConfig().MaximumGossipClockDisparity); err != nil { + if err := slots.VerifyTime(preState.GenesisTime(), b.Slot(), params.BeaconNetworkConfig().MaximumGossipClockDisparity); err != nil { return nil, err } @@ -122,7 +122,7 @@ func (s *Service) VerifyBlkDescendant(ctx context.Context, root [32]byte) error // verifyBlkFinalizedSlot validates input block is not less than or equal // to current finalized slot. func (s *Service) verifyBlkFinalizedSlot(b block.BeaconBlock) error { - finalizedSlot, err := time.StartSlot(s.finalizedCheckpt.Epoch) + finalizedSlot, err := slots.EpochStart(s.finalizedCheckpt.Epoch) if err != nil { return err } @@ -140,7 +140,7 @@ func (s *Service) shouldUpdateCurrentJustified(ctx context.Context, newJustified ctx, span := trace.StartSpan(ctx, "blockChain.shouldUpdateCurrentJustified") defer span.End() - if time.SlotsSinceEpochStarts(s.CurrentSlot()) < params.BeaconConfig().SafeSlotsToUpdateJustified { + if slots.SinceEpochStarts(s.CurrentSlot()) < params.BeaconConfig().SafeSlotsToUpdateJustified { return true, nil } var newJustifiedBlockSigned block.SignedBeaconBlock @@ -159,7 +159,7 @@ func (s *Service) shouldUpdateCurrentJustified(ctx context.Context, newJustified } newJustifiedBlock := newJustifiedBlockSigned.Block() - jSlot, err := time.StartSlot(s.justifiedCheckpt.Epoch) + jSlot, err := slots.EpochStart(s.justifiedCheckpt.Epoch) if err != nil { return false, err } @@ -348,7 +348,7 @@ func (s *Service) finalizedImpliesNewJustified(ctx context.Context, state state. } // Update justified if store justified is not in chain with finalized check point. - finalizedSlot, err := time.StartSlot(s.finalizedCheckpt.Epoch) + finalizedSlot, err := slots.EpochStart(s.finalizedCheckpt.Epoch) if err != nil { return err } @@ -377,7 +377,7 @@ func (s *Service) fillInForkChoiceMissingBlocks(ctx context.Context, blk block.B parentRoot := bytesutil.ToBytes32(blk.ParentRoot()) slot := blk.Slot() // Fork choice only matters from last finalized slot. - fSlot, err := time.StartSlot(s.finalizedCheckpt.Epoch) + fSlot, err := slots.EpochStart(s.finalizedCheckpt.Epoch) if err != nil { return err } diff --git a/beacon-chain/blockchain/receive_attestation.go b/beacon-chain/blockchain/receive_attestation.go index 599682dff..a015fb11a 100644 --- a/beacon-chain/blockchain/receive_attestation.go +++ b/beacon-chain/blockchain/receive_attestation.go @@ -9,7 +9,6 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" @@ -51,11 +50,11 @@ func (s *Service) ReceiveAttestationNoPubsub(ctx context.Context, att *ethpb.Att // AttestationTargetState returns the pre state of attestation. func (s *Service) AttestationTargetState(ctx context.Context, target *ethpb.Checkpoint) (state.BeaconState, error) { - ss, err := coreTime.StartSlot(target.Epoch) + ss, err := slots.EpochStart(target.Epoch) if err != nil { return nil, err } - if err := coreTime.ValidateSlotClock(ss, uint64(s.genesisTime.Unix())); err != nil { + if err := slots.ValidateClock(ss, uint64(s.genesisTime.Unix())); err != nil { return nil, err } return s.getAttPreState(ctx, target) @@ -63,7 +62,7 @@ func (s *Service) AttestationTargetState(ctx context.Context, target *ethpb.Chec // VerifyLmdFfgConsistency verifies that attestation's LMD and FFG votes are consistency to each other. func (s *Service) VerifyLmdFfgConsistency(ctx context.Context, a *ethpb.Attestation) error { - targetSlot, err := coreTime.StartSlot(a.Data.Target.Epoch) + targetSlot, err := slots.EpochStart(a.Data.Target.Epoch) if err != nil { return err } @@ -88,7 +87,7 @@ func (s *Service) VerifyFinalizedConsistency(ctx context.Context, root []byte) e } f := s.FinalizedCheckpt() - ss, err := coreTime.StartSlot(f.Epoch) + ss, err := slots.EpochStart(f.Epoch) if err != nil { return err } @@ -147,7 +146,7 @@ func (s *Service) processAttestations(ctx context.Context) { // This delays consideration in the fork choice until their slot is in the past. // https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/fork-choice.md#validate_on_attestation nextSlot := a.Data.Slot + 1 - if err := coreTime.VerifySlotTime(uint64(s.genesisTime.Unix()), nextSlot, params.BeaconNetworkConfig().MaximumGossipClockDisparity); err != nil { + if err := slots.VerifyTime(uint64(s.genesisTime.Unix()), nextSlot, params.BeaconNetworkConfig().MaximumGossipClockDisparity); err != nil { continue } diff --git a/beacon-chain/blockchain/receive_attestation_test.go b/beacon-chain/blockchain/receive_attestation_test.go index 427d7eb57..7a1e96ebf 100644 --- a/beacon-chain/blockchain/receive_attestation_test.go +++ b/beacon-chain/blockchain/receive_attestation_test.go @@ -7,7 +7,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray" @@ -20,6 +19,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" logTest "github.com/sirupsen/logrus/hooks/test" ) @@ -35,7 +35,7 @@ func TestAttestationCheckPtState_FarFutureSlot(t *testing.T) { chainService := setupBeaconChain(t, beaconDB) chainService.genesisTime = time.Now() - e := types.Epoch(coreTime.MaxSlotBuffer/uint64(params.BeaconConfig().SlotsPerEpoch) + 1) + e := types.Epoch(slots.MaxSlotBuffer/uint64(params.BeaconConfig().SlotsPerEpoch) + 1) _, err := chainService.AttestationTargetState(context.Background(), ðpb.Checkpoint{Epoch: e}) require.ErrorContains(t, "exceeds max allowed value relative to the local clock", err) } diff --git a/beacon-chain/blockchain/receive_block.go b/beacon-chain/blockchain/receive_block.go index d8689ca35..a86504e8c 100644 --- a/beacon-chain/blockchain/receive_block.go +++ b/beacon-chain/blockchain/receive_block.go @@ -7,10 +7,10 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/monitoring/tracing" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" ) @@ -142,7 +142,7 @@ func (s *Service) handlePostBlockOperations(b block.BeaconBlock) error { // This checks whether it's time to start saving hot state to DB. // It's time when there's `epochsSinceFinalitySaveHotStateDB` epochs of non-finality. func (s *Service) checkSaveHotStateDB(ctx context.Context) error { - currentEpoch := coreTime.SlotToEpoch(s.CurrentSlot()) + currentEpoch := slots.ToEpoch(s.CurrentSlot()) // Prevent `sinceFinality` going underflow. var sinceFinality types.Epoch if currentEpoch > s.finalizedCheckpt.Epoch { diff --git a/beacon-chain/blockchain/service.go b/beacon-chain/blockchain/service.go index 84623f574..b0dcdf65f 100644 --- a/beacon-chain/blockchain/service.go +++ b/beacon-chain/blockchain/service.go @@ -17,7 +17,6 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/beacon-chain/db" f "github.com/prysmaticlabs/prysm/beacon-chain/forkchoice" @@ -176,7 +175,7 @@ func (s *Service) Start() { s.prevFinalizedCheckpt = ethpb.CopyCheckpoint(finalizedCheckpoint) s.resumeForkChoice(justifiedCheckpoint, finalizedCheckpoint) - ss, err := coreTime.StartSlot(s.finalizedCheckpt.Epoch) + ss, err := slots.EpochStart(s.finalizedCheckpt.Epoch) if err != nil { log.Fatalf("Could not get start slot of finalized epoch: %v", err) } @@ -413,7 +412,7 @@ func (s *Service) initializeChainInfo(ctx context.Context) error { if err != nil { return errors.Wrap(err, "could not retrieve head block") } - headEpoch := coreTime.SlotToEpoch(headBlock.Block().Slot()) + headEpoch := slots.ToEpoch(headBlock.Block().Slot()) var epochsSinceFinality types.Epoch if headEpoch > finalized.Epoch { epochsSinceFinality = headEpoch - finalized.Epoch diff --git a/beacon-chain/blockchain/service_test.go b/beacon-chain/blockchain/service_test.go index ad38160d4..e530ffca7 100644 --- a/beacon-chain/blockchain/service_test.go +++ b/beacon-chain/blockchain/service_test.go @@ -14,7 +14,6 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/beacon-chain/db" testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" @@ -33,6 +32,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" logTest "github.com/sirupsen/logrus/hooks/test" "google.golang.org/protobuf/proto" ) @@ -281,7 +281,7 @@ func TestChainService_InitializeChainInfo(t *testing.T) { require.NoError(t, beaconDB.SaveState(ctx, headState, headRoot)) require.NoError(t, beaconDB.SaveState(ctx, headState, genesisRoot)) require.NoError(t, beaconDB.SaveBlock(ctx, wrapper.WrappedPhase0SignedBeaconBlock(headBlock))) - require.NoError(t, beaconDB.SaveFinalizedCheckpoint(ctx, ðpb.Checkpoint{Epoch: coreTime.SlotToEpoch(finalizedSlot), Root: headRoot[:]})) + require.NoError(t, beaconDB.SaveFinalizedCheckpoint(ctx, ðpb.Checkpoint{Epoch: slots.ToEpoch(finalizedSlot), Root: headRoot[:]})) c := &Service{cfg: &Config{BeaconDB: beaconDB, StateGen: stategen.New(beaconDB)}} require.NoError(t, c.initializeChainInfo(ctx)) headBlk, err := c.HeadBlock(ctx) @@ -375,7 +375,7 @@ func TestChainService_InitializeChainInfo_HeadSync(t *testing.T) { require.NoError(t, beaconDB.SaveState(ctx, headState, headRoot)) require.NoError(t, beaconDB.SaveHeadBlockRoot(ctx, headRoot)) require.NoError(t, beaconDB.SaveFinalizedCheckpoint(ctx, ðpb.Checkpoint{ - Epoch: coreTime.SlotToEpoch(finalizedBlock.Block.Slot), + Epoch: slots.ToEpoch(finalizedBlock.Block.Slot), Root: finalizedRoot[:], })) diff --git a/beacon-chain/blockchain/weak_subjectivity_checks.go b/beacon-chain/blockchain/weak_subjectivity_checks.go index 2aa4de8a3..5df003983 100644 --- a/beacon-chain/blockchain/weak_subjectivity_checks.go +++ b/beacon-chain/blockchain/weak_subjectivity_checks.go @@ -4,10 +4,10 @@ import ( "context" "fmt" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/db/filters" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" + "github.com/prysmaticlabs/prysm/time/slots" ) // VerifyWeakSubjectivityRoot verifies the weak subjectivity root in the service struct. @@ -38,7 +38,7 @@ func (s *Service) VerifyWeakSubjectivityRoot(ctx context.Context) error { return fmt.Errorf("node does not have root in DB: %#x", r) } - startSlot, err := time.StartSlot(s.cfg.WeakSubjectivityCheckpt.Epoch) + startSlot, err := slots.EpochStart(s.cfg.WeakSubjectivityCheckpt.Epoch) if err != nil { return err } diff --git a/beacon-chain/core/altair/BUILD.bazel b/beacon-chain/core/altair/BUILD.bazel index 8d947a2e7..1257e5eaa 100644 --- a/beacon-chain/core/altair/BUILD.bazel +++ b/beacon-chain/core/altair/BUILD.bazel @@ -38,6 +38,7 @@ go_library( "//proto/prysm/v1alpha1:go_default_library", "//proto/prysm/v1alpha1/attestation:go_default_library", "//proto/prysm/v1alpha1/block:go_default_library", + "//time/slots: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", @@ -81,6 +82,7 @@ go_test( "//testing/require:go_default_library", "//testing/util:go_default_library", "//time:go_default_library", + "//time/slots:go_default_library", "@com_github_google_gofuzz//:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", diff --git a/beacon-chain/core/altair/block.go b/beacon-chain/core/altair/block.go index c9e899d35..a3739eafa 100644 --- a/beacon-chain/core/altair/block.go +++ b/beacon-chain/core/altair/block.go @@ -7,13 +7,13 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" p2pType "github.com/prysmaticlabs/prysm/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/crypto/bls" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" ) // ProcessSyncAggregate verifies sync committee aggregate signature signing over the previous slot block root. @@ -101,8 +101,8 @@ func FilterSyncCommitteeVotes(s state.BeaconStateAltair, sync *ethpb.SyncAggrega // VerifySyncCommitteeSig verifies sync committee signature `syncSig` is valid with respect to public keys `syncKeys`. func VerifySyncCommitteeSig(s state.BeaconStateAltair, syncKeys []bls.PublicKey, syncSig []byte) error { - ps := time.PrevSlot(s.Slot()) - d, err := signing.Domain(s.Fork(), time.SlotToEpoch(ps), params.BeaconConfig().DomainSyncCommittee, s.GenesisValidatorRoot()) + ps := slots.PrevSlot(s.Slot()) + d, err := signing.Domain(s.Fork(), slots.ToEpoch(ps), params.BeaconConfig().DomainSyncCommittee, s.GenesisValidatorRoot()) if err != nil { return err } diff --git a/beacon-chain/core/altair/block_test.go b/beacon-chain/core/altair/block_test.go index 28ad5cd6c..abbb57919 100644 --- a/beacon-chain/core/altair/block_test.go +++ b/beacon-chain/core/altair/block_test.go @@ -18,6 +18,7 @@ import ( ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" ) func TestProcessSyncCommittee_PerfectParticipation(t *testing.T) { @@ -33,7 +34,7 @@ func TestProcessSyncCommittee_PerfectParticipation(t *testing.T) { } indices, err := altair.NextSyncCommitteeIndices(context.Background(), beaconState) require.NoError(t, err) - ps := time.PrevSlot(beaconState.Slot()) + ps := slots.PrevSlot(beaconState.Slot()) pbr, err := helpers.BlockRootAtSlot(beaconState, ps) require.NoError(t, err) sigs := make([]bls.Signature, len(indices)) @@ -107,7 +108,7 @@ func TestProcessSyncCommittee_MixParticipation_BadSignature(t *testing.T) { } indices, err := altair.NextSyncCommitteeIndices(context.Background(), beaconState) require.NoError(t, err) - ps := time.PrevSlot(beaconState.Slot()) + ps := slots.PrevSlot(beaconState.Slot()) pbr, err := helpers.BlockRootAtSlot(beaconState, ps) require.NoError(t, err) sigs := make([]bls.Signature, len(indices)) @@ -142,7 +143,7 @@ func TestProcessSyncCommittee_MixParticipation_GoodSignature(t *testing.T) { } indices, err := altair.NextSyncCommitteeIndices(context.Background(), beaconState) require.NoError(t, err) - ps := time.PrevSlot(beaconState.Slot()) + ps := slots.PrevSlot(beaconState.Slot()) pbr, err := helpers.BlockRootAtSlot(beaconState, ps) require.NoError(t, err) sigs := make([]bls.Signature, 0, len(indices)) @@ -215,7 +216,7 @@ func Test_VerifySyncCommitteeSig(t *testing.T) { } indices, err := altair.NextSyncCommitteeIndices(context.Background(), beaconState) require.NoError(t, err) - ps := time.PrevSlot(beaconState.Slot()) + ps := slots.PrevSlot(beaconState.Slot()) pbr, err := helpers.BlockRootAtSlot(beaconState, ps) require.NoError(t, err) sigs := make([]bls.Signature, len(indices)) diff --git a/beacon-chain/core/altair/sync_committee.go b/beacon-chain/core/altair/sync_committee.go index 49e9fa281..a4548c19c 100644 --- a/beacon-chain/core/altair/sync_committee.go +++ b/beacon-chain/core/altair/sync_committee.go @@ -16,6 +16,7 @@ import ( "github.com/prysmaticlabs/prysm/encoding/bytesutil" "github.com/prysmaticlabs/prysm/math" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" ) const maxRandomByte = uint64(1<<8 - 1) @@ -185,15 +186,15 @@ func IsSyncCommitteeAggregator(sig []byte) (bool, error) { // ValidateSyncMessageTime validates sync message to ensure that the provided slot is valid. func ValidateSyncMessageTime(slot types.Slot, genesisTime time.Time, clockDisparity time.Duration) error { - if err := coreTime.ValidateSlotClock(slot, uint64(genesisTime.Unix())); err != nil { + if err := slots.ValidateClock(slot, uint64(genesisTime.Unix())); err != nil { return err } - messageTime, err := coreTime.SlotToTime(uint64(genesisTime.Unix()), slot) + messageTime, err := slots.ToTime(uint64(genesisTime.Unix()), slot) if err != nil { return err } - currentSlot := coreTime.SlotsSince(genesisTime) - slotStartTime, err := coreTime.SlotToTime(uint64(genesisTime.Unix()), currentSlot) + currentSlot := slots.Since(genesisTime) + slotStartTime, err := slots.ToTime(uint64(genesisTime.Unix()), currentSlot) if err != nil { return err } diff --git a/beacon-chain/core/blocks/BUILD.bazel b/beacon-chain/core/blocks/BUILD.bazel index 48242a12a..e4cd4e884 100644 --- a/beacon-chain/core/blocks/BUILD.bazel +++ b/beacon-chain/core/blocks/BUILD.bazel @@ -43,6 +43,7 @@ go_library( "//proto/prysm/v1alpha1/block:go_default_library", "//proto/prysm/v1alpha1/slashings:go_default_library", "//runtime/version:go_default_library", + "//time/slots: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", @@ -93,6 +94,7 @@ go_test( "//testing/assert:go_default_library", "//testing/require:go_default_library", "//testing/util:go_default_library", + "//time/slots:go_default_library", "@com_github_google_gofuzz//:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", diff --git a/beacon-chain/core/blocks/attester_slashing.go b/beacon-chain/core/blocks/attester_slashing.go index c2e1d2198..d31be8a89 100644 --- a/beacon-chain/core/blocks/attester_slashing.go +++ b/beacon-chain/core/blocks/attester_slashing.go @@ -7,7 +7,6 @@ import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/container/slice" @@ -15,6 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/attestation" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/slashings" "github.com/prysmaticlabs/prysm/runtime/version" + "github.com/prysmaticlabs/prysm/time/slots" ) // ProcessAttesterSlashings is one of the operations performed @@ -50,7 +50,7 @@ func ProcessAttesterSlashings( sort.SliceStable(slashableIndices, func(i, j int) bool { return slashableIndices[i] < slashableIndices[j] }) - currentEpoch := time.SlotToEpoch(beaconState.Slot()) + currentEpoch := slots.ToEpoch(beaconState.Slot()) var err error var slashedAny bool var val state.ReadOnlyValidator diff --git a/beacon-chain/core/blocks/exit.go b/beacon-chain/core/blocks/exit.go index 56c6788cd..c9755abe7 100644 --- a/beacon-chain/core/blocks/exit.go +++ b/beacon-chain/core/blocks/exit.go @@ -8,11 +8,11 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" v "github.com/prysmaticlabs/prysm/beacon-chain/core/validators" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" ) // ValidatorAlreadyExitedMsg defines a message saying that a validator has already exited. @@ -135,7 +135,7 @@ func VerifyExitAndSignature( // # Initiate exit // initiate_validator_exit(state, voluntary_exit.validator_index) func verifyExitConditions(validator state.ReadOnlyValidator, currentSlot types.Slot, exit *ethpb.VoluntaryExit) error { - currentEpoch := time.SlotToEpoch(currentSlot) + currentEpoch := slots.ToEpoch(currentSlot) // Verify the validator is active. if !helpers.IsActiveValidatorUsingTrie(validator, currentEpoch) { return errors.New("non-active validator cannot exit") diff --git a/beacon-chain/core/blocks/proposer_slashing.go b/beacon-chain/core/blocks/proposer_slashing.go index 97c1ac7ab..8de5ced29 100644 --- a/beacon-chain/core/blocks/proposer_slashing.go +++ b/beacon-chain/core/blocks/proposer_slashing.go @@ -13,6 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/config/params" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/runtime/version" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/protobuf/proto" ) @@ -98,7 +99,7 @@ func VerifyProposerSlashing( } headers := []*ethpb.SignedBeaconBlockHeader{slashing.Header_1, slashing.Header_2} for _, header := range headers { - if err := signing.ComputeDomainVerifySigningRoot(beaconState, pIdx, time.SlotToEpoch(hSlot), + if err := signing.ComputeDomainVerifySigningRoot(beaconState, pIdx, slots.ToEpoch(hSlot), header.Header, params.BeaconConfig().DomainBeaconProposer, header.Signature); err != nil { return errors.Wrap(err, "could not verify beacon block header") } diff --git a/beacon-chain/core/blocks/proposer_slashing_test.go b/beacon-chain/core/blocks/proposer_slashing_test.go index 157a8f55c..00ff789ad 100644 --- a/beacon-chain/core/blocks/proposer_slashing_test.go +++ b/beacon-chain/core/blocks/proposer_slashing_test.go @@ -8,7 +8,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" v "github.com/prysmaticlabs/prysm/beacon-chain/core/validators" "github.com/prysmaticlabs/prysm/beacon-chain/state" v1 "github.com/prysmaticlabs/prysm/beacon-chain/state/v1" @@ -19,6 +18,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" ) func TestProcessProposerSlashings_UnmatchedHeaderSlots(t *testing.T) { @@ -329,7 +329,7 @@ func TestVerifyProposerSlashing(t *testing.T) { t.Run(tt.name, func(t *testing.T) { sk := sks[tt.args.slashing.Header_1.Header.ProposerIndex] - d, err := signing.Domain(tt.args.beaconState.Fork(), time.SlotToEpoch(tt.args.slashing.Header_1.Header.Slot), params.BeaconConfig().DomainBeaconProposer, tt.args.beaconState.GenesisValidatorRoot()) + d, err := signing.Domain(tt.args.beaconState.Fork(), slots.ToEpoch(tt.args.slashing.Header_1.Header.Slot), params.BeaconConfig().DomainBeaconProposer, tt.args.beaconState.GenesisValidatorRoot()) require.NoError(t, err) if tt.args.slashing.Header_1.Signature == nil { sr, err := signing.ComputeSigningRoot(tt.args.slashing.Header_1.Header, d) diff --git a/beacon-chain/core/blocks/randao.go b/beacon-chain/core/blocks/randao.go index c75f9b429..a7d39474b 100644 --- a/beacon-chain/core/blocks/randao.go +++ b/beacon-chain/core/blocks/randao.go @@ -5,11 +5,11 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/crypto/hash" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" + "github.com/prysmaticlabs/prysm/time/slots" ) // ProcessRandao checks the block proposer's @@ -63,7 +63,7 @@ func ProcessRandaoNoVerify( beaconState state.BeaconState, randaoReveal []byte, ) (state.BeaconState, error) { - currentEpoch := time.SlotToEpoch(beaconState.Slot()) + currentEpoch := slots.ToEpoch(beaconState.Slot()) // 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 diff --git a/beacon-chain/core/blocks/signature.go b/beacon-chain/core/blocks/signature.go index 40cf5646f..ced47060d 100644 --- a/beacon-chain/core/blocks/signature.go +++ b/beacon-chain/core/blocks/signature.go @@ -8,7 +8,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/crypto/bls" @@ -16,6 +15,7 @@ import ( ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/attestation" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" + "github.com/prysmaticlabs/prysm/time/slots" ) // retrieves the signature set from the raw data, public key,signature and domain provided. @@ -67,7 +67,7 @@ func VerifyBlockSignature(beaconState state.ReadOnlyBeaconState, proposerIndex types.ValidatorIndex, sig []byte, rootFunc func() ([32]byte, error)) error { - currentEpoch := time.SlotToEpoch(beaconState.Slot()) + currentEpoch := slots.ToEpoch(beaconState.Slot()) domain, err := signing.Domain(beaconState.Fork(), currentEpoch, params.BeaconConfig().DomainBeaconProposer, beaconState.GenesisValidatorRoot()) if err != nil { return err @@ -82,7 +82,7 @@ func VerifyBlockSignature(beaconState state.ReadOnlyBeaconState, // VerifyBlockHeaderSignature verifies the proposer signature of a beacon block header. func VerifyBlockHeaderSignature(beaconState state.BeaconState, header *ethpb.SignedBeaconBlockHeader) error { - currentEpoch := time.SlotToEpoch(beaconState.Slot()) + currentEpoch := slots.ToEpoch(beaconState.Slot()) domain, err := signing.Domain(beaconState.Fork(), currentEpoch, params.BeaconConfig().DomainBeaconProposer, beaconState.GenesisValidatorRoot()) if err != nil { return err @@ -99,7 +99,7 @@ func VerifyBlockHeaderSignature(beaconState state.BeaconState, header *ethpb.Sig // from the above method by not using fork data from the state and instead retrieving it // via the respective epoch. func VerifyBlockSignatureUsingCurrentFork(beaconState state.ReadOnlyBeaconState, blk block.SignedBeaconBlock) error { - currentEpoch := time.SlotToEpoch(blk.Block().Slot()) + currentEpoch := slots.ToEpoch(blk.Block().Slot()) fork, err := forks.Fork(currentEpoch) if err != nil { return err @@ -121,7 +121,7 @@ func BlockSignatureSet(beaconState state.ReadOnlyBeaconState, proposerIndex types.ValidatorIndex, sig []byte, rootFunc func() ([32]byte, error)) (*bls.SignatureSet, error) { - currentEpoch := time.SlotToEpoch(beaconState.Slot()) + currentEpoch := slots.ToEpoch(beaconState.Slot()) domain, err := signing.Domain(beaconState.Fork(), currentEpoch, params.BeaconConfig().DomainBeaconProposer, beaconState.GenesisValidatorRoot()) if err != nil { return nil, err @@ -160,7 +160,7 @@ func randaoSigningData(ctx context.Context, beaconState state.ReadOnlyBeaconStat } proposerPub := beaconState.PubkeyAtIndex(proposerIdx) - currentEpoch := time.SlotToEpoch(beaconState.Slot()) + currentEpoch := slots.ToEpoch(beaconState.Slot()) buf := make([]byte, 32) binary.LittleEndian.PutUint64(buf, uint64(currentEpoch)) @@ -238,7 +238,7 @@ func AttestationSignatureSet(ctx context.Context, beaconState state.ReadOnlyBeac var preForkAtts []*ethpb.Attestation var postForkAtts []*ethpb.Attestation for _, a := range atts { - if time.SlotToEpoch(a.Data.Slot) < fork.Epoch { + if slots.ToEpoch(a.Data.Slot) < fork.Epoch { preForkAtts = append(preForkAtts, a) } else { postForkAtts = append(postForkAtts, a) diff --git a/beacon-chain/core/epoch/precompute/BUILD.bazel b/beacon-chain/core/epoch/precompute/BUILD.bazel index 45d9f8e22..01de2faf8 100644 --- a/beacon-chain/core/epoch/precompute/BUILD.bazel +++ b/beacon-chain/core/epoch/precompute/BUILD.bazel @@ -24,6 +24,7 @@ go_library( "//monitoring/tracing:go_default_library", "//proto/prysm/v1alpha1:go_default_library", "//proto/prysm/v1alpha1/attestation:go_default_library", + "//time/slots:go_default_library", "@com_github_pkg_errors//:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@io_opencensus_go//trace:go_default_library", diff --git a/beacon-chain/core/epoch/precompute/justification_finalization.go b/beacon-chain/core/epoch/precompute/justification_finalization.go index 909ef4b44..1c71d2336 100644 --- a/beacon-chain/core/epoch/precompute/justification_finalization.go +++ b/beacon-chain/core/epoch/precompute/justification_finalization.go @@ -6,6 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/state" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" ) // ProcessJustificationAndFinalizationPreCompute processes justification and finalization during @@ -25,7 +26,7 @@ import ( // current_target_balance = get_attesting_balance(state, current_attestations) // weigh_justification_and_finalization(state, total_active_balance, previous_target_balance, current_target_balance) func ProcessJustificationAndFinalizationPreCompute(state state.BeaconState, pBal *Balance) (state.BeaconState, error) { - canProcessSlot, err := time.StartSlot(2 /*epoch*/) + canProcessSlot, err := slots.EpochStart(2 /*epoch*/) if err != nil { return nil, err } diff --git a/beacon-chain/core/helpers/BUILD.bazel b/beacon-chain/core/helpers/BUILD.bazel index 2298a0ce5..19b111403 100644 --- a/beacon-chain/core/helpers/BUILD.bazel +++ b/beacon-chain/core/helpers/BUILD.bazel @@ -49,6 +49,7 @@ go_library( "//proto/prysm/v1alpha1:go_default_library", "//proto/prysm/v1alpha1/block:go_default_library", "//time:go_default_library", + "//time/slots:go_default_library", "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prometheus_client_golang//prometheus/promauto:go_default_library", @@ -91,6 +92,7 @@ go_test( "//testing/require:go_default_library", "//testing/util:go_default_library", "//time:go_default_library", + "//time/slots:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", ], diff --git a/beacon-chain/core/helpers/attestation.go b/beacon-chain/core/helpers/attestation.go index 728c341b8..00f5d4b64 100644 --- a/beacon-chain/core/helpers/attestation.go +++ b/beacon-chain/core/helpers/attestation.go @@ -7,12 +7,12 @@ import ( "time" types "github.com/prysmaticlabs/eth2-types" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/crypto/bls" "github.com/prysmaticlabs/prysm/crypto/hash" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" ) // ValidateNilAttestation checks if any composite field of input attestation is nil. @@ -40,7 +40,7 @@ func ValidateNilAttestation(attestation *ethpb.Attestation) error { // ValidateSlotTargetEpoch checks if attestation data's epoch matches target checkpoint's epoch. // It is recommended to run `ValidateNilAttestation` first to ensure `data.Target` can't be nil. func ValidateSlotTargetEpoch(data *ethpb.AttestationData) error { - if coreTime.SlotToEpoch(data.Slot) != data.Target.Epoch { + if slots.ToEpoch(data.Slot) != data.Target.Epoch { return fmt.Errorf("slot %d does not match target epoch %d", data.Slot, data.Target.Epoch) } return nil @@ -121,7 +121,7 @@ func ComputeSubnetForAttestation(activeValCount uint64, att *ethpb.Attestation) // // return uint64((committees_since_epoch_start + committee_index) % ATTESTATION_SUBNET_COUNT) func ComputeSubnetFromCommitteeAndSlot(activeValCount uint64, comIdx types.CommitteeIndex, attSlot types.Slot) uint64 { - slotSinceStart := coreTime.SlotsSinceEpochStarts(attSlot) + slotSinceStart := slots.SinceEpochStarts(attSlot) comCount := SlotCommitteeCount(activeValCount) commsSinceStart := uint64(slotSinceStart.Mul(comCount)) computedSubnet := (commsSinceStart + uint64(comIdx)) % params.BeaconNetworkConfig().AttestationSubnetCount @@ -142,14 +142,14 @@ func ComputeSubnetFromCommitteeAndSlot(activeValCount uint64, comIdx types.Commi // valid_attestation_slot = 101 // In the attestation must be within the range of 95 to 102 in the example above. func ValidateAttestationTime(attSlot types.Slot, genesisTime time.Time, clockDisparity time.Duration) error { - if err := coreTime.ValidateSlotClock(attSlot, uint64(genesisTime.Unix())); err != nil { + if err := slots.ValidateClock(attSlot, uint64(genesisTime.Unix())); err != nil { return err } - attTime, err := coreTime.SlotToTime(uint64(genesisTime.Unix()), attSlot) + attTime, err := slots.ToTime(uint64(genesisTime.Unix()), attSlot) if err != nil { return err } - currentSlot := coreTime.SlotsSince(genesisTime) + currentSlot := slots.Since(genesisTime) // When receiving an attestation, it can be from the future. // so the upper bounds is set to now + clockDisparity(SECONDS_PER_SLOT * 2). @@ -163,7 +163,7 @@ func ValidateAttestationTime(attSlot types.Slot, genesisTime time.Time, clockDis if currentSlot > params.BeaconNetworkConfig().AttestationPropagationSlotRange { lowerBoundsSlot = currentSlot - params.BeaconNetworkConfig().AttestationPropagationSlotRange } - lowerTime, err := coreTime.SlotToTime(uint64(genesisTime.Unix()), lowerBoundsSlot) + lowerTime, err := slots.ToTime(uint64(genesisTime.Unix()), lowerBoundsSlot) if err != nil { return err } @@ -187,7 +187,7 @@ func VerifyCheckpointEpoch(c *ethpb.Checkpoint, genesis time.Time) bool { now := uint64(prysmTime.Now().Unix()) genesisTime := uint64(genesis.Unix()) currentSlot := types.Slot((now - genesisTime) / params.BeaconConfig().SecondsPerSlot) - currentEpoch := coreTime.SlotToEpoch(currentSlot) + currentEpoch := slots.ToEpoch(currentSlot) var prevEpoch types.Epoch if currentEpoch > 1 { diff --git a/beacon-chain/core/helpers/attestation_test.go b/beacon-chain/core/helpers/attestation_test.go index 3c43fd3c2..b51330aeb 100644 --- a/beacon-chain/core/helpers/attestation_test.go +++ b/beacon-chain/core/helpers/attestation_test.go @@ -8,7 +8,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" v1 "github.com/prysmaticlabs/prysm/beacon-chain/state/v1" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/crypto/bls" @@ -18,6 +17,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" ) func TestAttestation_IsAggregator(t *testing.T) { @@ -118,7 +118,7 @@ func TestAttestation_ComputeSubnetForAttestation(t *testing.T) { }, Signature: []byte{'B'}, } - valCount, err := helpers.ActiveValidatorCount(context.Background(), state, coreTime.SlotToEpoch(att.Data.Slot)) + valCount, err := helpers.ActiveValidatorCount(context.Background(), state, slots.ToEpoch(att.Data.Slot)) require.NoError(t, err) sub := helpers.ComputeSubnetForAttestation(valCount, att) assert.Equal(t, uint64(6), sub, "Did not get correct subnet for attestation") diff --git a/beacon-chain/core/helpers/beacon_committee.go b/beacon-chain/core/helpers/beacon_committee.go index 0adcfe982..48f907129 100644 --- a/beacon-chain/core/helpers/beacon_committee.go +++ b/beacon-chain/core/helpers/beacon_committee.go @@ -20,6 +20,7 @@ import ( "github.com/prysmaticlabs/prysm/encoding/bytesutil" "github.com/prysmaticlabs/prysm/math" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" ) var ( @@ -73,7 +74,7 @@ func SlotCommitteeCount(activeValidatorCount uint64) uint64 { // count=committees_per_slot * SLOTS_PER_EPOCH, // ) func BeaconCommitteeFromState(ctx context.Context, state state.ReadOnlyBeaconState, slot types.Slot, committeeIndex types.CommitteeIndex) ([]types.ValidatorIndex, error) { - epoch := time.SlotToEpoch(slot) + epoch := slots.ToEpoch(slot) seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester) if err != nil { return nil, errors.Wrap(err, "could not get seed") @@ -169,7 +170,7 @@ func CommitteeAssignments( // We determine the slots in which proposers are supposed to act. // Some validators may need to propose multiple times per epoch, so // we use a map of proposer idx -> []slot to keep track of this possibility. - startSlot, err := time.StartSlot(epoch) + startSlot, err := slots.EpochStart(epoch) if err != nil { return nil, nil, err } @@ -326,7 +327,7 @@ func UpdateProposerIndicesInCache(ctx context.Context, state state.ReadOnlyBeaco // Use state root from (current_epoch - 1)) wantedEpoch := time.PrevEpoch(state) - s, err := time.EndSlot(wantedEpoch) + s, err := slots.EpochEnd(wantedEpoch) if err != nil { return err } @@ -420,7 +421,7 @@ func precomputeProposerIndices(state state.ReadOnlyBeaconState, activeIndices [] if err != nil { return nil, errors.Wrap(err, "could not generate seed") } - slot, err := time.StartSlot(e) + slot, err := slots.EpochStart(e) if err != nil { return nil, err } diff --git a/beacon-chain/core/helpers/beacon_committee_test.go b/beacon-chain/core/helpers/beacon_committee_test.go index 0e0bcc4de..a7bb6d286 100644 --- a/beacon-chain/core/helpers/beacon_committee_test.go +++ b/beacon-chain/core/helpers/beacon_committee_test.go @@ -17,6 +17,7 @@ import ( ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" + "github.com/prysmaticlabs/prysm/time/slots" ) func TestComputeCommittee_WithoutCache(t *testing.T) { @@ -190,7 +191,7 @@ func TestCommitteeAssignments_CanRetrieve(t *testing.T) { for i, tt := range tests { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { ClearCache() - validatorIndexToCommittee, proposerIndexToSlots, err := CommitteeAssignments(context.Background(), state, time.SlotToEpoch(tt.slot)) + validatorIndexToCommittee, proposerIndexToSlots, err := CommitteeAssignments(context.Background(), state, slots.ToEpoch(tt.slot)) require.NoError(t, err, "Failed to determine CommitteeAssignments") cac := validatorIndexToCommittee[tt.index] assert.Equal(t, tt.committeeIndex, cac.CommitteeIndex, "Unexpected committeeIndex for validator index %d", tt.index) @@ -261,9 +262,9 @@ func TestCommitteeAssignments_EverySlotHasMin1Proposer(t *testing.T) { } } assert.Equal(t, uint64(params.BeaconConfig().SlotsPerEpoch), uint64(len(slotsWithProposers)), "Unexpected slots") - startSlot, err := time.StartSlot(epoch) + startSlot, err := slots.EpochStart(epoch) require.NoError(t, err) - endSlot, err := time.StartSlot(epoch + 1) + endSlot, err := slots.EpochStart(epoch + 1) require.NoError(t, err) for i := startSlot; i < endSlot; i++ { hasProposer := slotsWithProposers[i] diff --git a/beacon-chain/core/helpers/block.go b/beacon-chain/core/helpers/block.go index 949b6c231..7d9fb595a 100644 --- a/beacon-chain/core/helpers/block.go +++ b/beacon-chain/core/helpers/block.go @@ -5,10 +5,10 @@ import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" + "github.com/prysmaticlabs/prysm/time/slots" ) // VerifyNilBeaconBlock checks if any composite field of input signed beacon block is nil. @@ -65,7 +65,7 @@ func StateRootAtSlot(state state.ReadOnlyBeaconState, slot types.Slot) ([]byte, // """ // return get_block_root_at_slot(state, compute_start_slot_at_epoch(epoch)) func BlockRoot(state state.ReadOnlyBeaconState, epoch types.Epoch) ([]byte, error) { - s, err := time.StartSlot(epoch) + s, err := slots.EpochStart(epoch) if err != nil { return nil, err } diff --git a/beacon-chain/core/helpers/rewards_penalties.go b/beacon-chain/core/helpers/rewards_penalties.go index 0a0e9e54a..d7b9b2afd 100644 --- a/beacon-chain/core/helpers/rewards_penalties.go +++ b/beacon-chain/core/helpers/rewards_penalties.go @@ -5,10 +5,10 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/cache" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" mathutil "github.com/prysmaticlabs/prysm/math" + "github.com/prysmaticlabs/prysm/time/slots" ) var balanceCache = cache.NewEffectiveBalanceCache() @@ -66,7 +66,7 @@ func TotalActiveBalance(s state.ReadOnlyBeaconState) (uint64, error) { } total := uint64(0) - epoch := time.SlotToEpoch(s.Slot()) + epoch := slots.ToEpoch(s.Slot()) if err := s.ReadFromEveryValidator(func(idx int, val state.ReadOnlyValidator) error { if IsActiveValidatorUsingTrie(val, epoch) { total += val.EffectiveBalance() diff --git a/beacon-chain/core/helpers/sync_committee.go b/beacon-chain/core/helpers/sync_committee.go index 3974f9f75..4c0dd24c0 100644 --- a/beacon-chain/core/helpers/sync_committee.go +++ b/beacon-chain/core/helpers/sync_committee.go @@ -12,6 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" + "github.com/prysmaticlabs/prysm/time/slots" log "github.com/sirupsen/logrus" ) @@ -154,7 +155,7 @@ func UpdateSyncCommitteeCache(st state.BeaconStateAltair) error { if nextSlot%params.BeaconConfig().SlotsPerEpoch != 0 { return errors.New("not at the end of the epoch to update cache") } - if time.SlotToEpoch(nextSlot)%params.BeaconConfig().EpochsPerSyncCommitteePeriod != 0 { + if slots.ToEpoch(nextSlot)%params.BeaconConfig().EpochsPerSyncCommitteePeriod != 0 { return errors.New("not at sync committee period boundary to update cache") } @@ -191,11 +192,11 @@ func syncPeriodBoundaryRoot(st state.ReadOnlyBeaconState) ([]byte, error) { return params.BeaconConfig().ZeroHash[:], nil } - startEpoch, err := time.SyncCommitteePeriodStartEpoch(time.CurrentEpoch(st)) + startEpoch, err := slots.SyncCommitteePeriodStartEpoch(time.CurrentEpoch(st)) if err != nil { return nil, err } - startEpochSlot, err := time.StartSlot(startEpoch) + startEpochSlot, err := slots.EpochStart(startEpoch) if err != nil { return nil, err } diff --git a/beacon-chain/core/helpers/validators.go b/beacon-chain/core/helpers/validators.go index 124bca3ae..f593fbb14 100644 --- a/beacon-chain/core/helpers/validators.go +++ b/beacon-chain/core/helpers/validators.go @@ -15,6 +15,7 @@ import ( "github.com/prysmaticlabs/prysm/crypto/hash" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" log "github.com/sirupsen/logrus" ) @@ -229,7 +230,7 @@ func BeaconProposerIndex(ctx context.Context, state state.ReadOnlyBeaconState) ( // For simplicity, the node will skip caching of genesis epoch. if e > params.BeaconConfig().GenesisEpoch+params.BeaconConfig().MinSeedLookahead { wantedEpoch := time.PrevEpoch(state) - s, err := time.EndSlot(wantedEpoch) + s, err := slots.EpochEnd(wantedEpoch) if err != nil { return 0, err } diff --git a/beacon-chain/core/helpers/weak_subjectivity.go b/beacon-chain/core/helpers/weak_subjectivity.go index 1d006be03..0d66b4d21 100644 --- a/beacon-chain/core/helpers/weak_subjectivity.go +++ b/beacon-chain/core/helpers/weak_subjectivity.go @@ -15,6 +15,7 @@ import ( "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/math" eth "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" ) // ComputeWeakSubjectivityPeriod returns weak subjectivity period for the active validator count and finalized epoch. @@ -132,9 +133,9 @@ func IsWithinWeakSubjectivityPeriod( return false, fmt.Errorf("state (%#x) and checkpoint (%#x) roots do not match", wsState.LatestBlockHeader().StateRoot, wsCheckpoint.StateRoot) } - if time.SlotToEpoch(wsState.Slot()) != wsCheckpoint.Epoch { + if slots.ToEpoch(wsState.Slot()) != wsCheckpoint.Epoch { return false, fmt.Errorf("state (%v) and checkpoint (%v) epochs do not match", - time.SlotToEpoch(wsState.Slot()), wsCheckpoint.Epoch) + slots.ToEpoch(wsState.Slot()), wsCheckpoint.Epoch) } // Compare given epoch to state epoch + weak subjectivity period. @@ -142,7 +143,7 @@ func IsWithinWeakSubjectivityPeriod( if err != nil { return false, fmt.Errorf("cannot compute weak subjectivity period: %w", err) } - wsStateEpoch := time.SlotToEpoch(wsState.Slot()) + wsStateEpoch := slots.ToEpoch(wsState.Slot()) return currentEpoch <= wsStateEpoch+wsPeriod, nil } diff --git a/beacon-chain/core/time/BUILD.bazel b/beacon-chain/core/time/BUILD.bazel index be670473e..9b8ddc7c5 100644 --- a/beacon-chain/core/time/BUILD.bazel +++ b/beacon-chain/core/time/BUILD.bazel @@ -9,9 +9,7 @@ go_library( "//beacon-chain/state:go_default_library", "//config/params:go_default_library", "//runtime/version:go_default_library", - "//time:go_default_library", - "@com_github_ethereum_go_ethereum//common/math:go_default_library", - "@com_github_pkg_errors//:go_default_library", + "//time/slots:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", ], ) @@ -27,6 +25,7 @@ go_test( "//testing/assert:go_default_library", "//testing/require:go_default_library", "//time:go_default_library", + "//time/slots:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", ], ) diff --git a/beacon-chain/core/time/slot_epoch.go b/beacon-chain/core/time/slot_epoch.go index 6ace6cffd..f140271d2 100644 --- a/beacon-chain/core/time/slot_epoch.go +++ b/beacon-chain/core/time/slot_epoch.go @@ -1,35 +1,13 @@ package time import ( - "fmt" - "math" - "time" - - math2 "github.com/ethereum/go-ethereum/common/math" - "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/runtime/version" - prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" ) -// MaxSlotBuffer specifies the max buffer given to slots from -// incoming objects. (24 mins with mainnet spec) -const MaxSlotBuffer = uint64(1 << 7) - -// SlotToEpoch returns the epoch number of the input slot. -// -// Spec pseudocode definition: -// def compute_epoch_at_slot(slot: Slot) -> Epoch: -// """ -// Return the epoch number at ``slot``. -// """ -// return Epoch(slot // SLOTS_PER_EPOCH) -func SlotToEpoch(slot types.Slot) types.Epoch { - return types.Epoch(slot.DivSlot(params.BeaconConfig().SlotsPerEpoch)) -} - // CurrentEpoch returns the current epoch number calculated from // the slot number stored in beacon state. // @@ -40,7 +18,7 @@ func SlotToEpoch(slot types.Slot) types.Epoch { // """ // return compute_epoch_at_slot(state.slot) func CurrentEpoch(state state.ReadOnlyBeaconState) types.Epoch { - return SlotToEpoch(state.Slot()) + return slots.ToEpoch(state.Slot()) } // PrevEpoch returns the previous epoch number calculated from @@ -65,7 +43,7 @@ func PrevEpoch(state state.ReadOnlyBeaconState) types.Epoch { // NextEpoch returns the next epoch number calculated from // the slot number stored in beacon state. func NextEpoch(state state.ReadOnlyBeaconState) types.Epoch { - return SlotToEpoch(state.Slot()) + 1 + return slots.ToEpoch(state.Slot()) + 1 } // AltairCompatible returns if the input state `s` is altair compatible and input epoch `e` is higher equal than fork epoch. @@ -73,166 +51,11 @@ func AltairCompatible(s state.BeaconState, e types.Epoch) bool { return s.Version() == version.Altair && e >= params.BeaconConfig().AltairForkEpoch } -// StartSlot returns the first slot number of the -// current epoch. -// -// Spec pseudocode definition: -// def compute_start_slot_at_epoch(epoch: Epoch) -> Slot: -// """ -// Return the start slot of ``epoch``. -// """ -// return Slot(epoch * SLOTS_PER_EPOCH) -func StartSlot(epoch types.Epoch) (types.Slot, error) { - slot, err := params.BeaconConfig().SlotsPerEpoch.SafeMul(uint64(epoch)) - if err != nil { - return slot, errors.Errorf("start slot calculation overflows: %v", err) - } - return slot, nil -} - -// EndSlot returns the last slot number of the -// current epoch. -func EndSlot(epoch types.Epoch) (types.Slot, error) { - if epoch == math.MaxUint64 { - return 0, errors.New("start slot calculation overflows") - } - slot, err := StartSlot(epoch + 1) - if err != nil { - return 0, err - } - return slot - 1, nil -} - -// IsEpochStart returns true if the given slot number is an epoch starting slot -// number. -func IsEpochStart(slot types.Slot) bool { - return slot%params.BeaconConfig().SlotsPerEpoch == 0 -} - -// IsEpochEnd returns true if the given slot number is an epoch ending slot -// number. -func IsEpochEnd(slot types.Slot) bool { - return IsEpochStart(slot + 1) -} - -// SlotsSinceEpochStarts returns number of slots since the start of the epoch. -func SlotsSinceEpochStarts(slot types.Slot) types.Slot { - return slot % params.BeaconConfig().SlotsPerEpoch -} - -// VerifySlotTime validates the input slot is not from the future. -func VerifySlotTime(genesisTime uint64, slot types.Slot, timeTolerance time.Duration) error { - slotTime, err := SlotToTime(genesisTime, slot) - if err != nil { - return err - } - - // Defensive check to ensure unreasonable slots are rejected - // straight away. - if err := ValidateSlotClock(slot, genesisTime); err != nil { - return err - } - - currentTime := prysmTime.Now() - diff := slotTime.Sub(currentTime) - - if diff > timeTolerance { - return fmt.Errorf("could not process slot from the future, slot time %s > current time %s", slotTime, currentTime) - } - return nil -} - -// SlotToTime takes the given slot and genesis time to determine the start time of the slot. -func SlotToTime(genesisTimeSec uint64, slot types.Slot) (time.Time, error) { - timeSinceGenesis, err := slot.SafeMul(params.BeaconConfig().SecondsPerSlot) - if err != nil { - return time.Unix(0, 0), fmt.Errorf("slot (%d) is in the far distant future: %w", slot, err) - } - sTime, err := timeSinceGenesis.SafeAdd(genesisTimeSec) - if err != nil { - return time.Unix(0, 0), fmt.Errorf("slot (%d) is in the far distant future: %w", slot, err) - } - return time.Unix(int64(sTime), 0), nil -} - -// SlotsSince computes the number of time slots that have occurred since the given timestamp. -func SlotsSince(time time.Time) types.Slot { - return CurrentSlot(uint64(time.Unix())) -} - -// CurrentSlot returns the current slot as determined by the local clock and -// provided genesis time. -func CurrentSlot(genesisTimeSec uint64) types.Slot { - now := prysmTime.Now().Unix() - genesis := int64(genesisTimeSec) - if now < genesis { - return 0 - } - return types.Slot(uint64(now-genesis) / params.BeaconConfig().SecondsPerSlot) -} - -// ValidateSlotClock validates a provided slot against the local -// clock to ensure slots that are unreasonable are returned with -// an error. -func ValidateSlotClock(slot types.Slot, genesisTimeSec uint64) error { - maxPossibleSlot := CurrentSlot(genesisTimeSec).Add(MaxSlotBuffer) - // Defensive check to ensure that we only process slots up to a hard limit - // from our local clock. - if slot > maxPossibleSlot { - return fmt.Errorf("slot %d > %d which exceeds max allowed value relative to the local clock", slot, maxPossibleSlot) - } - return nil -} - -// RoundUpToNearestEpoch rounds up the provided slot value to the nearest epoch. -func RoundUpToNearestEpoch(slot types.Slot) types.Slot { - if slot%params.BeaconConfig().SlotsPerEpoch != 0 { - slot -= slot % params.BeaconConfig().SlotsPerEpoch - slot += params.BeaconConfig().SlotsPerEpoch - } - return slot -} - -// VotingPeriodStartTime returns the current voting period's start time -// depending on the provided genesis and current slot. -func VotingPeriodStartTime(genesis uint64, slot types.Slot) uint64 { - slots := params.BeaconConfig().SlotsPerEpoch.Mul(uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod)) - startTime := uint64((slot - slot.ModSlot(slots)).Mul(params.BeaconConfig().SecondsPerSlot)) - return genesis + startTime -} - -// PrevSlot returns previous slot, with an exception in slot 0 to prevent underflow. -func PrevSlot(slot types.Slot) types.Slot { - if slot > 0 { - return slot.Sub(1) - } - return 0 -} - -// SyncCommitteePeriod returns the sync committee period of input epoch `e`. -// -// Spec code: -// def compute_sync_committee_period(epoch: Epoch) -> uint64: -// return epoch // EPOCHS_PER_SYNC_COMMITTEE_PERIOD -func SyncCommitteePeriod(e types.Epoch) uint64 { - return uint64(e / params.BeaconConfig().EpochsPerSyncCommitteePeriod) -} - -// SyncCommitteePeriodStartEpoch returns the start epoch of a sync committee period. -func SyncCommitteePeriodStartEpoch(e types.Epoch) (types.Epoch, error) { - // Overflow is impossible here because of division of `EPOCHS_PER_SYNC_COMMITTEE_PERIOD`. - startEpoch, overflow := math2.SafeMul(SyncCommitteePeriod(e), uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod)) - if overflow { - return 0, errors.New("start epoch calculation overflow") - } - return types.Epoch(startEpoch), nil -} - // CanUpgradeToAltair returns true if the input `slot` can upgrade to Altair. // Spec code: // If state.slot % SLOTS_PER_EPOCH == 0 and compute_epoch_at_slot(state.slot) == ALTAIR_FORK_EPOCH func CanUpgradeToAltair(slot types.Slot) bool { - epochStart := IsEpochStart(slot) - altairEpoch := SlotToEpoch(slot) == params.BeaconConfig().AltairForkEpoch + epochStart := slots.IsEpochStart(slot) + altairEpoch := slots.ToEpoch(slot) == params.BeaconConfig().AltairForkEpoch return epochStart && altairEpoch } diff --git a/beacon-chain/core/time/slot_epoch_test.go b/beacon-chain/core/time/slot_epoch_test.go index e0d51486d..7ee2bda48 100644 --- a/beacon-chain/core/time/slot_epoch_test.go +++ b/beacon-chain/core/time/slot_epoch_test.go @@ -12,6 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" ) func TestSlotToEpoch_OK(t *testing.T) { @@ -26,7 +27,7 @@ func TestSlotToEpoch_OK(t *testing.T) { {slot: 200, epoch: 6}, } for _, tt := range tests { - assert.Equal(t, tt.epoch, SlotToEpoch(tt.slot), "SlotToEpoch(%d)", tt.slot) + assert.Equal(t, tt.epoch, slots.ToEpoch(tt.slot), "ToEpoch(%d)", tt.slot) } } @@ -96,10 +97,10 @@ func TestEpochStartSlot_OK(t *testing.T) { {epoch: 1 << 60, startSlot: 1 << 63, error: true}, } for _, tt := range tests { - ss, err := StartSlot(tt.epoch) + ss, err := slots.EpochStart(tt.epoch) if !tt.error { require.NoError(t, err) - assert.Equal(t, tt.startSlot, ss, "StartSlot(%d)", tt.epoch) + assert.Equal(t, tt.startSlot, ss, "EpochStart(%d)", tt.epoch) } else { require.ErrorContains(t, "start slot calculation overflow", err) } @@ -120,10 +121,10 @@ func TestEpochEndSlot_OK(t *testing.T) { {epoch: math.MaxUint64, startSlot: 0, error: true}, } for _, tt := range tests { - ss, err := EndSlot(tt.epoch) + ss, err := slots.EpochEnd(tt.epoch) if !tt.error { require.NoError(t, err) - assert.Equal(t, tt.startSlot, ss, "StartSlot(%d)", tt.epoch) + assert.Equal(t, tt.startSlot, ss, "EpochStart(%d)", tt.epoch) } else { require.ErrorContains(t, "start slot calculation overflow", err) } @@ -156,7 +157,7 @@ func TestIsEpochStart(t *testing.T) { } for _, tt := range tests { - assert.Equal(t, tt.result, IsEpochStart(tt.slot), "IsEpochStart(%d)", tt.slot) + assert.Equal(t, tt.result, slots.IsEpochStart(tt.slot), "IsEpochStart(%d)", tt.slot) } } @@ -182,7 +183,7 @@ func TestIsEpochEnd(t *testing.T) { } for _, tt := range tests { - assert.Equal(t, tt.result, IsEpochEnd(tt.slot), "IsEpochEnd(%d)", tt.slot) + assert.Equal(t, tt.result, slots.IsEpochEnd(tt.slot), "IsEpochEnd(%d)", tt.slot) } } @@ -198,7 +199,7 @@ func TestSlotsSinceEpochStarts(t *testing.T) { {slots: 10*params.BeaconConfig().SlotsPerEpoch + 2, wantedSlots: 2}, } for _, tt := range tests { - assert.Equal(t, tt.wantedSlots, SlotsSinceEpochStarts(tt.slots)) + assert.Equal(t, tt.wantedSlots, slots.SinceEpochStarts(tt.slots)) } } @@ -212,7 +213,7 @@ func TestRoundUpToNearestEpoch_OK(t *testing.T) { {startSlot: 10*params.BeaconConfig().SlotsPerEpoch - (params.BeaconConfig().SlotsPerEpoch - 1), roundedUpSlot: 10 * params.BeaconConfig().SlotsPerEpoch}, } for _, tt := range tests { - assert.Equal(t, tt.roundedUpSlot, RoundUpToNearestEpoch(tt.startSlot), "RoundUpToNearestEpoch(%d)", tt.startSlot) + assert.Equal(t, tt.roundedUpSlot, slots.RoundUpToNearestEpoch(tt.startSlot), "RoundUpToNearestEpoch(%d)", tt.startSlot) } } @@ -262,7 +263,7 @@ func TestSlotToTime(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := SlotToTime(tt.args.genesisTimeSec, tt.args.slot) + got, err := slots.ToTime(tt.args.genesisTimeSec, tt.args.slot) if tt.wantedErr != "" { assert.ErrorContains(t, tt.wantedErr, err) } else { @@ -310,7 +311,7 @@ func TestVerifySlotTime(t *testing.T) { name: "max future slot", args: args{ genesisTime: prysmTime.Now().Add(-1 * 5 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second).Unix(), - slot: types.Slot(MaxSlotBuffer + 6), + slot: types.Slot(slots.MaxSlotBuffer + 6), }, wantedErr: "exceeds max allowed value relative to the local clock", }, @@ -327,7 +328,7 @@ func TestVerifySlotTime(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err := VerifySlotTime(uint64(tt.args.genesisTime), tt.args.slot, tt.args.timeTolerance) + err := slots.VerifyTime(uint64(tt.args.genesisTime), tt.args.slot, tt.args.timeTolerance) if tt.wantedErr != "" { assert.ErrorContains(t, tt.wantedErr, err) } else { @@ -338,12 +339,12 @@ func TestVerifySlotTime(t *testing.T) { } func TestValidateSlotClock_HandlesBadSlot(t *testing.T) { - genTime := prysmTime.Now().Add(-1 * time.Duration(MaxSlotBuffer) * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second).Unix() + genTime := prysmTime.Now().Add(-1 * time.Duration(slots.MaxSlotBuffer) * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second).Unix() - assert.NoError(t, ValidateSlotClock(types.Slot(MaxSlotBuffer), uint64(genTime)), "unexpected error validating slot") - assert.NoError(t, ValidateSlotClock(types.Slot(2*MaxSlotBuffer), uint64(genTime)), "unexpected error validating slot") - assert.ErrorContains(t, "which exceeds max allowed value relative to the local clock", ValidateSlotClock(types.Slot(2*MaxSlotBuffer+1), uint64(genTime)), "no error from bad slot") - assert.ErrorContains(t, "which exceeds max allowed value relative to the local clock", ValidateSlotClock(1<<63, uint64(genTime)), "no error from bad slot") + assert.NoError(t, slots.ValidateClock(types.Slot(slots.MaxSlotBuffer), uint64(genTime)), "unexpected error validating slot") + assert.NoError(t, slots.ValidateClock(types.Slot(2*slots.MaxSlotBuffer), uint64(genTime)), "unexpected error validating slot") + assert.ErrorContains(t, "which exceeds max allowed value relative to the local clock", slots.ValidateClock(types.Slot(2*slots.MaxSlotBuffer+1), uint64(genTime)), "no error from bad slot") + assert.ErrorContains(t, "which exceeds max allowed value relative to the local clock", slots.ValidateClock(1<<63, uint64(genTime)), "no error from bad slot") } func TestPrevSlot(t *testing.T) { @@ -375,7 +376,7 @@ func TestPrevSlot(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := PrevSlot(tt.slot); got != tt.want { + if got := slots.PrevSlot(tt.slot); got != tt.want { t.Errorf("PrevSlot() = %v, want %v", got, tt.want) } }) @@ -393,7 +394,7 @@ func TestSyncCommitteePeriod(t *testing.T) { {epoch: 1000, wanted: 1000 / uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod)}, } for _, test := range tests { - require.Equal(t, test.wanted, SyncCommitteePeriod(test.epoch)) + require.Equal(t, test.wanted, slots.SyncCommitteePeriod(test.epoch)) } } @@ -408,7 +409,7 @@ func TestSyncCommitteePeriodStartEpoch(t *testing.T) { {epoch: params.BeaconConfig().EpochsPerSyncCommitteePeriod*params.BeaconConfig().EpochsPerSyncCommitteePeriod + 1, wanted: params.BeaconConfig().EpochsPerSyncCommitteePeriod * params.BeaconConfig().EpochsPerSyncCommitteePeriod}, } for _, test := range tests { - e, err := SyncCommitteePeriodStartEpoch(test.epoch) + e, err := slots.SyncCommitteePeriodStartEpoch(test.epoch) require.NoError(t, err) require.Equal(t, test.wanted, e) } diff --git a/beacon-chain/core/transition/BUILD.bazel b/beacon-chain/core/transition/BUILD.bazel index 1da96a65c..590d75dd0 100644 --- a/beacon-chain/core/transition/BUILD.bazel +++ b/beacon-chain/core/transition/BUILD.bazel @@ -46,6 +46,7 @@ go_library( "//proto/prysm/v1alpha1:go_default_library", "//proto/prysm/v1alpha1/block:go_default_library", "//runtime/version:go_default_library", + "//time/slots:go_default_library", "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prometheus_client_golang//prometheus/promauto:go_default_library", diff --git a/beacon-chain/core/transition/transition.go b/beacon-chain/core/transition/transition.go index b80f4ae4a..b8c4d2789 100644 --- a/beacon-chain/core/transition/transition.go +++ b/beacon-chain/core/transition/transition.go @@ -22,6 +22,7 @@ import ( "github.com/prysmaticlabs/prysm/monitoring/tracing" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" "github.com/prysmaticlabs/prysm/runtime/version" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" ) @@ -282,8 +283,8 @@ func ProcessSlots(ctx context.Context, state state.BeaconState, slot types.Slot) // Spec code: // If state.slot % SLOTS_PER_EPOCH == 0 and compute_epoch_at_slot(state.slot) == ALTAIR_FORK_EPOCH func CanUpgradeToAltair(slot types.Slot) bool { - epochStart := time.IsEpochStart(slot) - altairEpoch := time.SlotToEpoch(slot) == params.BeaconConfig().AltairForkEpoch + epochStart := slots.IsEpochStart(slot) + altairEpoch := slots.ToEpoch(slot) == params.BeaconConfig().AltairForkEpoch return epochStart && altairEpoch } diff --git a/beacon-chain/core/validators/BUILD.bazel b/beacon-chain/core/validators/BUILD.bazel index 4e11e6180..12667570b 100644 --- a/beacon-chain/core/validators/BUILD.bazel +++ b/beacon-chain/core/validators/BUILD.bazel @@ -14,6 +14,7 @@ go_library( "//beacon-chain/state:go_default_library", "//config/params:go_default_library", "//proto/prysm/v1alpha1:go_default_library", + "//time/slots:go_default_library", "@com_github_pkg_errors//:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", ], diff --git a/beacon-chain/core/validators/validator.go b/beacon-chain/core/validators/validator.go index 20458a755..ec76c4747 100644 --- a/beacon-chain/core/validators/validator.go +++ b/beacon-chain/core/validators/validator.go @@ -14,6 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" ) // InitiateValidatorExit takes in validator index and updates @@ -134,7 +135,7 @@ func SlashValidator( if err != nil { return nil, errors.Wrapf(err, "could not initiate validator %d exit", slashedIdx) } - currentEpoch := time.SlotToEpoch(s.Slot()) + currentEpoch := slots.ToEpoch(s.Slot()) validator, err := s.ValidatorAtIndex(slashedIdx) if err != nil { return nil, err diff --git a/beacon-chain/db/kv/BUILD.bazel b/beacon-chain/db/kv/BUILD.bazel index d4644e3eb..3da12b02d 100644 --- a/beacon-chain/db/kv/BUILD.bazel +++ b/beacon-chain/db/kv/BUILD.bazel @@ -36,7 +36,6 @@ go_library( deps = [ "//beacon-chain/core/blocks:go_default_library", "//beacon-chain/core/helpers:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/db/filters:go_default_library", "//beacon-chain/db/iface:go_default_library", "//beacon-chain/state:go_default_library", @@ -54,6 +53,7 @@ go_library( "//proto/prysm/v1alpha1/block:go_default_library", "//proto/prysm/v1alpha1/wrapper:go_default_library", "//runtime/version:go_default_library", + "//time/slots:go_default_library", "@com_github_dgraph_io_ristretto//:go_default_library", "@com_github_ethereum_go_ethereum//common:go_default_library", "@com_github_ethereum_go_ethereum//common/hexutil:go_default_library", diff --git a/beacon-chain/db/kv/blocks.go b/beacon-chain/db/kv/blocks.go index f6e0f5160..34c99778c 100644 --- a/beacon-chain/db/kv/blocks.go +++ b/beacon-chain/db/kv/blocks.go @@ -8,7 +8,6 @@ import ( "github.com/golang/snappy" "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/db/filters" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/container/slice" @@ -17,6 +16,7 @@ import ( "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/wrapper" "github.com/prysmaticlabs/prysm/runtime/version" + "github.com/prysmaticlabs/prysm/time/slots" bolt "go.etcd.io/bbolt" "go.opencensus.io/trace" ) @@ -479,11 +479,11 @@ func blockRootsBySlotRange( endEpoch, endEpochOk := endEpochEncoded.(types.Epoch) var err error if startEpochOk && endEpochOk { - startSlot, err = time.StartSlot(startEpoch) + startSlot, err = slots.EpochStart(startEpoch) if err != nil { return nil, err } - endSlot, err = time.StartSlot(endEpoch) + endSlot, err = slots.EpochStart(endEpoch) if err != nil { return nil, err } diff --git a/beacon-chain/db/kv/state.go b/beacon-chain/db/kv/state.go index baa8f1c4f..5554e59c2 100644 --- a/beacon-chain/db/kv/state.go +++ b/beacon-chain/db/kv/state.go @@ -8,7 +8,6 @@ import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/beacon-chain/state/genesis" v1 "github.com/prysmaticlabs/prysm/beacon-chain/state/v1" @@ -19,6 +18,7 @@ import ( "github.com/prysmaticlabs/prysm/monitoring/tracing" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/wrapper" + "github.com/prysmaticlabs/prysm/time/slots" bolt "go.etcd.io/bbolt" "go.opencensus.io/trace" ) @@ -666,7 +666,7 @@ func (s *Store) CleanUpDirtyStates(ctx context.Context, slotsPerArchivedPoint ty if err != nil { return err } - finalizedSlot, err := time.StartSlot(f.Epoch) + finalizedSlot, err := slots.EpochStart(f.Epoch) if err != nil { return err } diff --git a/beacon-chain/db/slasherkv/BUILD.bazel b/beacon-chain/db/slasherkv/BUILD.bazel index 7b2fd32c1..c3c168974 100644 --- a/beacon-chain/db/slasherkv/BUILD.bazel +++ b/beacon-chain/db/slasherkv/BUILD.bazel @@ -13,13 +13,13 @@ go_library( importpath = "github.com/prysmaticlabs/prysm/beacon-chain/db/slasherkv", visibility = ["//beacon-chain:__subpackages__"], deps = [ - "//beacon-chain/core/time:go_default_library", "//beacon-chain/db/iface:go_default_library", "//beacon-chain/slasher/types:go_default_library", "//config/params:go_default_library", "//encoding/bytesutil:go_default_library", "//io/file:go_default_library", "//proto/prysm/v1alpha1:go_default_library", + "//time/slots:go_default_library", "@com_github_ferranbt_fastssz//:go_default_library", "@com_github_golang_snappy//:go_default_library", "@com_github_pkg_errors//:go_default_library", @@ -43,13 +43,13 @@ go_test( ], embed = [":go_default_library"], deps = [ - "//beacon-chain/core/time:go_default_library", "//beacon-chain/slasher/types:go_default_library", "//config/params:go_default_library", "//encoding/bytesutil:go_default_library", "//proto/prysm/v1alpha1:go_default_library", "//testing/assert:go_default_library", "//testing/require:go_default_library", + "//time/slots:go_default_library", "@com_github_ferranbt_fastssz//:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", diff --git a/beacon-chain/db/slasherkv/pruning.go b/beacon-chain/db/slasherkv/pruning.go index 9710d580d..27cf1eca6 100644 --- a/beacon-chain/db/slasherkv/pruning.go +++ b/beacon-chain/db/slasherkv/pruning.go @@ -7,7 +7,7 @@ import ( fssz "github.com/ferranbt/fastssz" types "github.com/prysmaticlabs/eth2-types" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" + "github.com/prysmaticlabs/prysm/time/slots" bolt "go.etcd.io/bbolt" ) @@ -88,7 +88,7 @@ func (s *Store) PruneProposalsAtEpoch( ctx context.Context, maxEpoch types.Epoch, ) (numPruned uint, err error) { var endPruneSlot types.Slot - endPruneSlot, err = time.EndSlot(maxEpoch) + endPruneSlot, err = slots.EpochEnd(maxEpoch) if err != nil { return } diff --git a/beacon-chain/db/slasherkv/pruning_test.go b/beacon-chain/db/slasherkv/pruning_test.go index 346ca315d..ee530fc3c 100644 --- a/beacon-chain/db/slasherkv/pruning_test.go +++ b/beacon-chain/db/slasherkv/pruning_test.go @@ -6,10 +6,10 @@ import ( "testing" types "github.com/prysmaticlabs/eth2-types" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" slashertypes "github.com/prysmaticlabs/prysm/beacon-chain/slasher/types" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/testing/require" + "github.com/prysmaticlabs/prysm/time/slots" logTest "github.com/sirupsen/logrus/hooks/test" bolt "go.etcd.io/bbolt" ) @@ -29,7 +29,7 @@ func TestStore_PruneProposalsAtEpoch(t *testing.T) { historyLength := types.Epoch(10) pruningLimitEpoch := currentEpoch - historyLength - lowestStoredSlot, err := time.EndSlot(pruningLimitEpoch) + lowestStoredSlot, err := slots.EpochEnd(pruningLimitEpoch) require.NoError(t, err) err = beaconDB.db.Update(func(tx *bolt.Tx) error { @@ -68,9 +68,9 @@ func TestStore_PruneProposalsAtEpoch(t *testing.T) { slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch proposals := make([]*slashertypes.SignedBlockHeaderWrapper, 0, uint64(currentEpoch)*uint64(slotsPerEpoch)*2) for i := types.Epoch(0); i < currentEpoch; i++ { - startSlot, err := time.StartSlot(i) + startSlot, err := slots.EpochStart(i) require.NoError(t, err) - endSlot, err := time.StartSlot(i + 1) + endSlot, err := slots.EpochStart(i + 1) require.NoError(t, err) for j := startSlot; j < endSlot; j++ { prop1 := createProposalWrapper(t, j, 0 /* proposer index */, []byte{0}) @@ -89,9 +89,9 @@ func TestStore_PruneProposalsAtEpoch(t *testing.T) { for i := types.Epoch(0); i < pruningLimitEpoch; i++ { err = beaconDB.db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket(proposalRecordsBucket) - startSlot, err := time.StartSlot(i) + startSlot, err := slots.EpochStart(i) require.NoError(t, err) - endSlot, err := time.StartSlot(i + 1) + endSlot, err := slots.EpochStart(i + 1) require.NoError(t, err) for j := startSlot; j < endSlot; j++ { prop1Key, err := keyForValidatorProposal(j, 0) @@ -168,9 +168,9 @@ func TestStore_PruneAttestations_OK(t *testing.T) { slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch attestations := make([]*slashertypes.IndexedAttestationWrapper, 0, uint64(currentEpoch)*uint64(slotsPerEpoch)*2) for i := types.Epoch(0); i < currentEpoch; i++ { - startSlot, err := time.StartSlot(i) + startSlot, err := slots.EpochStart(i) require.NoError(t, err) - endSlot, err := time.StartSlot(i + 1) + endSlot, err := slots.EpochStart(i + 1) require.NoError(t, err) for j := startSlot; j < endSlot; j++ { attester1 := uint64(j + 10) @@ -196,9 +196,9 @@ func TestStore_PruneAttestations_OK(t *testing.T) { for i := types.Epoch(0); i < pruningLimitEpoch; i++ { err = beaconDB.db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket(attestationDataRootsBucket) - startSlot, err := time.StartSlot(i) + startSlot, err := slots.EpochStart(i) require.NoError(t, err) - endSlot, err := time.StartSlot(i + 1) + endSlot, err := slots.EpochStart(i + 1) require.NoError(t, err) for j := startSlot; j < endSlot; j++ { attester1 := types.ValidatorIndex(j + 10) diff --git a/beacon-chain/operations/voluntaryexits/BUILD.bazel b/beacon-chain/operations/voluntaryexits/BUILD.bazel index c8a285cd8..ad3dde9f5 100644 --- a/beacon-chain/operations/voluntaryexits/BUILD.bazel +++ b/beacon-chain/operations/voluntaryexits/BUILD.bazel @@ -13,10 +13,10 @@ go_library( "//testing/fuzz:__pkg__", ], deps = [ - "//beacon-chain/core/time:go_default_library", "//beacon-chain/state:go_default_library", "//config/params:go_default_library", "//proto/prysm/v1alpha1:go_default_library", + "//time/slots:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@io_opencensus_go//trace:go_default_library", ], diff --git a/beacon-chain/operations/voluntaryexits/service.go b/beacon-chain/operations/voluntaryexits/service.go index 72b487d15..4191efa2c 100644 --- a/beacon-chain/operations/voluntaryexits/service.go +++ b/beacon-chain/operations/voluntaryexits/service.go @@ -6,10 +6,10 @@ import ( "sync" types "github.com/prysmaticlabs/eth2-types" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" ) @@ -49,7 +49,7 @@ func (p *Pool) PendingExits(state state.ReadOnlyBeaconState, slot types.Slot, no } pending := make([]*ethpb.SignedVoluntaryExit, 0, maxExits) for _, e := range p.pending { - if e.Exit.Epoch > time.SlotToEpoch(slot) { + if e.Exit.Epoch > slots.ToEpoch(slot) { continue } if v, err := state.ValidatorAtIndexReadOnly(e.Exit.ValidatorIndex); err == nil && diff --git a/beacon-chain/p2p/broadcaster.go b/beacon-chain/p2p/broadcaster.go index 0e5258046..3d16670e6 100644 --- a/beacon-chain/p2p/broadcaster.go +++ b/beacon-chain/p2p/broadcaster.go @@ -10,12 +10,12 @@ import ( ssz "github.com/ferranbt/fastssz" "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/beacon-chain/core/altair" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/crypto/hash" "github.com/prysmaticlabs/prysm/monitoring/tracing" eth "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" "google.golang.org/protobuf/proto" ) @@ -130,7 +130,7 @@ func (s *Service) broadcastAttestation(ctx context.Context, subnet uint64, att * } // In the event our attestation is outdated and beyond the // acceptable threshold, we exit early and do not broadcast it. - currSlot := coreTime.CurrentSlot(uint64(s.genesisTime.Unix())) + currSlot := slots.CurrentSlot(uint64(s.genesisTime.Unix())) if att.Data.Slot+params.BeaconConfig().SlotsPerEpoch < currSlot { log.Warnf("Attestation is too old to broadcast, discarding it. Current Slot: %d , Attestation Slot: %d", currSlot, att.Data.Slot) return diff --git a/beacon-chain/p2p/discovery.go b/beacon-chain/p2p/discovery.go index ef1810099..997f00429 100644 --- a/beacon-chain/p2p/discovery.go +++ b/beacon-chain/p2p/discovery.go @@ -16,9 +16,9 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/beacon-chain/cache" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/runtime/version" + "github.com/prysmaticlabs/prysm/time/slots" ) // Listener defines the discovery V5 network interface that is used @@ -53,7 +53,7 @@ func (s *Service) RefreshENR() { return } // Compare current epoch with our fork epochs - currEpoch := coreTime.SlotToEpoch(coreTime.CurrentSlot(uint64(s.genesisTime.Unix()))) + currEpoch := slots.ToEpoch(slots.CurrentSlot(uint64(s.genesisTime.Unix()))) altairForkEpoch := params.BeaconConfig().AltairForkEpoch switch { // Altair Behaviour diff --git a/beacon-chain/p2p/fork.go b/beacon-chain/p2p/fork.go index 2ecccc1fc..67a19f128 100644 --- a/beacon-chain/p2p/fork.go +++ b/beacon-chain/p2p/fork.go @@ -8,11 +8,11 @@ import ( "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enr" "github.com/pkg/errors" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/network/forks" pb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" ) @@ -88,8 +88,8 @@ func addForkEntry( if err != nil { return nil, err } - currentSlot := coreTime.SlotsSince(genesisTime) - currentEpoch := coreTime.SlotToEpoch(currentSlot) + currentSlot := slots.Since(genesisTime) + currentEpoch := slots.ToEpoch(currentSlot) if prysmTime.Now().Before(genesisTime) { currentEpoch = 0 } diff --git a/beacon-chain/p2p/fork_watcher.go b/beacon-chain/p2p/fork_watcher.go index 632b89085..d7f3c3d31 100644 --- a/beacon-chain/p2p/fork_watcher.go +++ b/beacon-chain/p2p/fork_watcher.go @@ -1,7 +1,6 @@ package p2p import ( - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/time/slots" ) @@ -14,7 +13,7 @@ func (s *Service) forkWatcher() { for { select { case currSlot := <-slotTicker.C(): - currEpoch := time.SlotToEpoch(currSlot) + currEpoch := slots.ToEpoch(currSlot) if currEpoch == params.BeaconConfig().AltairForkEpoch { // If we are in the fork epoch, we update our enr with // the updated fork digest. These repeatedly does diff --git a/beacon-chain/p2p/peers/BUILD.bazel b/beacon-chain/p2p/peers/BUILD.bazel index e98e7a87c..d04e468a7 100644 --- a/beacon-chain/p2p/peers/BUILD.bazel +++ b/beacon-chain/p2p/peers/BUILD.bazel @@ -6,7 +6,6 @@ go_library( importpath = "github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers", visibility = ["//beacon-chain:__subpackages__"], deps = [ - "//beacon-chain/core/time:go_default_library", "//beacon-chain/p2p/peers/peerdata:go_default_library", "//beacon-chain/p2p/peers/scorers:go_default_library", "//config/features:go_default_library", @@ -15,6 +14,7 @@ go_library( "//proto/prysm/v1alpha1:go_default_library", "//proto/prysm/v1alpha1/metadata:go_default_library", "//time:go_default_library", + "//time/slots:go_default_library", "@com_github_ethereum_go_ethereum//p2p/enr:go_default_library", "@com_github_libp2p_go_libp2p_core//network:go_default_library", "@com_github_libp2p_go_libp2p_core//peer:go_default_library", diff --git a/beacon-chain/p2p/peers/status.go b/beacon-chain/p2p/peers/status.go index 810af0b5a..391d0ecf4 100644 --- a/beacon-chain/p2p/peers/status.go +++ b/beacon-chain/p2p/peers/status.go @@ -35,7 +35,6 @@ import ( manet "github.com/multiformats/go-multiaddr/net" types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/go-bitfield" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers/peerdata" "github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers/scorers" "github.com/prysmaticlabs/prysm/config/features" @@ -44,6 +43,7 @@ import ( pb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/metadata" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" ) const ( @@ -707,7 +707,7 @@ func (p *Status) BestNonFinalized(minPeers int, ourHeadEpoch types.Epoch) (types for _, pid := range connected { peerChainState, err := p.ChainState(pid) if err == nil && peerChainState != nil && peerChainState.HeadSlot > ourHeadSlot { - epoch := coreTime.SlotToEpoch(peerChainState.HeadSlot) + epoch := slots.ToEpoch(peerChainState.HeadSlot) epochVotes[epoch]++ pidEpoch[pid] = epoch pidHead[pid] = peerChainState.HeadSlot @@ -876,7 +876,7 @@ func (p *Status) HighestEpoch() types.Epoch { highestSlot = peerData.ChainState.HeadSlot } } - return coreTime.SlotToEpoch(highestSlot) + return slots.ToEpoch(highestSlot) } // ConnectedPeerLimit returns the peer limit of diff --git a/beacon-chain/powchain/BUILD.bazel b/beacon-chain/powchain/BUILD.bazel index e90449132..160a8d7c8 100644 --- a/beacon-chain/powchain/BUILD.bazel +++ b/beacon-chain/powchain/BUILD.bazel @@ -23,7 +23,6 @@ go_library( "//beacon-chain/core/feed:go_default_library", "//beacon-chain/core/feed/state:go_default_library", "//beacon-chain/core/helpers:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/core/transition:go_default_library", "//beacon-chain/db:go_default_library", "//beacon-chain/powchain/types:go_default_library", @@ -42,6 +41,7 @@ go_library( "//network/authorization:go_default_library", "//proto/prysm/v1alpha1:go_default_library", "//time:go_default_library", + "//time/slots:go_default_library", "@com_github_ethereum_go_ethereum//:go_default_library", "@com_github_ethereum_go_ethereum//accounts/abi/bind:go_default_library", "@com_github_ethereum_go_ethereum//common:go_default_library", @@ -80,7 +80,6 @@ go_test( "//beacon-chain/core/feed/state:go_default_library", "//beacon-chain/core/helpers:go_default_library", "//beacon-chain/core/signing:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/db:go_default_library", "//beacon-chain/db/testing:go_default_library", "//beacon-chain/powchain/testing:go_default_library", @@ -99,6 +98,7 @@ go_test( "//testing/assert:go_default_library", "//testing/require:go_default_library", "//testing/util:go_default_library", + "//time/slots:go_default_library", "@com_github_ethereum_go_ethereum//:go_default_library", "@com_github_ethereum_go_ethereum//accounts/abi/bind/backends:go_default_library", "@com_github_ethereum_go_ethereum//common:go_default_library", diff --git a/beacon-chain/powchain/service.go b/beacon-chain/powchain/service.go index 093bbe16e..405372ab8 100644 --- a/beacon-chain/powchain/service.go +++ b/beacon-chain/powchain/service.go @@ -25,7 +25,6 @@ import ( "github.com/prometheus/client_golang/prometheus/promauto" "github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache" statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/beacon-chain/db" "github.com/prysmaticlabs/prysm/beacon-chain/powchain/types" @@ -43,6 +42,7 @@ import ( ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" protodb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" ) @@ -891,7 +891,7 @@ func (s *Service) cacheHeadersForEth1DataVote(ctx context.Context) error { // determines the earliest voting block from which to start caching all our previous headers from. func (s *Service) determineEarliestVotingBlock(ctx context.Context, followBlock uint64) (uint64, error) { genesisTime := s.chainStartData.GenesisTime - currSlot := coreTime.CurrentSlot(genesisTime) + currSlot := slots.CurrentSlot(genesisTime) // In the event genesis has not occurred yet, we just request go back follow_distance blocks. if genesisTime == 0 || currSlot == 0 { @@ -901,7 +901,7 @@ func (s *Service) determineEarliestVotingBlock(ctx context.Context, followBlock } return earliestBlk, nil } - votingTime := coreTime.VotingPeriodStartTime(genesisTime, currSlot) + votingTime := slots.VotingPeriodStartTime(genesisTime, currSlot) followBackDist := 2 * params.BeaconConfig().SecondsPerETH1Block * params.BeaconConfig().Eth1FollowDistance if followBackDist > votingTime { return 0, errors.Errorf("invalid genesis time provided. %d > %d", followBackDist, votingTime) diff --git a/beacon-chain/powchain/service_test.go b/beacon-chain/powchain/service_test.go index 0dbf01e67..b6d4ac2a4 100644 --- a/beacon-chain/powchain/service_test.go +++ b/beacon-chain/powchain/service_test.go @@ -17,7 +17,6 @@ import ( gethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/prysmaticlabs/prysm/async/event" "github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" dbutil "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" mockPOW "github.com/prysmaticlabs/prysm/beacon-chain/powchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/state/stategen" @@ -32,6 +31,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" logTest "github.com/sirupsen/logrus/hooks/test" ) @@ -534,7 +534,7 @@ func TestInitDepositCacheWithFinalization_OK(t *testing.T) { require.NoError(t, stateGen.SaveState(ctx, headRoot, emptyState)) require.NoError(t, beaconDB.SaveState(ctx, emptyState, headRoot)) require.NoError(t, beaconDB.SaveBlock(ctx, wrapper.WrappedPhase0SignedBeaconBlock(headBlock))) - require.NoError(t, beaconDB.SaveFinalizedCheckpoint(ctx, ðpb.Checkpoint{Epoch: coreTime.SlotToEpoch(0), Root: headRoot[:]})) + require.NoError(t, beaconDB.SaveFinalizedCheckpoint(ctx, ðpb.Checkpoint{Epoch: slots.ToEpoch(0), Root: headRoot[:]})) s.chainStartData.Chainstarted = true require.NoError(t, s.initDepositCaches(context.Background(), ctrs)) diff --git a/beacon-chain/rpc/apimiddleware/BUILD.bazel b/beacon-chain/rpc/apimiddleware/BUILD.bazel index a2f8ec6a0..c0e14fc3e 100644 --- a/beacon-chain/rpc/apimiddleware/BUILD.bazel +++ b/beacon-chain/rpc/apimiddleware/BUILD.bazel @@ -14,11 +14,11 @@ go_library( deps = [ "//api/gateway/apimiddleware:go_default_library", "//api/grpc:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/rpc/eth/events:go_default_library", "//config/params:go_default_library", "//encoding/bytesutil:go_default_library", "//proto/eth/v2:go_default_library", + "//time/slots:go_default_library", "@com_github_ethereum_go_ethereum//common/hexutil:go_default_library", "@com_github_pkg_errors//:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", @@ -37,13 +37,13 @@ go_test( deps = [ "//api/gateway/apimiddleware:go_default_library", "//api/grpc:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/rpc/eth/events:go_default_library", "//config/params:go_default_library", "//encoding/bytesutil:go_default_library", "//proto/eth/v2:go_default_library", "//testing/assert:go_default_library", "//testing/require:go_default_library", + "//time/slots:go_default_library", "@com_github_gogo_protobuf//types:go_default_library", "@com_github_r3labs_sse//:go_default_library", ], diff --git a/beacon-chain/rpc/apimiddleware/custom_hooks.go b/beacon-chain/rpc/apimiddleware/custom_hooks.go index 6ff94768d..71e9c3b9f 100644 --- a/beacon-chain/rpc/apimiddleware/custom_hooks.go +++ b/beacon-chain/rpc/apimiddleware/custom_hooks.go @@ -12,10 +12,10 @@ import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/api/gateway/apimiddleware" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpbv2 "github.com/prysmaticlabs/prysm/proto/eth/v2" + "github.com/prysmaticlabs/prysm/time/slots" ) // https://ethereum.github.io/beacon-apis/#/Beacon/submitPoolAttestations expects posting a top-level array. @@ -208,7 +208,7 @@ func setInitialPublishBlockPostRequest(endpoint *apimiddleware.Endpoint, if err != nil { return false, apimiddleware.InternalServerErrorWithMessage(err, "slot is not an unsigned integer") } - if time.SlotToEpoch(types.Slot(slot)) < params.BeaconConfig().AltairForkEpoch { + if slots.ToEpoch(types.Slot(slot)) < params.BeaconConfig().AltairForkEpoch { endpoint.PostRequest = &signedBeaconBlockContainerJson{} } else { endpoint.PostRequest = &signedBeaconBlockAltairContainerJson{} diff --git a/beacon-chain/rpc/apimiddleware/custom_hooks_test.go b/beacon-chain/rpc/apimiddleware/custom_hooks_test.go index 2973c0e53..3e20b43c0 100644 --- a/beacon-chain/rpc/apimiddleware/custom_hooks_test.go +++ b/beacon-chain/rpc/apimiddleware/custom_hooks_test.go @@ -12,12 +12,12 @@ import ( "github.com/gogo/protobuf/types" "github.com/prysmaticlabs/prysm/api/gateway/apimiddleware" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpbv2 "github.com/prysmaticlabs/prysm/proto/eth/v2" "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" + "github.com/prysmaticlabs/prysm/time/slots" ) func TestWrapAttestationArray(t *testing.T) { @@ -384,7 +384,7 @@ func TestSetInitialPublishBlockPostRequest(t *testing.T) { assert.Equal(t, reflect.TypeOf(signedBeaconBlockContainerJson{}).Name(), reflect.Indirect(reflect.ValueOf(endpoint.PostRequest)).Type().Name()) }) t.Run("Altair", func(t *testing.T) { - slot, err := time.StartSlot(params.BeaconConfig().AltairForkEpoch) + slot, err := slots.EpochStart(params.BeaconConfig().AltairForkEpoch) require.NoError(t, err) s.Message = struct{ Slot string }{Slot: strconv.FormatUint(uint64(slot), 10)} j, err := json.Marshal(s) diff --git a/beacon-chain/rpc/eth/beacon/BUILD.bazel b/beacon-chain/rpc/eth/beacon/BUILD.bazel index ab5f0e0f9..2008698d3 100644 --- a/beacon-chain/rpc/eth/beacon/BUILD.bazel +++ b/beacon-chain/rpc/eth/beacon/BUILD.bazel @@ -23,7 +23,6 @@ go_library( "//beacon-chain/core/feed/block:go_default_library", "//beacon-chain/core/feed/operation:go_default_library", "//beacon-chain/core/helpers:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/db:go_default_library", "//beacon-chain/db/filters:go_default_library", "//beacon-chain/operations/attestations:go_default_library", @@ -47,6 +46,7 @@ go_library( "//proto/prysm/v1alpha1:go_default_library", "//proto/prysm/v1alpha1/block:go_default_library", "//proto/prysm/v1alpha1/wrapper:go_default_library", + "//time/slots:go_default_library", "@com_github_ethereum_go_ethereum//common/hexutil:go_default_library", "@com_github_pkg_errors//:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", @@ -77,7 +77,6 @@ go_test( "//api/grpc:go_default_library", "//beacon-chain/blockchain/testing:go_default_library", "//beacon-chain/core/signing:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/db:go_default_library", "//beacon-chain/db/testing:go_default_library", "//beacon-chain/operations/attestations:go_default_library", @@ -104,6 +103,7 @@ go_test( "//testing/assert:go_default_library", "//testing/require:go_default_library", "//testing/util:go_default_library", + "//time/slots:go_default_library", "@com_github_grpc_ecosystem_grpc_gateway_v2//runtime:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", diff --git a/beacon-chain/rpc/eth/beacon/pool.go b/beacon-chain/rpc/eth/beacon/pool.go index f5cf1d109..2caefd3b2 100644 --- a/beacon-chain/rpc/eth/beacon/pool.go +++ b/beacon-chain/rpc/eth/beacon/pool.go @@ -8,13 +8,13 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/operation" corehelpers "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/rpc/eth/helpers" "github.com/prysmaticlabs/prysm/config/features" "github.com/prysmaticlabs/prysm/crypto/bls" ethpbv1 "github.com/prysmaticlabs/prysm/proto/eth/v1" "github.com/prysmaticlabs/prysm/proto/migration" ethpbalpha "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -99,7 +99,7 @@ func (bs *Server) SubmitAttestations(ctx context.Context, req *ethpbv1.SubmitAtt broadcastFailed := false for _, att := range validAttestations { // Determine subnet to broadcast attestation to - wantedEpoch := time.SlotToEpoch(att.Data.Slot) + wantedEpoch := slots.ToEpoch(att.Data.Slot) vals, err := bs.HeadFetcher.HeadValidatorsIndices(ctx, wantedEpoch) if err != nil { return nil, err diff --git a/beacon-chain/rpc/eth/beacon/pool_test.go b/beacon-chain/rpc/eth/beacon/pool_test.go index 288859ddf..b66bf0e93 100644 --- a/beacon-chain/rpc/eth/beacon/pool_test.go +++ b/beacon-chain/rpc/eth/beacon/pool_test.go @@ -13,7 +13,6 @@ import ( chainMock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" notifiermock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/operations/attestations" "github.com/prysmaticlabs/prysm/beacon-chain/operations/slashings" "github.com/prysmaticlabs/prysm/beacon-chain/operations/voluntaryexits" @@ -27,6 +26,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/emptypb" ) @@ -526,7 +526,7 @@ func TestSubmitProposerSlashing_Ok(t *testing.T) { for _, h := range []*ethpbv1.SignedBeaconBlockHeader{slashing.SignedHeader_1, slashing.SignedHeader_2} { sb, err := signing.ComputeDomainAndSign( state, - time.SlotToEpoch(h.Message.Slot), + slots.ToEpoch(h.Message.Slot), h.Message, params.BeaconConfig().DomainBeaconProposer, keys[0], @@ -766,7 +766,7 @@ func TestServer_SubmitAttestations_Ok(t *testing.T) { for _, att := range []*ethpbv1.Attestation{att1, att2} { sb, err := signing.ComputeDomainAndSign( state, - time.SlotToEpoch(att.Data.Slot), + slots.ToEpoch(att.Data.Slot), att.Data, params.BeaconConfig().DomainBeaconAttester, keys[0], @@ -873,7 +873,7 @@ func TestServer_SubmitAttestations_ValidAttestationSubmitted(t *testing.T) { // Don't sign attInvalidSignature. sb, err := signing.ComputeDomainAndSign( state, - time.SlotToEpoch(attValid.Data.Slot), + slots.ToEpoch(attValid.Data.Slot), attValid.Data, params.BeaconConfig().DomainBeaconAttester, keys[0], diff --git a/beacon-chain/rpc/eth/beacon/state.go b/beacon-chain/rpc/eth/beacon/state.go index b893a5036..936502604 100644 --- a/beacon-chain/rpc/eth/beacon/state.go +++ b/beacon-chain/rpc/eth/beacon/state.go @@ -6,13 +6,13 @@ import ( "strconv" types "github.com/prysmaticlabs/eth2-types" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/rpc/eth/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/rpc/statefetcher" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" ethpb "github.com/prysmaticlabs/prysm/proto/eth/v1" eth "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -136,7 +136,7 @@ func (bs *Server) GetFinalityCheckpoints(ctx context.Context, req *ethpb.StateRe func (bs *Server) stateFromRequest(ctx context.Context, req *stateRequest) (state.BeaconState, error) { if req.epoch != nil { - slot, err := time.StartSlot(*req.epoch) + slot, err := slots.EpochStart(*req.epoch) if err != nil { return nil, status.Errorf( codes.Internal, diff --git a/beacon-chain/rpc/eth/beacon/validator.go b/beacon-chain/rpc/eth/beacon/validator.go index edbdb3fb8..921302c9d 100644 --- a/beacon-chain/rpc/eth/beacon/validator.go +++ b/beacon-chain/rpc/eth/beacon/validator.go @@ -7,7 +7,6 @@ import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" corehelpers "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/rpc/eth/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/state" v1 "github.com/prysmaticlabs/prysm/beacon-chain/state/v1" @@ -15,6 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/eth/v1" "github.com/prysmaticlabs/prysm/proto/migration" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -87,7 +87,7 @@ func (bs *Server) ListValidators(ctx context.Context, req *ethpb.StateValidators } filterStatus[ss] = true } - epoch := time.SlotToEpoch(st.Slot()) + epoch := slots.ToEpoch(st.Slot()) filteredVals := make([]*ethpb.ValidatorContainer, 0, len(valContainers)) for _, vc := range valContainers { readOnlyVal, err := v1.NewValidator(migration.V1ValidatorToV1Alpha1(vc.Validator)) @@ -144,7 +144,7 @@ func (bs *Server) ListCommittees(ctx context.Context, req *ethpb.StateCommittees return nil, helpers.PrepareStateFetchGRPCError(err) } - epoch := time.SlotToEpoch(st.Slot()) + epoch := slots.ToEpoch(st.Slot()) if req.Epoch != nil { epoch = *req.Epoch } @@ -153,11 +153,11 @@ func (bs *Server) ListCommittees(ctx context.Context, req *ethpb.StateCommittees return nil, status.Errorf(codes.Internal, "Could not get active validator count: %v", err) } - startSlot, err := time.StartSlot(epoch) + startSlot, err := slots.EpochStart(epoch) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "Invalid epoch: %v", err) } - endSlot, err := time.EndSlot(epoch) + endSlot, err := slots.EpochEnd(epoch) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "Invalid epoch: %v", err) } @@ -189,7 +189,7 @@ func (bs *Server) ListCommittees(ctx context.Context, req *ethpb.StateCommittees // This function returns the validator object based on the passed in ID. The validator ID could be its public key, // or its index. func valContainersByRequestIds(state state.BeaconState, validatorIds [][]byte) ([]*ethpb.ValidatorContainer, error) { - epoch := time.SlotToEpoch(state.Slot()) + epoch := slots.ToEpoch(state.Slot()) var valContainers []*ethpb.ValidatorContainer if len(validatorIds) == 0 { allValidators := state.Validators() diff --git a/beacon-chain/rpc/eth/beacon/validator_test.go b/beacon-chain/rpc/eth/beacon/validator_test.go index b6468066d..a19e8fb9a 100644 --- a/beacon-chain/rpc/eth/beacon/validator_test.go +++ b/beacon-chain/rpc/eth/beacon/validator_test.go @@ -8,7 +8,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" chainMock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" rpchelpers "github.com/prysmaticlabs/prysm/beacon-chain/rpc/eth/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/rpc/statefetcher" "github.com/prysmaticlabs/prysm/beacon-chain/rpc/testutil" @@ -21,6 +20,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" ) func TestGetValidator(t *testing.T) { @@ -511,7 +511,7 @@ func TestListCommittees(t *testing.T) { var st state.BeaconState st, _ = util.DeterministicGenesisState(t, 8192) - epoch := time.SlotToEpoch(st.Slot()) + epoch := slots.ToEpoch(st.Slot()) t.Run("Head All Committees", func(t *testing.T) { s := Server{ @@ -527,7 +527,7 @@ func TestListCommittees(t *testing.T) { assert.Equal(t, int(params.BeaconConfig().SlotsPerEpoch)*2, len(resp.Data)) for _, datum := range resp.Data { assert.Equal(t, true, datum.Index == types.CommitteeIndex(0) || datum.Index == types.CommitteeIndex(1)) - assert.Equal(t, epoch, time.SlotToEpoch(datum.Slot)) + assert.Equal(t, epoch, slots.ToEpoch(datum.Slot)) } }) @@ -564,7 +564,7 @@ func TestListCommittees(t *testing.T) { assert.Equal(t, 2, len(resp.Data)) index := types.CommitteeIndex(0) for _, datum := range resp.Data { - assert.Equal(t, epoch, time.SlotToEpoch(datum.Slot)) + assert.Equal(t, epoch, slots.ToEpoch(datum.Slot)) assert.Equal(t, slot, datum.Slot) assert.Equal(t, index, datum.Index) index++ @@ -587,7 +587,7 @@ func TestListCommittees(t *testing.T) { assert.Equal(t, int(params.BeaconConfig().SlotsPerEpoch), len(resp.Data)) slot := types.Slot(0) for _, datum := range resp.Data { - assert.Equal(t, epoch, time.SlotToEpoch(datum.Slot)) + assert.Equal(t, epoch, slots.ToEpoch(datum.Slot)) assert.Equal(t, slot, datum.Slot) assert.Equal(t, index, datum.Index) slot++ @@ -611,7 +611,7 @@ func TestListCommittees(t *testing.T) { require.NoError(t, err) assert.Equal(t, 1, len(resp.Data)) for _, datum := range resp.Data { - assert.Equal(t, epoch, time.SlotToEpoch(datum.Slot)) + assert.Equal(t, epoch, slots.ToEpoch(datum.Slot)) assert.Equal(t, slot, datum.Slot) assert.Equal(t, index, datum.Index) } diff --git a/beacon-chain/rpc/eth/validator/BUILD.bazel b/beacon-chain/rpc/eth/validator/BUILD.bazel index f1b183dee..51c087bb7 100644 --- a/beacon-chain/rpc/eth/validator/BUILD.bazel +++ b/beacon-chain/rpc/eth/validator/BUILD.bazel @@ -12,7 +12,6 @@ go_library( "//beacon-chain/blockchain:go_default_library", "//beacon-chain/cache:go_default_library", "//beacon-chain/core/helpers:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/core/transition:go_default_library", "//beacon-chain/operations/attestations:go_default_library", "//beacon-chain/operations/synccommittee:go_default_library", @@ -29,6 +28,7 @@ go_library( "//proto/eth/v2:go_default_library", "//proto/migration:go_default_library", "//proto/prysm/v1alpha1:go_default_library", + "//time/slots: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", @@ -75,6 +75,7 @@ go_test( "//testing/assert:go_default_library", "//testing/require:go_default_library", "//testing/util:go_default_library", + "//time/slots:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@org_golang_google_protobuf//proto:go_default_library", diff --git a/beacon-chain/rpc/eth/validator/validator.go b/beacon-chain/rpc/eth/validator/validator.go index 414630976..b586e42fe 100644 --- a/beacon-chain/rpc/eth/validator/validator.go +++ b/beacon-chain/rpc/eth/validator/validator.go @@ -12,7 +12,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/cache" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" rpchelpers "github.com/prysmaticlabs/prysm/beacon-chain/rpc/eth/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -23,6 +22,7 @@ import ( ethpbv2 "github.com/prysmaticlabs/prysm/proto/eth/v2" "github.com/prysmaticlabs/prysm/proto/migration" ethpbalpha "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" log "github.com/sirupsen/logrus" "go.opencensus.io/trace" "google.golang.org/grpc/codes" @@ -41,7 +41,7 @@ func (vs *Server) GetAttesterDuties(ctx context.Context, req *ethpbv1.AttesterDu } cs := vs.TimeFetcher.CurrentSlot() - currentEpoch := coreTime.SlotToEpoch(cs) + currentEpoch := slots.ToEpoch(cs) if req.Epoch > currentEpoch+1 { return nil, status.Errorf(codes.InvalidArgument, "Request epoch %d can not be greater than next epoch %d", req.Epoch, currentEpoch+1) } @@ -115,7 +115,7 @@ func (vs *Server) GetProposerDuties(ctx context.Context, req *ethpbv1.ProposerDu } cs := vs.TimeFetcher.CurrentSlot() - currentEpoch := coreTime.SlotToEpoch(cs) + currentEpoch := slots.ToEpoch(cs) if req.Epoch > currentEpoch { return nil, status.Errorf(codes.InvalidArgument, "Request epoch %d can not be greater than current epoch %d", req.Epoch, currentEpoch) } @@ -175,7 +175,7 @@ func (vs *Server) GetSyncCommitteeDuties(ctx context.Context, req *ethpbv2.SyncC return nil, status.Error(codes.Unavailable, "Syncing to latest head, not ready to respond") } - slot, err := coreTime.StartSlot(req.Epoch) + slot, err := slots.EpochStart(req.Epoch) if err != nil { return nil, status.Errorf(codes.Internal, "Could not get sync committee slot: %v", err) } @@ -235,7 +235,7 @@ func (vs *Server) ProduceBlockV2(ctx context.Context, req *ethpbv1.ProduceBlockR _, span := trace.StartSpan(ctx, "validator.ProduceBlockV2") defer span.End() - epoch := coreTime.SlotToEpoch(req.Slot) + epoch := slots.ToEpoch(req.Slot) if epoch < params.BeaconConfig().AltairForkEpoch { block, err := vs.v1BeaconBlock(ctx, req) if err != nil { @@ -403,7 +403,7 @@ func (vs *Server) SubmitBeaconCommitteeSubscription(ctx context.Context, req *et } fetchValsLen := func(slot types.Slot) (uint64, error) { - wantedEpoch := coreTime.SlotToEpoch(slot) + wantedEpoch := slots.ToEpoch(slot) vals, err := vs.HeadFetcher.HeadValidatorsIndices(ctx, wantedEpoch) if err != nil { return 0, err @@ -416,16 +416,16 @@ func (vs *Server) SubmitBeaconCommitteeSubscription(ctx context.Context, req *et if err != nil { return nil, status.Errorf(codes.Internal, "Could not retrieve head validator length: %v", err) } - currEpoch := coreTime.SlotToEpoch(req.Data[0].Slot) + currEpoch := slots.ToEpoch(req.Data[0].Slot) for _, sub := range req.Data { // If epoch has changed, re-request active validators length - if currEpoch != coreTime.SlotToEpoch(sub.Slot) { + if currEpoch != slots.ToEpoch(sub.Slot) { currValsLen, err = fetchValsLen(sub.Slot) if err != nil { return nil, status.Errorf(codes.Internal, "Could not retrieve head validator length: %v", err) } - currEpoch = coreTime.SlotToEpoch(sub.Slot) + currEpoch = slots.ToEpoch(sub.Slot) } subnet := helpers.ComputeSubnetFromCommitteeAndSlot(currValsLen, sub.CommitteeIndex, sub.Slot) cache.SubnetIDs.AddAttesterSubnetID(sub.Slot, subnet) @@ -465,7 +465,7 @@ func (vs *Server) SubmitSyncCommitteeSubscription(ctx context.Context, req *ethp if err != nil { return nil, status.Errorf(codes.Internal, "Could not get head state: %v", err) } - currEpoch := coreTime.SlotToEpoch(s.Slot()) + currEpoch := slots.ToEpoch(s.Slot()) validators := make([]state.ReadOnlyValidator, len(req.Data)) for i, sub := range req.Data { val, err := s.ValidatorAtIndexReadOnly(sub.ValidatorIndex) @@ -482,7 +482,7 @@ func (vs *Server) SubmitSyncCommitteeSubscription(ctx context.Context, req *ethp validators[i] = val } - currPeriod := coreTime.SyncCommitteePeriod(currEpoch) + currPeriod := slots.SyncCommitteePeriod(currEpoch) startEpoch := types.Epoch(currPeriod * uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod)) for i, sub := range req.Data { @@ -583,7 +583,7 @@ func attestationDependentRoot(s state.BeaconState, epoch types.Epoch) ([]byte, e if epoch <= 1 { dependentRootSlot = 0 } else { - prevEpochStartSlot, err := coreTime.StartSlot(epoch.Sub(1)) + prevEpochStartSlot, err := slots.EpochStart(epoch.Sub(1)) if err != nil { return nil, status.Errorf(codes.Internal, "Could not obtain epoch's start slot: %v", err) } @@ -603,7 +603,7 @@ func proposalDependentRoot(s state.BeaconState, epoch types.Epoch) ([]byte, erro if epoch == 0 { dependentRootSlot = 0 } else { - epochStartSlot, err := coreTime.StartSlot(epoch) + epochStartSlot, err := slots.EpochStart(epoch) if err != nil { return nil, status.Errorf(codes.Internal, "Could not obtain epoch's start slot: %v", err) } @@ -623,12 +623,12 @@ func advanceState(ctx context.Context, s state.BeaconState, requestedEpoch, curr var epochStartSlot types.Slot var err error if requestedEpoch == currentEpoch+1 { - epochStartSlot, err = coreTime.StartSlot(requestedEpoch.Sub(1)) + epochStartSlot, err = slots.EpochStart(requestedEpoch.Sub(1)) if err != nil { return nil, errors.Wrap(err, "Could not obtain epoch's start slot") } } else { - epochStartSlot, err = coreTime.StartSlot(requestedEpoch) + epochStartSlot, err = slots.EpochStart(requestedEpoch) if err != nil { return nil, errors.Wrap(err, "Could not obtain epoch's start slot") } diff --git a/beacon-chain/rpc/eth/validator/validator_test.go b/beacon-chain/rpc/eth/validator/validator_test.go index 3d959290a..a3fe876df 100644 --- a/beacon-chain/rpc/eth/validator/validator_test.go +++ b/beacon-chain/rpc/eth/validator/validator_test.go @@ -39,6 +39,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/protobuf/proto" ) @@ -106,7 +107,7 @@ func TestGetAttesterDuties(t *testing.T) { t.Run("Next epoch", func(t *testing.T) { req := ðpbv1.AttesterDutiesRequest{ - Epoch: coreTime.SlotToEpoch(bs.Slot()) + 1, + Epoch: slots.ToEpoch(bs.Slot()) + 1, Index: []types.ValidatorIndex{0}, } resp, err := vs.GetAttesterDuties(ctx, req) @@ -172,7 +173,7 @@ func TestGetAttesterDuties(t *testing.T) { }) t.Run("Epoch out of bound", func(t *testing.T) { - currentEpoch := coreTime.SlotToEpoch(bs.Slot()) + currentEpoch := slots.ToEpoch(bs.Slot()) req := ðpbv1.AttesterDutiesRequest{ Epoch: currentEpoch + 2, Index: []types.ValidatorIndex{0}, @@ -304,7 +305,7 @@ func TestGetProposerDuties(t *testing.T) { }) t.Run("Epoch out of bound", func(t *testing.T) { - currentEpoch := coreTime.SlotToEpoch(bs.Slot()) + currentEpoch := slots.ToEpoch(bs.Slot()) req := ðpbv1.ProposerDutiesRequest{ Epoch: currentEpoch + 1, } diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/BUILD.bazel b/beacon-chain/rpc/prysm/v1alpha1/beacon/BUILD.bazel index 7c6b582fe..6601b5a00 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/BUILD.bazel +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/BUILD.bazel @@ -113,6 +113,7 @@ go_test( "//testing/require:go_default_library", "//testing/util:go_default_library", "//time:go_default_library", + "//time/slots:go_default_library", "@com_github_golang_mock//gomock:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments.go index 02dade3c2..7d57689e0 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments.go @@ -7,10 +7,10 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/api/pagination" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/cmd" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -44,7 +44,7 @@ func (bs *Server) ListValidatorAssignments( requestedEpoch = q.Epoch } - currentEpoch := time.SlotToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) + currentEpoch := slots.ToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) if requestedEpoch > currentEpoch { return nil, status.Errorf( codes.InvalidArgument, @@ -54,7 +54,7 @@ func (bs *Server) ListValidatorAssignments( ) } - startSlot, err := time.StartSlot(requestedEpoch) + startSlot, err := slots.EpochStart(requestedEpoch) if err != nil { return nil, err } diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments_test.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments_test.go index 9c12c44e8..c0bd7fccb 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments_test.go @@ -10,7 +10,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" dbTest "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/state/stategen" "github.com/prysmaticlabs/prysm/cmd" @@ -20,6 +19,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/protobuf/proto" ) @@ -37,7 +37,7 @@ func TestServer_ListAssignments_CannotRequestFutureEpoch(t *testing.T) { ctx, ðpb.ListValidatorAssignmentsRequest{ QueryFilter: ðpb.ListValidatorAssignmentsRequest_Epoch{ - Epoch: time.SlotToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) + 1, + Epoch: slots.ToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) + 1, }, }, ) diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/attestations.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/attestations.go index 303190e8f..2782e9a9d 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/attestations.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/attestations.go @@ -10,7 +10,6 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/operation" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/db/filters" "github.com/prysmaticlabs/prysm/cmd" "github.com/prysmaticlabs/prysm/config/params" @@ -302,7 +301,7 @@ func (bs *Server) StreamIndexedAttestations( } // We use the retrieved committees for the epoch to convert all attestations // into indexed form effectively. - startSlot, err := time.StartSlot(targetEpoch) + startSlot, err := slots.EpochStart(targetEpoch) if err != nil { log.Error(err) continue diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/attestations_test.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/attestations_test.go index 700a89f29..2791b4e9a 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/attestations_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/attestations_test.go @@ -16,7 +16,6 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/operation" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" dbTest "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/operations/attestations" "github.com/prysmaticlabs/prysm/beacon-chain/state/stategen" @@ -33,6 +32,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/mock" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/emptypb" ) @@ -608,7 +608,7 @@ func TestServer_ListIndexedAttestations_OldEpoch(t *testing.T) { count := params.BeaconConfig().SlotsPerEpoch atts := make([]*ethpb.Attestation, 0, count) epoch := types.Epoch(50) - startSlot, err := coreTime.StartSlot(epoch) + startSlot, err := slots.EpochStart(epoch) require.NoError(t, err) for i := startSlot; i < count; i++ { diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/blocks.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/blocks.go index e79d14c20..7d3ffcb1b 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/blocks.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/blocks.go @@ -11,7 +11,6 @@ import ( blockfeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/block" statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/db/filters" "github.com/prysmaticlabs/prysm/cmd" "github.com/prysmaticlabs/prysm/config/params" @@ -19,6 +18,7 @@ import ( ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" "github.com/prysmaticlabs/prysm/runtime/version" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/emptypb" @@ -523,21 +523,21 @@ func (bs *Server) chainHeadRetrieval(ctx context.Context) (*ethpb.ChainHead, err } } - fSlot, err := time.StartSlot(finalizedCheckpoint.Epoch) + fSlot, err := slots.EpochStart(finalizedCheckpoint.Epoch) if err != nil { return nil, err } - jSlot, err := time.StartSlot(justifiedCheckpoint.Epoch) + jSlot, err := slots.EpochStart(justifiedCheckpoint.Epoch) if err != nil { return nil, err } - pjSlot, err := time.StartSlot(prevJustifiedCheckpoint.Epoch) + pjSlot, err := slots.EpochStart(prevJustifiedCheckpoint.Epoch) if err != nil { return nil, err } return ðpb.ChainHead{ HeadSlot: headBlock.Block().Slot(), - HeadEpoch: time.SlotToEpoch(headBlock.Block().Slot()), + HeadEpoch: slots.ToEpoch(headBlock.Block().Slot()), HeadBlockRoot: headBlockRoot[:], FinalizedSlot: fSlot, FinalizedEpoch: finalizedCheckpoint.Epoch, @@ -561,7 +561,7 @@ func (bs *Server) GetWeakSubjectivityCheckpoint(ctx context.Context, _ *emptypb. if err != nil { return nil, status.Error(codes.Internal, "Could not get weak subjectivity epoch") } - wsSlot, err := time.StartSlot(wsEpoch) + wsSlot, err := slots.EpochStart(wsEpoch) if err != nil { return nil, status.Error(codes.Internal, "Could not get weak subjectivity slot") } diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/blocks_test.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/blocks_test.go index b96df82d8..20f7f579b 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/blocks_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/blocks_test.go @@ -13,7 +13,6 @@ import ( blockfeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/block" statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" dbTest "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/state/stategen" v1 "github.com/prysmaticlabs/prysm/beacon-chain/state/v1" @@ -27,6 +26,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/mock" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/emptypb" ) @@ -447,7 +447,7 @@ func TestServer_GetChainHead(t *testing.T) { require.NoError(t, err) b := util.NewBeaconBlock() - b.Block.Slot, err = time.StartSlot(s.PreviousJustifiedCheckpoint().Epoch) + b.Block.Slot, err = slots.EpochStart(s.PreviousJustifiedCheckpoint().Epoch) require.NoError(t, err) b.Block.Slot++ bs := &Server{ @@ -537,7 +537,7 @@ func TestServer_StreamChainHead_OnHeadUpdated(t *testing.T) { require.NoError(t, err) b := util.NewBeaconBlock() - b.Block.Slot, err = time.StartSlot(s.PreviousJustifiedCheckpoint().Epoch) + b.Block.Slot, err = slots.EpochStart(s.PreviousJustifiedCheckpoint().Epoch) require.NoError(t, err) hRoot, err := b.Block.HashTreeRoot() @@ -562,7 +562,7 @@ func TestServer_StreamChainHead_OnHeadUpdated(t *testing.T) { mockStream.EXPECT().Send( ðpb.ChainHead{ HeadSlot: b.Block.Slot, - HeadEpoch: time.SlotToEpoch(b.Block.Slot), + HeadEpoch: slots.ToEpoch(b.Block.Slot), HeadBlockRoot: hRoot[:], FinalizedSlot: 32, FinalizedEpoch: 1, diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/committees.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/committees.go index c9c8f7ee8..b3819c7bf 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/committees.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/committees.go @@ -10,6 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -26,7 +27,7 @@ func (bs *Server) ListBeaconCommittees( var requestedSlot types.Slot switch q := req.QueryFilter.(type) { case *ethpb.ListCommitteesRequest_Epoch: - startSlot, err := time.StartSlot(q.Epoch) + startSlot, err := slots.EpochStart(q.Epoch) if err != nil { return nil, err } @@ -37,8 +38,8 @@ func (bs *Server) ListBeaconCommittees( requestedSlot = currentSlot } - requestedEpoch := time.SlotToEpoch(requestedSlot) - currentEpoch := time.SlotToEpoch(currentSlot) + requestedEpoch := slots.ToEpoch(requestedSlot) + currentEpoch := slots.ToEpoch(currentSlot) if requestedEpoch > currentEpoch { return nil, status.Errorf( codes.InvalidArgument, @@ -69,7 +70,7 @@ func (bs *Server) retrieveCommitteesForEpoch( ctx context.Context, epoch types.Epoch, ) (SlotToCommiteesMap, []types.ValidatorIndex, error) { - startSlot, err := time.StartSlot(epoch) + startSlot, err := slots.EpochStart(epoch) if err != nil { return nil, nil, err } @@ -91,7 +92,7 @@ func (bs *Server) retrieveCommitteesForEpoch( return nil, nil, status.Errorf( codes.InvalidArgument, "Could not compute committees for epoch %d: %v", - time.SlotToEpoch(startSlot), + slots.ToEpoch(startSlot), err, ) } @@ -119,7 +120,7 @@ func (bs *Server) retrieveCommitteesForRoot( return nil, nil, status.Error(codes.Internal, "Could not get active indices") } - startSlot, err := time.StartSlot(epoch) + startSlot, err := slots.EpochStart(epoch) if err != nil { return nil, nil, err } diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/committees_test.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/committees_test.go index 3a2a27967..121ca2bde 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/committees_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/committees_test.go @@ -8,7 +8,6 @@ import ( mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" dbTest "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/beacon-chain/state/stategen" @@ -19,6 +18,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/protobuf/proto" "gopkg.in/d4l3k/messagediff.v1" ) @@ -107,7 +107,7 @@ func TestServer_ListBeaconCommittees_PreviousEpoch(t *testing.T) { require.NoError(t, err) attesterSeed, err := helpers.Seed(headState, 1, params.BeaconConfig().DomainBeaconAttester) require.NoError(t, err) - startSlot, err := coreTime.StartSlot(1) + startSlot, err := slots.EpochStart(1) require.NoError(t, err) wanted, err := computeCommittees(context.Background(), startSlot, activeIndices, attesterSeed) require.NoError(t, err) diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/validators.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/validators.go index a2da55b7c..96e537973 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/validators.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/validators.go @@ -20,6 +20,7 @@ import ( "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/runtime/version" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/emptypb" @@ -45,7 +46,7 @@ func (bs *Server) ListValidatorBalances( if bs.GenesisTimeFetcher == nil { return nil, status.Errorf(codes.Internal, "Nil genesis time fetcher") } - currentEpoch := coreTime.SlotToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) + currentEpoch := slots.ToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) requestedEpoch := currentEpoch switch q := req.QueryFilter.(type) { case *ethpb.ListValidatorBalancesRequest_Epoch: @@ -65,7 +66,7 @@ func (bs *Server) ListValidatorBalances( res := make([]*ethpb.ValidatorBalances_Balance, 0) filtered := map[types.ValidatorIndex]bool{} // Track filtered validators to prevent duplication in the response. - startSlot, err := coreTime.StartSlot(requestedEpoch) + startSlot, err := slots.EpochStart(requestedEpoch) if err != nil { return nil, err } @@ -197,7 +198,7 @@ func (bs *Server) ListValidators( req.PageSize, cmd.Get().MaxRPCPageSize) } - currentEpoch := coreTime.SlotToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) + currentEpoch := slots.ToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) requestedEpoch := currentEpoch switch q := req.QueryFilter.(type) { @@ -220,7 +221,7 @@ func (bs *Server) ListValidators( var err error if requestedEpoch != currentEpoch { var s types.Slot - s, err = coreTime.StartSlot(requestedEpoch) + s, err = slots.EpochStart(requestedEpoch) if err != nil { return nil, err } @@ -235,7 +236,7 @@ func (bs *Server) ListValidators( return nil, status.Error(codes.Internal, "Requested state is nil") } - s, err := coreTime.StartSlot(requestedEpoch) + s, err := slots.EpochStart(requestedEpoch) if err != nil { return nil, err } @@ -392,7 +393,7 @@ func (bs *Server) GetValidator( func (bs *Server) GetValidatorActiveSetChanges( ctx context.Context, req *ethpb.GetValidatorActiveSetChangesRequest, ) (*ethpb.ActiveSetChanges, error) { - currentEpoch := coreTime.SlotToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) + currentEpoch := slots.ToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) var requestedEpoch types.Epoch switch q := req.QueryFilter.(type) { @@ -412,7 +413,7 @@ func (bs *Server) GetValidatorActiveSetChanges( ) } - s, err := coreTime.StartSlot(requestedEpoch) + s, err := slots.EpochStart(requestedEpoch) if err != nil { return nil, err } @@ -478,7 +479,7 @@ func (bs *Server) GetValidatorParticipation( ctx context.Context, req *ethpb.GetValidatorParticipationRequest, ) (*ethpb.ValidatorParticipationResponse, error) { currentSlot := bs.GenesisTimeFetcher.CurrentSlot() - currentEpoch := coreTime.SlotToEpoch(currentSlot) + currentEpoch := slots.ToEpoch(currentSlot) var requestedEpoch types.Epoch switch q := req.QueryFilter.(type) { @@ -500,7 +501,7 @@ func (bs *Server) GetValidatorParticipation( } // Get current slot state for current epoch attestations. - startSlot, err := coreTime.StartSlot(requestedEpoch) + startSlot, err := slots.EpochStart(requestedEpoch) if err != nil { return nil, err } @@ -819,7 +820,7 @@ func (bs *Server) GetIndividualVotes( ctx context.Context, req *ethpb.IndividualVotesRequest, ) (*ethpb.IndividualVotesRespond, error) { - currentEpoch := coreTime.SlotToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) + currentEpoch := slots.ToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) if req.Epoch > currentEpoch { return nil, status.Errorf( codes.InvalidArgument, @@ -829,7 +830,7 @@ func (bs *Server) GetIndividualVotes( ) } - s, err := coreTime.StartSlot(req.Epoch) + s, err := slots.EpochStart(req.Epoch) if err != nil { return nil, err } diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_test.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_test.go index b0da0aaae..32da3db82 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_test.go @@ -30,6 +30,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/emptypb" ) @@ -57,7 +58,7 @@ func TestServer_GetValidatorActiveSetChanges_CannotRequestFutureEpoch(t *testing ctx, ðpb.GetValidatorActiveSetChangesRequest{ QueryFilter: ðpb.GetValidatorActiveSetChangesRequest_Epoch{ - Epoch: coreTime.SlotToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) + 1, + Epoch: slots.ToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) + 1, }, }, ) @@ -84,7 +85,7 @@ func TestServer_ListValidatorBalances_CannotRequestFutureEpoch(t *testing.T) { ctx, ðpb.ListValidatorBalancesRequest{ QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{ - Epoch: coreTime.SlotToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) + 1, + Epoch: slots.ToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) + 1, }, }, ) @@ -1478,7 +1479,7 @@ func TestServer_GetValidatorParticipation_CannotRequestFutureEpoch(t *testing.T) ctx, ðpb.GetValidatorParticipationRequest{ QueryFilter: ðpb.GetValidatorParticipationRequest_Epoch{ - Epoch: coreTime.SlotToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) + 1, + Epoch: slots.ToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) + 1, }, }, ) @@ -2094,7 +2095,7 @@ func setupValidators(t testing.TB, _ db.Database, count int) ([]*ethpb.Validator func TestServer_GetIndividualVotes_RequestFutureSlot(t *testing.T) { ds := &Server{GenesisTimeFetcher: &mock.ChainService{}} req := ðpb.IndividualVotesRequest{ - Epoch: coreTime.SlotToEpoch(ds.GenesisTimeFetcher.CurrentSlot()) + 1, + Epoch: slots.ToEpoch(ds.GenesisTimeFetcher.CurrentSlot()) + 1, } wanted := errNoEpochInfoError _, err := ds.GetIndividualVotes(context.Background(), req) diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/BUILD.bazel b/beacon-chain/rpc/prysm/v1alpha1/validator/BUILD.bazel index 738cfc9d6..3f107a458 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/BUILD.bazel +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/BUILD.bazel @@ -136,6 +136,7 @@ go_test( "//testing/require:go_default_library", "//testing/util:go_default_library", "//time:go_default_library", + "//time/slots:go_default_library", "@com_github_golang_mock//gomock:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/aggregator.go b/beacon-chain/rpc/prysm/v1alpha1/validator/aggregator.go index 5b49571c0..db916f5be 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/aggregator.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/aggregator.go @@ -5,10 +5,10 @@ import ( "context" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" "go.opencensus.io/trace" "google.golang.org/grpc/codes" @@ -37,7 +37,7 @@ func (vs *Server) SubmitAggregateSelectionProof(ctx context.Context, req *ethpb. return nil, status.Error(codes.Internal, "Could not locate validator index in DB") } - epoch := time.SlotToEpoch(req.Slot) + epoch := slots.ToEpoch(req.Slot) activeValidatorIndices, err := helpers.ActiveValidatorIndices(ctx, st, epoch) if err != nil { return nil, status.Errorf(codes.Internal, "Could not get validators: %v", err) diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/assignments.go b/beacon-chain/rpc/prysm/v1alpha1/validator/assignments.go index 4794b7fe4..10870c912 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/assignments.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/assignments.go @@ -108,7 +108,7 @@ func (vs *Server) StreamDuties(req *ethpb.DutiesRequest, stream ethpb.BeaconNode // Compute the validator duties from the head state's corresponding epoch // for validators public key / indices requested. func (vs *Server) duties(ctx context.Context, req *ethpb.DutiesRequest) (*ethpb.DutiesResponse, error) { - currentEpoch := coreTime.SlotToEpoch(vs.TimeFetcher.CurrentSlot()) + currentEpoch := slots.ToEpoch(vs.TimeFetcher.CurrentSlot()) if req.Epoch > currentEpoch+1 { return nil, status.Errorf(codes.Unavailable, "Request epoch %d can not be greater than next epoch %d", req.Epoch, currentEpoch+1) } @@ -119,7 +119,7 @@ func (vs *Server) duties(ctx context.Context, req *ethpb.DutiesRequest) (*ethpb. } // Advance state with empty transitions up to the requested epoch start slot. - epochStartSlot, err := coreTime.StartSlot(req.Epoch) + epochStartSlot, err := slots.EpochStart(req.Epoch) if err != nil { return nil, err } @@ -198,9 +198,9 @@ func (vs *Server) duties(ctx context.Context, req *ethpb.DutiesRequest) (*ethpb. // Next epoch sync committee duty is assigned with next period sync committee only during // sync period epoch boundary (ie. EPOCHS_PER_SYNC_COMMITTEE_PERIOD - 1). Else wise // next epoch sync committee duty is the same as current epoch. - nextSlotToEpoch := coreTime.SlotToEpoch(s.Slot() + 1) + nextSlotToEpoch := slots.ToEpoch(s.Slot() + 1) currentEpoch := coreTime.CurrentEpoch(s) - if coreTime.SyncCommitteePeriod(nextSlotToEpoch) == coreTime.SyncCommitteePeriod(currentEpoch)+1 { + if slots.SyncCommitteePeriod(nextSlotToEpoch) == slots.SyncCommitteePeriod(currentEpoch)+1 { nextAssignment.IsSyncCommittee, err = helpers.IsNextPeriodSyncCommittee(s, idx) if err != nil { return nil, status.Errorf(codes.Internal, "Could not determine next epoch sync committee: %v", err) @@ -258,7 +258,7 @@ func registerSyncSubnetCurrentPeriod(s beaconState.BeaconState, epoch types.Epoc if err != nil { return err } - syncCommPeriod := coreTime.SyncCommitteePeriod(epoch) + syncCommPeriod := slots.SyncCommitteePeriod(epoch) registerSyncSubnet(epoch, syncCommPeriod, pubKey, committee, status) return nil } @@ -268,7 +268,7 @@ func registerSyncSubnetNextPeriod(s beaconState.BeaconState, epoch types.Epoch, if err != nil { return err } - syncCommPeriod := coreTime.SyncCommitteePeriod(epoch) + syncCommPeriod := slots.SyncCommitteePeriod(epoch) registerSyncSubnet(epoch, syncCommPeriod+1, pubKey, committee, status) return nil } @@ -281,7 +281,7 @@ func registerSyncSubnet(currEpoch types.Epoch, syncPeriod uint64, pubkey []byte, return } startEpoch := types.Epoch(syncPeriod * uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod)) - currPeriod := coreTime.SyncCommitteePeriod(currEpoch) + currPeriod := slots.SyncCommitteePeriod(currEpoch) endEpoch := startEpoch + params.BeaconConfig().EpochsPerSyncCommitteePeriod _, _, ok, expTime := cache.SyncSubnetIDs.GetSyncCommitteeSubnets(pubkey, startEpoch) if ok && expTime.After(prysmTime.Now()) { diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/attester.go b/beacon-chain/rpc/prysm/v1alpha1/validator/attester.go index b746ffe24..54e6bf1aa 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/attester.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/attester.go @@ -17,6 +17,7 @@ import ( "github.com/prysmaticlabs/prysm/crypto/bls" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -95,7 +96,7 @@ func (vs *Server) GetAttestationData(ctx context.Context, req *ethpb.Attestation return nil, status.Error(codes.Internal, "Could not lookup parent state from head.") } - if time.CurrentEpoch(headState) < time.SlotToEpoch(req.Slot) { + if time.CurrentEpoch(headState) < slots.ToEpoch(req.Slot) { if features.Get().EnableNextSlotStateCache { headState, err = transition.ProcessSlotsUsingNextSlotCache(ctx, headState, headRoot, req.Slot) if err != nil { @@ -110,7 +111,7 @@ func (vs *Server) GetAttestationData(ctx context.Context, req *ethpb.Attestation } targetEpoch := time.CurrentEpoch(headState) - epochStartSlot, err := time.StartSlot(targetEpoch) + epochStartSlot, err := slots.EpochStart(targetEpoch) if err != nil { return nil, err } @@ -169,7 +170,7 @@ func (vs *Server) ProposeAttestation(ctx context.Context, att *ethpb.Attestation }) // Determine subnet to broadcast attestation to - wantedEpoch := time.SlotToEpoch(att.Data.Slot) + wantedEpoch := slots.ToEpoch(att.Data.Slot) vals, err := vs.HeadFetcher.HeadValidatorsIndices(ctx, wantedEpoch) if err != nil { return nil, err @@ -208,7 +209,7 @@ func (vs *Server) SubscribeCommitteeSubnets(ctx context.Context, req *ethpb.Comm } fetchValsLen := func(slot types.Slot) (uint64, error) { - wantedEpoch := time.SlotToEpoch(slot) + wantedEpoch := slots.ToEpoch(slot) vals, err := vs.HeadFetcher.HeadValidatorsIndices(ctx, wantedEpoch) if err != nil { return 0, err @@ -222,16 +223,16 @@ func (vs *Server) SubscribeCommitteeSubnets(ctx context.Context, req *ethpb.Comm if err != nil { return nil, status.Errorf(codes.Internal, "Could not retrieve head validator length: %v", err) } - currEpoch := time.SlotToEpoch(req.Slots[0]) + currEpoch := slots.ToEpoch(req.Slots[0]) for i := 0; i < len(req.Slots); i++ { // If epoch has changed, re-request active validators length - if currEpoch != time.SlotToEpoch(req.Slots[i]) { + if currEpoch != slots.ToEpoch(req.Slots[i]) { currValsLen, err = fetchValsLen(req.Slots[i]) if err != nil { return nil, status.Errorf(codes.Internal, "Could not retrieve head validator length: %v", err) } - currEpoch = time.SlotToEpoch(req.Slots[i]) + currEpoch = slots.ToEpoch(req.Slots[i]) } subnet := helpers.ComputeSubnetFromCommitteeAndSlot(currValsLen, req.CommitteeIds[i], req.Slots[i]) cache.SubnetIDs.AddAttesterSubnetID(req.Slots[i], subnet) diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/attester_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/attester_test.go index edda22a81..ce8b26e40 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/attester_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/attester_test.go @@ -10,7 +10,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/cache" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" dbutil "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/operations/attestations" mockp2p "github.com/prysmaticlabs/prysm/beacon-chain/p2p/testing" @@ -26,6 +25,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/protobuf/proto" ) @@ -189,10 +189,10 @@ func TestAttestationDataAtSlot_HandlesFarAwayJustifiedEpoch(t *testing.T) { block.Block.Slot = 10000 epochBoundaryBlock := util.NewBeaconBlock() var err error - epochBoundaryBlock.Block.Slot, err = coreTime.StartSlot(coreTime.SlotToEpoch(10000)) + epochBoundaryBlock.Block.Slot, err = slots.EpochStart(slots.ToEpoch(10000)) require.NoError(t, err) justifiedBlock := util.NewBeaconBlock() - justifiedBlock.Block.Slot, err = coreTime.StartSlot(coreTime.SlotToEpoch(1500)) + justifiedBlock.Block.Slot, err = slots.EpochStart(slots.ToEpoch(1500)) require.NoError(t, err) justifiedBlock.Block.Slot -= 2 // Imagine two skip block blockRoot, err := block.Block.HashTreeRoot() @@ -207,7 +207,7 @@ func TestAttestationDataAtSlot_HandlesFarAwayJustifiedEpoch(t *testing.T) { require.NoError(t, err) require.NoError(t, beaconState.SetSlot(slot)) err = beaconState.SetCurrentJustifiedCheckpoint(ðpb.Checkpoint{ - Epoch: coreTime.SlotToEpoch(1500), + Epoch: slots.ToEpoch(1500), Root: justifiedBlockRoot[:], }) require.NoError(t, err) @@ -243,7 +243,7 @@ func TestAttestationDataAtSlot_HandlesFarAwayJustifiedEpoch(t *testing.T) { Slot: req.Slot, BeaconBlockRoot: blockRoot[:], Source: ðpb.Checkpoint{ - Epoch: coreTime.SlotToEpoch(1500), + Epoch: slots.ToEpoch(1500), Root: justifiedBlockRoot[:], }, Target: ðpb.Checkpoint{ diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer.go index 53bcec903..9ca4a02c9 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer.go @@ -15,7 +15,6 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" blockfeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/block" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition/interop" "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -32,6 +31,7 @@ import ( synccontribution "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/attestation/aggregation/sync_contribution" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/wrapper" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" "go.opencensus.io/trace" "google.golang.org/grpc/codes" @@ -68,7 +68,7 @@ func (vs *Server) GetBeaconBlock(ctx context.Context, req *ethpb.BlockRequest) ( ctx, span := trace.StartSpan(ctx, "ProposerServer.GetBeaconBlock") defer span.End() span.AddAttributes(trace.Int64Attribute("slot", int64(req.Slot))) - if coreTime.SlotToEpoch(req.Slot) < params.BeaconConfig().AltairForkEpoch { + if slots.ToEpoch(req.Slot) < params.BeaconConfig().AltairForkEpoch { blk, err := vs.getPhase0BeaconBlock(ctx, req) if err != nil { return nil, status.Errorf(codes.Internal, "Could not fetch phase0 beacon block: %v", err) @@ -460,7 +460,7 @@ func (vs *Server) eth1DataMajorityVote(ctx context.Context, beaconState state.Be func (vs *Server) slotStartTime(slot types.Slot) uint64 { startTime, _ := vs.Eth1InfoFetcher.Eth2GenesisPowchainInfo() - return coreTime.VotingPeriodStartTime(startTime, slot) + return slots.VotingPeriodStartTime(startTime, slot) } func (vs *Server) mockETH1DataVote(ctx context.Context, slot types.Slot) (*ethpb.Eth1Data, error) { @@ -483,7 +483,7 @@ func (vs *Server) mockETH1DataVote(ctx context.Context, slot types.Slot) (*ethpb return nil, err } var enc []byte - enc = fastssz.MarshalUint64(enc, uint64(coreTime.SlotToEpoch(slot))+uint64(slotInVotingPeriod)) + enc = fastssz.MarshalUint64(enc, uint64(slots.ToEpoch(slot))+uint64(slotInVotingPeriod)) depRoot := hash.Hash(enc) blockHash := hash.Hash(depRoot[:]) return ðpb.Eth1Data{ diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_test.go index cfe2170ef..8748ac59d 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_test.go @@ -36,6 +36,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/protobuf/proto" ) @@ -2132,7 +2133,7 @@ func TestProposer_GetBeaconBlock_PostForkEpoch(t *testing.T) { require.NoError(t, db.SaveState(ctx, beaconState, parentRoot), "Could not save genesis state") require.NoError(t, db.SaveHeadBlockRoot(ctx, parentRoot), "Could not save genesis state") - altairSlot, err := time.StartSlot(params.BeaconConfig().AltairForkEpoch) + altairSlot, err := slots.EpochStart(params.BeaconConfig().AltairForkEpoch) require.NoError(t, err) genAltair := ðpb.SignedBeaconBlockAltair{ diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/status.go b/beacon-chain/rpc/prysm/v1alpha1/validator/status.go index 6c4b3c714..b5b680a71 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/status.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/status.go @@ -14,6 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/encoding/bytesutil" "github.com/prysmaticlabs/prysm/monitoring/tracing" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -106,7 +107,7 @@ func (vs *Server) CheckDoppelGanger(ctx context.Context, req *ethpb.DoppelGanger } // We walk back from the current head state to the state at the beginning of the previous 2 epochs. // Where S_i , i := 0,1,2. i = 0 would signify the current head state in this epoch. - currEpoch := time.SlotToEpoch(headState.Slot()) + currEpoch := slots.ToEpoch(headState.Slot()) previousEpoch, err := currEpoch.SafeSub(1) if err != nil { previousEpoch = currEpoch diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/status_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/status_test.go index e2cc72e3d..c7adf1a18 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/status_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/status_test.go @@ -10,7 +10,6 @@ import ( mockChain "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" mockPOW "github.com/prysmaticlabs/prysm/beacon-chain/powchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/beacon-chain/state/stategen" @@ -24,6 +23,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/protobuf/proto" ) @@ -300,7 +300,7 @@ func TestValidatorStatus_Exiting(t *testing.T) { // Initiated exit because validator exit epoch and withdrawable epoch are not FAR_FUTURE_EPOCH slot := types.Slot(10000) - epoch := coreTime.SlotToEpoch(slot) + epoch := slots.ToEpoch(slot) exitEpoch := helpers.ActivationExitEpoch(epoch) withdrawableEpoch := exitEpoch + params.BeaconConfig().MinValidatorWithdrawabilityDelay block := util.NewBeaconBlock() @@ -360,7 +360,7 @@ func TestValidatorStatus_Slashing(t *testing.T) { // Exit slashed because slashed is true, exit epoch is =< current epoch and withdrawable epoch > epoch . slot := types.Slot(10000) - epoch := coreTime.SlotToEpoch(slot) + epoch := slots.ToEpoch(slot) block := util.NewBeaconBlock() genesisRoot, err := block.Block.HashTreeRoot() require.NoError(t, err, "Could not get signing root") @@ -417,7 +417,7 @@ func TestValidatorStatus_Exited(t *testing.T) { // Exit because only exit epoch is =< current epoch. slot := types.Slot(10000) - epoch := coreTime.SlotToEpoch(slot) + epoch := slots.ToEpoch(slot) block := util.NewBeaconBlock() genesisRoot, err := block.Block.HashTreeRoot() require.NoError(t, err, "Could not get signing root") @@ -790,7 +790,7 @@ func TestMultipleValidatorStatus_Pubkeys(t *testing.T) { func TestMultipleValidatorStatus_Indices(t *testing.T) { slot := types.Slot(10000) - epoch := coreTime.SlotToEpoch(slot) + epoch := slots.ToEpoch(slot) pubKeys := [][]byte{pubKey(1), pubKey(2), pubKey(3), pubKey(4), pubKey(5), pubKey(6), pubKey(7)} beaconState := ðpb.BeaconState{ Slot: 4000, diff --git a/beacon-chain/slasher/BUILD.bazel b/beacon-chain/slasher/BUILD.bazel index 8808b79e9..3a9b36e86 100644 --- a/beacon-chain/slasher/BUILD.bazel +++ b/beacon-chain/slasher/BUILD.bazel @@ -29,7 +29,6 @@ go_library( "//beacon-chain/core/blocks:go_default_library", "//beacon-chain/core/feed:go_default_library", "//beacon-chain/core/feed/state:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/db:go_default_library", "//beacon-chain/operations/slashings:go_default_library", "//beacon-chain/slasher/types:go_default_library", @@ -74,7 +73,6 @@ go_test( "//beacon-chain/core/feed:go_default_library", "//beacon-chain/core/feed/state:go_default_library", "//beacon-chain/core/signing:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/db/testing:go_default_library", "//beacon-chain/operations/slashings:go_default_library", "//beacon-chain/slasher/types:go_default_library", diff --git a/beacon-chain/slasher/detect_attestations_test.go b/beacon-chain/slasher/detect_attestations_test.go index a07771bf6..7d59ed36b 100644 --- a/beacon-chain/slasher/detect_attestations_test.go +++ b/beacon-chain/slasher/detect_attestations_test.go @@ -10,7 +10,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" dbtest "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/operations/slashings" slashertypes "github.com/prysmaticlabs/prysm/beacon-chain/slasher/types" @@ -21,6 +20,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" logTest "github.com/sirupsen/logrus/hooks/test" ) @@ -189,7 +189,7 @@ func Test_processQueuedAttestations(t *testing.T) { beaconState, err := util.NewBeaconState() require.NoError(t, err) - slot, err := coreTime.StartSlot(tt.args.currentEpoch) + slot, err := slots.EpochStart(tt.args.currentEpoch) require.NoError(t, err) require.NoError(t, beaconState.SetSlot(slot)) mockChain := &mock.ChainService{ @@ -322,7 +322,7 @@ func Test_processQueuedAttestations_MultipleChunkIndices(t *testing.T) { att := createAttestationWrapper(t, source, target, []uint64{0}, sr[:]) s.attsQueue = newAttestationsQueue() s.attsQueue.push(att) - slot, err := coreTime.StartSlot(i) + slot, err := slots.EpochStart(i) require.NoError(t, err) require.NoError(t, mockChain.State.SetSlot(slot)) s.serviceCfg.HeadStateFetcher = mockChain @@ -384,7 +384,7 @@ func Test_processQueuedAttestations_OverlappingChunkIndices(t *testing.T) { s.attsQueue = newAttestationsQueue() s.attsQueue.push(att1) s.attsQueue.push(att2) - slot, err := coreTime.StartSlot(att2.IndexedAttestation.Data.Target.Epoch) + slot, err := slots.EpochStart(att2.IndexedAttestation.Data.Target.Epoch) require.NoError(t, err) mockChain.Slot = &slot s.serviceCfg.HeadStateFetcher = mockChain @@ -763,7 +763,7 @@ func TestService_processQueuedAttestations(t *testing.T) { beaconState, err := util.NewBeaconState() require.NoError(t, err) - slot, err := coreTime.StartSlot(1) + slot, err := slots.EpochStart(1) require.NoError(t, err) require.NoError(t, beaconState.SetSlot(slot)) mockChain := &mock.ChainService{ diff --git a/beacon-chain/slasher/receive.go b/beacon-chain/slasher/receive.go index b4b103a3a..b73ef2f5f 100644 --- a/beacon-chain/slasher/receive.go +++ b/beacon-chain/slasher/receive.go @@ -6,9 +6,9 @@ import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" slashertypes "github.com/prysmaticlabs/prysm/beacon-chain/slasher/types" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" ) @@ -81,7 +81,7 @@ func (s *Service) processQueuedAttestations(ctx context.Context, slotTicker <-ch select { case currentSlot := <-slotTicker: attestations := s.attsQueue.dequeue() - currentEpoch := coreTime.SlotToEpoch(currentSlot) + currentEpoch := slots.ToEpoch(currentSlot) // We take all the attestations in the queue and filter out // those which are valid now and valid in the future. validAtts, validInFuture, numDropped := s.filterAttestations(attestations, currentEpoch) @@ -139,7 +139,7 @@ func (s *Service) processQueuedBlocks(ctx context.Context, slotTicker <-chan typ select { case currentSlot := <-slotTicker: blocks := s.blksQueue.dequeue() - currentEpoch := coreTime.SlotToEpoch(currentSlot) + currentEpoch := slots.ToEpoch(currentSlot) receivedBlocksTotal.Add(float64(len(blocks))) @@ -178,7 +178,7 @@ func (s *Service) pruneSlasherData(ctx context.Context, slotTicker <-chan types. for { select { case <-slotTicker: - headEpoch := coreTime.SlotToEpoch(s.serviceCfg.HeadStateFetcher.HeadSlot()) + headEpoch := slots.ToEpoch(s.serviceCfg.HeadStateFetcher.HeadSlot()) if err := s.pruneSlasherDataWithinSlidingWindow(ctx, headEpoch); err != nil { log.WithError(err).Error("Could not prune slasher data") continue diff --git a/beacon-chain/slasher/service.go b/beacon-chain/slasher/service.go index cefd79cef..97b281683 100644 --- a/beacon-chain/slasher/service.go +++ b/beacon-chain/slasher/service.go @@ -143,7 +143,7 @@ func (s *Service) Status() error { } func (s *Service) waitForSync(genesisTime time.Time) { - if slots.SlotsSinceGenesis(genesisTime) == 0 || !s.serviceCfg.SyncChecker.Syncing() { + if slots.SinceGenesis(genesisTime) == 0 || !s.serviceCfg.SyncChecker.Syncing() { return } for { diff --git a/beacon-chain/state/stategen/BUILD.bazel b/beacon-chain/state/stategen/BUILD.bazel index 1c1a92c90..972246162 100644 --- a/beacon-chain/state/stategen/BUILD.bazel +++ b/beacon-chain/state/stategen/BUILD.bazel @@ -35,6 +35,7 @@ go_library( "//proto/prysm/v1alpha1:go_default_library", "//proto/prysm/v1alpha1/block:go_default_library", "//runtime/version:go_default_library", + "//time/slots:go_default_library", "@com_github_hashicorp_golang_lru//:go_default_library", "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", diff --git a/beacon-chain/state/stategen/setter.go b/beacon-chain/state/stategen/setter.go index a90a1430c..6cb81ee1b 100644 --- a/beacon-chain/state/stategen/setter.go +++ b/beacon-chain/state/stategen/setter.go @@ -4,11 +4,11 @@ import ( "context" "math" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" "go.opencensus.io/trace" ) @@ -73,7 +73,7 @@ func (s *State) saveStateByRoot(ctx context.Context, blockRoot [32]byte, st stat } // Only on an epoch boundary slot, saves epoch boundary state in epoch boundary root state cache. - if time.IsEpochStart(st.Slot()) { + if slots.IsEpochStart(st.Slot()) { if err := s.epochBoundaryStateCache.put(blockRoot, st); err != nil { return err } diff --git a/beacon-chain/sync/BUILD.bazel b/beacon-chain/sync/BUILD.bazel index 266363fff..2977ef727 100644 --- a/beacon-chain/sync/BUILD.bazel +++ b/beacon-chain/sync/BUILD.bazel @@ -63,7 +63,6 @@ go_library( "//beacon-chain/core/feed/state:go_default_library", "//beacon-chain/core/helpers:go_default_library", "//beacon-chain/core/signing:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/core/transition:go_default_library", "//beacon-chain/core/transition/interop:go_default_library", "//beacon-chain/db:go_default_library", @@ -204,6 +203,7 @@ go_test( "//testing/require:go_default_library", "//testing/util:go_default_library", "//time:go_default_library", + "//time/slots:go_default_library", "@com_github_d4l3k_messagediff//:go_default_library", "@com_github_ethereum_go_ethereum//p2p/enr:go_default_library", "@com_github_golang_snappy//:go_default_library", diff --git a/beacon-chain/sync/fork_watcher.go b/beacon-chain/sync/fork_watcher.go index 003d4981a..de4b6e8d6 100644 --- a/beacon-chain/sync/fork_watcher.go +++ b/beacon-chain/sync/fork_watcher.go @@ -3,7 +3,6 @@ package sync import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/network/forks" @@ -20,7 +19,7 @@ func (s *Service) forkWatcher() { // topics during/after the fork epoch. This routine is to ensure correct // subscriptions for nodes running before a fork epoch. case currSlot := <-slotTicker.C(): - currEpoch := time.SlotToEpoch(currSlot) + currEpoch := slots.ToEpoch(currSlot) if err := s.registerForUpcomingFork(currEpoch); err != nil { log.WithError(err).Error("Unable to check for fork in the next epoch") continue diff --git a/beacon-chain/sync/initial-sync/BUILD.bazel b/beacon-chain/sync/initial-sync/BUILD.bazel index 8bbe902ec..f89d7750e 100644 --- a/beacon-chain/sync/initial-sync/BUILD.bazel +++ b/beacon-chain/sync/initial-sync/BUILD.bazel @@ -21,7 +21,6 @@ go_library( "//beacon-chain/core/feed:go_default_library", "//beacon-chain/core/feed/block:go_default_library", "//beacon-chain/core/feed/state:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/core/transition:go_default_library", "//beacon-chain/db:go_default_library", "//beacon-chain/p2p:go_default_library", @@ -37,6 +36,7 @@ go_library( "//proto/prysm/v1alpha1/block:go_default_library", "//runtime:go_default_library", "//time:go_default_library", + "//time/slots:go_default_library", "@com_github_kevinms_leakybucket_go//:go_default_library", "@com_github_libp2p_go_libp2p_core//peer:go_default_library", "@com_github_paulbellamy_ratecounter//:go_default_library", @@ -113,7 +113,6 @@ go_test( "//beacon-chain/blockchain/testing:go_default_library", "//beacon-chain/core/feed:go_default_library", "//beacon-chain/core/feed/state:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/db:go_default_library", "//beacon-chain/db/testing:go_default_library", "//beacon-chain/p2p:go_default_library", @@ -135,6 +134,7 @@ go_test( "//testing/require:go_default_library", "//testing/util:go_default_library", "//time:go_default_library", + "//time/slots:go_default_library", "@com_github_ethereum_go_ethereum//p2p/enr:go_default_library", "@com_github_kevinms_leakybucket_go//:go_default_library", "@com_github_libp2p_go_libp2p_core//:go_default_library", diff --git a/beacon-chain/sync/initial-sync/blocks_fetcher_peers.go b/beacon-chain/sync/initial-sync/blocks_fetcher_peers.go index f6da74ec2..aafe44fdc 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher_peers.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher_peers.go @@ -7,12 +7,12 @@ import ( "time" "github.com/libp2p/go-libp2p-core/peer" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers/scorers" "github.com/prysmaticlabs/prysm/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/config/params" mathutil "github.com/prysmaticlabs/prysm/math" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" "go.opencensus.io/trace" ) @@ -76,7 +76,7 @@ func (f *blocksFetcher) waitForMinimumPeers(ctx context.Context) ([]peer.ID, err headEpoch := f.chain.FinalizedCheckpt().Epoch _, peers = f.p2p.Peers().BestFinalized(params.BeaconConfig().MaxPeersToSync, headEpoch) } else { - headEpoch := coreTime.SlotToEpoch(f.chain.HeadSlot()) + headEpoch := slots.ToEpoch(f.chain.HeadSlot()) _, peers = f.p2p.Peers().BestNonFinalized(flags.Get().MinimumSyncPeers, headEpoch) } if len(peers) >= required { diff --git a/beacon-chain/sync/initial-sync/blocks_fetcher_test.go b/beacon-chain/sync/initial-sync/blocks_fetcher_test.go index 34cdc913a..896d41372 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher_test.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher_test.go @@ -13,7 +13,6 @@ import ( "github.com/libp2p/go-libp2p-core/network" types "github.com/prysmaticlabs/eth2-types" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" dbtest "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" p2pm "github.com/prysmaticlabs/prysm/beacon-chain/p2p" p2pt "github.com/prysmaticlabs/prysm/beacon-chain/p2p/testing" @@ -28,6 +27,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" logTest "github.com/sirupsen/logrus/hooks/test" ) @@ -124,7 +124,7 @@ func TestBlocksFetcher_RoundRobin(t *testing.T) { peers: []*peerData{ { blocks: makeSequence(1, 3*slotsInBatch), - finalizedEpoch: coreTime.SlotToEpoch(3 * slotsInBatch), + finalizedEpoch: slots.ToEpoch(3 * slotsInBatch), headSlot: 3 * slotsInBatch, }, }, @@ -136,7 +136,7 @@ func TestBlocksFetcher_RoundRobin(t *testing.T) { peers: []*peerData{ { blocks: makeSequence(1, 3*slotsInBatch), - finalizedEpoch: coreTime.SlotToEpoch(3 * slotsInBatch), + finalizedEpoch: slots.ToEpoch(3 * slotsInBatch), headSlot: 3 * slotsInBatch, }, }, @@ -148,17 +148,17 @@ func TestBlocksFetcher_RoundRobin(t *testing.T) { peers: []*peerData{ { blocks: makeSequence(1, 3*slotsInBatch), - finalizedEpoch: coreTime.SlotToEpoch(3 * slotsInBatch), + finalizedEpoch: slots.ToEpoch(3 * slotsInBatch), headSlot: 3 * slotsInBatch, }, { blocks: makeSequence(1, 3*slotsInBatch), - finalizedEpoch: coreTime.SlotToEpoch(3 * slotsInBatch), + finalizedEpoch: slots.ToEpoch(3 * slotsInBatch), headSlot: 3 * slotsInBatch, }, { blocks: makeSequence(1, 3*slotsInBatch), - finalizedEpoch: coreTime.SlotToEpoch(3 * slotsInBatch), + finalizedEpoch: slots.ToEpoch(3 * slotsInBatch), headSlot: 3 * slotsInBatch, }, }, @@ -506,7 +506,7 @@ func TestBlocksFetcher_requestBeaconBlocksByRange(t *testing.T) { p2p: p2p, }) - _, peerIDs := p2p.Peers().BestFinalized(params.BeaconConfig().MaxPeersToSync, coreTime.SlotToEpoch(mc.HeadSlot())) + _, peerIDs := p2p.Peers().BestFinalized(params.BeaconConfig().MaxPeersToSync, slots.ToEpoch(mc.HeadSlot())) req := &p2ppb.BeaconBlocksByRangeRequest{ StartSlot: 1, Step: 1, diff --git a/beacon-chain/sync/initial-sync/blocks_fetcher_utils.go b/beacon-chain/sync/initial-sync/blocks_fetcher_utils.go index dc2af5000..a9d519a08 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher_utils.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher_utils.go @@ -8,13 +8,13 @@ import ( "github.com/libp2p/go-libp2p-core/peer" "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" p2pTypes "github.com/prysmaticlabs/prysm/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" p2ppb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" "go.opencensus.io/trace" ) @@ -103,7 +103,7 @@ func (f *blocksFetcher) nonSkippedSlotAfterWithPeersTarget( // Quickly find the close enough epoch where a non-empty slot definitely exists. // Only single random slot per epoch is checked - allowing to move forward relatively quickly. slot += nonSkippedSlotsFullSearchEpochs * slotsPerEpoch - upperBoundSlot, err := time.StartSlot(targetEpoch + 1) + upperBoundSlot, err := slots.EpochStart(targetEpoch + 1) if err != nil { return 0, err } @@ -124,7 +124,7 @@ func (f *blocksFetcher) nonSkippedSlotAfterWithPeersTarget( if upperBoundSlot > slotsPerEpoch { upperBoundSlot -= slotsPerEpoch } - upperBoundSlot, err = time.StartSlot(time.SlotToEpoch(upperBoundSlot)) + upperBoundSlot, err = slots.EpochStart(slots.ToEpoch(upperBoundSlot)) if err != nil { return 0, err } @@ -132,7 +132,7 @@ func (f *blocksFetcher) nonSkippedSlotAfterWithPeersTarget( if err != nil { return 0, err } - s, err := time.StartSlot(targetEpoch + 1) + s, err := slots.EpochStart(targetEpoch + 1) if err != nil { return 0, err } @@ -158,12 +158,12 @@ func (f *blocksFetcher) findFork(ctx context.Context, slot types.Slot) (*forkDat // The current slot's epoch must be after the finalization epoch, // triggering backtracking on earlier epochs is unnecessary. finalizedEpoch := f.chain.FinalizedCheckpt().Epoch - epoch := time.SlotToEpoch(slot) + epoch := slots.ToEpoch(slot) if epoch <= finalizedEpoch { return nil, errors.New("slot is not after the finalized epoch, no backtracking is necessary") } // Update slot to the beginning of the current epoch (preserve original slot for comparison). - slot, err := time.StartSlot(epoch) + slot, err := slots.EpochStart(epoch) if err != nil { return nil, err } @@ -215,7 +215,7 @@ func (f *blocksFetcher) findForkWithPeer(ctx context.Context, pid peer.ID, slot return nil, fmt.Errorf("cannot obtain peer's status: %w", err) } nonSkippedSlot, err := f.nonSkippedSlotAfterWithPeersTarget( - ctx, slot-slotsPerEpoch, []peer.ID{pid}, time.SlotToEpoch(pidState.HeadSlot)) + ctx, slot-slotsPerEpoch, []peer.ID{pid}, slots.ToEpoch(pidState.HeadSlot)) if err != nil { return nil, fmt.Errorf("cannot locate non-empty slot for a peer: %w", err) } @@ -294,7 +294,7 @@ func (f *blocksFetcher) bestFinalizedSlot() types.Slot { // bestNonFinalizedSlot returns the highest non-finalized slot of enough number of connected peers. func (f *blocksFetcher) bestNonFinalizedSlot() types.Slot { - headEpoch := time.SlotToEpoch(f.chain.HeadSlot()) + headEpoch := slots.ToEpoch(f.chain.HeadSlot()) targetEpoch, _ := f.p2p.Peers().BestNonFinalized(flags.Get().MinimumSyncPeers*2, headEpoch) return params.BeaconConfig().SlotsPerEpoch.Mul(uint64(targetEpoch)) } @@ -306,7 +306,7 @@ func (f *blocksFetcher) calculateHeadAndTargetEpochs() (headEpoch, targetEpoch t headEpoch = f.chain.FinalizedCheckpt().Epoch targetEpoch, peers = f.p2p.Peers().BestFinalized(params.BeaconConfig().MaxPeersToSync, headEpoch) } else { - headEpoch = time.SlotToEpoch(f.chain.HeadSlot()) + headEpoch = slots.ToEpoch(f.chain.HeadSlot()) targetEpoch, peers = f.p2p.Peers().BestNonFinalized(flags.Get().MinimumSyncPeers, headEpoch) } return headEpoch, targetEpoch, peers diff --git a/beacon-chain/sync/initial-sync/blocks_fetcher_utils_test.go b/beacon-chain/sync/initial-sync/blocks_fetcher_utils_test.go index de7e38c7d..84ec9fc25 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher_utils_test.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher_utils_test.go @@ -12,7 +12,6 @@ import ( "github.com/libp2p/go-libp2p-core/peer" types "github.com/prysmaticlabs/eth2-types" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" dbtest "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" p2pm "github.com/prysmaticlabs/prysm/beacon-chain/p2p" p2pt "github.com/prysmaticlabs/prysm/beacon-chain/p2p/testing" @@ -25,6 +24,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" ) func TestBlocksFetcher_nonSkippedSlotAfter(t *testing.T) { @@ -161,7 +161,7 @@ func TestBlocksFetcher_findFork(t *testing.T) { // Chain contains blocks from 8 epochs (from 0 to 7, 256 is the start slot of epoch8). chain1 := extendBlockSequence(t, []*eth.SignedBeaconBlock{}, 250) finalizedSlot := types.Slot(63) - finalizedEpoch := coreTime.SlotToEpoch(finalizedSlot) + finalizedEpoch := slots.ToEpoch(finalizedSlot) genesisBlock := chain1[0] require.NoError(t, beaconDB.SaveBlock(context.Background(), wrapper.WrappedPhase0SignedBeaconBlock(genesisBlock))) @@ -425,7 +425,7 @@ func TestBlocksFetcher_findAncestor(t *testing.T) { knownBlocks := extendBlockSequence(t, []*eth.SignedBeaconBlock{}, 128) finalizedSlot := types.Slot(63) - finalizedEpoch := coreTime.SlotToEpoch(finalizedSlot) + finalizedEpoch := slots.ToEpoch(finalizedSlot) genesisBlock := knownBlocks[0] require.NoError(t, beaconDB.SaveBlock(context.Background(), wrapper.WrappedPhase0SignedBeaconBlock(genesisBlock))) diff --git a/beacon-chain/sync/initial-sync/blocks_queue.go b/beacon-chain/sync/initial-sync/blocks_queue.go index 77a55b97a..f9f39e6a7 100644 --- a/beacon-chain/sync/initial-sync/blocks_queue.go +++ b/beacon-chain/sync/initial-sync/blocks_queue.go @@ -7,11 +7,11 @@ import ( "github.com/libp2p/go-libp2p-core/peer" types "github.com/prysmaticlabs/eth2-types" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/db" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" beaconsync "github.com/prysmaticlabs/prysm/beacon-chain/sync" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" ) @@ -221,7 +221,7 @@ func (q *blocksQueue) loop() { "highestExpectedSlot": q.highestExpectedSlot, "noRequiredPeersErrRetries": q.exitConditions.noRequiredPeersErrRetries, "event": eventTick, - "epoch": coreTime.SlotToEpoch(fsm.start), + "epoch": slots.ToEpoch(fsm.start), "start": fsm.start, "error": err.Error(), }).Debug("Can not trigger event") @@ -263,7 +263,7 @@ func (q *blocksQueue) loop() { if err := fsm.trigger(eventDataReceived, response); err != nil { log.WithFields(logrus.Fields{ "event": eventDataReceived, - "epoch": coreTime.SlotToEpoch(fsm.start), + "epoch": slots.ToEpoch(fsm.start), "error": err.Error(), }).Debug("Can not process event") fsm.setState(stateNew) @@ -419,16 +419,16 @@ func (q *blocksQueue) onProcessSkippedEvent(ctx context.Context) eventHandlerFn // All machines are skipped, FSMs need reset. startSlot := q.chain.HeadSlot() + 1 if q.mode == modeNonConstrained && startSlot > bestFinalizedSlot { - q.staleEpochs[coreTime.SlotToEpoch(startSlot)]++ + q.staleEpochs[slots.ToEpoch(startSlot)]++ // If FSMs have been reset enough times, try to explore alternative forks. - if q.staleEpochs[coreTime.SlotToEpoch(startSlot)] >= maxResetAttempts { - delete(q.staleEpochs, coreTime.SlotToEpoch(startSlot)) + if q.staleEpochs[slots.ToEpoch(startSlot)] >= maxResetAttempts { + delete(q.staleEpochs, slots.ToEpoch(startSlot)) fork, err := q.blocksFetcher.findFork(ctx, startSlot) if err == nil { return stateSkipped, q.resetFromFork(ctx, fork) } log.WithFields(logrus.Fields{ - "epoch": coreTime.SlotToEpoch(startSlot), + "epoch": slots.ToEpoch(startSlot), "error": err.Error(), }).Debug("Can not explore alternative branches") } diff --git a/beacon-chain/sync/initial-sync/blocks_queue_test.go b/beacon-chain/sync/initial-sync/blocks_queue_test.go index a7b911061..8da7e30bd 100644 --- a/beacon-chain/sync/initial-sync/blocks_queue_test.go +++ b/beacon-chain/sync/initial-sync/blocks_queue_test.go @@ -10,7 +10,6 @@ import ( "github.com/libp2p/go-libp2p-core/peer" types "github.com/prysmaticlabs/eth2-types" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" dbtest "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers" p2pt "github.com/prysmaticlabs/prysm/beacon-chain/p2p/testing" @@ -25,6 +24,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" logTest "github.com/sirupsen/logrus/hooks/test" ) @@ -1035,7 +1035,7 @@ func TestBlocksQueue_stuckInUnfavourableFork(t *testing.T) { forkedSlot := types.Slot(201) chain2 := extendBlockSequence(t, chain1[:forkedSlot], 100) finalizedSlot := types.Slot(63) - finalizedEpoch := coreTime.SlotToEpoch(finalizedSlot) + finalizedEpoch := slots.ToEpoch(finalizedSlot) genesisBlock := chain1[0] require.NoError(t, beaconDB.SaveBlock(context.Background(), wrapper.WrappedPhase0SignedBeaconBlock(genesisBlock))) @@ -1135,7 +1135,7 @@ func TestBlocksQueue_stuckInUnfavourableFork(t *testing.T) { } // Update counter, and trigger backtracking. - queue.staleEpochs[coreTime.SlotToEpoch(machineSlots[0])] = maxResetAttempts + queue.staleEpochs[slots.ToEpoch(machineSlots[0])] = maxResetAttempts handlerFn = queue.onProcessSkippedEvent(ctx) updatedState, err = handlerFn(queue.smm.machines[machineSlots[len(machineSlots)-1]], nil) assert.ErrorContains(t, "invalid range for non-skipped slot", err) @@ -1185,7 +1185,7 @@ func TestBlocksQueue_stuckInUnfavourableFork(t *testing.T) { } // Update counter, and trigger backtracking. - queue.staleEpochs[coreTime.SlotToEpoch(machineSlots[0])] = maxResetAttempts + queue.staleEpochs[slots.ToEpoch(machineSlots[0])] = maxResetAttempts handlerFn = queue.onProcessSkippedEvent(ctx) updatedState, err = handlerFn(queue.smm.machines[machineSlots[len(machineSlots)-1]], nil) require.NoError(t, err) @@ -1196,7 +1196,7 @@ func TestBlocksQueue_stuckInUnfavourableFork(t *testing.T) { // Alternative fork should start on slot 201, make sure that the first machine contains all // required forked data, including data on and after slot 201. - forkedEpochStartSlot, err := coreTime.StartSlot(coreTime.SlotToEpoch(forkedSlot)) + forkedEpochStartSlot, err := slots.EpochStart(slots.ToEpoch(forkedSlot)) require.NoError(t, err) firstFSM, ok := queue.smm.findStateMachine(forkedEpochStartSlot + 1) require.Equal(t, true, ok) @@ -1236,7 +1236,7 @@ func TestBlocksQueue_stuckWhenHeadIsSetToOrphanedBlock(t *testing.T) { chain := extendBlockSequence(t, []*eth.SignedBeaconBlock{}, 128) finalizedSlot := types.Slot(82) - finalizedEpoch := coreTime.SlotToEpoch(finalizedSlot) + finalizedEpoch := slots.ToEpoch(finalizedSlot) genesisBlock := chain[0] require.NoError(t, beaconDB.SaveBlock(context.Background(), wrapper.WrappedPhase0SignedBeaconBlock(genesisBlock))) @@ -1304,7 +1304,7 @@ func TestBlocksQueue_stuckWhenHeadIsSetToOrphanedBlock(t *testing.T) { require.NoError(t, queue.start()) isProcessedBlock := func(ctx context.Context, blk block.SignedBeaconBlock, blkRoot [32]byte) bool { - finalizedSlot, err := coreTime.StartSlot(mc.FinalizedCheckpt().Epoch) + finalizedSlot, err := slots.EpochStart(mc.FinalizedCheckpt().Epoch) if err != nil { return false } diff --git a/beacon-chain/sync/initial-sync/fsm.go b/beacon-chain/sync/initial-sync/fsm.go index bffc9fae0..ee3b97bed 100644 --- a/beacon-chain/sync/initial-sync/fsm.go +++ b/beacon-chain/sync/initial-sync/fsm.go @@ -8,9 +8,9 @@ import ( "github.com/libp2p/go-libp2p-core/peer" types "github.com/prysmaticlabs/eth2-types" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" ) const ( @@ -189,7 +189,7 @@ func (m *stateMachine) isLast() bool { // String returns human-readable representation of a FSM state. func (m *stateMachine) String() string { - return fmt.Sprintf("{%d:%s}", coreTime.SlotToEpoch(m.start), m.state) + return fmt.Sprintf("{%d:%s}", slots.ToEpoch(m.start), m.state) } // String returns human-readable representation of a state. diff --git a/beacon-chain/sync/initial-sync/initial_sync_test.go b/beacon-chain/sync/initial-sync/initial_sync_test.go index 51cee0dc5..2094e0afc 100644 --- a/beacon-chain/sync/initial-sync/initial_sync_test.go +++ b/beacon-chain/sync/initial-sync/initial_sync_test.go @@ -13,7 +13,6 @@ import ( "github.com/libp2p/go-libp2p-core/peer" types "github.com/prysmaticlabs/eth2-types" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/db" dbtest "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers" @@ -33,6 +32,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" ) @@ -110,7 +110,7 @@ func makeGenesisTime(currentSlot types.Slot) time.Time { func TestMakeGenesisTime(t *testing.T) { currentSlot := types.Slot(64) gt := makeGenesisTime(currentSlot) - require.Equal(t, currentSlot, coreTime.SlotsSince(gt)) + require.Equal(t, currentSlot, slots.Since(gt)) } // helper function for sequences of block slots @@ -320,7 +320,7 @@ func connectPeerHavingBlocks( p.Connect(host) - finalizedEpoch := coreTime.SlotToEpoch(finalizedSlot) + finalizedEpoch := slots.ToEpoch(finalizedSlot) headRoot, err := blocks[len(blocks)-1].Block.HashTreeRoot() require.NoError(t, err) diff --git a/beacon-chain/sync/initial-sync/round_robin.go b/beacon-chain/sync/initial-sync/round_robin.go index d28606138..f76909f50 100644 --- a/beacon-chain/sync/initial-sync/round_robin.go +++ b/beacon-chain/sync/initial-sync/round_robin.go @@ -11,10 +11,10 @@ import ( "github.com/libp2p/go-libp2p-core/peer" "github.com/paulbellamy/ratecounter" types "github.com/prysmaticlabs/eth2-types" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/encoding/bytesutil" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" ) @@ -51,7 +51,7 @@ func (s *Service) roundRobinSync(genesis time.Time) error { } // Already at head, no need for 2nd phase. - if s.cfg.Chain.HeadSlot() == coreTime.SlotsSince(genesis) { + if s.cfg.Chain.HeadSlot() == slots.Since(genesis) { return nil } @@ -62,7 +62,7 @@ func (s *Service) roundRobinSync(genesis time.Time) error { // syncToFinalizedEpoch sync from head to best known finalized epoch. func (s *Service) syncToFinalizedEpoch(ctx context.Context, genesis time.Time) error { - highestFinalizedSlot, err := coreTime.StartSlot(s.highestFinalizedEpoch() + 1) + highestFinalizedSlot, err := slots.EpochStart(s.highestFinalizedEpoch() + 1) if err != nil { return err } @@ -88,7 +88,7 @@ func (s *Service) syncToFinalizedEpoch(ctx context.Context, genesis time.Time) e log.WithFields(logrus.Fields{ "syncedSlot": s.cfg.Chain.HeadSlot(), - "currentSlot": coreTime.SlotsSince(genesis), + "currentSlot": slots.Since(genesis), }).Info("Synced to finalized epoch - now syncing blocks up to current head") if err := queue.stop(); err != nil { log.WithError(err).Debug("Error stopping queue") @@ -104,7 +104,7 @@ func (s *Service) syncToNonFinalizedEpoch(ctx context.Context, genesis time.Time p2p: s.cfg.P2P, db: s.cfg.DB, chain: s.cfg.Chain, - highestExpectedSlot: coreTime.SlotsSince(genesis), + highestExpectedSlot: slots.Since(genesis), mode: modeNonConstrained, }) if err := queue.start(); err != nil { @@ -115,7 +115,7 @@ func (s *Service) syncToNonFinalizedEpoch(ctx context.Context, genesis time.Time } log.WithFields(logrus.Fields{ "syncedSlot": s.cfg.Chain.HeadSlot(), - "currentSlot": coreTime.SlotsSince(genesis), + "currentSlot": slots.Since(genesis), }).Info("Synced to head of chain") if err := queue.stop(); err != nil { log.WithError(err).Debug("Error stopping queue") @@ -184,15 +184,15 @@ func (s *Service) logSyncStatus(genesis time.Time, blk block.BeaconBlock, blkRoo if rate == 0 { rate = 1 } - if coreTime.IsEpochStart(blk.Slot()) { - timeRemaining := time.Duration(float64(coreTime.SlotsSince(genesis)-blk.Slot())/rate) * time.Second + if slots.IsEpochStart(blk.Slot()) { + timeRemaining := time.Duration(float64(slots.Since(genesis)-blk.Slot())/rate) * time.Second log.WithFields(logrus.Fields{ "peers": len(s.cfg.P2P.Peers().Connected()), "blocksPerSecond": fmt.Sprintf("%.1f", rate), }).Infof( "Processing block %s %d/%d - estimated time remaining %s", fmt.Sprintf("0x%s...", hex.EncodeToString(blkRoot[:])[:8]), - blk.Slot(), coreTime.SlotsSince(genesis), timeRemaining, + blk.Slot(), slots.Since(genesis), timeRemaining, ) } } @@ -205,14 +205,14 @@ func (s *Service) logBatchSyncStatus(genesis time.Time, blks []block.SignedBeaco rate = 1 } firstBlk := blks[0] - timeRemaining := time.Duration(float64(coreTime.SlotsSince(genesis)-firstBlk.Block().Slot())/rate) * time.Second + timeRemaining := time.Duration(float64(slots.Since(genesis)-firstBlk.Block().Slot())/rate) * time.Second log.WithFields(logrus.Fields{ "peers": len(s.cfg.P2P.Peers().Connected()), "blocksPerSecond": fmt.Sprintf("%.1f", rate), }).Infof( "Processing block batch of size %d starting from %s %d/%d - estimated time remaining %s", len(blks), fmt.Sprintf("0x%s...", hex.EncodeToString(blkRoot[:])[:8]), - firstBlk.Block().Slot(), coreTime.SlotsSince(genesis), timeRemaining, + firstBlk.Block().Slot(), slots.Since(genesis), timeRemaining, ) } @@ -300,7 +300,7 @@ func (s *Service) updatePeerScorerStats(pid peer.ID, startSlot types.Slot) { // isProcessedBlock checks DB and local cache for presence of a given block, to avoid duplicates. func (s *Service) isProcessedBlock(ctx context.Context, blk block.SignedBeaconBlock, blkRoot [32]byte) bool { - finalizedSlot, err := coreTime.StartSlot(s.cfg.Chain.FinalizedCheckpt().Epoch) + finalizedSlot, err := slots.EpochStart(s.cfg.Chain.FinalizedCheckpt().Epoch) if err != nil { return false } diff --git a/beacon-chain/sync/initial-sync/service.go b/beacon-chain/sync/initial-sync/service.go index 69f2a0ad6..1f6d6407d 100644 --- a/beacon-chain/sync/initial-sync/service.go +++ b/beacon-chain/sync/initial-sync/service.go @@ -14,13 +14,13 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" blockfeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/block" statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/db" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" "github.com/prysmaticlabs/prysm/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/runtime" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" ) @@ -87,8 +87,8 @@ func (s *Service) Start() { log.WithField("genesisTime", genesis).Info("Genesis time has not arrived - not syncing") return } - currentSlot := coreTime.SlotsSince(genesis) - if coreTime.SlotToEpoch(currentSlot) == 0 { + currentSlot := slots.Since(genesis) + if slots.ToEpoch(currentSlot) == 0 { log.WithField("genesisTime", genesis).Info("Chain started within the last epoch - not syncing") s.markSynced(genesis) return @@ -96,7 +96,7 @@ func (s *Service) Start() { s.chainStarted.Set() log.Info("Starting initial chain sync...") // Are we already in sync, or close to it? - if coreTime.SlotToEpoch(s.cfg.Chain.HeadSlot()) == coreTime.SlotToEpoch(currentSlot) { + if slots.ToEpoch(s.cfg.Chain.HeadSlot()) == slots.ToEpoch(currentSlot) { log.Info("Already synced to the current chain head") s.markSynced(genesis) return diff --git a/beacon-chain/sync/initial-sync/service_test.go b/beacon-chain/sync/initial-sync/service_test.go index 0afe0b858..60617a52e 100644 --- a/beacon-chain/sync/initial-sync/service_test.go +++ b/beacon-chain/sync/initial-sync/service_test.go @@ -13,7 +13,6 @@ import ( mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" dbtest "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" p2pt "github.com/prysmaticlabs/prysm/beacon-chain/p2p/testing" "github.com/prysmaticlabs/prysm/cmd/beacon-chain/flags" @@ -23,6 +22,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" logTest "github.com/sirupsen/logrus/hooks/test" ) @@ -119,7 +119,7 @@ func TestService_InitStartStop(t *testing.T) { return &mock.ChainService{ State: st, FinalizedCheckPoint: ð.Checkpoint{ - Epoch: coreTime.SlotToEpoch(futureSlot), + Epoch: slots.ToEpoch(futureSlot), }, Genesis: makeGenesisTime(futureSlot), ValidatorsRoot: [32]byte{}, @@ -407,7 +407,7 @@ func TestService_Resync(t *testing.T) { Root: genesisRoot[:], DB: beaconDB, FinalizedCheckPoint: ð.Checkpoint{ - Epoch: coreTime.SlotToEpoch(futureSlot), + Epoch: slots.ToEpoch(futureSlot), }, Genesis: time.Now(), ValidatorsRoot: [32]byte{}, diff --git a/beacon-chain/sync/metrics.go b/beacon-chain/sync/metrics.go index 8e190cbc2..514a686d1 100644 --- a/beacon-chain/sync/metrics.go +++ b/beacon-chain/sync/metrics.go @@ -8,11 +8,11 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "github.com/prysmaticlabs/prysm/beacon-chain/cache" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" "github.com/prysmaticlabs/prysm/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/config/params" pb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" ) var ( @@ -84,7 +84,7 @@ func (s *Service) updateMetrics() { log.WithError(err).Debugf("Could not compute fork digest") } indices := s.aggregatorSubnetIndices(s.cfg.Chain.CurrentSlot()) - syncIndices := cache.SyncSubnetIDs.GetAllSubnets(time.SlotToEpoch(s.cfg.Chain.CurrentSlot())) + syncIndices := cache.SyncSubnetIDs.GetAllSubnets(slots.ToEpoch(s.cfg.Chain.CurrentSlot())) attTopic := p2p.GossipTypeMapping[reflect.TypeOf(&pb.Attestation{})] syncTopic := p2p.GossipTypeMapping[reflect.TypeOf(&pb.SyncCommitteeMessage{})] attTopic += s.cfg.P2P.Encoding().ProtocolSuffix() diff --git a/beacon-chain/sync/pending_attestations_queue.go b/beacon-chain/sync/pending_attestations_queue.go index dcf848036..23f60b2f5 100644 --- a/beacon-chain/sync/pending_attestations_queue.go +++ b/beacon-chain/sync/pending_attestations_queue.go @@ -9,7 +9,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/async" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/crypto/rand" "github.com/prysmaticlabs/prysm/encoding/bytesutil" @@ -117,7 +116,7 @@ func (s *Service) processPendingAtts(ctx context.Context) error { } s.setSeenCommitteeIndicesSlot(att.Aggregate.Data.Slot, att.Aggregate.Data.CommitteeIndex, att.Aggregate.AggregationBits) - valCount, err := helpers.ActiveValidatorCount(ctx, preState, time.SlotToEpoch(att.Aggregate.Data.Slot)) + valCount, err := helpers.ActiveValidatorCount(ctx, preState, slots.ToEpoch(att.Aggregate.Data.Slot)) if err != nil { log.WithError(err).Debug("Could not retrieve active validator count") continue diff --git a/beacon-chain/sync/pending_blocks_queue.go b/beacon-chain/sync/pending_blocks_queue.go index 8b13a6c24..4e10a9990 100644 --- a/beacon-chain/sync/pending_blocks_queue.go +++ b/beacon-chain/sync/pending_blocks_queue.go @@ -11,7 +11,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/async" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" p2ptypes "github.com/prysmaticlabs/prysm/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/crypto/rand" @@ -262,7 +261,7 @@ func (s *Service) validatePendingSlots() error { slot := cacheKeyToSlot(k) blks := s.pendingBlocksInCache(slot) for _, b := range blks { - epoch := coreTime.SlotToEpoch(slot) + epoch := slots.ToEpoch(slot) // remove all descendant blocks of old blocks if oldBlockRoots[bytesutil.ToBytes32(b.Block().ParentRoot())] { root, err := b.Block().HashTreeRoot() diff --git a/beacon-chain/sync/rpc.go b/beacon-chain/sync/rpc.go index 6fc894ad0..1f8f7f28c 100644 --- a/beacon-chain/sync/rpc.go +++ b/beacon-chain/sync/rpc.go @@ -10,12 +10,12 @@ import ( libp2pcore "github.com/libp2p/go-libp2p-core" "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/protocol" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" p2ptypes "github.com/prysmaticlabs/prysm/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/monitoring/tracing" "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" ) @@ -34,7 +34,7 @@ type rpcHandler func(context.Context, interface{}, libp2pcore.Stream) error // registerRPCHandlers for p2p RPC. func (s *Service) registerRPCHandlers() { - currEpoch := coreTime.SlotToEpoch(s.cfg.Chain.CurrentSlot()) + currEpoch := slots.ToEpoch(s.cfg.Chain.CurrentSlot()) // Register V2 handlers if we are past altair fork epoch. if currEpoch >= params.BeaconConfig().AltairForkEpoch { s.registerRPC( diff --git a/beacon-chain/sync/rpc_beacon_blocks_by_range_test.go b/beacon-chain/sync/rpc_beacon_blocks_by_range_test.go index bfae9228e..67a783ee2 100644 --- a/beacon-chain/sync/rpc_beacon_blocks_by_range_test.go +++ b/beacon-chain/sync/rpc_beacon_blocks_by_range_test.go @@ -12,7 +12,6 @@ import ( "github.com/libp2p/go-libp2p-core/protocol" types "github.com/prysmaticlabs/eth2-types" chainMock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" db2 "github.com/prysmaticlabs/prysm/beacon-chain/db" db "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" @@ -28,6 +27,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" logTest "github.com/sirupsen/logrus/hooks/test" ) @@ -651,7 +651,7 @@ func TestRPCBeaconBlocksByRange_FilterBlocks(t *testing.T) { } require.NoError(t, d.SaveStateSummaries(context.Background(), stateSummaries)) require.NoError(t, d.SaveFinalizedCheckpoint(context.Background(), ðpb.Checkpoint{ - Epoch: coreTime.SlotToEpoch(stateSummaries[len(stateSummaries)-1].Slot), + Epoch: slots.ToEpoch(stateSummaries[len(stateSummaries)-1].Slot), Root: stateSummaries[len(stateSummaries)-1].Root, })) } @@ -700,7 +700,7 @@ func TestRPCBeaconBlocksByRange_FilterBlocks(t *testing.T) { } require.NoError(t, d.SaveStateSummaries(context.Background(), stateSummaries)) require.NoError(t, d.SaveFinalizedCheckpoint(context.Background(), ðpb.Checkpoint{ - Epoch: coreTime.SlotToEpoch(stateSummaries[len(stateSummaries)-1].Slot), + Epoch: slots.ToEpoch(stateSummaries[len(stateSummaries)-1].Slot), Root: stateSummaries[len(stateSummaries)-1].Root, })) } diff --git a/beacon-chain/sync/rpc_goodbye.go b/beacon-chain/sync/rpc_goodbye.go index 4bc158862..68eec82df 100644 --- a/beacon-chain/sync/rpc_goodbye.go +++ b/beacon-chain/sync/rpc_goodbye.go @@ -10,9 +10,9 @@ import ( "github.com/libp2p/go-libp2p-core/peer" types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/async" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" p2ptypes "github.com/prysmaticlabs/prysm/beacon-chain/p2p/types" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" ) @@ -96,7 +96,7 @@ func (s *Service) sendGoodByeMessage(ctx context.Context, code p2ptypes.RPCGoodb ctx, cancel := context.WithTimeout(ctx, respTimeout) defer cancel() - topic, err := p2p.TopicFromMessage(p2p.GoodbyeMessageName, coreTime.SlotToEpoch(s.cfg.Chain.CurrentSlot())) + topic, err := p2p.TopicFromMessage(p2p.GoodbyeMessageName, slots.ToEpoch(s.cfg.Chain.CurrentSlot())) if err != nil { return err } diff --git a/beacon-chain/sync/rpc_metadata.go b/beacon-chain/sync/rpc_metadata.go index a7a9831dd..e6474db69 100644 --- a/beacon-chain/sync/rpc_metadata.go +++ b/beacon-chain/sync/rpc_metadata.go @@ -9,7 +9,6 @@ import ( "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/beacon-chain/blockchain" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" "github.com/prysmaticlabs/prysm/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/config/params" @@ -19,6 +18,7 @@ import ( "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/metadata" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/wrapper" "github.com/prysmaticlabs/prysm/runtime/version" + "github.com/prysmaticlabs/prysm/time/slots" ) // metaDataHandler reads the incoming metadata rpc request from the peer. @@ -89,7 +89,7 @@ func (s *Service) sendMetaDataRequest(ctx context.Context, id peer.ID) (metadata ctx, cancel := context.WithTimeout(ctx, respTimeout) defer cancel() - topic, err := p2p.TopicFromMessage(p2p.MetadataMessageName, time.SlotToEpoch(s.cfg.Chain.CurrentSlot())) + topic, err := p2p.TopicFromMessage(p2p.MetadataMessageName, slots.ToEpoch(s.cfg.Chain.CurrentSlot())) if err != nil { return nil, err } @@ -107,7 +107,7 @@ func (s *Service) sendMetaDataRequest(ctx context.Context, id peer.ID) (metadata return nil, errors.New(errMsg) } valRoot := s.cfg.Chain.GenesisValidatorRoot() - rpcCtx, err := forks.ForkDigestFromEpoch(time.SlotToEpoch(s.cfg.Chain.CurrentSlot()), valRoot[:]) + rpcCtx, err := forks.ForkDigestFromEpoch(slots.ToEpoch(s.cfg.Chain.CurrentSlot()), valRoot[:]) if err != nil { return nil, err } diff --git a/beacon-chain/sync/rpc_ping.go b/beacon-chain/sync/rpc_ping.go index 79128e408..f012ba723 100644 --- a/beacon-chain/sync/rpc_ping.go +++ b/beacon-chain/sync/rpc_ping.go @@ -9,10 +9,10 @@ import ( libp2pcore "github.com/libp2p/go-libp2p-core" "github.com/libp2p/go-libp2p-core/peer" types "github.com/prysmaticlabs/eth2-types" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" p2ptypes "github.com/prysmaticlabs/prysm/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" ) // pingHandler reads the incoming ping rpc message from the peer. @@ -78,7 +78,7 @@ func (s *Service) sendPingRequest(ctx context.Context, id peer.ID) error { defer cancel() metadataSeq := types.SSZUint64(s.cfg.P2P.MetadataSeq()) - topic, err := p2p.TopicFromMessage(p2p.PingMessageName, coreTime.SlotToEpoch(s.cfg.Chain.CurrentSlot())) + topic, err := p2p.TopicFromMessage(p2p.PingMessageName, slots.ToEpoch(s.cfg.Chain.CurrentSlot())) if err != nil { return err } diff --git a/beacon-chain/sync/rpc_send_request.go b/beacon-chain/sync/rpc_send_request.go index 05f850613..4dc3db5ab 100644 --- a/beacon-chain/sync/rpc_send_request.go +++ b/beacon-chain/sync/rpc_send_request.go @@ -8,12 +8,12 @@ import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/blockchain" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" p2ptypes "github.com/prysmaticlabs/prysm/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/config/params" pb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" + "github.com/prysmaticlabs/prysm/time/slots" ) // ErrInvalidFetchedData is thrown if stream fails to provide requested blocks. @@ -28,7 +28,7 @@ func SendBeaconBlocksByRangeRequest( ctx context.Context, chain blockchain.ChainInfoFetcher, p2pProvider p2p.P2P, pid peer.ID, req *pb.BeaconBlocksByRangeRequest, blockProcessor BeaconBlockProcessor, ) ([]block.SignedBeaconBlock, error) { - topic, err := p2p.TopicFromMessage(p2p.BeaconBlocksByRangeMessageName, time.SlotToEpoch(chain.CurrentSlot())) + topic, err := p2p.TopicFromMessage(p2p.BeaconBlocksByRangeMessageName, slots.ToEpoch(chain.CurrentSlot())) if err != nil { return nil, err } @@ -90,7 +90,7 @@ func SendBeaconBlocksByRootRequest( ctx context.Context, chain blockchain.ChainInfoFetcher, p2pProvider p2p.P2P, pid peer.ID, req *p2ptypes.BeaconBlockByRootsReq, blockProcessor BeaconBlockProcessor, ) ([]block.SignedBeaconBlock, error) { - topic, err := p2p.TopicFromMessage(p2p.BeaconBlocksByRootsMessageName, time.SlotToEpoch(chain.CurrentSlot())) + topic, err := p2p.TopicFromMessage(p2p.BeaconBlocksByRootsMessageName, slots.ToEpoch(chain.CurrentSlot())) if err != nil { return nil, err } diff --git a/beacon-chain/sync/rpc_status.go b/beacon-chain/sync/rpc_status.go index 3929949fa..078075db6 100644 --- a/beacon-chain/sync/rpc_status.go +++ b/beacon-chain/sync/rpc_status.go @@ -12,7 +12,6 @@ import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/async" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" "github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers" p2ptypes "github.com/prysmaticlabs/prysm/beacon-chain/p2p/types" @@ -85,7 +84,7 @@ func (s *Service) resyncIfBehind() { interval := time.Duration(millisecondsPerEpoch/16) * time.Millisecond async.RunEvery(s.ctx, interval, func() { if s.shouldReSync() { - syncedEpoch := coreTime.SlotToEpoch(s.cfg.Chain.HeadSlot()) + syncedEpoch := slots.ToEpoch(s.cfg.Chain.HeadSlot()) // Factor number of expected minimum sync peers, to make sure that enough peers are // available to resync (some peers may go away between checking non-finalized peers and // actual resyncing). @@ -93,7 +92,7 @@ func (s *Service) resyncIfBehind() { // Check if the current node is more than 1 epoch behind. if highestEpoch > (syncedEpoch + 1) { log.WithFields(logrus.Fields{ - "currentEpoch": coreTime.SlotToEpoch(s.cfg.Chain.CurrentSlot()), + "currentEpoch": slots.ToEpoch(s.cfg.Chain.CurrentSlot()), "syncedEpoch": syncedEpoch, "peersEpoch": highestEpoch, }).Info("Fallen behind peers; reverting to initial sync to catch up") @@ -109,8 +108,8 @@ func (s *Service) resyncIfBehind() { // shouldReSync returns true if the node is not syncing and falls behind two epochs. func (s *Service) shouldReSync() bool { - syncedEpoch := coreTime.SlotToEpoch(s.cfg.Chain.HeadSlot()) - currentEpoch := coreTime.SlotToEpoch(s.cfg.Chain.CurrentSlot()) + syncedEpoch := slots.ToEpoch(s.cfg.Chain.HeadSlot()) + currentEpoch := slots.ToEpoch(s.cfg.Chain.CurrentSlot()) prevEpoch := types.Epoch(0) if currentEpoch > 1 { prevEpoch = currentEpoch - 1 @@ -139,7 +138,7 @@ func (s *Service) sendRPCStatusRequest(ctx context.Context, id peer.ID) error { HeadRoot: headRoot, HeadSlot: s.cfg.Chain.HeadSlot(), } - topic, err := p2p.TopicFromMessage(p2p.StatusMessageName, coreTime.SlotToEpoch(s.cfg.Chain.CurrentSlot())) + topic, err := p2p.TopicFromMessage(p2p.StatusMessageName, slots.ToEpoch(s.cfg.Chain.CurrentSlot())) if err != nil { return err } @@ -317,11 +316,11 @@ func (s *Service) validateStatusMessage(ctx context.Context, msg *pb.Status) err if blk == nil || blk.IsNil() { return p2ptypes.ErrGeneric } - if coreTime.SlotToEpoch(blk.Block().Slot()) == msg.FinalizedEpoch { + if slots.ToEpoch(blk.Block().Slot()) == msg.FinalizedEpoch { return nil } - startSlot, err := coreTime.StartSlot(msg.FinalizedEpoch) + startSlot, err := slots.EpochStart(msg.FinalizedEpoch) if err != nil { return p2ptypes.ErrGeneric } diff --git a/beacon-chain/sync/service.go b/beacon-chain/sync/service.go index 449a45555..cebcbe03d 100644 --- a/beacon-chain/sync/service.go +++ b/beacon-chain/sync/service.go @@ -23,7 +23,6 @@ import ( blockfeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/block" "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/operation" statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/db" "github.com/prysmaticlabs/prysm/beacon-chain/operations/attestations" "github.com/prysmaticlabs/prysm/beacon-chain/operations/slashings" @@ -203,7 +202,7 @@ func (s *Service) Stop() error { func (s *Service) Status() error { // If our head slot is on a previous epoch and our peers are reporting their head block are // in the most recent epoch, then we might be out of sync. - if headEpoch := coreTime.SlotToEpoch(s.cfg.Chain.HeadSlot()); headEpoch+1 < coreTime.SlotToEpoch(s.cfg.Chain.CurrentSlot()) && + if headEpoch := slots.ToEpoch(s.cfg.Chain.HeadSlot()); headEpoch+1 < slots.ToEpoch(s.cfg.Chain.CurrentSlot()) && headEpoch+1 < s.cfg.P2P.Peers().HighestEpoch() { return errors.New("out of sync") } @@ -264,7 +263,7 @@ func (s *Service) registerHandlers() { log.WithError(err).Error("Could not retrieve current fork digest") return } - currentEpoch := coreTime.SlotToEpoch(coreTime.CurrentSlot(uint64(s.cfg.Chain.GenesisTime().Unix()))) + currentEpoch := slots.ToEpoch(slots.CurrentSlot(uint64(s.cfg.Chain.GenesisTime().Unix()))) s.registerSubscribers(currentEpoch, digest) go s.forkWatcher() return diff --git a/beacon-chain/sync/subscriber.go b/beacon-chain/sync/subscriber.go index fa9ab8920..0d2127cb1 100644 --- a/beacon-chain/sync/subscriber.go +++ b/beacon-chain/sync/subscriber.go @@ -13,7 +13,6 @@ import ( pubsub "github.com/libp2p/go-libp2p-pubsub" types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/cache" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" "github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers" "github.com/prysmaticlabs/prysm/cmd/beacon-chain/flags" @@ -596,7 +595,7 @@ func (s *Service) subscribeDynamicWithSyncSubnets( return } - wantedSubs := s.retrieveActiveSyncSubnets(coreTime.SlotToEpoch(currentSlot)) + wantedSubs := s.retrieveActiveSyncSubnets(slots.ToEpoch(currentSlot)) // Resize as appropriate. s.reValidateSubscriptions(subscriptions, wantedSubs, topicFormat, digest) diff --git a/beacon-chain/sync/subscriber_beacon_attestation.go b/beacon-chain/sync/subscriber_beacon_attestation.go index e13c4038b..7f2dec486 100644 --- a/beacon-chain/sync/subscriber_beacon_attestation.go +++ b/beacon-chain/sync/subscriber_beacon_attestation.go @@ -7,10 +7,10 @@ import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/cache" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/container/slice" eth "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/protobuf/proto" ) @@ -41,7 +41,7 @@ func (s *Service) persistentSubnetIndices() []uint64 { } func (s *Service) aggregatorSubnetIndices(currentSlot types.Slot) []uint64 { - endEpoch := time.SlotToEpoch(currentSlot) + 1 + endEpoch := slots.ToEpoch(currentSlot) + 1 endSlot := params.BeaconConfig().SlotsPerEpoch.Mul(uint64(endEpoch)) var commIds []uint64 for i := currentSlot; i <= endSlot; i++ { @@ -51,7 +51,7 @@ func (s *Service) aggregatorSubnetIndices(currentSlot types.Slot) []uint64 { } func (s *Service) attesterSubnetIndices(currentSlot types.Slot) []uint64 { - endEpoch := time.SlotToEpoch(currentSlot) + 1 + endEpoch := slots.ToEpoch(currentSlot) + 1 endSlot := params.BeaconConfig().SlotsPerEpoch.Mul(uint64(endEpoch)) var commIds []uint64 for i := currentSlot; i <= endSlot; i++ { diff --git a/beacon-chain/sync/subscriber_test.go b/beacon-chain/sync/subscriber_test.go index 354bd3b44..195648918 100644 --- a/beacon-chain/sync/subscriber_test.go +++ b/beacon-chain/sync/subscriber_test.go @@ -16,7 +16,6 @@ import ( mockChain "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/cache" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" db "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/operations/slashings" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" @@ -32,6 +31,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" logTest "github.com/sirupsen/logrus/hooks/test" "google.golang.org/protobuf/proto" ) @@ -552,7 +552,7 @@ func TestSubscribeWithSyncSubnets_DynamicOK(t *testing.T) { // Empty cache at the end of the test. defer cache.SyncSubnetIDs.EmptyAllCaches() slot := r.cfg.Chain.CurrentSlot() - currEpoch := coreTime.SlotToEpoch(slot) + currEpoch := slots.ToEpoch(slot) cache.SyncSubnetIDs.AddSyncCommitteeSubnets([]byte("pubkey"), currEpoch, []uint64{0, 1}, 10*time.Second) digest, err := r.currentForkDigest() assert.NoError(t, err) diff --git a/beacon-chain/sync/validate_aggregate_proof.go b/beacon-chain/sync/validate_aggregate_proof.go index bd8058355..5c1a6f3a7 100644 --- a/beacon-chain/sync/validate_aggregate_proof.go +++ b/beacon-chain/sync/validate_aggregate_proof.go @@ -13,7 +13,6 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/operation" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/features" @@ -22,6 +21,7 @@ import ( "github.com/prysmaticlabs/prysm/encoding/bytesutil" "github.com/prysmaticlabs/prysm/monitoring/tracing" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" ) @@ -145,8 +145,8 @@ func (s *Service) validateAggregatedAtt(ctx context.Context, signed *ethpb.Signe attSlot := signed.Message.Aggregate.Data.Slot // Only advance state if different epoch as the committee can only change on an epoch transition. - if time.SlotToEpoch(attSlot) > time.SlotToEpoch(bs.Slot()) { - startSlot, err := time.StartSlot(time.SlotToEpoch(attSlot)) + if slots.ToEpoch(attSlot) > slots.ToEpoch(bs.Slot()) { + startSlot, err := slots.EpochStart(slots.ToEpoch(attSlot)) if err != nil { return pubsub.ValidationIgnore, err } @@ -282,7 +282,7 @@ func validateSelectionIndex( } domain := params.BeaconConfig().DomainSelectionProof - epoch := time.SlotToEpoch(data.Slot) + epoch := slots.ToEpoch(data.Slot) v, err := bs.ValidatorAtIndex(validatorIndex) if err != nil { @@ -320,7 +320,7 @@ func aggSigSet(s state.ReadOnlyBeaconState, a *ethpb.SignedAggregateAttestationA return nil, err } - epoch := time.SlotToEpoch(a.Message.Aggregate.Data.Slot) + epoch := slots.ToEpoch(a.Message.Aggregate.Data.Slot) d, err := signing.Domain(s.Fork(), epoch, params.BeaconConfig().DomainAggregateAndProof, s.GenesisValidatorRoot()) if err != nil { return nil, err diff --git a/beacon-chain/sync/validate_beacon_attestation.go b/beacon-chain/sync/validate_beacon_attestation.go index e722c2e1b..ae280131f 100644 --- a/beacon-chain/sync/validate_beacon_attestation.go +++ b/beacon-chain/sync/validate_beacon_attestation.go @@ -14,7 +14,6 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/operation" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/features" @@ -22,6 +21,7 @@ import ( "github.com/prysmaticlabs/prysm/monitoring/tracing" eth "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/attestation" + "github.com/prysmaticlabs/prysm/time/slots" "go.opencensus.io/trace" ) @@ -171,7 +171,7 @@ func (s *Service) validateUnaggregatedAttTopic(ctx context.Context, a *eth.Attes ctx, span := trace.StartSpan(ctx, "sync.validateUnaggregatedAttTopic") defer span.End() - valCount, err := helpers.ActiveValidatorCount(ctx, bs, time.SlotToEpoch(a.Data.Slot)) + valCount, err := helpers.ActiveValidatorCount(ctx, bs, slots.ToEpoch(a.Data.Slot)) if err != nil { tracing.AnnotateError(span, err) return pubsub.ValidationIgnore, err diff --git a/beacon-chain/sync/validate_beacon_blocks.go b/beacon-chain/sync/validate_beacon_blocks.go index 05ff5120e..124696c55 100644 --- a/beacon-chain/sync/validate_beacon_blocks.go +++ b/beacon-chain/sync/validate_beacon_blocks.go @@ -13,7 +13,6 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" blockfeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/block" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/config/features" "github.com/prysmaticlabs/prysm/config/params" @@ -21,6 +20,7 @@ import ( "github.com/prysmaticlabs/prysm/monitoring/tracing" "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" "go.opencensus.io/trace" ) @@ -114,7 +114,7 @@ func (s *Service) validateBeaconBlockPubSub(ctx context.Context, pid peer.ID, ms // MAXIMUM_GOSSIP_CLOCK_DISPARITY in future, we tolerate blocks arriving at max two slots // earlier (SECONDS_PER_SLOT * 2 seconds). Queue such blocks and process them at the right slot. genesisTime := uint64(s.cfg.Chain.GenesisTime().Unix()) - if err := coreTime.VerifySlotTime(genesisTime, blk.Block().Slot(), earlyBlockProcessingTolerance); err != nil { + if err := slots.VerifyTime(genesisTime, blk.Block().Slot(), earlyBlockProcessingTolerance); err != nil { log.WithError(err).WithField("blockSlot", blk.Block().Slot()).Debug("Ignored block") return pubsub.ValidationIgnore, nil } @@ -125,7 +125,7 @@ func (s *Service) validateBeaconBlockPubSub(ctx context.Context, pid peer.ID, ms return pubsub.ValidationIgnore, nil } - startSlot, err := coreTime.StartSlot(s.cfg.Chain.FinalizedCheckpt().Epoch) + startSlot, err := slots.EpochStart(s.cfg.Chain.FinalizedCheckpt().Epoch) if err != nil { log.WithError(err).WithField("blockSlot", blk.Block().Slot()).Debug("Ignored block") return pubsub.ValidationIgnore, nil @@ -168,7 +168,7 @@ func (s *Service) validateBeaconBlockPubSub(ctx context.Context, pid peer.ID, ms msg.ValidatorData = blk.Proto() // Used in downstream subscriber // Log the arrival time of the accepted block - startTime, err := coreTime.SlotToTime(genesisTime, blk.Block().Slot()) + startTime, err := slots.ToTime(genesisTime, blk.Block().Slot()) if err != nil { return pubsub.ValidationIgnore, err } @@ -266,7 +266,7 @@ func (s *Service) setBadBlock(ctx context.Context, root [32]byte) { // This captures metrics for block arrival time by subtracts slot start time. func captureArrivalTimeMetric(genesisTime uint64, currentSlot types.Slot) error { - startTime, err := coreTime.SlotToTime(genesisTime, currentSlot) + startTime, err := slots.ToTime(genesisTime, currentSlot) if err != nil { return err } @@ -281,7 +281,7 @@ func captureArrivalTimeMetric(genesisTime uint64, currentSlot types.Slot) error // returns true if the corresponding block should be queued and false if // the block should be processed immediately. func isBlockQueueable(genesisTime uint64, slot types.Slot, receivedTime time.Time) bool { - slotTime, err := coreTime.SlotToTime(genesisTime, slot) + slotTime, err := slots.ToTime(genesisTime, slot) if err != nil { return false } diff --git a/beacon-chain/sync/validate_sync_committee_message_test.go b/beacon-chain/sync/validate_sync_committee_message_test.go index ae2555fcc..7a84dd9df 100644 --- a/beacon-chain/sync/validate_sync_committee_message_test.go +++ b/beacon-chain/sync/validate_sync_committee_message_test.go @@ -14,7 +14,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" mockChain "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" testingDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" "github.com/prysmaticlabs/prysm/beacon-chain/p2p/encoder" @@ -27,6 +26,7 @@ import ( ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" + "github.com/prysmaticlabs/prysm/time/slots" ) func TestService_ValidateSyncCommitteeMessage(t *testing.T) { @@ -226,7 +226,7 @@ func TestService_ValidateSyncCommitteeMessage(t *testing.T) { msg.Signature = emptySig[:] msg.BlockRoot = headRoot[:] msg.ValidatorIndex = types.ValidatorIndex(chosenVal) - msg.Slot = coreTime.PrevSlot(hState.Slot()) + msg.Slot = slots.PrevSlot(hState.Slot()) // Set Bad Topic and Subnet digest, err := s.currentForkDigest() @@ -274,7 +274,7 @@ func TestService_ValidateSyncCommitteeMessage(t *testing.T) { msg.Signature = emptySig[:] msg.BlockRoot = headRoot[:] msg.ValidatorIndex = types.ValidatorIndex(chosenVal) - msg.Slot = coreTime.PrevSlot(hState.Slot()) + msg.Slot = slots.PrevSlot(hState.Slot()) digest, err := s.currentForkDigest() assert.NoError(t, err) @@ -317,9 +317,9 @@ func TestService_ValidateSyncCommitteeMessage(t *testing.T) { msg.Signature = emptySig[:] msg.BlockRoot = headRoot[:] msg.ValidatorIndex = types.ValidatorIndex(chosenVal) - msg.Slot = coreTime.PrevSlot(hState.Slot()) + msg.Slot = slots.PrevSlot(hState.Slot()) - d, err := signing.Domain(hState.Fork(), coreTime.SlotToEpoch(hState.Slot()), params.BeaconConfig().DomainSyncCommittee, hState.GenesisValidatorRoot()) + d, err := signing.Domain(hState.Fork(), slots.ToEpoch(hState.Slot()), params.BeaconConfig().DomainSyncCommittee, hState.GenesisValidatorRoot()) assert.NoError(t, err) subCommitteeSize := params.BeaconConfig().SyncCommitteeSize / params.BeaconConfig().SyncCommitteeSubnetCount s.cfg.Chain = &mockChain.ChainService{ @@ -370,7 +370,7 @@ func TestService_ValidateSyncCommitteeMessage(t *testing.T) { numOfVals := hState.NumValidators() chosenVal := numOfVals - 10 - d, err := signing.Domain(hState.Fork(), coreTime.SlotToEpoch(hState.Slot()), params.BeaconConfig().DomainSyncCommittee, hState.GenesisValidatorRoot()) + d, err := signing.Domain(hState.Fork(), slots.ToEpoch(hState.Slot()), params.BeaconConfig().DomainSyncCommittee, hState.GenesisValidatorRoot()) assert.NoError(t, err) rawBytes := p2ptypes.SSZBytes(headRoot[:]) sigRoot, err := signing.ComputeSigningRoot(&rawBytes, d) @@ -387,7 +387,7 @@ func TestService_ValidateSyncCommitteeMessage(t *testing.T) { msg.Signature = keys[chosenVal].Sign(sigRoot[:]).Marshal() msg.BlockRoot = headRoot[:] msg.ValidatorIndex = types.ValidatorIndex(chosenVal) - msg.Slot = coreTime.PrevSlot(hState.Slot()) + msg.Slot = slots.PrevSlot(hState.Slot()) // Set Topic and Subnet digest, err := s.currentForkDigest() diff --git a/beacon-chain/sync/validate_sync_contribution_proof_test.go b/beacon-chain/sync/validate_sync_contribution_proof_test.go index 5f49f144a..b1015fb6e 100644 --- a/beacon-chain/sync/validate_sync_contribution_proof_test.go +++ b/beacon-chain/sync/validate_sync_contribution_proof_test.go @@ -15,7 +15,6 @@ import ( mockChain "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/altair" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/beacon-chain/db" testingDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" @@ -34,6 +33,7 @@ import ( "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" "github.com/prysmaticlabs/prysm/testing/util" + "github.com/prysmaticlabs/prysm/time/slots" ) func TestService_ValidateSyncContributionAndProof(t *testing.T) { @@ -325,7 +325,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, coreTime.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -382,7 +382,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, coreTime.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -449,7 +449,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, coreTime.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -459,7 +459,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { pubkey = keys[idx].PublicKey().Marshal() msg.Message.AggregatorIndex = idx msg.Message.SelectionProof = sig.Marshal() - msg.Message.Contribution.Slot = coreTime.PrevSlot(hState.Slot()) + msg.Message.Contribution.Slot = slots.PrevSlot(hState.Slot()) msg.Message.Contribution.SubcommitteeIndex = i msg.Message.Contribution.Signature = infiniteSig[:] msg.Message.Contribution.BlockRoot = headRoot[:] @@ -470,7 +470,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { } } } - d, err := signing.Domain(hState.Fork(), coreTime.SlotToEpoch(coreTime.PrevSlot(hState.Slot())), params.BeaconConfig().DomainSyncCommitteeSelectionProof, hState.GenesisValidatorRoot()) + d, err := signing.Domain(hState.Fork(), slots.ToEpoch(slots.PrevSlot(hState.Slot())), params.BeaconConfig().DomainSyncCommitteeSelectionProof, hState.GenesisValidatorRoot()) require.NoError(t, err) subCommitteeSize := params.BeaconConfig().SyncCommitteeSize / params.BeaconConfig().SyncCommitteeSubnetCount s.cfg.Chain = &mockChain.ChainService{ @@ -527,7 +527,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, coreTime.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -538,7 +538,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { badSig := keys[idx].Sign(junkRoot[:]) msg.Message.AggregatorIndex = idx msg.Message.SelectionProof = sig.Marshal() - msg.Message.Contribution.Slot = coreTime.PrevSlot(hState.Slot()) + msg.Message.Contribution.Slot = slots.PrevSlot(hState.Slot()) msg.Message.Contribution.SubcommitteeIndex = i msg.Message.Contribution.Signature = badSig.Marshal() msg.Message.Contribution.BlockRoot = headRoot[:] @@ -546,7 +546,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { msg.Message.Contribution.AggregationBits.SetBitAt(1, true) msg.Signature = infiniteSig[:] - d, err := signing.Domain(hState.Fork(), coreTime.SlotToEpoch(coreTime.PrevSlot(hState.Slot())), params.BeaconConfig().DomainContributionAndProof, hState.GenesisValidatorRoot()) + d, err := signing.Domain(hState.Fork(), slots.ToEpoch(slots.PrevSlot(hState.Slot())), params.BeaconConfig().DomainContributionAndProof, hState.GenesisValidatorRoot()) assert.NoError(t, err) sigRoot, err := signing.ComputeSigningRoot(msg.Message, d) assert.NoError(t, err) @@ -603,7 +603,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { assert.NoError(t, err) sc, err := hState.CurrentSyncCommittee() assert.NoError(t, err) - cd, err := signing.Domain(hState.Fork(), coreTime.SlotToEpoch(coreTime.PrevSlot(hState.Slot())), params.BeaconConfig().DomainContributionAndProof, hState.GenesisValidatorRoot()) + cd, err := signing.Domain(hState.Fork(), slots.ToEpoch(slots.PrevSlot(hState.Slot())), params.BeaconConfig().DomainContributionAndProof, hState.GenesisValidatorRoot()) assert.NoError(t, err) for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSubnetCount; i++ { coms, err := altair.SyncSubCommitteePubkeys(sc, types.CommitteeIndex(i)) @@ -611,7 +611,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, coreTime.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -620,7 +620,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { infiniteSig := [96]byte{0xC0} msg.Message.AggregatorIndex = idx msg.Message.SelectionProof = sig.Marshal() - msg.Message.Contribution.Slot = coreTime.PrevSlot(hState.Slot()) + msg.Message.Contribution.Slot = slots.PrevSlot(hState.Slot()) msg.Message.Contribution.SubcommitteeIndex = i msg.Message.Contribution.Signature = infiniteSig[:] msg.Message.Contribution.BlockRoot = headRoot[:] @@ -635,7 +635,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { } } - d, err := signing.Domain(hState.Fork(), coreTime.SlotToEpoch(coreTime.PrevSlot(hState.Slot())), params.BeaconConfig().DomainSyncCommitteeSelectionProof, hState.GenesisValidatorRoot()) + d, err := signing.Domain(hState.Fork(), slots.ToEpoch(slots.PrevSlot(hState.Slot())), params.BeaconConfig().DomainSyncCommitteeSelectionProof, hState.GenesisValidatorRoot()) require.NoError(t, err) subCommitteeSize := params.BeaconConfig().SyncCommitteeSize / params.BeaconConfig().SyncCommitteeSubnetCount s.cfg.Chain = &mockChain.ChainService{ @@ -687,9 +687,9 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { assert.NoError(t, err) sc, err := hState.CurrentSyncCommittee() assert.NoError(t, err) - cd, err := signing.Domain(hState.Fork(), coreTime.SlotToEpoch(coreTime.PrevSlot(hState.Slot())), params.BeaconConfig().DomainContributionAndProof, hState.GenesisValidatorRoot()) + cd, err := signing.Domain(hState.Fork(), slots.ToEpoch(slots.PrevSlot(hState.Slot())), params.BeaconConfig().DomainContributionAndProof, hState.GenesisValidatorRoot()) assert.NoError(t, err) - d, err := signing.Domain(hState.Fork(), coreTime.SlotToEpoch(hState.Slot()), params.BeaconConfig().DomainSyncCommittee, hState.GenesisValidatorRoot()) + d, err := signing.Domain(hState.Fork(), slots.ToEpoch(hState.Slot()), params.BeaconConfig().DomainSyncCommittee, hState.GenesisValidatorRoot()) assert.NoError(t, err) var pubkeys [][]byte for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSubnetCount; i++ { @@ -699,7 +699,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, coreTime.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -707,7 +707,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { if isAggregator { msg.Message.AggregatorIndex = idx msg.Message.SelectionProof = sig.Marshal() - msg.Message.Contribution.Slot = coreTime.PrevSlot(hState.Slot()) + msg.Message.Contribution.Slot = slots.PrevSlot(hState.Slot()) msg.Message.Contribution.SubcommitteeIndex = i msg.Message.Contribution.BlockRoot = headRoot[:] msg.Message.Contribution.AggregationBits = bitfield.NewBitvector128() @@ -730,7 +730,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { } } - pd, err := signing.Domain(hState.Fork(), coreTime.SlotToEpoch(coreTime.PrevSlot(hState.Slot())), params.BeaconConfig().DomainSyncCommitteeSelectionProof, hState.GenesisValidatorRoot()) + pd, err := signing.Domain(hState.Fork(), slots.ToEpoch(slots.PrevSlot(hState.Slot())), params.BeaconConfig().DomainSyncCommitteeSelectionProof, hState.GenesisValidatorRoot()) require.NoError(t, err) subCommitteeSize := params.BeaconConfig().SyncCommitteeSize / params.BeaconConfig().SyncCommitteeSubnetCount s.cfg.Chain = &mockChain.ChainService{ @@ -783,9 +783,9 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { assert.NoError(t, err) sc, err := hState.CurrentSyncCommittee() assert.NoError(t, err) - cd, err := signing.Domain(hState.Fork(), coreTime.SlotToEpoch(coreTime.PrevSlot(hState.Slot())), params.BeaconConfig().DomainContributionAndProof, hState.GenesisValidatorRoot()) + cd, err := signing.Domain(hState.Fork(), slots.ToEpoch(slots.PrevSlot(hState.Slot())), params.BeaconConfig().DomainContributionAndProof, hState.GenesisValidatorRoot()) assert.NoError(t, err) - d, err := signing.Domain(hState.Fork(), coreTime.SlotToEpoch(hState.Slot()), params.BeaconConfig().DomainSyncCommittee, hState.GenesisValidatorRoot()) + d, err := signing.Domain(hState.Fork(), slots.ToEpoch(hState.Slot()), params.BeaconConfig().DomainSyncCommittee, hState.GenesisValidatorRoot()) assert.NoError(t, err) var pubkeys [][]byte for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSubnetCount; i++ { @@ -795,7 +795,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, coreTime.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -803,7 +803,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { if isAggregator { msg.Message.AggregatorIndex = idx msg.Message.SelectionProof = sig.Marshal() - msg.Message.Contribution.Slot = coreTime.PrevSlot(hState.Slot()) + msg.Message.Contribution.Slot = slots.PrevSlot(hState.Slot()) msg.Message.Contribution.SubcommitteeIndex = i msg.Message.Contribution.BlockRoot = headRoot[:] msg.Message.Contribution.AggregationBits = bitfield.NewBitvector128() @@ -828,7 +828,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { } } - pd, err := signing.Domain(hState.Fork(), coreTime.SlotToEpoch(coreTime.PrevSlot(hState.Slot())), params.BeaconConfig().DomainSyncCommitteeSelectionProof, hState.GenesisValidatorRoot()) + pd, err := signing.Domain(hState.Fork(), slots.ToEpoch(slots.PrevSlot(hState.Slot())), params.BeaconConfig().DomainSyncCommitteeSelectionProof, hState.GenesisValidatorRoot()) require.NoError(t, err) subCommitteeSize := params.BeaconConfig().SyncCommitteeSize / params.BeaconConfig().SyncCommitteeSubnetCount s.cfg.Chain = &mockChain.ChainService{ @@ -916,7 +916,7 @@ func fillUpBlocksAndState(ctx context.Context, t *testing.T, beaconDB db.Databas } func syncSelectionProofSigningRoot(st state.BeaconState, slot types.Slot, comIdx types.CommitteeIndex) ([32]byte, error) { - dom, err := signing.Domain(st.Fork(), coreTime.SlotToEpoch(slot), params.BeaconConfig().DomainSyncCommitteeSelectionProof, st.GenesisValidatorRoot()) + dom, err := signing.Domain(st.Fork(), slots.ToEpoch(slot), params.BeaconConfig().DomainSyncCommitteeSelectionProof, st.GenesisValidatorRoot()) if err != nil { return [32]byte{}, err } diff --git a/network/forks/BUILD.bazel b/network/forks/BUILD.bazel index f0d9d447b..1180ea714 100644 --- a/network/forks/BUILD.bazel +++ b/network/forks/BUILD.bazel @@ -7,10 +7,10 @@ go_library( visibility = ["//visibility:public"], deps = [ "//beacon-chain/core/signing:go_default_library", - "//beacon-chain/core/time:go_default_library", "//config/params:go_default_library", "//encoding/bytesutil:go_default_library", "//proto/prysm/v1alpha1:go_default_library", + "//time/slots:go_default_library", "@com_github_pkg_errors//:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", ], diff --git a/network/forks/fork.go b/network/forks/fork.go index 9f91bacc2..7f0451994 100644 --- a/network/forks/fork.go +++ b/network/forks/fork.go @@ -9,10 +9,10 @@ import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" ) // IsForkNextEpoch checks if an alloted fork is in the following epoch. @@ -23,8 +23,8 @@ func IsForkNextEpoch(genesisTime time.Time, genesisValidatorsRoot []byte) (bool, if len(genesisValidatorsRoot) == 0 { return false, errors.New("genesis validators root is not set") } - currentSlot := coreTime.SlotsSince(genesisTime) - currentEpoch := coreTime.SlotToEpoch(currentSlot) + currentSlot := slots.Since(genesisTime) + currentEpoch := slots.ToEpoch(currentSlot) fSchedule := params.BeaconConfig().ForkVersionSchedule scheduledForks := SortedForkVersions(fSchedule) isForkEpoch := false @@ -64,8 +64,8 @@ func CreateForkDigest( if len(genesisValidatorsRoot) == 0 { return [4]byte{}, errors.New("genesis validators root is not set") } - currentSlot := coreTime.SlotsSince(genesisTime) - currentEpoch := coreTime.SlotToEpoch(currentSlot) + currentSlot := slots.Since(genesisTime) + currentEpoch := slots.ToEpoch(currentSlot) forkData, err := Fork(currentEpoch) if err != nil { diff --git a/testing/endtoend/evaluators/BUILD.bazel b/testing/endtoend/evaluators/BUILD.bazel index 4b4c53555..0bdbc9530 100644 --- a/testing/endtoend/evaluators/BUILD.bazel +++ b/testing/endtoend/evaluators/BUILD.bazel @@ -20,7 +20,6 @@ go_library( deps = [ "//beacon-chain/core/helpers:go_default_library", "//beacon-chain/core/signing:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/p2p:go_default_library", "//config/params:go_default_library", "//container/slice:go_default_library", diff --git a/testing/endtoend/evaluators/fork.go b/testing/endtoend/evaluators/fork.go index 42357a708..2ab80ce70 100644 --- a/testing/endtoend/evaluators/fork.go +++ b/testing/endtoend/evaluators/fork.go @@ -4,12 +4,12 @@ import ( "context" "github.com/pkg/errors" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" wrapperv2 "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/wrapper" "github.com/prysmaticlabs/prysm/testing/endtoend/helpers" "github.com/prysmaticlabs/prysm/testing/endtoend/policies" "github.com/prysmaticlabs/prysm/testing/endtoend/types" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/grpc" ) @@ -29,7 +29,7 @@ func forkOccurs(conns ...*grpc.ClientConn) error { if err != nil { return errors.Wrap(err, "failed to get stream") } - fSlot, err := time.StartSlot(helpers.AltairE2EForkEpoch) + fSlot, err := slots.EpochStart(helpers.AltairE2EForkEpoch) if err != nil { return err } diff --git a/testing/endtoend/evaluators/metrics.go b/testing/endtoend/evaluators/metrics.go index 8cd274314..81f13ff0d 100644 --- a/testing/endtoend/evaluators/metrics.go +++ b/testing/endtoend/evaluators/metrics.go @@ -120,7 +120,7 @@ func metricsTest(conns ...*grpc.ClientConn) error { if err != nil { return err } - timeSlot := slots.SlotsSinceGenesis(genesisResp.GenesisTime.AsTime()) + timeSlot := slots.SinceGenesis(genesisResp.GenesisTime.AsTime()) if uint64(chainHead.HeadSlot) != uint64(timeSlot) { return fmt.Errorf("expected metrics slot to equal chain head slot, expected %d, received %d", chainHead.HeadSlot, timeSlot) } diff --git a/testing/endtoend/evaluators/validator.go b/testing/endtoend/evaluators/validator.go index 7d4f31d6a..adf8953b8 100644 --- a/testing/endtoend/evaluators/validator.go +++ b/testing/endtoend/evaluators/validator.go @@ -6,12 +6,12 @@ import ( "github.com/pkg/errors" ethtypes "github.com/prysmaticlabs/eth2-types" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/testing/endtoend/helpers" "github.com/prysmaticlabs/prysm/testing/endtoend/policies" "github.com/prysmaticlabs/prysm/testing/endtoend/types" + "github.com/prysmaticlabs/prysm/time/slots" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/emptypb" ) @@ -129,8 +129,8 @@ func validatorsSyncParticipation(conns ...*grpc.ClientConn) error { if err != nil { return errors.Wrap(err, "failed to get genesis data") } - currSlot := time.CurrentSlot(uint64(genesis.GenesisTime.AsTime().Unix())) - currEpoch := time.SlotToEpoch(currSlot) + currSlot := slots.CurrentSlot(uint64(genesis.GenesisTime.AsTime().Unix())) + currEpoch := slots.ToEpoch(currSlot) lowestBound := currEpoch - 1 if lowestBound < helpers.AltairE2EForkEpoch { @@ -148,7 +148,7 @@ func validatorsSyncParticipation(conns ...*grpc.ClientConn) error { if blk.Block == nil || blk.Block.Body == nil || blk.Block.Body.SyncAggregate == nil { return errors.New("nil block provided") } - forkSlot, err := time.StartSlot(helpers.AltairE2EForkEpoch) + forkSlot, err := slots.EpochStart(helpers.AltairE2EForkEpoch) if err != nil { return err } @@ -177,7 +177,7 @@ func validatorsSyncParticipation(conns ...*grpc.ClientConn) error { if blk.Block == nil || blk.Block.Body == nil || blk.Block.Body.SyncAggregate == nil { return errors.New("nil block provided") } - forkSlot, err := time.StartSlot(helpers.AltairE2EForkEpoch) + forkSlot, err := slots.EpochStart(helpers.AltairE2EForkEpoch) if err != nil { return err } diff --git a/testing/fuzz/BUILD.bazel b/testing/fuzz/BUILD.bazel index d27826354..4c7c5efa7 100644 --- a/testing/fuzz/BUILD.bazel +++ b/testing/fuzz/BUILD.bazel @@ -147,6 +147,7 @@ go_fuzz_test( "//beacon-chain/core/transition:go_default_library", "//beacon-chain/core/helpers:go_default_library", "//beacon-chain/core/time:go_default_library", + "//time/slots:go_default_library", "//config/params:go_default_library", ] + COMMON_DEPS, ) @@ -170,6 +171,7 @@ go_library( "//beacon-chain/cache:go_default_library", "//beacon-chain/core/time:go_default_library", "//beacon-chain/core/blocks:go_default_library", + "//time/slots:go_default_library", "//beacon-chain/core/helpers:go_default_library", "//beacon-chain/core/transition:go_default_library", "//beacon-chain/db:go_default_library", diff --git a/testing/fuzz/state_fuzz.go b/testing/fuzz/state_fuzz.go index 8c274fc0d..991a09bbc 100644 --- a/testing/fuzz/state_fuzz.go +++ b/testing/fuzz/state_fuzz.go @@ -4,12 +4,12 @@ import ( "context" "fmt" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" stateutil "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" v1 "github.com/prysmaticlabs/prysm/beacon-chain/state/v1" "github.com/prysmaticlabs/prysm/config/features" "github.com/prysmaticlabs/prysm/config/params" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" ) func init() { @@ -30,8 +30,8 @@ func BeaconStateFuzz(input []byte) { panic(err) } validateStateHTR(s) - nextEpoch := time.SlotToEpoch(s.Slot()) + 1 - slot, err := time.StartSlot(nextEpoch) + nextEpoch := slots.ToEpoch(s.Slot()) + 1 + slot, err := slots.EpochStart(nextEpoch) if err != nil { return } diff --git a/testing/slasher/simulator/BUILD.bazel b/testing/slasher/simulator/BUILD.bazel index 00a904f76..7837b9229 100644 --- a/testing/slasher/simulator/BUILD.bazel +++ b/testing/slasher/simulator/BUILD.bazel @@ -19,7 +19,6 @@ go_library( "//beacon-chain/core/feed/state:go_default_library", "//beacon-chain/core/helpers:go_default_library", "//beacon-chain/core/signing:go_default_library", - "//beacon-chain/core/time:go_default_library", "//beacon-chain/db:go_default_library", "//beacon-chain/operations/slashings:go_default_library", "//beacon-chain/slasher:go_default_library", diff --git a/testing/slasher/simulator/attestation_generator.go b/testing/slasher/simulator/attestation_generator.go index 7ca951135..bfc6e00b9 100644 --- a/testing/slasher/simulator/attestation_generator.go +++ b/testing/slasher/simulator/attestation_generator.go @@ -7,13 +7,13 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/crypto/bls" "github.com/prysmaticlabs/prysm/crypto/rand" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" ) @@ -22,7 +22,7 @@ func (s *Simulator) generateAttestationsForSlot( ) ([]*ethpb.IndexedAttestation, []*ethpb.AttesterSlashing, error) { attestations := make([]*ethpb.IndexedAttestation, 0) slashings := make([]*ethpb.AttesterSlashing, 0) - currentEpoch := time.SlotToEpoch(slot) + currentEpoch := slots.ToEpoch(slot) committeesPerSlot := helpers.SlotCommitteeCount(s.srvConfig.Params.NumValidators) valsPerCommittee := s.srvConfig.Params.NumValidators / diff --git a/testing/slasher/simulator/simulator.go b/testing/slasher/simulator/simulator.go index 2d098293f..a94152e0a 100644 --- a/testing/slasher/simulator/simulator.go +++ b/testing/slasher/simulator/simulator.go @@ -9,7 +9,6 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/blockchain" "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/db" "github.com/prysmaticlabs/prysm/beacon-chain/operations/slashings" "github.com/prysmaticlabs/prysm/beacon-chain/slasher" @@ -159,13 +158,13 @@ func (s *Simulator) simulateBlocksAndAttestations(ctx context.Context) { case slot := <-ticker.C(): // We only run the simulator for a specified number of epochs. totalEpochs := types.Epoch(s.srvConfig.Params.NumEpochs) - if coreTime.SlotToEpoch(slot) >= totalEpochs { + if slots.ToEpoch(slot) >= totalEpochs { return } // Since processing slashings requires at least one slot, we do nothing // if we are a few slots from the end of the simulation. - endSlot, err := coreTime.StartSlot(totalEpochs) + endSlot, err := slots.EpochStart(totalEpochs) if err != nil { log.WithError(err).Fatal("Could not get epoch start slot") } diff --git a/testing/util/BUILD.bazel b/testing/util/BUILD.bazel index 0a29c9803..9667aa08d 100644 --- a/testing/util/BUILD.bazel +++ b/testing/util/BUILD.bazel @@ -40,6 +40,7 @@ go_library( "//proto/prysm/v1alpha1/wrapper:go_default_library", "//runtime/interop:go_default_library", "//runtime/version:go_default_library", + "//time/slots:go_default_library", "@com_github_ethereum_go_ethereum//common/hexutil:go_default_library", "@com_github_pkg_errors//:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", @@ -73,6 +74,7 @@ go_test( "//proto/prysm/v1alpha1/wrapper:go_default_library", "//testing/assert:go_default_library", "//testing/require:go_default_library", + "//time/slots:go_default_library", "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@org_golang_google_protobuf//proto:go_default_library", ], diff --git a/testing/util/attestation.go b/testing/util/attestation.go index fafb0d50e..b520f2d9c 100644 --- a/testing/util/attestation.go +++ b/testing/util/attestation.go @@ -10,7 +10,6 @@ import ( "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/beacon-chain/state" v1 "github.com/prysmaticlabs/prysm/beacon-chain/state/v1" @@ -21,6 +20,7 @@ import ( attv1 "github.com/prysmaticlabs/prysm/proto/eth/v1" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/runtime/version" + "github.com/prysmaticlabs/prysm/time/slots" log "github.com/sirupsen/logrus" ) @@ -59,7 +59,7 @@ func GenerateAttestations( slot-- generateHeadState = true } - currentEpoch := time.SlotToEpoch(slot) + currentEpoch := slots.ToEpoch(slot) targetRoot := make([]byte, 32) var headRoot []byte diff --git a/testing/util/helpers_test.go b/testing/util/helpers_test.go index 26c418aab..bb7c793eb 100644 --- a/testing/util/helpers_test.go +++ b/testing/util/helpers_test.go @@ -13,6 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/testing/assert" "github.com/prysmaticlabs/prysm/testing/require" + "github.com/prysmaticlabs/prysm/time/slots" ) func TestBlockSignature(t *testing.T) { @@ -25,7 +26,7 @@ func TestBlockSignature(t *testing.T) { assert.NoError(t, err) assert.NoError(t, beaconState.SetSlot(beaconState.Slot()-1)) - epoch := time.SlotToEpoch(block.Block.Slot) + epoch := slots.ToEpoch(block.Block.Slot) blockSig, err := signing.ComputeDomainAndSign(beaconState, epoch, block.Block, params.BeaconConfig().DomainBeaconProposer, privKeys[proposerIdx]) require.NoError(t, err) diff --git a/testing/util/sync_aggregate.go b/testing/util/sync_aggregate.go index cc0b00790..78fd80538 100644 --- a/testing/util/sync_aggregate.go +++ b/testing/util/sync_aggregate.go @@ -4,7 +4,6 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" p2pType "github.com/prysmaticlabs/prysm/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/config/params" @@ -12,6 +11,7 @@ import ( "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/runtime/version" + "github.com/prysmaticlabs/prysm/time/slots" ) func generateSyncAggregate(bState state.BeaconState, privs []bls.SecretKey, parentRoot [32]byte) (*ethpb.SyncAggregate, error) { @@ -19,12 +19,12 @@ func generateSyncAggregate(bState state.BeaconState, privs []bls.SecretKey, pare if !ok || bState.Version() == version.Phase0 { return nil, errors.Errorf("state cannot be asserted to altair state") } - nextSlotEpoch := time.SlotToEpoch(st.Slot() + 1) - currEpoch := time.SlotToEpoch(st.Slot()) + nextSlotEpoch := slots.ToEpoch(st.Slot() + 1) + currEpoch := slots.ToEpoch(st.Slot()) var syncCommittee *ethpb.SyncCommittee var err error - if time.SyncCommitteePeriod(currEpoch) == time.SyncCommitteePeriod(nextSlotEpoch) { + if slots.SyncCommitteePeriod(currEpoch) == slots.SyncCommitteePeriod(nextSlotEpoch) { syncCommittee, err = st.CurrentSyncCommittee() if err != nil { return nil, err @@ -52,7 +52,7 @@ func generateSyncAggregate(bState state.BeaconState, privs []bls.SecretKey, pare if !ok { continue } - d, err := signing.Domain(st.Fork(), time.SlotToEpoch(st.Slot()), params.BeaconConfig().DomainSyncCommittee, st.GenesisValidatorRoot()) + d, err := signing.Domain(st.Fork(), slots.ToEpoch(st.Slot()), params.BeaconConfig().DomainSyncCommittee, st.GenesisValidatorRoot()) if err != nil { return nil, err } diff --git a/time/slots/BUILD.bazel b/time/slots/BUILD.bazel index ad19d52bc..fe8cf0524 100644 --- a/time/slots/BUILD.bazel +++ b/time/slots/BUILD.bazel @@ -12,6 +12,8 @@ go_library( deps = [ "//config/params:go_default_library", "//time:go_default_library", + "@com_github_ethereum_go_ethereum//common/math: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", ], diff --git a/time/slots/slottime.go b/time/slots/slottime.go index 4f9beb33a..70aa2b189 100644 --- a/time/slots/slottime.go +++ b/time/slots/slottime.go @@ -1,24 +1,32 @@ package slots import ( + "fmt" + "math" "time" + commonMath "github.com/ethereum/go-ethereum/common/math" + "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/config/params" prysmTime "github.com/prysmaticlabs/prysm/time" ) -// SlotStartTime returns the start time in terms of its unix epoch +// MaxSlotBuffer specifies the max buffer given to slots from +// incoming objects. (24 mins with mainnet spec) +const MaxSlotBuffer = uint64(1 << 7) + +// StartTime returns the start time in terms of its unix epoch // value. -func SlotStartTime(genesis uint64, slot types.Slot) time.Time { +func StartTime(genesis uint64, slot types.Slot) time.Time { duration := time.Second * time.Duration(slot.Mul(params.BeaconConfig().SecondsPerSlot)) startTime := time.Unix(int64(genesis), 0).Add(duration) return startTime } -// SlotsSinceGenesis returns the number of slots since +// SinceGenesis returns the number of slots since // the provided genesis time. -func SlotsSinceGenesis(genesis time.Time) types.Slot { +func SinceGenesis(genesis time.Time) types.Slot { if genesis.After(prysmTime.Now()) { // Genesis has not occurred yet. return 0 } @@ -28,7 +36,7 @@ func SlotsSinceGenesis(genesis time.Time) types.Slot { // EpochsSinceGenesis returns the number of slots since // the provided genesis time. func EpochsSinceGenesis(genesis time.Time) types.Epoch { - return types.Epoch(SlotsSinceGenesis(genesis) / params.BeaconConfig().SlotsPerEpoch) + return types.Epoch(SinceGenesis(genesis) / params.BeaconConfig().SlotsPerEpoch) } // DivideSlotBy divides the SECONDS_PER_SLOT configuration @@ -53,3 +61,170 @@ func AbsoluteValueSlotDifference(x, y types.Slot) uint64 { } return uint64(y.SubSlot(x)) } + +// ToEpoch returns the epoch number of the input slot. +// +// Spec pseudocode definition: +// def compute_epoch_at_slot(slot: Slot) -> Epoch: +// """ +// Return the epoch number at ``slot``. +// """ +// return Epoch(slot // SLOTS_PER_EPOCH) +func ToEpoch(slot types.Slot) types.Epoch { + return types.Epoch(slot.DivSlot(params.BeaconConfig().SlotsPerEpoch)) +} + +// EpochStart returns the first slot number of the +// current epoch. +// +// Spec pseudocode definition: +// def compute_start_slot_at_epoch(epoch: Epoch) -> Slot: +// """ +// Return the start slot of ``epoch``. +// """ +// return Slot(epoch * SLOTS_PER_EPOCH) +func EpochStart(epoch types.Epoch) (types.Slot, error) { + slot, err := params.BeaconConfig().SlotsPerEpoch.SafeMul(uint64(epoch)) + if err != nil { + return slot, errors.Errorf("start slot calculation overflows: %v", err) + } + return slot, nil +} + +// EpochEnd returns the last slot number of the +// current epoch. +func EpochEnd(epoch types.Epoch) (types.Slot, error) { + if epoch == math.MaxUint64 { + return 0, errors.New("start slot calculation overflows") + } + slot, err := EpochStart(epoch + 1) + if err != nil { + return 0, err + } + return slot - 1, nil +} + +// IsEpochStart returns true if the given slot number is an epoch starting slot +// number. +func IsEpochStart(slot types.Slot) bool { + return slot%params.BeaconConfig().SlotsPerEpoch == 0 +} + +// IsEpochEnd returns true if the given slot number is an epoch ending slot +// number. +func IsEpochEnd(slot types.Slot) bool { + return IsEpochStart(slot + 1) +} + +// SinceEpochStarts returns number of slots since the start of the epoch. +func SinceEpochStarts(slot types.Slot) types.Slot { + return slot % params.BeaconConfig().SlotsPerEpoch +} + +// VerifyTime validates the input slot is not from the future. +func VerifyTime(genesisTime uint64, slot types.Slot, timeTolerance time.Duration) error { + slotTime, err := ToTime(genesisTime, slot) + if err != nil { + return err + } + + // Defensive check to ensure unreasonable slots are rejected + // straight away. + if err := ValidateClock(slot, genesisTime); err != nil { + return err + } + + currentTime := prysmTime.Now() + diff := slotTime.Sub(currentTime) + + if diff > timeTolerance { + return fmt.Errorf("could not process slot from the future, slot time %s > current time %s", slotTime, currentTime) + } + return nil +} + +// ToTime takes the given slot and genesis time to determine the start time of the slot. +func ToTime(genesisTimeSec uint64, slot types.Slot) (time.Time, error) { + timeSinceGenesis, err := slot.SafeMul(params.BeaconConfig().SecondsPerSlot) + if err != nil { + return time.Unix(0, 0), fmt.Errorf("slot (%d) is in the far distant future: %w", slot, err) + } + sTime, err := timeSinceGenesis.SafeAdd(genesisTimeSec) + if err != nil { + return time.Unix(0, 0), fmt.Errorf("slot (%d) is in the far distant future: %w", slot, err) + } + return time.Unix(int64(sTime), 0), nil +} + +// Since computes the number of time slots that have occurred since the given timestamp. +func Since(time time.Time) types.Slot { + return CurrentSlot(uint64(time.Unix())) +} + +// CurrentSlot returns the current slot as determined by the local clock and +// provided genesis time. +func CurrentSlot(genesisTimeSec uint64) types.Slot { + now := prysmTime.Now().Unix() + genesis := int64(genesisTimeSec) + if now < genesis { + return 0 + } + return types.Slot(uint64(now-genesis) / params.BeaconConfig().SecondsPerSlot) +} + +// ValidateClock validates a provided slot against the local +// clock to ensure slots that are unreasonable are returned with +// an error. +func ValidateClock(slot types.Slot, genesisTimeSec uint64) error { + maxPossibleSlot := CurrentSlot(genesisTimeSec).Add(MaxSlotBuffer) + // Defensive check to ensure that we only process slots up to a hard limit + // from our local clock. + if slot > maxPossibleSlot { + return fmt.Errorf("slot %d > %d which exceeds max allowed value relative to the local clock", slot, maxPossibleSlot) + } + return nil +} + +// RoundUpToNearestEpoch rounds up the provided slot value to the nearest epoch. +func RoundUpToNearestEpoch(slot types.Slot) types.Slot { + if slot%params.BeaconConfig().SlotsPerEpoch != 0 { + slot -= slot % params.BeaconConfig().SlotsPerEpoch + slot += params.BeaconConfig().SlotsPerEpoch + } + return slot +} + +// VotingPeriodStartTime returns the current voting period's start time +// depending on the provided genesis and current slot. +func VotingPeriodStartTime(genesis uint64, slot types.Slot) uint64 { + slots := params.BeaconConfig().SlotsPerEpoch.Mul(uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod)) + startTime := uint64((slot - slot.ModSlot(slots)).Mul(params.BeaconConfig().SecondsPerSlot)) + return genesis + startTime +} + +// PrevSlot returns previous slot, with an exception in slot 0 to prevent underflow. +func PrevSlot(slot types.Slot) types.Slot { + if slot > 0 { + return slot.Sub(1) + } + return 0 +} + +// SyncCommitteePeriod returns the sync committee period of input epoch `e`. +// +// Spec code: +// def compute_sync_committee_period(epoch: Epoch) -> uint64: +// return epoch // EPOCHS_PER_SYNC_COMMITTEE_PERIOD +func SyncCommitteePeriod(e types.Epoch) uint64 { + return uint64(e / params.BeaconConfig().EpochsPerSyncCommitteePeriod) +} + +// SyncCommitteePeriodStartEpoch returns the start epoch of a sync committee period. +func SyncCommitteePeriodStartEpoch(e types.Epoch) (types.Epoch, error) { + // Overflow is impossible here because of division of `EPOCHS_PER_SYNC_COMMITTEE_PERIOD`. + startEpoch, overflow := commonMath.SafeMul(SyncCommitteePeriod(e), uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod)) + if overflow { + return 0, errors.New("start epoch calculation overflow") + } + return types.Epoch(startEpoch), nil +} diff --git a/time/slots/slottime_test.go b/time/slots/slottime_test.go index 399a5201e..ec1534995 100644 --- a/time/slots/slottime_test.go +++ b/time/slots/slottime_test.go @@ -35,8 +35,8 @@ func TestSlotsSinceGenesis(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := SlotsSinceGenesis(tt.args.genesis); got != tt.want { - t.Errorf("SlotsSinceGenesis() = %v, want %v", got, tt.want) + if got := SinceGenesis(tt.args.genesis); got != tt.want { + t.Errorf("SinceGenesis() = %v, want %v", got, tt.want) } }) } diff --git a/validator/client/BUILD.bazel b/validator/client/BUILD.bazel index eb1c2fd12..a4a523f1a 100644 --- a/validator/client/BUILD.bazel +++ b/validator/client/BUILD.bazel @@ -26,7 +26,6 @@ go_library( "//async/event:go_default_library", "//beacon-chain/core/altair:go_default_library", "//beacon-chain/core/signing:go_default_library", - "//beacon-chain/core/time:go_default_library", "//cache/lru:go_default_library", "//config/features:go_default_library", "//config/params:go_default_library", diff --git a/validator/client/aggregate.go b/validator/client/aggregate.go index b1000bc4d..9fd7c7706 100644 --- a/validator/client/aggregate.go +++ b/validator/client/aggregate.go @@ -7,7 +7,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/crypto/bls" "github.com/prysmaticlabs/prysm/monitoring/tracing" @@ -118,7 +117,7 @@ func (v *validator) SubmitAggregateAndProof(ctx context.Context, slot types.Slot // Signs input slot with domain selection proof. This is used to create the signature for aggregator selection. func (v *validator) signSlotWithSelectionProof(ctx context.Context, pubKey [48]byte, slot types.Slot) (signature []byte, err error) { - domain, err := v.domainData(ctx, coreTime.SlotToEpoch(slot), params.BeaconConfig().DomainSelectionProof[:]) + domain, err := v.domainData(ctx, slots.ToEpoch(slot), params.BeaconConfig().DomainSelectionProof[:]) if err != nil { return nil, err } @@ -153,7 +152,7 @@ func (v *validator) waitToSlotTwoThirds(ctx context.Context, slot types.Slot) { twoThird := oneThird + oneThird delay := twoThird - startTime := slots.SlotStartTime(v.genesisTime, slot) + startTime := slots.StartTime(v.genesisTime, slot) finalTime := startTime.Add(delay) wait := prysmTime.Until(finalTime) if wait <= 0 { @@ -173,7 +172,7 @@ func (v *validator) waitToSlotTwoThirds(ctx context.Context, slot types.Slot) { // This returns the signature of validator signing over aggregate and // proof object. func (v *validator) aggregateAndProofSig(ctx context.Context, pubKey [48]byte, agg *ethpb.AggregateAttestationAndProof) ([]byte, error) { - d, err := v.domainData(ctx, coreTime.SlotToEpoch(agg.Aggregate.Data.Slot), params.BeaconConfig().DomainAggregateAndProof[:]) + d, err := v.domainData(ctx, slots.ToEpoch(agg.Aggregate.Data.Slot), params.BeaconConfig().DomainAggregateAndProof[:]) if err != nil { return nil, err } diff --git a/validator/client/attest.go b/validator/client/attest.go index 0a899ac0f..5926996d7 100644 --- a/validator/client/attest.go +++ b/validator/client/attest.go @@ -258,7 +258,7 @@ func (v *validator) waitOneThirdOrValidBlock(ctx context.Context, slot types.Slo } delay := slots.DivideSlotBy(3 /* a third of the slot duration */) - startTime := slots.SlotStartTime(v.genesisTime, slot) + startTime := slots.StartTime(v.genesisTime, slot) finalTime := startTime.Add(delay) wait := prysmTime.Until(finalTime) if wait <= 0 { diff --git a/validator/client/log.go b/validator/client/log.go index d57201060..2cf75b7a4 100644 --- a/validator/client/log.go +++ b/validator/client/log.go @@ -5,11 +5,11 @@ import ( "time" types "github.com/prysmaticlabs/eth2-types" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" ) @@ -73,7 +73,7 @@ func (v *validator) LogNextDutyTimeLeft(slot types.Slot) error { if nextDutySlot == 0 { log.WithField("slotInEpoch", slot%params.BeaconConfig().SlotsPerEpoch).Info("No duty until next epoch") } else { - nextDutyTime, err := coreTime.SlotToTime(v.genesisTime, nextDutySlot) + nextDutyTime, err := slots.ToTime(v.genesisTime, nextDutySlot) if err != nil { return err } diff --git a/validator/client/metrics.go b/validator/client/metrics.go index 8ba426240..6d4e785d7 100644 --- a/validator/client/metrics.go +++ b/validator/client/metrics.go @@ -7,10 +7,10 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" types "github.com/prysmaticlabs/eth2-types" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" ) @@ -218,7 +218,7 @@ var ( // and penalties over time, percentage gain/loss, and gives the end user a better idea // of how the validator performs with respect to the rest. func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot types.Slot) error { - if !time.IsEpochEnd(slot) || slot <= params.BeaconConfig().SlotsPerEpoch { + if !slots.IsEpochEnd(slot) || slot <= params.BeaconConfig().SlotsPerEpoch { // Do nothing unless we are at the end of the epoch, and not in the first epoch. return nil } @@ -324,7 +324,7 @@ func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot types.S } // These fields are deprecated after Altair. - if time.SlotToEpoch(slot) < params.BeaconConfig().AltairForkEpoch { + if slots.ToEpoch(slot) < params.BeaconConfig().AltairForkEpoch { if i < len(resp.InclusionSlots) { previousEpochSummaryFields["inclusionSlot"] = resp.InclusionSlots[i] } else { @@ -336,7 +336,7 @@ func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot types.S log.WithField("pubKey", truncatedKey).Warn("Missing inclusion distance") } } - if time.SlotToEpoch(slot) >= params.BeaconConfig().AltairForkEpoch { + if slots.ToEpoch(slot) >= params.BeaconConfig().AltairForkEpoch { if i < len(resp.InactivityScores) { previousEpochSummaryFields["inactivityScore"] = resp.InactivityScores[i] } else { @@ -364,7 +364,7 @@ func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot types.S } // Phase0 specific metrics - if time.SlotToEpoch(slot) < params.BeaconConfig().AltairForkEpoch { + if slots.ToEpoch(slot) < params.BeaconConfig().AltairForkEpoch { if i < len(resp.InclusionDistances) { ValidatorInclusionDistancesGaugeVec.WithLabelValues(fmtKey).Set(float64(resp.InclusionDistances[i])) } @@ -395,7 +395,7 @@ func (v *validator) UpdateLogAggregateStats(resp *ethpb.ValidatorPerformanceResp for i := range resp.PublicKeys { // In phase0, we consider attestations included if the inclusion slot is not max uint64. // In altair, we consider attestations included if correctlyVotedTarget is true. - if time.SlotToEpoch(slot) < params.BeaconConfig().AltairForkEpoch && i < len(resp.InclusionDistances) { + if slots.ToEpoch(slot) < params.BeaconConfig().AltairForkEpoch && i < len(resp.InclusionDistances) { if uint64(resp.InclusionSlots[i]) != ^uint64(0) { included++ summary.includedAttestedCount++ @@ -420,7 +420,7 @@ func (v *validator) UpdateLogAggregateStats(resp *ethpb.ValidatorPerformanceResp } // Altair metrics - if time.SlotToEpoch(slot) > params.BeaconConfig().AltairForkEpoch && i < len(resp.InactivityScores) { + if slots.ToEpoch(slot) > params.BeaconConfig().AltairForkEpoch && i < len(resp.InactivityScores) { inactivityScore += int(resp.InactivityScores[i]) } } @@ -445,7 +445,7 @@ func (v *validator) UpdateLogAggregateStats(resp *ethpb.ValidatorPerformanceResp } // Altair summary fields. - if time.SlotToEpoch(slot) > params.BeaconConfig().AltairForkEpoch && len(resp.CorrectlyVotedTarget) > 0 { + if slots.ToEpoch(slot) > params.BeaconConfig().AltairForkEpoch && len(resp.CorrectlyVotedTarget) > 0 { epochSummaryFields["averageInactivityScore"] = fmt.Sprintf("%.0f", float64(inactivityScore)/float64(len(resp.CorrectlyVotedTarget))) } @@ -476,7 +476,7 @@ func (v *validator) UpdateLogAggregateStats(resp *ethpb.ValidatorPerformanceResp } // Add phase0 specific fields - if time.SlotToEpoch(slot) < params.BeaconConfig().AltairForkEpoch { + if slots.ToEpoch(slot) < params.BeaconConfig().AltairForkEpoch { launchSummaryFields["averageInclusionDistance"] = fmt.Sprintf("%.2f slots", float64(summary.totalDistance)/float64(summary.includedAttestedCount)) } diff --git a/validator/client/propose.go b/validator/client/propose.go index 0024a3a9f..7f4b6c70c 100644 --- a/validator/client/propose.go +++ b/validator/client/propose.go @@ -10,7 +10,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/async" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/crypto/bls" "github.com/prysmaticlabs/prysm/crypto/rand" @@ -21,6 +20,7 @@ import ( "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/wrapper" "github.com/prysmaticlabs/prysm/runtime/version" prysmTime "github.com/prysmaticlabs/prysm/time" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/prysmaticlabs/prysm/validator/client/iface" "github.com/sirupsen/logrus" "go.opencensus.io/trace" @@ -39,7 +39,7 @@ const signExitErr = "could not sign voluntary exit proposal" // the state root computation, and finally signed by the validator before being // sent back to the beacon node for broadcasting. func (v *validator) ProposeBlock(ctx context.Context, slot types.Slot, pubKey [48]byte) { - currEpoch := coreTime.SlotToEpoch(slot) + currEpoch := slots.ToEpoch(slot) switch { case currEpoch >= params.BeaconConfig().AltairForkEpoch: v.proposeBlockAltair(ctx, slot, pubKey) diff --git a/validator/client/runner.go b/validator/client/runner.go index 354b6ab7f..da83110ba 100644 --- a/validator/client/runner.go +++ b/validator/client/runner.go @@ -8,9 +8,9 @@ import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/prysmaticlabs/prysm/validator/client/iface" "github.com/prysmaticlabs/prysm/validator/keymanager/remote" "go.opencensus.io/trace" @@ -170,7 +170,7 @@ func run(ctx context.Context, v iface.Validator) { } // Start fetching domain data for the next epoch. - if coreTime.IsEpochEnd(slot) { + if slots.IsEpochEnd(slot) { go v.UpdateDomainDataCaches(ctx, slot+1) } diff --git a/validator/client/sync_committee.go b/validator/client/sync_committee.go index 4805efc15..6039aeba3 100644 --- a/validator/client/sync_committee.go +++ b/validator/client/sync_committee.go @@ -9,13 +9,13 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/altair" "github.com/prysmaticlabs/prysm/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/crypto/bls" "github.com/prysmaticlabs/prysm/encoding/bytesutil" "github.com/prysmaticlabs/prysm/monitoring/tracing" ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1" validatorpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/validator-client" + "github.com/prysmaticlabs/prysm/time/slots" "github.com/sirupsen/logrus" "go.opencensus.io/trace" ) @@ -41,7 +41,7 @@ func (v *validator) SubmitSyncCommitteeMessage(ctx context.Context, slot types.S return } - d, err := v.domainData(ctx, time.SlotToEpoch(slot), params.BeaconConfig().DomainSyncCommittee[:]) + d, err := v.domainData(ctx, slots.ToEpoch(slot), params.BeaconConfig().DomainSyncCommittee[:]) if err != nil { log.WithError(err).Error("Could not get sync committee domain data") return @@ -191,7 +191,7 @@ func (v *validator) selectionProofs(ctx context.Context, slot types.Slot, pubKey // Signs input slot with domain sync committee selection proof. This is used to create the signature for sync committee selection. func (v *validator) signSyncSelectionData(ctx context.Context, pubKey [48]byte, index uint64, slot types.Slot) (signature []byte, err error) { - domain, err := v.domainData(ctx, time.SlotToEpoch(slot), params.BeaconConfig().DomainSyncCommitteeSelectionProof[:]) + domain, err := v.domainData(ctx, slots.ToEpoch(slot), params.BeaconConfig().DomainSyncCommitteeSelectionProof[:]) if err != nil { return nil, err } @@ -208,7 +208,7 @@ func (v *validator) signSyncSelectionData(ctx context.Context, pubKey [48]byte, // This returns the signature of validator signing over sync committee contribution and proof object. func (v *validator) signContributionAndProof(ctx context.Context, pubKey [48]byte, c *ethpb.ContributionAndProof) ([]byte, error) { - d, err := v.domainData(ctx, time.SlotToEpoch(c.Contribution.Slot), params.BeaconConfig().DomainContributionAndProof[:]) + d, err := v.domainData(ctx, slots.ToEpoch(c.Contribution.Slot), params.BeaconConfig().DomainContributionAndProof[:]) if err != nil { return nil, err } diff --git a/validator/client/validator.go b/validator/client/validator.go index 05727c76b..9b0fc0f9c 100644 --- a/validator/client/validator.go +++ b/validator/client/validator.go @@ -20,7 +20,6 @@ import ( types "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/async/event" "github.com/prysmaticlabs/prysm/beacon-chain/core/altair" - coreTime "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/features" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/crypto/hash" @@ -458,7 +457,7 @@ func (v *validator) UpdateDuties(ctx context.Context, slot types.Slot) error { return nil } // Set deadline to end of epoch. - ss, err := coreTime.StartSlot(coreTime.SlotToEpoch(slot) + 1) + ss, err := slots.EpochStart(slots.ToEpoch(slot) + 1) if err != nil { return err } @@ -615,7 +614,7 @@ func (v *validator) RolesAt(ctx context.Context, slot types.Slot) (map[[48]byte] // broadcasts signatures for `slot - 1` for inclusion in `slot`. At the last slot of the epoch, // the validator checks whether it's in the sync committee of following epoch. inSyncCommittee := false - if coreTime.IsEpochEnd(slot) { + if slots.IsEpochEnd(slot) { if v.duties.NextEpochDuties[validator].IsSyncCommittee { roles = append(roles, iface.RoleSyncCommittee) inSyncCommittee = true @@ -717,7 +716,7 @@ func (v *validator) UpdateDomainDataCaches(ctx context.Context, slot types.Slot) params.BeaconConfig().DomainSelectionProof[:], params.BeaconConfig().DomainAggregateAndProof[:], } { - _, err := v.domainData(ctx, coreTime.SlotToEpoch(slot), d) + _, err := v.domainData(ctx, slots.ToEpoch(slot), d) if err != nil { log.WithError(err).Errorf("Failed to update domain data for domain %v", d) } diff --git a/validator/db/kv/BUILD.bazel b/validator/db/kv/BUILD.bazel index 4701ba332..e904a9650 100644 --- a/validator/db/kv/BUILD.bazel +++ b/validator/db/kv/BUILD.bazel @@ -23,7 +23,6 @@ go_library( deps = [ "//async/abool:go_default_library", "//async/event:go_default_library", - "//beacon-chain/core/time:go_default_library", "//config/features:go_default_library", "//config/params:go_default_library", "//encoding/bytesutil:go_default_library", @@ -32,6 +31,7 @@ go_library( "//monitoring/tracing:go_default_library", "//proto/prysm/v1alpha1:go_default_library", "//proto/prysm/v1alpha1/slashings:go_default_library", + "//time/slots: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", diff --git a/validator/db/kv/proposer_protection.go b/validator/db/kv/proposer_protection.go index e8b7db5f5..c694e7b47 100644 --- a/validator/db/kv/proposer_protection.go +++ b/validator/db/kv/proposer_protection.go @@ -6,9 +6,9 @@ import ( "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" - "github.com/prysmaticlabs/prysm/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/config/params" "github.com/prysmaticlabs/prysm/encoding/bytesutil" + "github.com/prysmaticlabs/prysm/time/slots" bolt "go.etcd.io/bbolt" "go.opencensus.io/trace" ) @@ -193,8 +193,8 @@ func pruneProposalHistoryBySlot(valBucket *bolt.Bucket, newestSlot types.Slot) e c := valBucket.Cursor() for k, _ := c.First(); k != nil; k, _ = c.First() { slot := bytesutil.BytesToSlotBigEndian(k) - epoch := time.SlotToEpoch(slot) - newestEpoch := time.SlotToEpoch(newestSlot) + epoch := slots.ToEpoch(slot) + newestEpoch := slots.ToEpoch(newestSlot) // Only delete epochs that are older than the weak subjectivity period. if epoch+params.BeaconConfig().WeakSubjectivityPeriod <= newestEpoch { if err := c.Delete(); err != nil {