From a8e501b3cfec96f1362b3a9bdbee92cc82f70154 Mon Sep 17 00:00:00 2001 From: Victor Farazdagi Date: Tue, 9 Feb 2021 13:05:22 +0300 Subject: [PATCH] ETH2 Types: Epoch (#8373) * update deps * update deps * update protos/* * update deps * reset protos * update protos * update shared/params/config * update protos * update /shared * update shared/slotutil and shared/testutil * update beacon-chain/core/helpers * updates beacon-chain/state * update beacon-chain/forkchoice * update beacon-chain/blockchain * update beacon-chain/cache * update beacon-chain/core * update beacon-chain/db * update beacon-chain/node * update beacon-chain/p2p * update beacon-chain/rpc * update beacon-chain/sync * go mod tidy * make sure that beacon-chain build suceeds * go fmt * update e2e tests * update slasher * remove redundant alias * update validator * gazelle * fix build errors in unit tests * go fmt * update deps * update fuzz/BUILD.bazel * fix unit tests * more unit test fixes * fix blockchain UTs * more unit test fixes --- beacon-chain/blockchain/BUILD.bazel | 1 + beacon-chain/blockchain/chain_info.go | 12 +- beacon-chain/blockchain/metrics.go | 3 +- .../blockchain/process_attestation_helpers.go | 5 +- .../blockchain/process_attestation_test.go | 7 +- beacon-chain/blockchain/process_block_test.go | 9 +- .../blockchain/receive_attestation_test.go | 3 +- beacon-chain/blockchain/receive_block.go | 7 +- beacon-chain/blockchain/service.go | 7 +- beacon-chain/blockchain/testing/BUILD.bazel | 1 + beacon-chain/blockchain/testing/mock.go | 5 +- .../weak_subjectivity_checks_test.go | 5 +- beacon-chain/cache/BUILD.bazel | 1 + beacon-chain/cache/checkpoint_state_test.go | 3 +- beacon-chain/core/blocks/BUILD.bazel | 2 + beacon-chain/core/blocks/attestation.go | 7 +- beacon-chain/core/blocks/attestation_test.go | 3 +- .../core/blocks/attester_slashing_test.go | 3 +- .../core/blocks/block_regression_test.go | 3 +- beacon-chain/core/blocks/deposit_test.go | 5 +- beacon-chain/core/blocks/eth1_data.go | 4 +- beacon-chain/core/blocks/eth1_data_test.go | 5 +- beacon-chain/core/blocks/exit_test.go | 11 +- beacon-chain/core/blocks/randao.go | 4 +- beacon-chain/core/blocks/randao_test.go | 5 +- beacon-chain/core/blocks/signature.go | 2 +- beacon-chain/core/epoch/BUILD.bazel | 1 + beacon-chain/core/epoch/epoch_processing.go | 10 +- .../core/epoch/epoch_processing_test.go | 7 +- .../core/epoch/precompute/BUILD.bazel | 2 + .../core/epoch/precompute/attestation.go | 3 +- .../core/epoch/precompute/attestation_test.go | 4 +- .../justification_finalization_test.go | 25 +- beacon-chain/core/epoch/precompute/new.go | 4 +- .../core/epoch/precompute/new_test.go | 2 +- .../core/epoch/precompute/reward_penalty.go | 9 +- .../epoch/precompute/reward_penalty_test.go | 11 +- beacon-chain/core/helpers/BUILD.bazel | 2 + beacon-chain/core/helpers/attestation.go | 3 +- beacon-chain/core/helpers/block.go | 3 +- beacon-chain/core/helpers/committee.go | 11 +- beacon-chain/core/helpers/committee_test.go | 15 +- beacon-chain/core/helpers/randao.go | 9 +- beacon-chain/core/helpers/randao_test.go | 13 +- beacon-chain/core/helpers/signing_root.go | 5 +- beacon-chain/core/helpers/slot_epoch.go | 27 +- beacon-chain/core/helpers/slot_epoch_test.go | 32 +-- beacon-chain/core/helpers/validators.go | 25 +- beacon-chain/core/helpers/validators_test.go | 15 +- beacon-chain/core/state/BUILD.bazel | 2 +- .../core/state/skip_slot_cache_test.go | 5 +- beacon-chain/core/state/state_test.go | 21 +- beacon-chain/core/state/transition_test.go | 7 +- beacon-chain/core/validators/BUILD.bazel | 3 +- beacon-chain/core/validators/validator.go | 28 +- .../core/validators/validator_test.go | 9 +- beacon-chain/db/filters/BUILD.bazel | 1 + beacon-chain/db/filters/filter.go | 10 +- beacon-chain/db/kv/BUILD.bazel | 2 + beacon-chain/db/kv/blocks.go | 5 +- beacon-chain/db/kv/state_test.go | 6 +- beacon-chain/forkchoice/BUILD.bazel | 5 +- beacon-chain/forkchoice/interfaces.go | 7 +- .../forkchoice/protoarray/BUILD.bazel | 2 + .../forkchoice/protoarray/ffg_update_test.go | 3 +- beacon-chain/forkchoice/protoarray/node.go | 6 +- .../forkchoice/protoarray/node_test.go | 5 +- beacon-chain/forkchoice/protoarray/store.go | 17 +- .../forkchoice/protoarray/store_test.go | 25 +- beacon-chain/forkchoice/protoarray/types.go | 34 +-- beacon-chain/node/BUILD.bazel | 2 + beacon-chain/node/helper.go | 6 +- beacon-chain/node/helper_test.go | 3 +- beacon-chain/p2p/BUILD.bazel | 1 + beacon-chain/p2p/fork_test.go | 7 +- beacon-chain/p2p/peers/BUILD.bazel | 2 + beacon-chain/p2p/peers/status.go | 21 +- beacon-chain/p2p/peers/status_test.go | 15 +- .../p2p/testing/mock_peersprovider.go | 4 +- beacon-chain/rpc/beacon/BUILD.bazel | 2 + beacon-chain/rpc/beacon/assignments.go | 3 +- beacon-chain/rpc/beacon/attestations_test.go | 13 +- beacon-chain/rpc/beacon/blocks_test.go | 11 +- beacon-chain/rpc/beacon/committees.go | 3 +- beacon-chain/rpc/beacon/validators.go | 13 +- beacon-chain/rpc/beacon/validators_stream.go | 21 +- .../rpc/beacon/validators_stream_test.go | 3 +- beacon-chain/rpc/beacon/validators_test.go | 89 ++++--- beacon-chain/rpc/beaconv1/BUILD.bazel | 2 + beacon-chain/rpc/beaconv1/config.go | 5 +- beacon-chain/rpc/beaconv1/config_test.go | 19 +- beacon-chain/rpc/beaconv1/state.go | 13 +- beacon-chain/rpc/beaconv1/state_test.go | 8 +- beacon-chain/rpc/debug/block_test.go | 2 +- beacon-chain/rpc/validator/BUILD.bazel | 2 + beacon-chain/rpc/validator/assignments.go | 7 +- .../rpc/validator/assignments_test.go | 3 +- beacon-chain/rpc/validator/exit_test.go | 9 +- beacon-chain/rpc/validator/proposer.go | 4 +- beacon-chain/rpc/validator/proposer_test.go | 10 +- beacon-chain/rpc/validator/status_test.go | 7 +- beacon-chain/state/BUILD.bazel | 3 +- beacon-chain/state/field_trie_test.go | 2 +- beacon-chain/state/getters.go | 11 +- beacon-chain/state/getters_test.go | 3 +- beacon-chain/state/state_trie.go | 4 +- beacon-chain/state/stateutil/attestations.go | 4 +- beacon-chain/state/stateutil/blocks.go | 2 +- beacon-chain/state/stateutil/state_root.go | 2 +- beacon-chain/state/stateutil/validators.go | 16 +- beacon-chain/state/types_test.go | 5 +- beacon-chain/sync/BUILD.bazel | 2 + beacon-chain/sync/initial-sync/BUILD.bazel | 2 + .../sync/initial-sync/blocks_fetcher.go | 2 +- .../sync/initial-sync/blocks_fetcher_utils.go | 9 +- .../initial-sync/blocks_fetcher_utils_test.go | 9 +- .../sync/initial-sync/blocks_queue.go | 5 +- beacon-chain/sync/initial-sync/fsm_test.go | 21 +- .../sync/initial-sync/initial_sync_test.go | 3 +- beacon-chain/sync/initial-sync/round_robin.go | 5 +- beacon-chain/sync/rpc_status.go | 5 +- beacon-chain/sync/rpc_status_test.go | 7 +- .../sync/subscriber_beacon_attestation.go | 4 +- beacon-chain/sync/validate_aggregate_proof.go | 9 +- .../sync/validate_attester_slashing_test.go | 3 +- .../sync/validate_beacon_blocks_test.go | 2 +- .../sync/validate_voluntary_exit_test.go | 2 +- deps.bzl | 11 +- endtoend/BUILD.bazel | 1 + endtoend/endtoend_test.go | 10 +- endtoend/evaluators/BUILD.bazel | 1 + endtoend/evaluators/data.go | 9 +- endtoend/evaluators/node.go | 13 +- endtoend/evaluators/operations.go | 23 +- endtoend/policies/BUILD.bazel | 1 + endtoend/policies/policies.go | 16 +- endtoend/types/BUILD.bazel | 5 +- endtoend/types/types.go | 3 +- fuzz/BUILD.bazel | 1 + go.mod | 3 +- go.sum | 7 +- proto/beacon/p2p/v1/BUILD.bazel | 2 + proto/beacon/p2p/v1/generated.ssz.go | 19 +- proto/beacon/p2p/v1/messages.pb.go | 102 +++---- proto/beacon/p2p/v1/messages.proto | 4 +- proto/beacon/p2p/v1/types.pb.go | 188 ++++++------- proto/beacon/p2p/v1/types.proto | 2 +- proto/beacon/rpc/v1/BUILD.bazel | 4 + proto/beacon/rpc/v1/debug.pb.go | 250 +++++++++--------- proto/beacon/rpc/v1/debug.proto | 9 +- proto/slashing/BUILD.bazel | 1 + proto/slashing/slashing.pb.go | 128 ++++----- proto/slashing/slashing.proto | 8 +- proto/validator/accounts/v2/BUILD.bazel | 2 + proto/validator/accounts/v2/keymanager.pb.go | 100 +++---- proto/validator/accounts/v2/keymanager.proto | 3 +- shared/bytesutil/BUILD.bazel | 1 + shared/bytesutil/bytes.go | 17 ++ shared/htrutils/htrutils.go | 4 +- shared/htrutils/htrutils_test.go | 4 +- shared/p2putils/BUILD.bazel | 1 + shared/p2putils/fork.go | 5 +- shared/params/BUILD.bazel | 1 + shared/params/config.go | 62 ++--- shared/params/mainnet_config.go | 3 +- shared/slashutil/BUILD.bazel | 1 + shared/slashutil/surround_votes_test.go | 3 +- shared/slotutil/BUILD.bazel | 1 + shared/slotutil/slottime.go | 5 +- shared/sszutil/BUILD.bazel | 1 + shared/sszutil/deep_equal.go | 8 + shared/sszutil/deep_equal_test.go | 8 +- shared/testutil/BUILD.bazel | 1 + shared/testutil/block_test.go | 2 +- shared/testutil/helpers.go | 5 +- shared/testutil/helpers_test.go | 2 +- shared/testutil/state.go | 2 +- slasher/beaconclient/BUILD.bazel | 1 + .../beaconclient/historical_data_retrieval.go | 3 +- slasher/cache/BUILD.bazel | 2 + slasher/cache/flat_span_cache.go | 15 +- .../cache/highest_attestation_cache_test.go | 6 +- slasher/db/iface/BUILD.bazel | 1 + slasher/db/iface/interface.go | 41 +-- slasher/db/kv/BUILD.bazel | 2 + slasher/db/kv/attester_slashings.go | 35 +-- slasher/db/kv/attester_slashings_test.go | 33 +-- slasher/db/kv/benchmark_test.go | 35 +-- slasher/db/kv/block_header.go | 3 +- slasher/db/kv/block_header_test.go | 5 +- slasher/db/kv/indexed_attestations.go | 9 +- slasher/db/kv/indexed_attestations_test.go | 9 +- slasher/db/kv/schema.go | 11 +- slasher/db/kv/spanner_new.go | 25 +- slasher/db/kv/spanner_new_test.go | 49 ++-- slasher/detection/BUILD.bazel | 1 + slasher/detection/attestations/BUILD.bazel | 2 + slasher/detection/attestations/spanner.go | 59 +++-- .../detection/attestations/spanner_test.go | 93 +++---- .../detection/attestations/types/BUILD.bazel | 1 + slasher/detection/attestations/types/types.go | 5 +- slasher/detection/detect.go | 2 +- slasher/detection/service.go | 5 +- tools/forkchecker/BUILD.bazel | 1 + tools/forkchecker/forkchecker.go | 3 +- validator/client/BUILD.bazel | 2 + validator/client/attest_protect_test.go | 9 +- validator/client/metrics.go | 9 +- validator/client/propose.go | 13 +- validator/client/propose_test.go | 8 +- validator/client/service.go | 3 +- .../slashing_protection_interchange_test.go | 4 +- validator/client/validator.go | 9 +- validator/db/iface/BUILD.bazel | 1 + validator/db/iface/interface.go | 7 +- validator/db/kv/BUILD.bazel | 2 + validator/db/kv/attester_protection.go | 57 ++-- validator/db/kv/attester_protection_test.go | 63 ++--- .../db/kv/deprecated_attester_protection.go | 31 +-- .../kv/deprecated_attester_protection_test.go | 9 +- .../migration_optimal_attester_protection.go | 21 +- ...ration_optimal_attester_protection_test.go | 11 +- validator/db/kv/proposer_protection_test.go | 8 +- validator/db/kv/prune_attester_protection.go | 11 +- .../db/kv/prune_attester_protection_test.go | 49 ++-- .../standard-protection-format/BUILD.bazel | 2 + .../standard-protection-format/export_test.go | 5 +- .../standard-protection-format/helpers.go | 10 + .../standard-protection-format/import.go | 11 +- validator/testing/BUILD.bazel | 1 + validator/testing/protection_history.go | 11 +- 231 files changed, 1595 insertions(+), 1308 deletions(-) diff --git a/beacon-chain/blockchain/BUILD.bazel b/beacon-chain/blockchain/BUILD.bazel index c01aca6845..360ee1161c 100644 --- a/beacon-chain/blockchain/BUILD.bazel +++ b/beacon-chain/blockchain/BUILD.bazel @@ -59,6 +59,7 @@ go_library( "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prometheus_client_golang//prometheus/promauto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@io_opencensus_go//trace:go_default_library", diff --git a/beacon-chain/blockchain/chain_info.go b/beacon-chain/blockchain/chain_info.go index 657715170f..5c2292b039 100644 --- a/beacon-chain/blockchain/chain_info.go +++ b/beacon-chain/blockchain/chain_info.go @@ -4,15 +4,15 @@ import ( "context" "time" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" - "go.opencensus.io/trace" - "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray" "github.com/prysmaticlabs/prysm/beacon-chain/state" pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/params" + "go.opencensus.io/trace" ) // ChainInfoFetcher defines a common interface for methods in blockchain service which @@ -42,8 +42,8 @@ type HeadFetcher interface { HeadRoot(ctx context.Context) ([]byte, error) HeadBlock(ctx context.Context) (*ethpb.SignedBeaconBlock, error) HeadState(ctx context.Context) (*state.BeaconState, error) - HeadValidatorsIndices(ctx context.Context, epoch uint64) ([]uint64, error) - HeadSeed(ctx context.Context, epoch uint64) ([32]byte, error) + HeadValidatorsIndices(ctx context.Context, epoch types.Epoch) ([]uint64, error) + HeadSeed(ctx context.Context, epoch types.Epoch) ([32]byte, error) HeadGenesisValidatorRoot() [32]byte HeadETH1Data() *ethpb.Eth1Data ProtoArrayStore() *protoarray.Store @@ -167,7 +167,7 @@ func (s *Service) HeadState(ctx context.Context) (*state.BeaconState, error) { } // HeadValidatorsIndices returns a list of active validator indices from the head view of a given epoch. -func (s *Service) HeadValidatorsIndices(ctx context.Context, epoch uint64) ([]uint64, error) { +func (s *Service) HeadValidatorsIndices(ctx context.Context, epoch types.Epoch) ([]uint64, error) { s.headLock.RLock() defer s.headLock.RUnlock() @@ -178,7 +178,7 @@ func (s *Service) HeadValidatorsIndices(ctx context.Context, epoch uint64) ([]ui } // HeadSeed returns the seed from the head view of a given epoch. -func (s *Service) HeadSeed(ctx context.Context, epoch uint64) ([32]byte, error) { +func (s *Service) HeadSeed(ctx context.Context, epoch types.Epoch) ([32]byte, error) { s.headLock.RLock() defer s.headLock.RUnlock() diff --git a/beacon-chain/blockchain/metrics.go b/beacon-chain/blockchain/metrics.go index dcb53facaa..155899496e 100644 --- a/beacon-chain/blockchain/metrics.go +++ b/beacon-chain/blockchain/metrics.go @@ -5,6 +5,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -120,7 +121,7 @@ func reportSlotMetrics(stateSlot, headSlot, clockSlot uint64, finalizedCheckpoin // reportEpochMetrics reports epoch related metrics. func reportEpochMetrics(ctx context.Context, postState, headState *stateTrie.BeaconState) error { - currentEpoch := postState.Slot() / params.BeaconConfig().SlotsPerEpoch + currentEpoch := types.Epoch(postState.Slot() / params.BeaconConfig().SlotsPerEpoch) // Validator instances pendingInstances := 0 diff --git a/beacon-chain/blockchain/process_attestation_helpers.go b/beacon-chain/blockchain/process_attestation_helpers.go index 5d32fe5505..7462b3a189 100644 --- a/beacon-chain/blockchain/process_attestation_helpers.go +++ b/beacon-chain/blockchain/process_attestation_helpers.go @@ -6,6 +6,7 @@ import ( "strconv" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/state" @@ -20,7 +21,7 @@ import ( func (s *Service) getAttPreState(ctx context.Context, c *ethpb.Checkpoint) (*stateTrie.BeaconState, error) { // Use a multilock to allow scoped holding of a mutex by a checkpoint root + epoch // allowing us to behave smarter in terms of how this function is used concurrently. - epochKey := strconv.FormatUint(c.Epoch, 10 /* base 10 */) + epochKey := strconv.FormatUint(uint64(c.Epoch), 10 /* base 10 */) lock := mputil.NewMultilock(string(c.Root) + epochKey) lock.Lock() defer lock.Unlock() @@ -78,7 +79,7 @@ func (s *Service) getAttPreState(ctx context.Context, c *ethpb.Checkpoint) (*sta func (s *Service) verifyAttTargetEpoch(_ context.Context, genesisTime, nowTime uint64, c *ethpb.Checkpoint) error { currentSlot := (nowTime - genesisTime) / params.BeaconConfig().SecondsPerSlot currentEpoch := helpers.SlotToEpoch(currentSlot) - var prevEpoch uint64 + var prevEpoch types.Epoch // Prevents previous epoch under flow if currentEpoch > 1 { prevEpoch = currentEpoch - 1 diff --git a/beacon-chain/blockchain/process_attestation_test.go b/beacon-chain/blockchain/process_attestation_test.go index 985f60248a..f47c144c3c 100644 --- a/beacon-chain/blockchain/process_attestation_test.go +++ b/beacon-chain/blockchain/process_attestation_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/gogo/protobuf/proto" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/state" @@ -234,19 +235,19 @@ func TestStore_UpdateCheckpointState(t *testing.T) { service, err := New(ctx, cfg) require.NoError(t, err) - epoch := uint64(1) + epoch := types.Epoch(1) baseState, _ := testutil.DeterministicGenesisState(t, 1) checkpoint := ðpb.Checkpoint{Epoch: epoch, Root: bytesutil.PadTo([]byte("hi"), 32)} require.NoError(t, service.beaconDB.SaveState(ctx, baseState, bytesutil.ToBytes32(checkpoint.Root))) returned, err := service.getAttPreState(ctx, checkpoint) require.NoError(t, err) - assert.Equal(t, returned.Slot(), checkpoint.Epoch*params.BeaconConfig().SlotsPerEpoch, "Incorrectly returned base state") + assert.Equal(t, uint64(checkpoint.Epoch.Mul(params.BeaconConfig().SlotsPerEpoch)), returned.Slot(), "Incorrectly returned base state") cached, err := service.checkpointStateCache.StateByCheckpoint(checkpoint) require.NoError(t, err) assert.Equal(t, returned.Slot(), cached.Slot(), "State should have been cached") - epoch = uint64(2) + epoch = 2 newCheckpoint := ðpb.Checkpoint{Epoch: epoch, Root: bytesutil.PadTo([]byte("bye"), 32)} require.NoError(t, service.beaconDB.SaveState(ctx, baseState, bytesutil.ToBytes32(newCheckpoint.Root))) returned, err = service.getAttPreState(ctx, newCheckpoint) diff --git a/beacon-chain/blockchain/process_block_test.go b/beacon-chain/blockchain/process_block_test.go index 946d81a2c9..ed2c2964d3 100644 --- a/beacon-chain/blockchain/process_block_test.go +++ b/beacon-chain/blockchain/process_block_test.go @@ -7,6 +7,7 @@ import ( "time" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" @@ -77,7 +78,7 @@ func TestStore_OnBlock(t *testing.T) { blk: func() *ethpb.SignedBeaconBlock { b := testutil.NewBeaconBlock() b.Block.ParentRoot = randomParentRoot2 - b.Block.Slot = params.BeaconConfig().FarFutureEpoch + b.Block.Slot = uint64(params.BeaconConfig().FarFutureEpoch) return b }(), s: st.Copy(), @@ -336,7 +337,7 @@ func TestUpdateJustified_CouldUpdateBest(t *testing.T) { service.bestJustifiedCheckpt.Epoch = 2 require.NoError(t, service.updateJustified(context.Background(), s)) - assert.Equal(t, uint64(2), service.bestJustifiedCheckpt.Epoch, "Incorrect justified epoch in service") + assert.Equal(t, types.Epoch(2), service.bestJustifiedCheckpt.Epoch, "Incorrect justified epoch in service") } func TestFillForkChoiceMissingBlocks_CanSave(t *testing.T) { @@ -944,6 +945,6 @@ func TestOnBlock_CanFinalize(t *testing.T) { testState, err = service.stateGen.StateByRoot(ctx, r) require.NoError(t, err) } - require.Equal(t, uint64(3), service.CurrentJustifiedCheckpt().Epoch) - require.Equal(t, uint64(2), service.FinalizedCheckpt().Epoch) + require.Equal(t, types.Epoch(3), service.CurrentJustifiedCheckpt().Epoch) + require.Equal(t, types.Epoch(2), service.FinalizedCheckpt().Epoch) } diff --git a/beacon-chain/blockchain/receive_attestation_test.go b/beacon-chain/blockchain/receive_attestation_test.go index 864117ebac..8c913a0da1 100644 --- a/beacon-chain/blockchain/receive_attestation_test.go +++ b/beacon-chain/blockchain/receive_attestation_test.go @@ -5,6 +5,7 @@ import ( "testing" "time" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/state" @@ -27,7 +28,7 @@ func TestAttestationCheckPtState_FarFutureSlot(t *testing.T) { chainService := setupBeaconChain(t, beaconDB) chainService.genesisTime = time.Now() - e := helpers.MaxSlotBuffer/params.BeaconConfig().SlotsPerEpoch + 1 + e := types.Epoch(helpers.MaxSlotBuffer/params.BeaconConfig().SlotsPerEpoch + 1) _, err := chainService.AttestationPreState(context.Background(), ðpb.Attestation{Data: ðpb.AttestationData{Target: ð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 4c4312604d..94efcc310f 100644 --- a/beacon-chain/blockchain/receive_block.go +++ b/beacon-chain/blockchain/receive_block.go @@ -4,6 +4,7 @@ import ( "context" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state" @@ -15,7 +16,7 @@ import ( ) // This defines how many epochs since finality the run time will begin to save hot state on to the DB. -var epochsSinceFinalitySaveHotStateDB = 100 +var epochsSinceFinalitySaveHotStateDB = types.Epoch(100) // BlockReceiver interface defines the methods of chain service receive and processing new blocks. type BlockReceiver interface { @@ -197,12 +198,12 @@ func (s *Service) handlePostBlockOperations(b *ethpb.BeaconBlock) error { func (s *Service) checkSaveHotStateDB(ctx context.Context) error { currentEpoch := helpers.SlotToEpoch(s.CurrentSlot()) // Prevent `sinceFinality` going underflow. - var sinceFinality uint64 + var sinceFinality types.Epoch if currentEpoch > s.finalizedCheckpt.Epoch { sinceFinality = currentEpoch - s.finalizedCheckpt.Epoch } - if sinceFinality >= uint64(epochsSinceFinalitySaveHotStateDB) { + if sinceFinality >= epochsSinceFinalitySaveHotStateDB { s.stateGen.EnableSaveHotStateToDB(ctx) return nil } diff --git a/beacon-chain/blockchain/service.go b/beacon-chain/blockchain/service.go index cfbd0520e3..7d40a3ce56 100644 --- a/beacon-chain/blockchain/service.go +++ b/beacon-chain/blockchain/service.go @@ -11,6 +11,7 @@ import ( "time" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/cache" "github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache" @@ -75,7 +76,7 @@ type Service struct { initSyncBlocksLock sync.RWMutex justifiedBalances []uint64 justifiedBalancesLock sync.RWMutex - wsEpoch uint64 + wsEpoch types.Epoch wsRoot []byte wsVerified bool } @@ -96,7 +97,7 @@ type Config struct { OpsService *attestations.Service StateGen *stategen.State WspBlockRoot []byte - WspEpoch uint64 + WspEpoch types.Epoch } // New instantiates a new block service instance that will @@ -458,7 +459,7 @@ func (s *Service) initializeChainInfo(ctx context.Context) error { return errors.Wrap(err, "could not retrieve head block") } headEpoch := helpers.SlotToEpoch(headBlock.Block.Slot) - var epochsSinceFinality uint64 + var epochsSinceFinality types.Epoch if headEpoch > finalized.Epoch { epochsSinceFinality = headEpoch - finalized.Epoch } diff --git a/beacon-chain/blockchain/testing/BUILD.bazel b/beacon-chain/blockchain/testing/BUILD.bazel index 9cf71f3c13..00a5b95876 100644 --- a/beacon-chain/blockchain/testing/BUILD.bazel +++ b/beacon-chain/blockchain/testing/BUILD.bazel @@ -23,6 +23,7 @@ go_library( "//shared/event:go_default_library", "//shared/params:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", ], diff --git a/beacon-chain/blockchain/testing/mock.go b/beacon-chain/blockchain/testing/mock.go index 232f69aecb..4bd2d8ea4b 100644 --- a/beacon-chain/blockchain/testing/mock.go +++ b/beacon-chain/blockchain/testing/mock.go @@ -9,6 +9,7 @@ import ( "time" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute" "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" @@ -290,7 +291,7 @@ func (s *ChainService) AttestationPreState(_ context.Context, _ *ethpb.Attestati } // HeadValidatorsIndices mocks the same method in the chain service. -func (s *ChainService) HeadValidatorsIndices(_ context.Context, epoch uint64) ([]uint64, error) { +func (s *ChainService) HeadValidatorsIndices(_ context.Context, epoch types.Epoch) ([]uint64, error) { if s.State == nil { return []uint64{}, nil } @@ -298,7 +299,7 @@ func (s *ChainService) HeadValidatorsIndices(_ context.Context, epoch uint64) ([ } // HeadSeed mocks the same method in the chain service. -func (s *ChainService) HeadSeed(_ context.Context, epoch uint64) ([32]byte, error) { +func (s *ChainService) HeadSeed(_ context.Context, epoch types.Epoch) ([32]byte, error) { return helpers.Seed(s.State, epoch, params.BeaconConfig().DomainBeaconAttester) } diff --git a/beacon-chain/blockchain/weak_subjectivity_checks_test.go b/beacon-chain/blockchain/weak_subjectivity_checks_test.go index e89d3d72ff..29e509d66a 100644 --- a/beacon-chain/blockchain/weak_subjectivity_checks_test.go +++ b/beacon-chain/blockchain/weak_subjectivity_checks_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/shared/testutil" @@ -22,8 +23,8 @@ func TestService_VerifyWeakSubjectivityRoot(t *testing.T) { wsVerified bool wantErr bool wsRoot [32]byte - wsEpoch uint64 - finalizedEpoch uint64 + wsEpoch types.Epoch + finalizedEpoch types.Epoch errString string name string }{ diff --git a/beacon-chain/cache/BUILD.bazel b/beacon-chain/cache/BUILD.bazel index db2aaf91fc..38024d8f68 100644 --- a/beacon-chain/cache/BUILD.bazel +++ b/beacon-chain/cache/BUILD.bazel @@ -71,6 +71,7 @@ go_test( "//shared/testutil/require:go_default_library", "@com_github_gogo_protobuf//proto:go_default_library", "@com_github_google_gofuzz//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", ], ) diff --git a/beacon-chain/cache/checkpoint_state_test.go b/beacon-chain/cache/checkpoint_state_test.go index a40b5314c0..fd8125f27f 100644 --- a/beacon-chain/cache/checkpoint_state_test.go +++ b/beacon-chain/cache/checkpoint_state_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/gogo/protobuf/proto" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" @@ -61,7 +62,7 @@ func TestCheckpointStateCache_MaxSize(t *testing.T) { for i := uint64(0); i < uint64(maxCheckpointStateSize+100); i++ { require.NoError(t, st.SetSlot(i)) - require.NoError(t, c.AddCheckpointState(ðpb.Checkpoint{Epoch: i, Root: make([]byte, 32)}, st)) + require.NoError(t, c.AddCheckpointState(ðpb.Checkpoint{Epoch: types.Epoch(i), Root: make([]byte, 32)}, st)) } assert.Equal(t, maxCheckpointStateSize, len(c.cache.Keys())) diff --git a/beacon-chain/core/blocks/BUILD.bazel b/beacon-chain/core/blocks/BUILD.bazel index 3c7808d001..8354ffef7f 100644 --- a/beacon-chain/core/blocks/BUILD.bazel +++ b/beacon-chain/core/blocks/BUILD.bazel @@ -40,6 +40,7 @@ go_library( "//shared/trieutil:go_default_library", "@com_github_gogo_protobuf//proto:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@io_opencensus_go//trace:go_default_library", @@ -84,6 +85,7 @@ go_test( "//shared/trieutil:go_default_library", "@com_github_gogo_protobuf//proto:go_default_library", "@com_github_google_gofuzz//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", diff --git a/beacon-chain/core/blocks/attestation.go b/beacon-chain/core/blocks/attestation.go index 65541671cf..923a94178a 100644 --- a/beacon-chain/core/blocks/attestation.go +++ b/beacon-chain/core/blocks/attestation.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -113,7 +114,7 @@ func ProcessAttestationNoVerifySignature( return nil, err } currEpoch := helpers.SlotToEpoch(beaconState.Slot()) - var prevEpoch uint64 + var prevEpoch types.Epoch if currEpoch == 0 { prevEpoch = 0 } else { @@ -175,9 +176,9 @@ func ProcessAttestationNoVerifySignature( ProposerIndex: proposerIndex, } - var ffgSourceEpoch uint64 + var ffgSourceEpoch types.Epoch var ffgSourceRoot []byte - var ffgTargetEpoch uint64 + var ffgTargetEpoch types.Epoch if data.Target.Epoch == currEpoch { ffgSourceEpoch = beaconState.CurrentJustifiedCheckpoint().Epoch ffgSourceRoot = beaconState.CurrentJustifiedCheckpoint().Root diff --git a/beacon-chain/core/blocks/attestation_test.go b/beacon-chain/core/blocks/attestation_test.go index f9eb742016..fdb9c070da 100644 --- a/beacon-chain/core/blocks/attestation_test.go +++ b/beacon-chain/core/blocks/attestation_test.go @@ -5,6 +5,7 @@ import ( "fmt" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" @@ -596,7 +597,7 @@ func TestValidateIndexedAttestation_AboveMaxLength(t *testing.T) { indexedAtt1.AttestingIndices[i] = i indexedAtt1.Data = ðpb.AttestationData{ Target: ðpb.Checkpoint{ - Epoch: i, + Epoch: types.Epoch(i), }, } } diff --git a/beacon-chain/core/blocks/attester_slashing_test.go b/beacon-chain/core/blocks/attester_slashing_test.go index 5c0a4ca9f7..1efe678b82 100644 --- a/beacon-chain/core/blocks/attester_slashing_test.go +++ b/beacon-chain/core/blocks/attester_slashing_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" @@ -98,7 +99,7 @@ func TestProcessAttesterSlashings_IndexedAttestationFailedToVerify(t *testing.T) func TestProcessAttesterSlashings_AppliesCorrectStatus(t *testing.T) { beaconState, privKeys := testutil.DeterministicGenesisState(t, 100) for _, vv := range beaconState.Validators() { - vv.WithdrawableEpoch = 1 * params.BeaconConfig().SlotsPerEpoch + vv.WithdrawableEpoch = types.Epoch(1 * params.BeaconConfig().SlotsPerEpoch) } att1 := testutil.HydrateIndexedAttestation(ðpb.IndexedAttestation{ diff --git a/beacon-chain/core/blocks/block_regression_test.go b/beacon-chain/core/blocks/block_regression_test.go index fc13d2f052..418e0de775 100644 --- a/beacon-chain/core/blocks/block_regression_test.go +++ b/beacon-chain/core/blocks/block_regression_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" @@ -18,7 +19,7 @@ func TestProcessAttesterSlashings_RegressionSlashableIndices(t *testing.T) { testutil.ResetCache() beaconState, privKeys := testutil.DeterministicGenesisState(t, 5500) for _, vv := range beaconState.Validators() { - vv.WithdrawableEpoch = 1 * params.BeaconConfig().SlotsPerEpoch + vv.WithdrawableEpoch = types.Epoch(1 * params.BeaconConfig().SlotsPerEpoch) } // This set of indices is very similar to the one from our sapphire testnet // when close to 100 validators were incorrectly slashed. The set is from 0 -5500, diff --git a/beacon-chain/core/blocks/deposit_test.go b/beacon-chain/core/blocks/deposit_test.go index ac7edde783..92aac69b06 100644 --- a/beacon-chain/core/blocks/deposit_test.go +++ b/beacon-chain/core/blocks/deposit_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" @@ -319,8 +320,8 @@ func TestPreGenesisDeposits_SkipInvalidDeposit(t *testing.T) { val, err := newState.ValidatorAtIndex(uint64(i)) require.NoError(t, err) require.Equal(t, params.BeaconConfig().MaxEffectiveBalance, val.EffectiveBalance, "unequal effective balance") - require.Equal(t, uint64(0), val.ActivationEpoch) - require.Equal(t, uint64(0), val.ActivationEligibilityEpoch) + require.Equal(t, types.Epoch(0), val.ActivationEpoch) + require.Equal(t, types.Epoch(0), val.ActivationEligibilityEpoch) } if newState.Eth1DepositIndex() != 100 { t.Errorf( diff --git a/beacon-chain/core/blocks/eth1_data.go b/beacon-chain/core/blocks/eth1_data.go index 047b0b82c9..3a1dcda0cf 100644 --- a/beacon-chain/core/blocks/eth1_data.go +++ b/beacon-chain/core/blocks/eth1_data.go @@ -71,6 +71,6 @@ func Eth1DataHasEnoughSupport(beaconState *stateTrie.BeaconState, data *ethpb.Et // If 50+% majority converged on the same eth1data, then it has enough support to update the // state. - support := params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch - return voteCount*2 > support, nil + support := params.BeaconConfig().EpochsPerEth1VotingPeriod.Mul(params.BeaconConfig().SlotsPerEpoch) + return voteCount*2 > uint64(support), nil } diff --git a/beacon-chain/core/blocks/eth1_data_test.go b/beacon-chain/core/blocks/eth1_data_test.go index 4105b68804..a3ad988711 100644 --- a/beacon-chain/core/blocks/eth1_data_test.go +++ b/beacon-chain/core/blocks/eth1_data_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/gogo/protobuf/proto" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -33,7 +34,7 @@ func TestEth1DataHasEnoughSupport(t *testing.T) { stateVotes []*ethpb.Eth1Data data *ethpb.Eth1Data hasSupport bool - votingPeriodLength uint64 + votingPeriodLength types.Epoch }{ { stateVotes: FakeDeposits(4 * params.BeaconConfig().SlotsPerEpoch), @@ -174,7 +175,7 @@ func TestProcessEth1Data_SetsCorrectly(t *testing.T) { }, } - period := params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch + period := uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod.Mul(params.BeaconConfig().SlotsPerEpoch)) for i := uint64(0); i < period; i++ { beaconState, err = blocks.ProcessEth1DataInBlock(context.Background(), beaconState, b) require.NoError(t, err) diff --git a/beacon-chain/core/blocks/exit_test.go b/beacon-chain/core/blocks/exit_test.go index 8dd90a1611..d4c622ee08 100644 --- a/beacon-chain/core/blocks/exit_test.go +++ b/beacon-chain/core/blocks/exit_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" @@ -168,7 +169,7 @@ func TestProcessVoluntaryExits_AppliesCorrectStatus(t *testing.T) { Slot: params.BeaconConfig().SlotsPerEpoch * 5, }) require.NoError(t, err) - err = state.SetSlot(state.Slot() + (params.BeaconConfig().ShardCommitteePeriod * params.BeaconConfig().SlotsPerEpoch)) + err = state.SetSlot(state.Slot() + uint64(params.BeaconConfig().ShardCommitteePeriod.Mul(params.BeaconConfig().SlotsPerEpoch))) require.NoError(t, err) priv, err := bls.RandKey() @@ -192,17 +193,17 @@ func TestProcessVoluntaryExits_AppliesCorrectStatus(t *testing.T) { newState, err := blocks.ProcessVoluntaryExits(context.Background(), state, b) require.NoError(t, err, "Could not process exits") newRegistry := newState.Validators() - if newRegistry[0].ExitEpoch != helpers.ActivationExitEpoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch) { + if newRegistry[0].ExitEpoch != helpers.ActivationExitEpoch(types.Epoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch)) { t.Errorf("Expected validator exit epoch to be %d, got %d", - helpers.ActivationExitEpoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch), newRegistry[0].ExitEpoch) + helpers.ActivationExitEpoch(types.Epoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch)), newRegistry[0].ExitEpoch) } // Check conformance with NoVerify Exit Method. newState, err = blocks.ProcessVoluntaryExitsNoVerifySignature(stateCopy, b.Block.Body) require.NoError(t, err, "Could not process exits") newRegistry = newState.Validators() - if newRegistry[0].ExitEpoch != helpers.ActivationExitEpoch(stateCopy.Slot()/params.BeaconConfig().SlotsPerEpoch) { + if newRegistry[0].ExitEpoch != helpers.ActivationExitEpoch(types.Epoch(stateCopy.Slot()/params.BeaconConfig().SlotsPerEpoch)) { t.Errorf("Expected validator exit epoch to be %d, got %d", - helpers.ActivationExitEpoch(stateCopy.Slot()/params.BeaconConfig().SlotsPerEpoch), newRegistry[0].ExitEpoch) + helpers.ActivationExitEpoch(types.Epoch(stateCopy.Slot()/params.BeaconConfig().SlotsPerEpoch)), newRegistry[0].ExitEpoch) } } diff --git a/beacon-chain/core/blocks/randao.go b/beacon-chain/core/blocks/randao.go index 4e551542cb..6ae3d375da 100644 --- a/beacon-chain/core/blocks/randao.go +++ b/beacon-chain/core/blocks/randao.go @@ -67,7 +67,7 @@ func ProcessRandaoNoVerify( // If block randao passed verification, we XOR the state's latest randao mix with the block's // randao and update the state's corresponding latest randao mix value. latestMixesLength := params.BeaconConfig().EpochsPerHistoricalVector - latestMixSlice, err := beaconState.RandaoMixAtIndex(currentEpoch % latestMixesLength) + latestMixSlice, err := beaconState.RandaoMixAtIndex(uint64(currentEpoch % latestMixesLength)) if err != nil { return nil, err } @@ -78,7 +78,7 @@ func ProcessRandaoNoVerify( for i, x := range blockRandaoReveal { latestMixSlice[i] ^= x } - if err := beaconState.UpdateRandaoMixesAtIndex(currentEpoch%latestMixesLength, latestMixSlice); err != nil { + if err := beaconState.UpdateRandaoMixesAtIndex(uint64(currentEpoch%latestMixesLength), latestMixSlice); err != nil { return nil, err } return beaconState, nil diff --git a/beacon-chain/core/blocks/randao_test.go b/beacon-chain/core/blocks/randao_test.go index 4494111e90..64c35cd3d4 100644 --- a/beacon-chain/core/blocks/randao_test.go +++ b/beacon-chain/core/blocks/randao_test.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" @@ -20,9 +21,9 @@ func TestProcessRandao_IncorrectProposerFailsVerification(t *testing.T) { // We fetch the proposer's index as that is whom the RANDAO will be verified against. proposerIdx, err := helpers.BeaconProposerIndex(beaconState) require.NoError(t, err) - epoch := uint64(0) + epoch := types.Epoch(0) buf := make([]byte, 32) - binary.LittleEndian.PutUint64(buf, epoch) + binary.LittleEndian.PutUint64(buf, uint64(epoch)) domain, err := helpers.Domain(beaconState.Fork(), epoch, params.BeaconConfig().DomainRandao, beaconState.GenesisValidatorRoot()) require.NoError(t, err) root, err := (&pb.SigningData{ObjectRoot: buf, Domain: domain}).HashTreeRoot() diff --git a/beacon-chain/core/blocks/signature.go b/beacon-chain/core/blocks/signature.go index f4a3bb57e8..0a47170f33 100644 --- a/beacon-chain/core/blocks/signature.go +++ b/beacon-chain/core/blocks/signature.go @@ -114,7 +114,7 @@ func randaoSigningData(beaconState *stateTrie.BeaconState) ([]byte, []byte, []by currentEpoch := helpers.SlotToEpoch(beaconState.Slot()) buf := make([]byte, 32) - binary.LittleEndian.PutUint64(buf, currentEpoch) + binary.LittleEndian.PutUint64(buf, uint64(currentEpoch)) domain, err := helpers.Domain(beaconState.Fork(), currentEpoch, params.BeaconConfig().DomainRandao, beaconState.GenesisValidatorRoot()) if err != nil { diff --git a/beacon-chain/core/epoch/BUILD.bazel b/beacon-chain/core/epoch/BUILD.bazel index 3399946abe..c35460d13d 100644 --- a/beacon-chain/core/epoch/BUILD.bazel +++ b/beacon-chain/core/epoch/BUILD.bazel @@ -37,6 +37,7 @@ go_test( "//shared/testutil/require:go_default_library", "@com_github_gogo_protobuf//proto:go_default_library", "@com_github_google_gofuzz//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", ], diff --git a/beacon-chain/core/epoch/epoch_processing.go b/beacon-chain/core/epoch/epoch_processing.go index e41a6868f7..5cba16040b 100644 --- a/beacon-chain/core/epoch/epoch_processing.go +++ b/beacon-chain/core/epoch/epoch_processing.go @@ -276,20 +276,20 @@ func ProcessFinalUpdates(state *stateTrie.BeaconState) (*stateTrie.BeaconState, slashedExitLength := params.BeaconConfig().EpochsPerSlashingsVector slashedEpoch := nextEpoch % slashedExitLength slashings := state.Slashings() - if uint64(len(slashings)) != slashedExitLength { + if uint64(len(slashings)) != uint64(slashedExitLength) { return nil, fmt.Errorf( "state slashing length %d different than EpochsPerHistoricalVector %d", len(slashings), slashedExitLength, ) } - if err := state.UpdateSlashingsAtIndex(slashedEpoch /* index */, 0 /* value */); err != nil { + if err := state.UpdateSlashingsAtIndex(uint64(slashedEpoch) /* index */, 0 /* value */); err != nil { return nil, err } // Set RANDAO mix. randaoMixLength := params.BeaconConfig().EpochsPerHistoricalVector - if uint64(state.RandaoMixesLength()) != randaoMixLength { + if uint64(state.RandaoMixesLength()) != uint64(randaoMixLength) { return nil, fmt.Errorf( "state randao length %d different than EpochsPerHistoricalVector %d", state.RandaoMixesLength(), @@ -300,13 +300,13 @@ func ProcessFinalUpdates(state *stateTrie.BeaconState) (*stateTrie.BeaconState, if err != nil { return nil, err } - if err := state.UpdateRandaoMixesAtIndex(nextEpoch%randaoMixLength, mix); err != nil { + if err := state.UpdateRandaoMixesAtIndex(uint64(nextEpoch%randaoMixLength), mix); err != nil { return nil, err } // Set historical root accumulator. epochsPerHistoricalRoot := params.BeaconConfig().SlotsPerHistoricalRoot / params.BeaconConfig().SlotsPerEpoch - if nextEpoch%epochsPerHistoricalRoot == 0 { + if nextEpoch.Mod(epochsPerHistoricalRoot) == 0 { historicalBatch := &pb.HistoricalBatch{ BlockRoots: state.BlockRoots(), StateRoots: state.StateRoots(), diff --git a/beacon-chain/core/epoch/epoch_processing_test.go b/beacon-chain/core/epoch/epoch_processing_test.go index 6964291621..a1e761f26e 100644 --- a/beacon-chain/core/epoch/epoch_processing_test.go +++ b/beacon-chain/core/epoch/epoch_processing_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/gogo/protobuf/proto" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/beacon-chain/core/epoch" @@ -288,7 +289,7 @@ func TestProcessFinalUpdates_CanProcess(t *testing.T) { assert.Equal(t, newS.Slashings()[ce], newS.Slashings()[ne], "Unexpected slashed balance") // Verify randao is correctly updated in the right position. - mix, err := newS.RandaoMixAtIndex(ne) + mix, err := newS.RandaoMixAtIndex(uint64(ne)) assert.NoError(t, err) assert.DeepNotEqual(t, params.BeaconConfig().ZeroHash[:], mix, "latest RANDAO still zero hashes") @@ -396,11 +397,11 @@ func TestProcessRegistryUpdates_ValidatorsEjected(t *testing.T) { } func TestProcessRegistryUpdates_CanExits(t *testing.T) { - e := uint64(5) + e := types.Epoch(5) exitEpoch := helpers.ActivationExitEpoch(e) minWithdrawalDelay := params.BeaconConfig().MinValidatorWithdrawabilityDelay base := &pb.BeaconState{ - Slot: e * params.BeaconConfig().SlotsPerEpoch, + Slot: uint64(e) * params.BeaconConfig().SlotsPerEpoch, Validators: []*ethpb.Validator{ { ExitEpoch: exitEpoch, diff --git a/beacon-chain/core/epoch/precompute/BUILD.bazel b/beacon-chain/core/epoch/precompute/BUILD.bazel index cc3fee30e6..1e68d7b6e9 100644 --- a/beacon-chain/core/epoch/precompute/BUILD.bazel +++ b/beacon-chain/core/epoch/precompute/BUILD.bazel @@ -22,6 +22,7 @@ go_library( "//shared/params:go_default_library", "//shared/traceutil:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@io_opencensus_go//trace:go_default_library", ], @@ -49,6 +50,7 @@ go_test( "//shared/testutil/assert:go_default_library", "//shared/testutil/require:go_default_library", "@com_github_gogo_protobuf//proto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", ], diff --git a/beacon-chain/core/epoch/precompute/attestation.go b/beacon-chain/core/epoch/precompute/attestation.go index d8cda17c23..d53e9b4bc9 100644 --- a/beacon-chain/core/epoch/precompute/attestation.go +++ b/beacon-chain/core/epoch/precompute/attestation.go @@ -5,6 +5,7 @@ import ( "context" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" @@ -106,7 +107,7 @@ func AttestedPrevEpoch(s *stateTrie.BeaconState, a *pb.PendingAttestation) (bool } // SameTarget returns true if attestation `a` attested to the same target block in state. -func SameTarget(state *stateTrie.BeaconState, a *pb.PendingAttestation, e uint64) (bool, error) { +func SameTarget(state *stateTrie.BeaconState, a *pb.PendingAttestation, e types.Epoch) (bool, error) { r, err := helpers.BlockRoot(state, e) if err != nil { return false, err diff --git a/beacon-chain/core/epoch/precompute/attestation_test.go b/beacon-chain/core/epoch/precompute/attestation_test.go index bb6414c8b2..98a224f073 100644 --- a/beacon-chain/core/epoch/precompute/attestation_test.go +++ b/beacon-chain/core/epoch/precompute/attestation_test.go @@ -17,7 +17,7 @@ import ( ) func TestUpdateValidator_Works(t *testing.T) { - e := params.BeaconConfig().FarFutureEpoch + e := uint64(params.BeaconConfig().FarFutureEpoch) vp := []*precompute.Validator{{}, {InclusionSlot: e}, {}, {InclusionSlot: e}, {}, {InclusionSlot: e}} record := &precompute.Validator{IsCurrentEpochAttester: true, IsCurrentEpochTargetAttester: true, IsPrevEpochAttester: true, IsPrevEpochTargetAttester: true, IsPrevEpochHeadAttester: true} @@ -34,7 +34,7 @@ func TestUpdateValidator_Works(t *testing.T) { } func TestUpdateValidator_InclusionOnlyCountsPrevEpoch(t *testing.T) { - e := params.BeaconConfig().FarFutureEpoch + e := uint64(params.BeaconConfig().FarFutureEpoch) vp := []*precompute.Validator{{InclusionSlot: e}} record := &precompute.Validator{IsCurrentEpochAttester: true, IsCurrentEpochTargetAttester: true} a := &pb.PendingAttestation{InclusionDelay: 1, ProposerIndex: 2} diff --git a/beacon-chain/core/epoch/precompute/justification_finalization_test.go b/beacon-chain/core/epoch/precompute/justification_finalization_test.go index 8e02e323d6..626ec9fbee 100644 --- a/beacon-chain/core/epoch/precompute/justification_finalization_test.go +++ b/beacon-chain/core/epoch/precompute/justification_finalization_test.go @@ -3,6 +3,7 @@ package precompute_test import ( "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute" @@ -38,16 +39,16 @@ func TestProcessJustificationAndFinalizationPreCompute_ConsecutiveEpochs(t *test } state, err := beaconstate.InitializeFromProto(base) require.NoError(t, err) - attestedBalance := 4 * e * 3 / 2 + attestedBalance := 4 * uint64(e) * 3 / 2 b := &precompute.Balance{PrevEpochTargetAttested: attestedBalance} newState, err := precompute.ProcessJustificationAndFinalizationPreCompute(state, b) require.NoError(t, err) rt := [32]byte{byte(64)} assert.DeepEqual(t, rt[:], newState.CurrentJustifiedCheckpoint().Root, "Unexpected justified root") - assert.Equal(t, uint64(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch") - assert.Equal(t, uint64(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch") + assert.Equal(t, types.Epoch(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch") + assert.Equal(t, types.Epoch(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch") assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], newState.FinalizedCheckpoint().Root, "Unexpected finalized root") - assert.Equal(t, uint64(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch") + assert.Equal(t, types.Epoch(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch") } func TestProcessJustificationAndFinalizationPreCompute_JustifyCurrentEpoch(t *testing.T) { @@ -75,16 +76,16 @@ func TestProcessJustificationAndFinalizationPreCompute_JustifyCurrentEpoch(t *te } state, err := beaconstate.InitializeFromProto(base) require.NoError(t, err) - attestedBalance := 4 * e * 3 / 2 + attestedBalance := 4 * uint64(e) * 3 / 2 b := &precompute.Balance{PrevEpochTargetAttested: attestedBalance} newState, err := precompute.ProcessJustificationAndFinalizationPreCompute(state, b) require.NoError(t, err) rt := [32]byte{byte(64)} assert.DeepEqual(t, rt[:], newState.CurrentJustifiedCheckpoint().Root, "Unexpected current justified root") - assert.Equal(t, uint64(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch") - assert.Equal(t, uint64(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch") + assert.Equal(t, types.Epoch(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch") + assert.Equal(t, types.Epoch(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch") assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], newState.FinalizedCheckpoint().Root) - assert.Equal(t, uint64(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch") + assert.Equal(t, types.Epoch(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch") } func TestProcessJustificationAndFinalizationPreCompute_JustifyPrevEpoch(t *testing.T) { @@ -111,14 +112,14 @@ func TestProcessJustificationAndFinalizationPreCompute_JustifyPrevEpoch(t *testi } state, err := beaconstate.InitializeFromProto(base) require.NoError(t, err) - attestedBalance := 4 * e * 3 / 2 + attestedBalance := 4 * uint64(e) * 3 / 2 b := &precompute.Balance{PrevEpochTargetAttested: attestedBalance} newState, err := precompute.ProcessJustificationAndFinalizationPreCompute(state, b) require.NoError(t, err) rt := [32]byte{byte(64)} assert.DeepEqual(t, rt[:], newState.CurrentJustifiedCheckpoint().Root, "Unexpected current justified root") - assert.Equal(t, uint64(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch") - assert.Equal(t, uint64(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch") + assert.Equal(t, types.Epoch(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch") + assert.Equal(t, types.Epoch(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch") assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], newState.FinalizedCheckpoint().Root) - assert.Equal(t, uint64(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch") + assert.Equal(t, types.Epoch(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch") } diff --git a/beacon-chain/core/epoch/precompute/new.go b/beacon-chain/core/epoch/precompute/new.go index f0bad6dea4..4c0b883d73 100644 --- a/beacon-chain/core/epoch/precompute/new.go +++ b/beacon-chain/core/epoch/precompute/new.go @@ -45,8 +45,8 @@ func New(ctx context.Context, state *stateTrie.BeaconState) ([]*Validator, *Bala } // Set inclusion slot and inclusion distance to be max, they will be compared and replaced // with the lower values - pVal.InclusionSlot = params.BeaconConfig().FarFutureEpoch - pVal.InclusionDistance = params.BeaconConfig().FarFutureEpoch + pVal.InclusionSlot = uint64(params.BeaconConfig().FarFutureEpoch) + pVal.InclusionDistance = uint64(params.BeaconConfig().FarFutureEpoch) pValidators[idx] = pVal return nil diff --git a/beacon-chain/core/epoch/precompute/new_test.go b/beacon-chain/core/epoch/precompute/new_test.go index 07aea490e6..f2e685ea26 100644 --- a/beacon-chain/core/epoch/precompute/new_test.go +++ b/beacon-chain/core/epoch/precompute/new_test.go @@ -29,7 +29,7 @@ func TestNew(t *testing.T) { }, }) require.NoError(t, err) - e := params.BeaconConfig().FarFutureEpoch + e := uint64(params.BeaconConfig().FarFutureEpoch) v, b, err := precompute.New(context.Background(), s) require.NoError(t, err) assert.DeepEqual(t, &precompute.Validator{ diff --git a/beacon-chain/core/epoch/precompute/reward_penalty.go b/beacon-chain/core/epoch/precompute/reward_penalty.go index 90bc10c015..0c238855b7 100644 --- a/beacon-chain/core/epoch/precompute/reward_penalty.go +++ b/beacon-chain/core/epoch/precompute/reward_penalty.go @@ -2,6 +2,7 @@ package precompute import ( "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/shared/mathutil" @@ -68,7 +69,7 @@ func AttestationsDelta(state *stateTrie.BeaconState, pBal *Balance, vp []*Valida return rewards, penalties, nil } -func attestationDelta(pBal *Balance, v *Validator, prevEpoch, finalizedEpoch uint64) (uint64, uint64) { +func attestationDelta(pBal *Balance, v *Validator, prevEpoch, finalizedEpoch types.Epoch) (uint64, uint64) { eligible := v.IsActivePrevEpoch || (v.IsSlashed && !v.IsWithdrawableCurrentEpoch) if !eligible || pBal.ActiveCurrentEpoch == 0 { return 0, 0 @@ -139,7 +140,7 @@ func attestationDelta(pBal *Balance, v *Validator, prevEpoch, finalizedEpoch uin // Equivalent to the following condition from the spec: // `index not in get_unslashed_attesting_indices(state, matching_target_attestations)` if !v.IsPrevEpochTargetAttester || v.IsSlashed { - p += vb * finalityDelay / params.BeaconConfig().InactivityPenaltyQuotient + p += vb * uint64(finalityDelay) / params.BeaconConfig().InactivityPenaltyQuotient } } return r, p @@ -182,7 +183,7 @@ func ProposersDelta(state *stateTrie.BeaconState, pBal *Balance, vp []*Validator // Spec code: // def is_in_inactivity_leak(state: BeaconState) -> bool: // return get_finality_delay(state) > MIN_EPOCHS_TO_INACTIVITY_PENALTY -func isInInactivityLeak(prevEpoch, finalizedEpoch uint64) bool { +func isInInactivityLeak(prevEpoch, finalizedEpoch types.Epoch) bool { return finalityDelay(prevEpoch, finalizedEpoch) > params.BeaconConfig().MinEpochsToInactivityPenalty } @@ -191,6 +192,6 @@ func isInInactivityLeak(prevEpoch, finalizedEpoch uint64) bool { // Spec code: // def get_finality_delay(state: BeaconState) -> uint64: // return get_previous_epoch(state) - state.finalized_checkpoint.epoch -func finalityDelay(prevEpoch, finalizedEpoch uint64) uint64 { +func finalityDelay(prevEpoch, finalizedEpoch types.Epoch) types.Epoch { return prevEpoch - finalizedEpoch } diff --git a/beacon-chain/core/epoch/precompute/reward_penalty_test.go b/beacon-chain/core/epoch/precompute/reward_penalty_test.go index 31e265f129..d4a89a05aa 100644 --- a/beacon-chain/core/epoch/precompute/reward_penalty_test.go +++ b/beacon-chain/core/epoch/precompute/reward_penalty_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/beacon-chain/core/epoch" @@ -248,7 +249,7 @@ func TestProcessRewardsAndPenaltiesPrecompute_SlashedInactivePenalty(t *testing. penalty := 3 * base proposerReward := base / params.BeaconConfig().ProposerRewardQuotient penalty += params.BeaconConfig().BaseRewardsPerEpoch*base - proposerReward - penalty += vp[i].CurrentEpochEffectiveBalance * finalityDelay / params.BeaconConfig().InactivityPenaltyQuotient + penalty += vp[i].CurrentEpochEffectiveBalance * uint64(finalityDelay) / params.BeaconConfig().InactivityPenaltyQuotient assert.Equal(t, penalty, penalties[i], "Unexpected slashed indices penalty balance") assert.Equal(t, uint64(0), rewards[i], "Unexpected slashed indices reward balance") } @@ -353,8 +354,8 @@ func TestFinalityDelay(t *testing.T) { base.FinalizedCheckpoint = ðpb.Checkpoint{Epoch: 3} beaconState, err := state.InitializeFromProto(base) require.NoError(t, err) - prevEpoch := uint64(0) - finalizedEpoch := uint64(0) + prevEpoch := types.Epoch(0) + finalizedEpoch := types.Epoch(0) // Set values for each test case setVal := func() { prevEpoch = helpers.PrevEpoch(beaconState) @@ -383,8 +384,8 @@ func TestIsInInactivityLeak(t *testing.T) { base.FinalizedCheckpoint = ðpb.Checkpoint{Epoch: 3} beaconState, err := state.InitializeFromProto(base) require.NoError(t, err) - prevEpoch := uint64(0) - finalizedEpoch := uint64(0) + prevEpoch := types.Epoch(0) + finalizedEpoch := types.Epoch(0) // Set values for each test case setVal := func() { prevEpoch = helpers.PrevEpoch(beaconState) diff --git a/beacon-chain/core/helpers/BUILD.bazel b/beacon-chain/core/helpers/BUILD.bazel index 5ab9fddef4..39ed2bfc9f 100644 --- a/beacon-chain/core/helpers/BUILD.bazel +++ b/beacon-chain/core/helpers/BUILD.bazel @@ -43,6 +43,7 @@ go_library( "//shared/timeutils:go_default_library", "@com_github_ferranbt_fastssz//:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", ], @@ -78,6 +79,7 @@ go_test( "//shared/testutil/require:go_default_library", "//shared/timeutils:go_default_library", "@com_github_google_gofuzz//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", ], diff --git a/beacon-chain/core/helpers/attestation.go b/beacon-chain/core/helpers/attestation.go index 7823a36bee..702002eb53 100644 --- a/beacon-chain/core/helpers/attestation.go +++ b/beacon-chain/core/helpers/attestation.go @@ -6,6 +6,7 @@ import ( "fmt" "time" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/bls" "github.com/prysmaticlabs/prysm/shared/hashutil" @@ -185,7 +186,7 @@ func VerifyCheckpointEpoch(c *ethpb.Checkpoint, genesis time.Time) bool { currentSlot := (now - genesisTime) / params.BeaconConfig().SecondsPerSlot currentEpoch := SlotToEpoch(currentSlot) - var prevEpoch uint64 + var prevEpoch types.Epoch if currentEpoch > 1 { prevEpoch = currentEpoch - 1 } diff --git a/beacon-chain/core/helpers/block.go b/beacon-chain/core/helpers/block.go index d964170ef0..047d2fe889 100644 --- a/beacon-chain/core/helpers/block.go +++ b/beacon-chain/core/helpers/block.go @@ -4,6 +4,7 @@ import ( "math" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/shared/params" ) @@ -45,7 +46,7 @@ func StateRootAtSlot(state *stateTrie.BeaconState, slot uint64) ([]byte, error) // Return the block root at the start of a recent ``epoch``. // """ // return get_block_root_at_slot(state, compute_start_slot_at_epoch(epoch)) -func BlockRoot(state *stateTrie.BeaconState, epoch uint64) ([]byte, error) { +func BlockRoot(state *stateTrie.BeaconState, epoch types.Epoch) ([]byte, error) { s, err := StartSlot(epoch) if err != nil { return nil, err diff --git a/beacon-chain/core/helpers/committee.go b/beacon-chain/core/helpers/committee.go index b587348b78..ec4d196034 100644 --- a/beacon-chain/core/helpers/committee.go +++ b/beacon-chain/core/helpers/committee.go @@ -8,6 +8,7 @@ import ( "sort" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/beacon-chain/cache" @@ -167,7 +168,7 @@ type CommitteeAssignmentContainer struct { // 4. Construct a map of validator indices pointing to the respective committees. func CommitteeAssignments( state *stateTrie.BeaconState, - epoch uint64, + epoch types.Epoch, ) (map[uint64]*CommitteeAssignmentContainer, map[uint64][]uint64, error) { nextEpoch := NextEpoch(state) if epoch > nextEpoch { @@ -267,7 +268,7 @@ func VerifyAttestationBitfieldLengths(state *stateTrie.BeaconState, att *ethpb.A // ShuffledIndices uses input beacon state and returns the shuffled indices of the input epoch, // the shuffled indices then can be used to break up into committees. -func ShuffledIndices(state *stateTrie.BeaconState, epoch uint64) ([]uint64, error) { +func ShuffledIndices(state *stateTrie.BeaconState, epoch types.Epoch) ([]uint64, error) { seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester) if err != nil { return nil, errors.Wrapf(err, "could not get seed for epoch %d", epoch) @@ -289,8 +290,8 @@ func ShuffledIndices(state *stateTrie.BeaconState, epoch uint64) ([]uint64, erro // UpdateCommitteeCache gets called at the beginning of every epoch to cache the committee shuffled indices // list with committee index and epoch number. It caches the shuffled indices for current epoch and next epoch. -func UpdateCommitteeCache(state *stateTrie.BeaconState, epoch uint64) error { - for _, e := range []uint64{epoch, epoch + 1} { +func UpdateCommitteeCache(state *stateTrie.BeaconState, epoch types.Epoch) error { + for _, e := range []types.Epoch{epoch, epoch + 1} { seed, err := Seed(state, e, params.BeaconConfig().DomainBeaconAttester) if err != nil { return err @@ -330,7 +331,7 @@ func UpdateCommitteeCache(state *stateTrie.BeaconState, epoch uint64) error { } // UpdateProposerIndicesInCache updates proposer indices entry of the committee cache. -func UpdateProposerIndicesInCache(state *stateTrie.BeaconState, epoch uint64) error { +func UpdateProposerIndicesInCache(state *stateTrie.BeaconState, epoch types.Epoch) error { // The cache uses the state root at the (current epoch - 2)'s slot as key. (e.g. for epoch 2, the key is root at slot 31) // Which is the reason why we skip genesis epoch. if epoch <= params.BeaconConfig().GenesisEpoch+params.BeaconConfig().MinSeedLookahead { diff --git a/beacon-chain/core/helpers/committee_test.go b/beacon-chain/core/helpers/committee_test.go index 045eaba404..e53a57a3b2 100644 --- a/beacon-chain/core/helpers/committee_test.go +++ b/beacon-chain/core/helpers/committee_test.go @@ -6,6 +6,7 @@ import ( "strconv" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -89,7 +90,7 @@ func TestVerifyBitfieldLength_OK(t *testing.T) { func TestCommitteeAssignments_CannotRetrieveFutureEpoch(t *testing.T) { ClearCache() - epoch := uint64(1) + epoch := types.Epoch(1) state, err := beaconstate.InitializeFromProto(&pb.BeaconState{ Slot: 0, // Epoch 0. }) @@ -101,7 +102,7 @@ func TestCommitteeAssignments_CannotRetrieveFutureEpoch(t *testing.T) { func TestCommitteeAssignments_NoProposerForSlot0(t *testing.T) { validators := make([]*ethpb.Validator, 4*params.BeaconConfig().SlotsPerEpoch) for i := 0; i < len(validators); i++ { - var activationEpoch uint64 + var activationEpoch types.Epoch if i >= len(validators)/2 { activationEpoch = 3 } @@ -131,7 +132,7 @@ func TestCommitteeAssignments_CanRetrieve(t *testing.T) { validators := make([]*ethpb.Validator, 4*params.BeaconConfig().SlotsPerEpoch) for i := 0; i < len(validators); i++ { // First 2 epochs only half validators are activated. - var activationEpoch uint64 + var activationEpoch types.Epoch if i >= len(validators)/2 { activationEpoch = 3 } @@ -208,7 +209,7 @@ func TestCommitteeAssignments_CannotRetrieveFuture(t *testing.T) { validators := make([]*ethpb.Validator, 4*params.BeaconConfig().SlotsPerEpoch) for i := 0; i < len(validators); i++ { // First 2 epochs only half validators are activated. - var activationEpoch uint64 + var activationEpoch types.Epoch if i >= len(validators)/2 { activationEpoch = 3 } @@ -249,7 +250,7 @@ func TestCommitteeAssignments_EverySlotHasMin1Proposer(t *testing.T) { }) require.NoError(t, err) ClearCache() - epoch := uint64(1) + epoch := types.Epoch(1) _, proposerIndexToSlots, err := CommitteeAssignments(state, epoch) require.NoError(t, err, "Failed to determine CommitteeAssignments") @@ -417,12 +418,12 @@ func TestUpdateCommitteeCache_CanUpdate(t *testing.T) { require.NoError(t, err) require.NoError(t, UpdateCommitteeCache(state, CurrentEpoch(state))) - epoch := uint64(1) + epoch := types.Epoch(1) idx := uint64(1) seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester) require.NoError(t, err) - indices, err = committeeCache.Committee(epoch*params.BeaconConfig().SlotsPerEpoch, seed, idx) + indices, err = committeeCache.Committee(uint64(epoch.Mul(params.BeaconConfig().SlotsPerEpoch)), seed, idx) require.NoError(t, err) assert.Equal(t, params.BeaconConfig().TargetCommitteeSize, uint64(len(indices)), "Did not save correct indices lengths") } diff --git a/beacon-chain/core/helpers/randao.go b/beacon-chain/core/helpers/randao.go index 25774fb9b2..aa92edf3ec 100644 --- a/beacon-chain/core/helpers/randao.go +++ b/beacon-chain/core/helpers/randao.go @@ -1,6 +1,7 @@ package helpers import ( + "github.com/prysmaticlabs/eth2-types" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/shared/bls" "github.com/prysmaticlabs/prysm/shared/bytesutil" @@ -17,7 +18,7 @@ import ( // """ // mix = get_randao_mix(state, Epoch(epoch + EPOCHS_PER_HISTORICAL_VECTOR - MIN_SEED_LOOKAHEAD - 1)) # Avoid underflow // return hash(domain_type + int_to_bytes(epoch, length=8) + mix) -func Seed(state *stateTrie.BeaconState, epoch uint64, domain [bls.DomainByteLength]byte) ([32]byte, error) { +func Seed(state *stateTrie.BeaconState, epoch types.Epoch, domain [bls.DomainByteLength]byte) ([32]byte, error) { // See https://github.com/ethereum/eth2.0-specs/pull/1296 for // rationale on why offset has to look down by 1. lookAheadEpoch := epoch + params.BeaconConfig().EpochsPerHistoricalVector - @@ -27,7 +28,7 @@ func Seed(state *stateTrie.BeaconState, epoch uint64, domain [bls.DomainByteLeng if err != nil { return [32]byte{}, err } - seed := append(domain[:], bytesutil.Bytes8(epoch)...) + seed := append(domain[:], bytesutil.Bytes8(uint64(epoch))...) seed = append(seed, randaoMix...) seed32 := hashutil.Hash(seed) @@ -44,6 +45,6 @@ func Seed(state *stateTrie.BeaconState, epoch uint64, domain [bls.DomainByteLeng // Return the randao mix at a recent ``epoch``. // """ // return state.randao_mixes[epoch % EPOCHS_PER_HISTORICAL_VECTOR] -func RandaoMix(state *stateTrie.BeaconState, epoch uint64) ([]byte, error) { - return state.RandaoMixAtIndex(epoch % params.BeaconConfig().EpochsPerHistoricalVector) +func RandaoMix(state *stateTrie.BeaconState, epoch types.Epoch) ([]byte, error) { + return state.RandaoMixAtIndex(uint64(epoch % params.BeaconConfig().EpochsPerHistoricalVector)) } diff --git a/beacon-chain/core/helpers/randao_test.go b/beacon-chain/core/helpers/randao_test.go index 8c7f17c545..80c2c771a3 100644 --- a/beacon-chain/core/helpers/randao_test.go +++ b/beacon-chain/core/helpers/randao_test.go @@ -4,6 +4,7 @@ import ( "encoding/binary" "testing" + "github.com/prysmaticlabs/eth2-types" beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state" pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" "github.com/prysmaticlabs/prysm/shared/bytesutil" @@ -22,7 +23,7 @@ func TestRandaoMix_OK(t *testing.T) { state, err := beaconstate.InitializeFromProto(&pb.BeaconState{RandaoMixes: randaoMixes}) require.NoError(t, err) tests := []struct { - epoch uint64 + epoch types.Epoch randaoMix []byte }{ { @@ -39,7 +40,7 @@ func TestRandaoMix_OK(t *testing.T) { }, } for _, test := range tests { - require.NoError(t, state.SetSlot((test.epoch+1)*params.BeaconConfig().SlotsPerEpoch)) + require.NoError(t, state.SetSlot(uint64(test.epoch.Add(1).Mul(params.BeaconConfig().SlotsPerEpoch)))) mix, err := RandaoMix(state, test.epoch) require.NoError(t, err) assert.DeepEqual(t, test.randaoMix, mix, "Incorrect randao mix") @@ -56,7 +57,7 @@ func TestRandaoMix_CopyOK(t *testing.T) { state, err := beaconstate.InitializeFromProto(&pb.BeaconState{RandaoMixes: randaoMixes}) require.NoError(t, err) tests := []struct { - epoch uint64 + epoch types.Epoch randaoMix []byte }{ { @@ -73,10 +74,10 @@ func TestRandaoMix_CopyOK(t *testing.T) { }, } for _, test := range tests { - require.NoError(t, state.SetSlot((test.epoch+1)*params.BeaconConfig().SlotsPerEpoch)) + require.NoError(t, state.SetSlot(uint64((test.epoch + 1).Mul(params.BeaconConfig().SlotsPerEpoch)))) mix, err := RandaoMix(state, test.epoch) require.NoError(t, err) - uniqueNumber := params.BeaconConfig().EpochsPerHistoricalVector + 1000 + uniqueNumber := uint64(params.BeaconConfig().EpochsPerHistoricalVector.Add(1000)) binary.LittleEndian.PutUint64(mix, uniqueNumber) for _, mx := range randaoMixes { @@ -93,7 +94,7 @@ func TestGenerateSeed_OK(t *testing.T) { binary.LittleEndian.PutUint64(intInBytes, uint64(i)) randaoMixes[i] = intInBytes } - slot := 10 * params.BeaconConfig().MinSeedLookahead * params.BeaconConfig().SlotsPerEpoch + slot := uint64(params.BeaconConfig().MinSeedLookahead.Mul(10 * params.BeaconConfig().SlotsPerEpoch)) state, err := beaconstate.InitializeFromProto(&pb.BeaconState{ RandaoMixes: randaoMixes, Slot: slot, diff --git a/beacon-chain/core/helpers/signing_root.go b/beacon-chain/core/helpers/signing_root.go index 4d1037caee..4cb47b8644 100644 --- a/beacon-chain/core/helpers/signing_root.go +++ b/beacon-chain/core/helpers/signing_root.go @@ -3,6 +3,7 @@ package helpers import ( fssz "github.com/ferranbt/fastssz" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/state" pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" @@ -22,7 +23,7 @@ const DomainByteLength = 4 var ErrSigFailedToVerify = errors.New("signature did not verify") // ComputeDomainAndSign computes the domain and signing root and sign it using the passed in private key. -func ComputeDomainAndSign(st *state.BeaconState, epoch uint64, obj fssz.HashRoot, domain [4]byte, key bls.SecretKey) ([]byte, error) { +func ComputeDomainAndSign(st *state.BeaconState, epoch types.Epoch, obj fssz.HashRoot, domain [4]byte, key bls.SecretKey) ([]byte, error) { d, err := Domain(st.Fork(), epoch, domain, st.GenesisValidatorRoot()) if err != nil { return nil, err @@ -64,7 +65,7 @@ func signingData(rootFunc func() ([32]byte, error), domain []byte) ([32]byte, er } // ComputeDomainVerifySigningRoot computes domain and verifies signing root of an object given the beacon state, validator index and signature. -func ComputeDomainVerifySigningRoot(st *state.BeaconState, index, epoch uint64, obj fssz.HashRoot, domain [4]byte, sig []byte) error { +func ComputeDomainVerifySigningRoot(st *state.BeaconState, index uint64, epoch types.Epoch, obj fssz.HashRoot, domain [4]byte, sig []byte) error { v, err := st.ValidatorAtIndex(index) if err != nil { return err diff --git a/beacon-chain/core/helpers/slot_epoch.go b/beacon-chain/core/helpers/slot_epoch.go index a02000419d..d4337ff0de 100644 --- a/beacon-chain/core/helpers/slot_epoch.go +++ b/beacon-chain/core/helpers/slot_epoch.go @@ -6,6 +6,7 @@ import ( "time" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/shared/mathutil" "github.com/prysmaticlabs/prysm/shared/params" @@ -24,8 +25,10 @@ const MaxSlotBuffer = uint64(1 << 7) // Return the epoch number of ``slot``. // """ // return Epoch(slot // SLOTS_PER_EPOCH) -func SlotToEpoch(slot uint64) uint64 { - return slot / params.BeaconConfig().SlotsPerEpoch +func SlotToEpoch(slot uint64) types.Epoch { + // TODO(#8205): Once types.Slot PR is ready, replace with + // return types.Epoch(slot.DivSlot(params.BeaconConfig().SlotsPerEpoch)) + return types.Epoch(slot / params.BeaconConfig().SlotsPerEpoch) } // CurrentEpoch returns the current epoch number calculated from @@ -37,7 +40,7 @@ func SlotToEpoch(slot uint64) uint64 { // Return the current epoch. // """ // return compute_epoch_of_slot(state.slot) -func CurrentEpoch(state *stateTrie.BeaconState) uint64 { +func CurrentEpoch(state *stateTrie.BeaconState) types.Epoch { return SlotToEpoch(state.Slot()) } @@ -52,7 +55,7 @@ func CurrentEpoch(state *stateTrie.BeaconState) uint64 { // """ // current_epoch = get_current_epoch(state) // return GENESIS_EPOCH if current_epoch == GENESIS_EPOCH else Epoch(current_epoch - 1) -func PrevEpoch(state *stateTrie.BeaconState) uint64 { +func PrevEpoch(state *stateTrie.BeaconState) types.Epoch { currentEpoch := CurrentEpoch(state) if currentEpoch == 0 { return 0 @@ -62,7 +65,7 @@ func PrevEpoch(state *stateTrie.BeaconState) uint64 { // NextEpoch returns the next epoch number calculated from // the slot number stored in beacon state. -func NextEpoch(state *stateTrie.BeaconState) uint64 { +func NextEpoch(state *stateTrie.BeaconState) types.Epoch { return SlotToEpoch(state.Slot()) + 1 } @@ -75,8 +78,8 @@ func NextEpoch(state *stateTrie.BeaconState) uint64 { // Return the start slot of ``epoch``. // """ // return Slot(epoch * SLOTS_PER_EPOCH) -func StartSlot(epoch uint64) (uint64, error) { - slot, err := mathutil.Mul64(epoch, params.BeaconConfig().SlotsPerEpoch) +func StartSlot(epoch types.Epoch) (uint64, error) { + slot, err := mathutil.Mul64(uint64(epoch), params.BeaconConfig().SlotsPerEpoch) if err != nil { return slot, errors.Errorf("start slot calculation overflows: %v", err) } @@ -85,7 +88,7 @@ func StartSlot(epoch uint64) (uint64, error) { // EndSlot returns the last slot number of the // current epoch. -func EndSlot(epoch uint64) (uint64, error) { +func EndSlot(epoch types.Epoch) (uint64, error) { if epoch == math.MaxUint64 { return 0, errors.New("start slot calculation overflows") } @@ -199,7 +202,7 @@ func RoundUpToNearestEpoch(slot uint64) uint64 { // else: // weak_subjectivity_period += SAFETY_DECAY*val_count/(2*100*MIN_PER_EPOCH_CHURN_LIMIT) // return weak_subjectivity_period -func WeakSubjectivityCheckptEpoch(valCount uint64) (uint64, error) { +func WeakSubjectivityCheckptEpoch(valCount uint64) (types.Epoch, error) { wsp := params.BeaconConfig().MinValidatorWithdrawabilityDelay m := params.BeaconConfig().MinPerEpochChurnLimit @@ -207,14 +210,14 @@ func WeakSubjectivityCheckptEpoch(valCount uint64) (uint64, error) { d := params.BeaconConfig().SafetyDecay if valCount >= m*q { v := d * q / (2 * 100) - wsp += v + wsp += types.Epoch(v) } else { v, err := mathutil.Mul64(d, valCount) if err != nil { return 0, err } v /= 2 * 100 * m - wsp += v + wsp += types.Epoch(v) } return wsp, nil } @@ -224,7 +227,7 @@ func WeakSubjectivityCheckptEpoch(valCount uint64) (uint64, error) { func VotingPeriodStartTime(genesis, slot uint64) uint64 { startTime := genesis startTime += - (slot - (slot % (params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch))) * + (slot - (slot % (uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod) * params.BeaconConfig().SlotsPerEpoch))) * params.BeaconConfig().SecondsPerSlot return startTime } diff --git a/beacon-chain/core/helpers/slot_epoch_test.go b/beacon-chain/core/helpers/slot_epoch_test.go index 093f5715d1..ee9d2fb253 100644 --- a/beacon-chain/core/helpers/slot_epoch_test.go +++ b/beacon-chain/core/helpers/slot_epoch_test.go @@ -5,19 +5,19 @@ import ( "testing" "time" - "github.com/prysmaticlabs/prysm/shared/testutil/assert" - "github.com/prysmaticlabs/prysm/shared/testutil/require" - "github.com/prysmaticlabs/prysm/shared/timeutils" - + "github.com/prysmaticlabs/eth2-types" beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state" pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" "github.com/prysmaticlabs/prysm/shared/params" + "github.com/prysmaticlabs/prysm/shared/testutil/assert" + "github.com/prysmaticlabs/prysm/shared/testutil/require" + "github.com/prysmaticlabs/prysm/shared/timeutils" ) func TestSlotToEpoch_OK(t *testing.T) { tests := []struct { slot uint64 - epoch uint64 + epoch types.Epoch }{ {slot: 0, epoch: 0}, {slot: 50, epoch: 1}, @@ -33,7 +33,7 @@ func TestSlotToEpoch_OK(t *testing.T) { func TestCurrentEpoch_OK(t *testing.T) { tests := []struct { slot uint64 - epoch uint64 + epoch types.Epoch }{ {slot: 0, epoch: 0}, {slot: 50, epoch: 1}, @@ -51,7 +51,7 @@ func TestCurrentEpoch_OK(t *testing.T) { func TestPrevEpoch_OK(t *testing.T) { tests := []struct { slot uint64 - epoch uint64 + epoch types.Epoch }{ {slot: 0, epoch: 0}, {slot: 0 + params.BeaconConfig().SlotsPerEpoch + 1, epoch: 0}, @@ -67,13 +67,13 @@ func TestPrevEpoch_OK(t *testing.T) { func TestNextEpoch_OK(t *testing.T) { tests := []struct { slot uint64 - epoch uint64 + epoch types.Epoch }{ - {slot: 0, epoch: 0/params.BeaconConfig().SlotsPerEpoch + 1}, - {slot: 50, epoch: 0/params.BeaconConfig().SlotsPerEpoch + 2}, - {slot: 64, epoch: 64/params.BeaconConfig().SlotsPerEpoch + 1}, - {slot: 128, epoch: 128/params.BeaconConfig().SlotsPerEpoch + 1}, - {slot: 200, epoch: 200/params.BeaconConfig().SlotsPerEpoch + 1}, + {slot: 0, epoch: types.Epoch(0/params.BeaconConfig().SlotsPerEpoch + 1)}, + {slot: 50, epoch: types.Epoch(0/params.BeaconConfig().SlotsPerEpoch + 2)}, + {slot: 64, epoch: types.Epoch(64/params.BeaconConfig().SlotsPerEpoch + 1)}, + {slot: 128, epoch: types.Epoch(128/params.BeaconConfig().SlotsPerEpoch + 1)}, + {slot: 200, epoch: types.Epoch(200/params.BeaconConfig().SlotsPerEpoch + 1)}, } for _, tt := range tests { state, err := beaconstate.InitializeFromProto(&pb.BeaconState{Slot: tt.slot}) @@ -84,7 +84,7 @@ func TestNextEpoch_OK(t *testing.T) { func TestEpochStartSlot_OK(t *testing.T) { tests := []struct { - epoch uint64 + epoch types.Epoch startSlot uint64 error bool }{ @@ -108,7 +108,7 @@ func TestEpochStartSlot_OK(t *testing.T) { func TestEpochEndSlot_OK(t *testing.T) { tests := []struct { - epoch uint64 + epoch types.Epoch startSlot uint64 error bool }{ @@ -349,7 +349,7 @@ func TestValidateSlotClock_HandlesBadSlot(t *testing.T) { func TestWeakSubjectivityCheckptEpoch(t *testing.T) { tests := []struct { valCount uint64 - want uint64 + want types.Epoch }{ // Verifying these numbers aligned with the reference table defined: // https://github.com/ethereum/eth2.0-specs/blob/weak-subjectivity-guide/specs/phase0/weak-subjectivity.md#calculating-the-weak-subjectivity-period diff --git a/beacon-chain/core/helpers/validators.go b/beacon-chain/core/helpers/validators.go index 26fdcfff94..a6c2d8f252 100644 --- a/beacon-chain/core/helpers/validators.go +++ b/beacon-chain/core/helpers/validators.go @@ -4,6 +4,7 @@ import ( "bytes" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" @@ -22,16 +23,16 @@ import ( // Check if ``validator`` is active. // """ // return validator.activation_epoch <= epoch < validator.exit_epoch -func IsActiveValidator(validator *ethpb.Validator, epoch uint64) bool { +func IsActiveValidator(validator *ethpb.Validator, epoch types.Epoch) bool { return checkValidatorActiveStatus(validator.ActivationEpoch, validator.ExitEpoch, epoch) } // IsActiveValidatorUsingTrie checks if a read only validator is active. -func IsActiveValidatorUsingTrie(validator stateTrie.ReadOnlyValidator, epoch uint64) bool { +func IsActiveValidatorUsingTrie(validator stateTrie.ReadOnlyValidator, epoch types.Epoch) bool { return checkValidatorActiveStatus(validator.ActivationEpoch(), validator.ExitEpoch(), epoch) } -func checkValidatorActiveStatus(activationEpoch, exitEpoch, epoch uint64) bool { +func checkValidatorActiveStatus(activationEpoch, exitEpoch, epoch types.Epoch) bool { return activationEpoch <= epoch && epoch < exitEpoch } @@ -44,16 +45,16 @@ func checkValidatorActiveStatus(activationEpoch, exitEpoch, epoch uint64) bool { // Check if ``validator`` is slashable. // """ // return (not validator.slashed) and (validator.activation_epoch <= epoch < validator.withdrawable_epoch) -func IsSlashableValidator(activationEpoch, withdrawableEpoch uint64, slashed bool, epoch uint64) bool { +func IsSlashableValidator(activationEpoch, withdrawableEpoch types.Epoch, slashed bool, epoch types.Epoch) bool { return checkValidatorSlashable(activationEpoch, withdrawableEpoch, slashed, epoch) } // IsSlashableValidatorUsingTrie checks if a read only validator is slashable. -func IsSlashableValidatorUsingTrie(val stateTrie.ReadOnlyValidator, epoch uint64) bool { +func IsSlashableValidatorUsingTrie(val stateTrie.ReadOnlyValidator, epoch types.Epoch) bool { return checkValidatorSlashable(val.ActivationEpoch(), val.WithdrawableEpoch(), val.Slashed(), epoch) } -func checkValidatorSlashable(activationEpoch, withdrawableEpoch uint64, slashed bool, epoch uint64) bool { +func checkValidatorSlashable(activationEpoch, withdrawableEpoch types.Epoch, slashed bool, epoch types.Epoch) bool { active := activationEpoch <= epoch beforeWithdrawable := epoch < withdrawableEpoch return beforeWithdrawable && active && !slashed @@ -72,7 +73,7 @@ func checkValidatorSlashable(activationEpoch, withdrawableEpoch uint64, slashed // Return the sequence of active validator indices at ``epoch``. // """ // return [ValidatorIndex(i) for i, v in enumerate(state.validators) if is_active_validator(v, epoch)] -func ActiveValidatorIndices(state *stateTrie.BeaconState, epoch uint64) ([]uint64, error) { +func ActiveValidatorIndices(state *stateTrie.BeaconState, epoch types.Epoch) ([]uint64, error) { seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester) if err != nil { return nil, errors.Wrap(err, "could not get seed") @@ -103,7 +104,7 @@ func ActiveValidatorIndices(state *stateTrie.BeaconState, epoch uint64) ([]uint6 // ActiveValidatorCount returns the number of active validators in the state // at the given epoch. -func ActiveValidatorCount(state *stateTrie.BeaconState, epoch uint64) (uint64, error) { +func ActiveValidatorCount(state *stateTrie.BeaconState, epoch types.Epoch) (uint64, error) { seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester) if err != nil { return 0, errors.Wrap(err, "could not get seed") @@ -142,7 +143,7 @@ func ActiveValidatorCount(state *stateTrie.BeaconState, epoch uint64) (uint64, e // Return the epoch during which validator activations and exits initiated in ``epoch`` take effect. // """ // return Epoch(epoch + 1 + MAX_SEED_LOOKAHEAD) -func ActivationExitEpoch(epoch uint64) uint64 { +func ActivationExitEpoch(epoch types.Epoch) types.Epoch { return epoch + 1 + params.BeaconConfig().MaxSeedLookahead } @@ -283,7 +284,7 @@ func ComputeProposerIndex(bState *stateTrie.BeaconState, activeIndices []uint64, // epoch = get_current_epoch(state) if epoch is None else epoch // fork_version = state.fork.previous_version if epoch < state.fork.epoch else state.fork.current_version // return compute_domain(domain_type, fork_version, state.genesis_validators_root) -func Domain(fork *pb.Fork, epoch uint64, domainType [bls.DomainByteLength]byte, genesisRoot []byte) ([]byte, error) { +func Domain(fork *pb.Fork, epoch types.Epoch, domainType [bls.DomainByteLength]byte, genesisRoot []byte) ([]byte, error) { if fork == nil { return []byte{}, errors.New("nil fork or domain type") } @@ -324,7 +325,7 @@ func IsEligibleForActivationQueueUsingTrie(validator stateTrie.ReadOnlyValidator } // isEligibleForActivationQueue carries out the logic for IsEligibleForActivationQueue* -func isEligibileForActivationQueue(activationEligibilityEpoch, effectiveBalance uint64) bool { +func isEligibileForActivationQueue(activationEligibilityEpoch types.Epoch, effectiveBalance uint64) bool { return activationEligibilityEpoch == params.BeaconConfig().FarFutureEpoch && effectiveBalance == params.BeaconConfig().MaxEffectiveBalance } @@ -357,7 +358,7 @@ func IsEligibleForActivationUsingTrie(state *stateTrie.BeaconState, validator st } // isEligibleForActivation carries out the logic for IsEligibleForActivation* -func isEligibleForActivation(activationEligibilityEpoch, activationEpoch, finalizedEpoch uint64) bool { +func isEligibleForActivation(activationEligibilityEpoch, activationEpoch, finalizedEpoch types.Epoch) bool { return activationEligibilityEpoch <= finalizedEpoch && activationEpoch == params.BeaconConfig().FarFutureEpoch } diff --git a/beacon-chain/core/helpers/validators_test.go b/beacon-chain/core/helpers/validators_test.go index d8b057c2e4..f8d2465885 100644 --- a/beacon-chain/core/helpers/validators_test.go +++ b/beacon-chain/core/helpers/validators_test.go @@ -4,6 +4,7 @@ import ( "errors" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/cache" beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -17,7 +18,7 @@ import ( func TestIsActiveValidator_OK(t *testing.T) { tests := []struct { - a uint64 + a types.Epoch b bool }{ {a: 0, b: false}, @@ -34,7 +35,7 @@ func TestIsActiveValidator_OK(t *testing.T) { func TestIsActiveValidatorUsingTrie_OK(t *testing.T) { tests := []struct { - a uint64 + a types.Epoch b bool }{ {a: 0, b: false}, @@ -57,7 +58,7 @@ func TestIsSlashableValidator_OK(t *testing.T) { tests := []struct { name string validator *ethpb.Validator - epoch uint64 + epoch types.Epoch slashable bool }{ { @@ -139,7 +140,7 @@ func TestIsSlashableValidatorUsingTrie_OK(t *testing.T) { tests := []struct { name string validator *ethpb.Validator - epoch uint64 + epoch types.Epoch slashable bool }{ { @@ -350,7 +351,7 @@ func TestComputeProposerIndex_Compatibility(t *testing.T) { } func TestDelayedActivationExitEpoch_OK(t *testing.T) { - epoch := uint64(9999) + epoch := types.Epoch(9999) wanted := epoch + 1 + params.BeaconConfig().MaxSeedLookahead assert.Equal(t, wanted, ActivationExitEpoch(epoch)) } @@ -422,7 +423,7 @@ func TestDomain_OK(t *testing.T) { }, } tests := []struct { - epoch uint64 + epoch types.Epoch domainType [4]byte result []byte }{ @@ -445,7 +446,7 @@ func TestActiveValidatorIndices(t *testing.T) { farFutureEpoch := params.BeaconConfig().FarFutureEpoch type args struct { state *pb.BeaconState - epoch uint64 + epoch types.Epoch } tests := []struct { name string diff --git a/beacon-chain/core/state/BUILD.bazel b/beacon-chain/core/state/BUILD.bazel index a89695c9da..6e415276cb 100644 --- a/beacon-chain/core/state/BUILD.bazel +++ b/beacon-chain/core/state/BUILD.bazel @@ -79,13 +79,13 @@ go_test( "//shared/bytesutil:go_default_library", "//shared/hashutil:go_default_library", "//shared/params:go_default_library", - "//shared/sszutil:go_default_library", "//shared/testutil:go_default_library", "//shared/testutil/assert:go_default_library", "//shared/testutil/require:go_default_library", "//shared/trieutil:go_default_library", "@com_github_gogo_protobuf//proto:go_default_library", "@com_github_google_gofuzz//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", diff --git a/beacon-chain/core/state/skip_slot_cache_test.go b/beacon-chain/core/state/skip_slot_cache_test.go index f668bf6fa6..01b81a4f57 100644 --- a/beacon-chain/core/state/skip_slot_cache_test.go +++ b/beacon-chain/core/state/skip_slot_cache_test.go @@ -8,7 +8,6 @@ import ( "github.com/prysmaticlabs/prysm/beacon-chain/core/state" beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/shared/params" - "github.com/prysmaticlabs/prysm/shared/sszutil" "github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/require" @@ -34,9 +33,7 @@ func TestSkipSlotCache_OK(t *testing.T) { bState, err = state.ExecuteStateTransition(context.Background(), bState, blk) require.NoError(t, err, "Could not process state transition") - if !sszutil.DeepEqual(originalState.CloneInnerState(), bState.CloneInnerState()) { - t.Fatal("Skipped slots cache leads to different states") - } + assert.DeepEqual(t, originalState.CloneInnerState(), bState.CloneInnerState(), "Skipped slots cache leads to different states") } func TestSkipSlotCache_ConcurrentMixup(t *testing.T) { diff --git a/beacon-chain/core/state/state_test.go b/beacon-chain/core/state/state_test.go index 6fb232cb06..c19795a089 100644 --- a/beacon-chain/core/state/state_test.go +++ b/beacon-chain/core/state/state_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/gogo/protobuf/proto" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/state" pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" @@ -15,19 +16,19 @@ import ( ) func TestGenesisBeaconState_OK(t *testing.T) { - genesisEpochNumber := uint64(0) + genesisEpoch := types.Epoch(0) assert.DeepEqual(t, []byte{0, 0, 0, 0}, params.BeaconConfig().GenesisForkVersion, "GenesisSlot( should be {0,0,0,0} for these tests to pass") genesisForkVersion := params.BeaconConfig().GenesisForkVersion assert.Equal(t, [32]byte{}, params.BeaconConfig().ZeroHash, "ZeroHash should be all 0s for these tests to pass") - assert.Equal(t, uint64(65536), params.BeaconConfig().EpochsPerHistoricalVector, "EpochsPerHistoricalVector should be 8192 for these tests to pass") + assert.Equal(t, types.Epoch(65536), params.BeaconConfig().EpochsPerHistoricalVector, "EpochsPerHistoricalVector should be 8192 for these tests to pass") latestRandaoMixesLength := params.BeaconConfig().EpochsPerHistoricalVector assert.Equal(t, uint64(16777216), params.BeaconConfig().HistoricalRootsLimit, "HistoricalRootsLimit should be 16777216 for these tests to pass") depositsForChainStart := 100 - assert.Equal(t, uint64(8192), params.BeaconConfig().EpochsPerSlashingsVector, "EpochsPerSlashingsVector should be 8192 for these tests to pass") + assert.Equal(t, types.Epoch(8192), params.BeaconConfig().EpochsPerSlashingsVector, "EpochsPerSlashingsVector should be 8192 for these tests to pass") genesisTime := uint64(99999) deposits, _, err := testutil.DeterministicDepositsAndKeys(uint64(depositsForChainStart)) @@ -42,7 +43,7 @@ func TestGenesisBeaconState_OK(t *testing.T) { if !proto.Equal(newState.Fork(), &pb.Fork{ PreviousVersion: genesisForkVersion, CurrentVersion: genesisForkVersion, - Epoch: genesisEpochNumber, + Epoch: genesisEpoch, }) { t.Error("Fork was not correctly initialized") } @@ -51,22 +52,22 @@ func TestGenesisBeaconState_OK(t *testing.T) { assert.Equal(t, depositsForChainStart, len(newState.Validators()), "Validators was not correctly initialized") v, err := newState.ValidatorAtIndex(0) require.NoError(t, err) - assert.Equal(t, uint64(0), v.ActivationEpoch, "Validators was not correctly initialized") + assert.Equal(t, types.Epoch(0), v.ActivationEpoch, "Validators was not correctly initialized") v, err = newState.ValidatorAtIndex(0) require.NoError(t, err) - assert.Equal(t, uint64(0), v.ActivationEligibilityEpoch, "Validators was not correctly initialized") + assert.Equal(t, types.Epoch(0), v.ActivationEligibilityEpoch, "Validators was not correctly initialized") assert.Equal(t, depositsForChainStart, len(newState.Balances()), "Balances was not correctly initialized") // Randomness and committees fields checks. - assert.Equal(t, latestRandaoMixesLength, uint64(len(newState.RandaoMixes())), "Length of RandaoMixes was not correctly initialized") + assert.Equal(t, latestRandaoMixesLength, types.Epoch(len(newState.RandaoMixes())), "Length of RandaoMixes was not correctly initialized") mix, err := newState.RandaoMixAtIndex(0) require.NoError(t, err) assert.DeepEqual(t, eth1Data.BlockHash, mix, "RandaoMixes was not correctly initialized") // Finality fields checks. - assert.Equal(t, genesisEpochNumber, newState.PreviousJustifiedCheckpoint().Epoch, "PreviousJustifiedCheckpoint.Epoch was not correctly initialized") - assert.Equal(t, genesisEpochNumber, newState.CurrentJustifiedCheckpoint().Epoch, "JustifiedEpoch was not correctly initialized") - assert.Equal(t, genesisEpochNumber, newState.FinalizedCheckpointEpoch(), "FinalizedSlot was not correctly initialized") + assert.Equal(t, genesisEpoch, newState.PreviousJustifiedCheckpoint().Epoch, "PreviousJustifiedCheckpoint.Epoch was not correctly initialized") + assert.Equal(t, genesisEpoch, newState.CurrentJustifiedCheckpoint().Epoch, "JustifiedEpoch was not correctly initialized") + assert.Equal(t, genesisEpoch, newState.FinalizedCheckpointEpoch(), "FinalizedSlot was not correctly initialized") assert.Equal(t, uint8(0x00), newState.JustificationBits()[0], "JustificationBits was not correctly initialized") // Recent state checks. diff --git a/beacon-chain/core/state/transition_test.go b/beacon-chain/core/state/transition_test.go index 3a47857c4a..e34a208580 100644 --- a/beacon-chain/core/state/transition_test.go +++ b/beacon-chain/core/state/transition_test.go @@ -6,6 +6,7 @@ import ( "fmt" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" @@ -321,7 +322,7 @@ func createFullBlockWithOperations(t *testing.T) (*beaconstate.BeaconState, proposerSlashIdx := uint64(3) slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch - err = beaconState.SetSlot((params.BeaconConfig().ShardCommitteePeriod * slotsPerEpoch) + params.BeaconConfig().MinAttestationInclusionDelay) + err = beaconState.SetSlot(uint64(params.BeaconConfig().ShardCommitteePeriod.Mul(slotsPerEpoch)) + params.BeaconConfig().MinAttestationInclusionDelay) require.NoError(t, err) currentEpoch := helpers.CurrentEpoch(beaconState) @@ -501,12 +502,12 @@ func TestProcessBlockNoVerify_PassesProcessingConditions(t *testing.T) { } func TestProcessEpochPrecompute_CanProcess(t *testing.T) { - epoch := uint64(1) + epoch := types.Epoch(1) atts := []*pb.PendingAttestation{{Data: ðpb.AttestationData{Target: ðpb.Checkpoint{Root: make([]byte, 32)}}, InclusionDelay: 1}} slashing := make([]uint64, params.BeaconConfig().EpochsPerSlashingsVector) base := &pb.BeaconState{ - Slot: epoch*params.BeaconConfig().SlotsPerEpoch + 1, + Slot: uint64(epoch.Mul(params.BeaconConfig().SlotsPerEpoch)) + 1, BlockRoots: make([][]byte, 128), Slashings: slashing, RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector), diff --git a/beacon-chain/core/validators/BUILD.bazel b/beacon-chain/core/validators/BUILD.bazel index 66a380c2a9..7b1f6b6c93 100644 --- a/beacon-chain/core/validators/BUILD.bazel +++ b/beacon-chain/core/validators/BUILD.bazel @@ -9,9 +9,9 @@ go_library( deps = [ "//beacon-chain/core/helpers:go_default_library", "//beacon-chain/state:go_default_library", - "//shared/mathutil:go_default_library", "//shared/params:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", ], ) @@ -28,6 +28,7 @@ go_test( "//shared/params:go_default_library", "//shared/testutil/assert:go_default_library", "//shared/testutil/require:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", ], ) diff --git a/beacon-chain/core/validators/validator.go b/beacon-chain/core/validators/validator.go index 9c707429fb..e4703288d3 100644 --- a/beacon-chain/core/validators/validator.go +++ b/beacon-chain/core/validators/validator.go @@ -6,10 +6,10 @@ package validators import ( "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state" - "github.com/prysmaticlabs/prysm/shared/mathutil" "github.com/prysmaticlabs/prysm/shared/params" ) @@ -44,7 +44,7 @@ func InitiateValidatorExit(state *stateTrie.BeaconState, idx uint64) (*stateTrie if validator.ExitEpoch != params.BeaconConfig().FarFutureEpoch { return state, nil } - var exitEpochs []uint64 + var exitEpochs []types.Epoch err = state.ReadFromEveryValidator(func(idx int, val stateTrie.ReadOnlyValidator) error { if val.ExitEpoch() != params.BeaconConfig().FarFutureEpoch { exitEpochs = append(exitEpochs, val.ExitEpoch()) @@ -57,7 +57,7 @@ func InitiateValidatorExit(state *stateTrie.BeaconState, idx uint64) (*stateTrie exitEpochs = append(exitEpochs, helpers.ActivationExitEpoch(helpers.CurrentEpoch(state))) // Obtain the exit queue epoch as the maximum number in the exit epochs array. - exitQueueEpoch := uint64(0) + exitQueueEpoch := types.Epoch(0) for _, i := range exitEpochs { if exitQueueEpoch < i { exitQueueEpoch = i @@ -132,7 +132,7 @@ func SlashValidator(state *stateTrie.BeaconState, slashedIdx uint64) (*stateTrie return nil, err } validator.Slashed = true - maxWithdrawableEpoch := mathutil.Max(validator.WithdrawableEpoch, currentEpoch+params.BeaconConfig().EpochsPerSlashingsVector) + maxWithdrawableEpoch := types.MaxEpoch(validator.WithdrawableEpoch, currentEpoch+params.BeaconConfig().EpochsPerSlashingsVector) validator.WithdrawableEpoch = maxWithdrawableEpoch if err := state.UpdateValidatorAtIndex(slashedIdx, validator); err != nil { @@ -143,7 +143,7 @@ func SlashValidator(state *stateTrie.BeaconState, slashedIdx uint64) (*stateTrie slashings := state.Slashings() currentSlashing := slashings[currentEpoch%params.BeaconConfig().EpochsPerSlashingsVector] if err := state.UpdateSlashingsAtIndex( - currentEpoch%params.BeaconConfig().EpochsPerSlashingsVector, + uint64(currentEpoch%params.BeaconConfig().EpochsPerSlashingsVector), currentSlashing+validator.EffectiveBalance, ); err != nil { return nil, err @@ -172,7 +172,7 @@ func SlashValidator(state *stateTrie.BeaconState, slashedIdx uint64) (*stateTrie } // ActivatedValidatorIndices determines the indices activated during the given epoch. -func ActivatedValidatorIndices(epoch uint64, validators []*ethpb.Validator) []uint64 { +func ActivatedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []uint64 { activations := make([]uint64, 0) for i := 0; i < len(validators); i++ { val := validators[i] @@ -184,11 +184,11 @@ func ActivatedValidatorIndices(epoch uint64, validators []*ethpb.Validator) []ui } // SlashedValidatorIndices determines the indices slashed during the given epoch. -func SlashedValidatorIndices(epoch uint64, validators []*ethpb.Validator) []uint64 { +func SlashedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []uint64 { slashed := make([]uint64, 0) for i := 0; i < len(validators); i++ { val := validators[i] - maxWithdrawableEpoch := mathutil.Max(val.WithdrawableEpoch, epoch+params.BeaconConfig().EpochsPerSlashingsVector) + maxWithdrawableEpoch := types.MaxEpoch(val.WithdrawableEpoch, epoch+params.BeaconConfig().EpochsPerSlashingsVector) if val.WithdrawableEpoch == maxWithdrawableEpoch && val.Slashed { slashed = append(slashed, uint64(i)) } @@ -197,16 +197,16 @@ func SlashedValidatorIndices(epoch uint64, validators []*ethpb.Validator) []uint } // ExitedValidatorIndices determines the indices exited during the current epoch. -func ExitedValidatorIndices(epoch uint64, validators []*ethpb.Validator, activeValidatorCount uint64) ([]uint64, error) { +func ExitedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]uint64, error) { exited := make([]uint64, 0) - exitEpochs := make([]uint64, 0) + exitEpochs := make([]types.Epoch, 0) for i := 0; i < len(validators); i++ { val := validators[i] if val.ExitEpoch != params.BeaconConfig().FarFutureEpoch { exitEpochs = append(exitEpochs, val.ExitEpoch) } } - exitQueueEpoch := uint64(0) + exitQueueEpoch := types.Epoch(0) for _, i := range exitEpochs { if exitQueueEpoch < i { exitQueueEpoch = i @@ -238,16 +238,16 @@ func ExitedValidatorIndices(epoch uint64, validators []*ethpb.Validator, activeV } // EjectedValidatorIndices determines the indices ejected during the given epoch. -func EjectedValidatorIndices(epoch uint64, validators []*ethpb.Validator, activeValidatorCount uint64) ([]uint64, error) { +func EjectedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]uint64, error) { ejected := make([]uint64, 0) - exitEpochs := make([]uint64, 0) + exitEpochs := make([]types.Epoch, 0) for i := 0; i < len(validators); i++ { val := validators[i] if val.ExitEpoch != params.BeaconConfig().FarFutureEpoch { exitEpochs = append(exitEpochs, val.ExitEpoch) } } - exitQueueEpoch := uint64(0) + exitQueueEpoch := types.Epoch(0) for _, i := range exitEpochs { if exitQueueEpoch < i { exitQueueEpoch = i diff --git a/beacon-chain/core/validators/validator_test.go b/beacon-chain/core/validators/validator_test.go index 419f43fd14..75446750d7 100644 --- a/beacon-chain/core/validators/validator_test.go +++ b/beacon-chain/core/validators/validator_test.go @@ -3,6 +3,7 @@ package validators import ( "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -39,7 +40,7 @@ func TestHasVoted_OK(t *testing.T) { } func TestInitiateValidatorExit_AlreadyExited(t *testing.T) { - exitEpoch := uint64(199) + exitEpoch := types.Epoch(199) base := &pb.BeaconState{Validators: []*ethpb.Validator{{ ExitEpoch: exitEpoch}, }} @@ -53,7 +54,7 @@ func TestInitiateValidatorExit_AlreadyExited(t *testing.T) { } func TestInitiateValidatorExit_ProperExit(t *testing.T) { - exitedEpoch := uint64(100) + exitedEpoch := types.Epoch(100) idx := uint64(3) base := &pb.BeaconState{Validators: []*ethpb.Validator{ {ExitEpoch: exitedEpoch}, @@ -71,7 +72,7 @@ func TestInitiateValidatorExit_ProperExit(t *testing.T) { } func TestInitiateValidatorExit_ChurnOverflow(t *testing.T) { - exitedEpoch := uint64(100) + exitedEpoch := types.Epoch(100) idx := uint64(4) base := &pb.BeaconState{Validators: []*ethpb.Validator{ {ExitEpoch: exitedEpoch + 2}, @@ -133,7 +134,7 @@ func TestSlashValidator_OK(t *testing.T) { assert.Equal(t, helpers.CurrentEpoch(state)+params.BeaconConfig().EpochsPerSlashingsVector, v.WithdrawableEpoch, "Withdrawable epoch not the expected value") maxBalance := params.BeaconConfig().MaxEffectiveBalance - slashedBalance := state.Slashings()[state.Slot()%params.BeaconConfig().EpochsPerSlashingsVector] + slashedBalance := state.Slashings()[state.Slot()%uint64(params.BeaconConfig().EpochsPerSlashingsVector)] assert.Equal(t, maxBalance, slashedBalance, "Slashed balance isnt the expected amount") whistleblowerReward := slashedBalance / params.BeaconConfig().WhistleBlowerRewardQuotient diff --git a/beacon-chain/db/filters/BUILD.bazel b/beacon-chain/db/filters/BUILD.bazel index b5c9a9f945..85cbc3d818 100644 --- a/beacon-chain/db/filters/BUILD.bazel +++ b/beacon-chain/db/filters/BUILD.bazel @@ -9,6 +9,7 @@ go_library( "//beacon-chain:__subpackages__", "//tools:__subpackages__", ], + deps = ["@com_github_prysmaticlabs_eth2_types//:go_default_library"], ) go_test( diff --git a/beacon-chain/db/filters/filter.go b/beacon-chain/db/filters/filter.go index c1aa85c2ed..a2f326a2c3 100644 --- a/beacon-chain/db/filters/filter.go +++ b/beacon-chain/db/filters/filter.go @@ -14,6 +14,8 @@ // } package filters +import "github.com/prysmaticlabs/eth2-types" + // FilterType defines an enum which is used as the keys in a map that tracks // set attribute filters for data as part of the `FilterQuery` struct type. type FilterType uint8 @@ -89,13 +91,13 @@ func (q *QueryFilter) SetTargetRoot(val []byte) *QueryFilter { } // SetSourceEpoch enables filtering by the source epoch data attribute of an object. -func (q *QueryFilter) SetSourceEpoch(val uint64) *QueryFilter { +func (q *QueryFilter) SetSourceEpoch(val types.Epoch) *QueryFilter { q.queries[SourceEpoch] = val return q } // SetTargetEpoch enables filtering by the target epoch data attribute of an object. -func (q *QueryFilter) SetTargetEpoch(val uint64) *QueryFilter { +func (q *QueryFilter) SetTargetEpoch(val types.Epoch) *QueryFilter { q.queries[TargetEpoch] = val return q } @@ -113,13 +115,13 @@ func (q *QueryFilter) SetEndSlot(val uint64) *QueryFilter { } // SetStartEpoch enables filtering by the StartEpoch attribute of an object (inclusive). -func (q *QueryFilter) SetStartEpoch(val uint64) *QueryFilter { +func (q *QueryFilter) SetStartEpoch(val types.Epoch) *QueryFilter { q.queries[StartEpoch] = val return q } // SetEndEpoch enables filtering by the EndEpoch attribute of an object (inclusive). -func (q *QueryFilter) SetEndEpoch(val uint64) *QueryFilter { +func (q *QueryFilter) SetEndEpoch(val types.Epoch) *QueryFilter { q.queries[EndEpoch] = val return q } diff --git a/beacon-chain/db/kv/BUILD.bazel b/beacon-chain/db/kv/BUILD.bazel index 0af106ffbf..0ce029264f 100644 --- a/beacon-chain/db/kv/BUILD.bazel +++ b/beacon-chain/db/kv/BUILD.bazel @@ -46,6 +46,7 @@ go_library( "@com_github_golang_snappy//:go_default_library", "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_prombbolt//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", @@ -88,6 +89,7 @@ go_test( "//shared/testutil/require:go_default_library", "@com_github_ethereum_go_ethereum//common:go_default_library", "@com_github_gogo_protobuf//proto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@in_gopkg_d4l3k_messagediff_v1//:go_default_library", "@io_etcd_go_bbolt//:go_default_library", diff --git a/beacon-chain/db/kv/blocks.go b/beacon-chain/db/kv/blocks.go index 083deedf8e..5bc6be3fc3 100644 --- a/beacon-chain/db/kv/blocks.go +++ b/beacon-chain/db/kv/blocks.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/db/filters" @@ -458,8 +459,8 @@ func blockRootsBySlotRange( if step, ok = slotStepEncoded.(uint64); !ok || step == 0 { step = 1 } - startEpoch, startEpochOk := startEpochEncoded.(uint64) - endEpoch, endEpochOk := endEpochEncoded.(uint64) + startEpoch, startEpochOk := startEpochEncoded.(types.Epoch) + endEpoch, endEpochOk := endEpochEncoded.(types.Epoch) var err error if startEpochOk && endEpochOk { startSlot, err = helpers.StartSlot(startEpoch) diff --git a/beacon-chain/db/kv/state_test.go b/beacon-chain/db/kv/state_test.go index 02e83a4687..712ff7197d 100644 --- a/beacon-chain/db/kv/state_test.go +++ b/beacon-chain/db/kv/state_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/gogo/protobuf/proto" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/shared/bytesutil" @@ -267,7 +268,10 @@ func TestStore_CleanUpDirtyStates_AboveThreshold(t *testing.T) { require.NoError(t, db.SaveState(context.Background(), st, r)) } - require.NoError(t, db.SaveFinalizedCheckpoint(context.Background(), ðpb.Checkpoint{Root: bRoots[len(bRoots)-1][:], Epoch: slotsPerArchivedPoint / params.BeaconConfig().SlotsPerEpoch})) + require.NoError(t, db.SaveFinalizedCheckpoint(context.Background(), ðpb.Checkpoint{ + Root: bRoots[len(bRoots)-1][:], + Epoch: types.Epoch(slotsPerArchivedPoint / params.BeaconConfig().SlotsPerEpoch), + })) require.NoError(t, db.CleanUpDirtyStates(context.Background(), slotsPerArchivedPoint)) for i, root := range bRoots { diff --git a/beacon-chain/forkchoice/BUILD.bazel b/beacon-chain/forkchoice/BUILD.bazel index e48470ef96..16ef1c9775 100644 --- a/beacon-chain/forkchoice/BUILD.bazel +++ b/beacon-chain/forkchoice/BUILD.bazel @@ -8,5 +8,8 @@ go_library( ], importpath = "github.com/prysmaticlabs/prysm/beacon-chain/forkchoice", visibility = ["//beacon-chain:__subpackages__"], - deps = ["//beacon-chain/forkchoice/protoarray:go_default_library"], + deps = [ + "//beacon-chain/forkchoice/protoarray:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", + ], ) diff --git a/beacon-chain/forkchoice/interfaces.go b/beacon-chain/forkchoice/interfaces.go index c8ae8321a7..e6c2eb62d9 100644 --- a/beacon-chain/forkchoice/interfaces.go +++ b/beacon-chain/forkchoice/interfaces.go @@ -3,6 +3,7 @@ package forkchoice import ( "context" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray" ) @@ -17,17 +18,17 @@ type ForkChoicer interface { // HeadRetriever retrieves head root of the current chain. type HeadRetriever interface { - Head(context.Context, uint64, [32]byte, []uint64, uint64) ([32]byte, error) + Head(context.Context, types.Epoch, [32]byte, []uint64, types.Epoch) ([32]byte, error) } // BlockProcessor processes the block that's used for accounting fork choice. type BlockProcessor interface { - ProcessBlock(context.Context, uint64, [32]byte, [32]byte, [32]byte, uint64, uint64) error + ProcessBlock(context.Context, uint64, [32]byte, [32]byte, [32]byte, types.Epoch, types.Epoch) error } // AttestationProcessor processes the attestation that's used for accounting fork choice. type AttestationProcessor interface { - ProcessAttestation(context.Context, []uint64, [32]byte, uint64) + ProcessAttestation(context.Context, []uint64, [32]byte, types.Epoch) } // Pruner prunes the fork choice upon new finalization. This is used to keep fork choice sane. diff --git a/beacon-chain/forkchoice/protoarray/BUILD.bazel b/beacon-chain/forkchoice/protoarray/BUILD.bazel index b828ab939e..f6b63f6b3b 100644 --- a/beacon-chain/forkchoice/protoarray/BUILD.bazel +++ b/beacon-chain/forkchoice/protoarray/BUILD.bazel @@ -22,6 +22,7 @@ go_library( "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prometheus_client_golang//prometheus/promauto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@io_opencensus_go//trace:go_default_library", ], ) @@ -43,5 +44,6 @@ go_test( "//shared/params:go_default_library", "//shared/testutil/assert:go_default_library", "//shared/testutil/require:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", ], ) diff --git a/beacon-chain/forkchoice/protoarray/ffg_update_test.go b/beacon-chain/forkchoice/protoarray/ffg_update_test.go index 02d31a0df9..38eef40417 100644 --- a/beacon-chain/forkchoice/protoarray/ffg_update_test.go +++ b/beacon-chain/forkchoice/protoarray/ffg_update_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/require" @@ -181,7 +182,7 @@ func TestFFGUpdates_TwoBranches(t *testing.T) { assert.Equal(t, indexToHash(7), r, "Incorrect head with justified epoch at 0") } -func setup(justifiedEpoch, finalizedEpoch uint64) *ForkChoice { +func setup(justifiedEpoch, finalizedEpoch types.Epoch) *ForkChoice { f := New(0, 0, params.BeaconConfig().ZeroHash) f.store.nodesIndices[params.BeaconConfig().ZeroHash] = 0 f.store.nodes = append(f.store.nodes, &Node{ diff --git a/beacon-chain/forkchoice/protoarray/node.go b/beacon-chain/forkchoice/protoarray/node.go index 1ad26ebf6d..ba93c62c8e 100644 --- a/beacon-chain/forkchoice/protoarray/node.go +++ b/beacon-chain/forkchoice/protoarray/node.go @@ -1,5 +1,7 @@ package protoarray +import "github.com/prysmaticlabs/eth2-types" + // Slot of the fork choice node. func (n *Node) Slot() uint64 { return n.slot @@ -16,12 +18,12 @@ func (n *Node) Parent() uint64 { } // JustifiedEpoch of the fork choice node. -func (n *Node) JustifiedEpoch() uint64 { +func (n *Node) JustifiedEpoch() types.Epoch { return n.justifiedEpoch } // FinalizedEpoch of the fork choice node. -func (n *Node) FinalizedEpoch() uint64 { +func (n *Node) FinalizedEpoch() types.Epoch { return n.finalizedEpoch } diff --git a/beacon-chain/forkchoice/protoarray/node_test.go b/beacon-chain/forkchoice/protoarray/node_test.go index 57b9750e16..daedf3722c 100644 --- a/beacon-chain/forkchoice/protoarray/node_test.go +++ b/beacon-chain/forkchoice/protoarray/node_test.go @@ -3,6 +3,7 @@ package protoarray import ( "testing" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/testutil/require" ) @@ -10,8 +11,8 @@ func TestNode_Getters(t *testing.T) { slot := uint64(100) root := [32]byte{'a'} parent := uint64(10) - jEpoch := uint64(20) - fEpoch := uint64(30) + jEpoch := types.Epoch(20) + fEpoch := types.Epoch(30) weight := uint64(10000) bestChild := uint64(5) bestDescendant := uint64(4) diff --git a/beacon-chain/forkchoice/protoarray/store.go b/beacon-chain/forkchoice/protoarray/store.go index dc8b8941e2..3ad2c58c92 100644 --- a/beacon-chain/forkchoice/protoarray/store.go +++ b/beacon-chain/forkchoice/protoarray/store.go @@ -7,6 +7,7 @@ import ( "math" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/params" "go.opencensus.io/trace" ) @@ -19,7 +20,7 @@ const defaultPruneThreshold = 256 var lastHeadRoot [32]byte // New initializes a new fork choice store. -func New(justifiedEpoch, finalizedEpoch uint64, finalizedRoot [32]byte) *ForkChoice { +func New(justifiedEpoch, finalizedEpoch types.Epoch, finalizedRoot [32]byte) *ForkChoice { s := &Store{ justifiedEpoch: justifiedEpoch, finalizedEpoch: finalizedEpoch, @@ -38,7 +39,7 @@ func New(justifiedEpoch, finalizedEpoch uint64, finalizedRoot [32]byte) *ForkCho // Head returns the head root from fork choice store. // It firsts computes validator's balance changes then recalculates block tree from leaves to root. -func (f *ForkChoice) Head(ctx context.Context, justifiedEpoch uint64, justifiedRoot [32]byte, justifiedStateBalances []uint64, finalizedEpoch uint64) ([32]byte, error) { +func (f *ForkChoice) Head(ctx context.Context, justifiedEpoch types.Epoch, justifiedRoot [32]byte, justifiedStateBalances []uint64, finalizedEpoch types.Epoch) ([32]byte, error) { ctx, span := trace.StartSpan(ctx, "protoArrayForkChoice.Head") defer span.End() f.votesLock.Lock() @@ -67,7 +68,7 @@ func (f *ForkChoice) Head(ctx context.Context, justifiedEpoch uint64, justifiedR // ProcessAttestation processes attestation for vote accounting, it iterates around validator indices // and update their votes accordingly. -func (f *ForkChoice) ProcessAttestation(ctx context.Context, validatorIndices []uint64, blockRoot [32]byte, targetEpoch uint64) { +func (f *ForkChoice) ProcessAttestation(ctx context.Context, validatorIndices []uint64, blockRoot [32]byte, targetEpoch types.Epoch) { ctx, span := trace.StartSpan(ctx, "protoArrayForkChoice.ProcessAttestation") defer span.End() f.votesLock.Lock() @@ -94,7 +95,7 @@ func (f *ForkChoice) ProcessAttestation(ctx context.Context, validatorIndices [] } // ProcessBlock processes a new block by inserting it to the fork choice store. -func (f *ForkChoice) ProcessBlock(ctx context.Context, slot uint64, blockRoot, parentRoot, graffiti [32]byte, justifiedEpoch, finalizedEpoch uint64) error { +func (f *ForkChoice) ProcessBlock(ctx context.Context, slot uint64, blockRoot, parentRoot, graffiti [32]byte, justifiedEpoch, finalizedEpoch types.Epoch) error { ctx, span := trace.StartSpan(ctx, "protoArrayForkChoice.ProcessBlock") defer span.End() @@ -206,12 +207,12 @@ func (s *Store) PruneThreshold() uint64 { } // JustifiedEpoch of fork choice store. -func (s *Store) JustifiedEpoch() uint64 { +func (s *Store) JustifiedEpoch() types.Epoch { return s.justifiedEpoch } // FinalizedEpoch of fork choice store. -func (s *Store) FinalizedEpoch() uint64 { +func (s *Store) FinalizedEpoch() types.Epoch { return s.finalizedEpoch } @@ -315,7 +316,7 @@ func (s *Store) updateCanonicalNodes(ctx context.Context, root [32]byte) error { func (s *Store) insert(ctx context.Context, slot uint64, root, parent, graffiti [32]byte, - justifiedEpoch, finalizedEpoch uint64) error { + justifiedEpoch, finalizedEpoch types.Epoch) error { ctx, span := trace.StartSpan(ctx, "protoArrayForkChoice.insert") defer span.End() @@ -367,7 +368,7 @@ func (s *Store) insert(ctx context.Context, // and its best child. For each node, it updates the weight with input delta and // back propagate the nodes delta to its parents delta. After scoring changes, // the best child is then updated along with best descendant. -func (s *Store) applyWeightChanges(ctx context.Context, justifiedEpoch, finalizedEpoch uint64, delta []int) error { +func (s *Store) applyWeightChanges(ctx context.Context, justifiedEpoch, finalizedEpoch types.Epoch, delta []int) error { ctx, span := trace.StartSpan(ctx, "protoArrayForkChoice.applyWeightChanges") defer span.End() diff --git a/beacon-chain/forkchoice/protoarray/store_test.go b/beacon-chain/forkchoice/protoarray/store_test.go index c5658f61f1..fb53037d52 100644 --- a/beacon-chain/forkchoice/protoarray/store_test.go +++ b/beacon-chain/forkchoice/protoarray/store_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/require" @@ -19,7 +20,7 @@ func TestStore_PruneThreshold(t *testing.T) { } func TestStore_JustifiedEpoch(t *testing.T) { - j := uint64(100) + j := types.Epoch(100) s := &Store{ justifiedEpoch: j, } @@ -29,7 +30,7 @@ func TestStore_JustifiedEpoch(t *testing.T) { } func TestStore_FinalizedEpoch(t *testing.T) { - f := uint64(50) + f := types.Epoch(50) s := &Store{ finalizedEpoch: f, } @@ -159,8 +160,8 @@ func TestStore_Insert_UnknownParent(t *testing.T) { assert.Equal(t, 1, len(s.nodes), "Did not insert block") assert.Equal(t, 1, len(s.nodesIndices), "Did not insert block") assert.Equal(t, NonExistentNode, s.nodes[0].parent, "Incorrect parent") - assert.Equal(t, uint64(1), s.nodes[0].justifiedEpoch, "Incorrect justification") - assert.Equal(t, uint64(1), s.nodes[0].finalizedEpoch, "Incorrect finalization") + assert.Equal(t, types.Epoch(1), s.nodes[0].justifiedEpoch, "Incorrect justification") + assert.Equal(t, types.Epoch(1), s.nodes[0].finalizedEpoch, "Incorrect finalization") assert.Equal(t, [32]byte{'A'}, s.nodes[0].root, "Incorrect root") } @@ -175,8 +176,8 @@ func TestStore_Insert_KnownParent(t *testing.T) { assert.Equal(t, 2, len(s.nodes), "Did not insert block") assert.Equal(t, 2, len(s.nodesIndices), "Did not insert block") assert.Equal(t, uint64(0), s.nodes[1].parent, "Incorrect parent") - assert.Equal(t, uint64(1), s.nodes[1].justifiedEpoch, "Incorrect justification") - assert.Equal(t, uint64(1), s.nodes[1].finalizedEpoch, "Incorrect finalization") + assert.Equal(t, types.Epoch(1), s.nodes[1].justifiedEpoch, "Incorrect justification") + assert.Equal(t, types.Epoch(1), s.nodes[1].finalizedEpoch, "Incorrect finalization") assert.Equal(t, [32]byte{'A'}, s.nodes[1].root, "Incorrect root") } @@ -193,8 +194,8 @@ func TestStore_ApplyScoreChanges_UpdateEpochs(t *testing.T) { // The justified and finalized epochs in Store should be updated to 1 and 1 given the following input. require.NoError(t, s.applyWeightChanges(context.Background(), 1, 1, []int{})) - assert.Equal(t, uint64(1), s.justifiedEpoch, "Did not update justified epoch") - assert.Equal(t, uint64(1), s.finalizedEpoch, "Did not update finalized epoch") + assert.Equal(t, types.Epoch(1), s.justifiedEpoch, "Did not update justified epoch") + assert.Equal(t, types.Epoch(1), s.finalizedEpoch, "Did not update finalized epoch") } func TestStore_ApplyScoreChanges_UpdateWeightsPositiveDelta(t *testing.T) { @@ -419,8 +420,8 @@ func TestStore_Prune_MoreThanOnce(t *testing.T) { func TestStore_LeadsToViableHead(t *testing.T) { tests := []struct { n *Node - justifiedEpoch uint64 - finalizedEpoch uint64 + justifiedEpoch types.Epoch + finalizedEpoch types.Epoch want bool }{ {&Node{}, 0, 0, true}, @@ -445,8 +446,8 @@ func TestStore_LeadsToViableHead(t *testing.T) { func TestStore_ViableForHead(t *testing.T) { tests := []struct { n *Node - justifiedEpoch uint64 - finalizedEpoch uint64 + justifiedEpoch types.Epoch + finalizedEpoch types.Epoch want bool }{ {&Node{}, 0, 0, true}, diff --git a/beacon-chain/forkchoice/protoarray/types.go b/beacon-chain/forkchoice/protoarray/types.go index ec8d825a2b..cf28614e62 100644 --- a/beacon-chain/forkchoice/protoarray/types.go +++ b/beacon-chain/forkchoice/protoarray/types.go @@ -1,6 +1,10 @@ package protoarray -import "sync" +import ( + "sync" + + "github.com/prysmaticlabs/eth2-types" +) // ForkChoice defines the overall fork choice store which includes all block nodes, validator's latest votes and balances. type ForkChoice struct { @@ -13,8 +17,8 @@ type ForkChoice struct { // Store defines the fork choice store which includes block nodes and the last view of checkpoint information. type Store struct { pruneThreshold uint64 // do not prune tree unless threshold is reached. - justifiedEpoch uint64 // latest justified epoch in store. - finalizedEpoch uint64 // latest finalized epoch in store. + justifiedEpoch types.Epoch // latest justified epoch in store. + finalizedEpoch types.Epoch // latest finalized epoch in store. finalizedRoot [32]byte // latest finalized root in store. nodes []*Node // list of block nodes, each node is a representation of one block. nodesIndices map[[32]byte]uint64 // the root of block node and the nodes index in the list. @@ -25,22 +29,22 @@ type Store struct { // Node defines the individual block which includes its block parent, ancestor and how much weight accounted for it. // This is used as an array based stateful DAG for efficient fork choice look up. type Node struct { - slot uint64 // slot of the block converted to the node. - root [32]byte // root of the block converted to the node. - parent uint64 // parent index of this node. - justifiedEpoch uint64 // justifiedEpoch of this node. - finalizedEpoch uint64 // finalizedEpoch of this node. - weight uint64 // weight of this node. - bestChild uint64 // bestChild index of this node. - bestDescendant uint64 // bestDescendant of this node. - graffiti [32]byte // graffiti of the block node. + slot uint64 // slot of the block converted to the node. + root [32]byte // root of the block converted to the node. + parent uint64 // parent index of this node. + justifiedEpoch types.Epoch // justifiedEpoch of this node. + finalizedEpoch types.Epoch // finalizedEpoch of this node. + weight uint64 // weight of this node. + bestChild uint64 // bestChild index of this node. + bestDescendant uint64 // bestDescendant of this node. + graffiti [32]byte // graffiti of the block node. } // Vote defines an individual validator's vote. type Vote struct { - currentRoot [32]byte // current voting root. - nextRoot [32]byte // next voting root. - nextEpoch uint64 // epoch of next voting period. + currentRoot [32]byte // current voting root. + nextRoot [32]byte // next voting root. + nextEpoch types.Epoch // epoch of next voting period. } // NonExistentNode defines an unknown node which is used for the array based stateful DAG. diff --git a/beacon-chain/node/BUILD.bazel b/beacon-chain/node/BUILD.bazel index 16ddb44c10..c525552cb2 100644 --- a/beacon-chain/node/BUILD.bazel +++ b/beacon-chain/node/BUILD.bazel @@ -43,6 +43,7 @@ go_library( "//shared/version:go_default_library", "@com_github_ethereum_go_ethereum//common:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@com_github_urfave_cli_v2//:go_default_library", "@in_gopkg_yaml_v2//:go_default_library", @@ -62,6 +63,7 @@ go_test( "//shared/cmd:go_default_library", "//shared/testutil/assert:go_default_library", "//shared/testutil/require:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_sirupsen_logrus//hooks/test:go_default_library", "@com_github_urfave_cli_v2//:go_default_library", ], diff --git a/beacon-chain/node/helper.go b/beacon-chain/node/helper.go index ef3194c5f5..7c111199c0 100644 --- a/beacon-chain/node/helper.go +++ b/beacon-chain/node/helper.go @@ -6,11 +6,13 @@ import ( "fmt" "strconv" "strings" + + "github.com/prysmaticlabs/eth2-types" ) // Given input string `block_root:epoch_number`, this verifies the input string is valid, and // returns the block root as bytes and epoch number as unsigned integers. -func convertWspInput(wsp string) ([]byte, uint64, error) { +func convertWspInput(wsp string) ([]byte, types.Epoch, error) { if wsp == "" { return nil, 0, nil } @@ -43,5 +45,5 @@ func convertWspInput(wsp string) ([]byte, uint64, error) { return nil, 0, err } - return bRoot, epoch, nil + return bRoot, types.Epoch(epoch), nil } diff --git a/beacon-chain/node/helper_test.go b/beacon-chain/node/helper_test.go index bef86c34ff..8b73086c79 100644 --- a/beacon-chain/node/helper_test.go +++ b/beacon-chain/node/helper_test.go @@ -4,6 +4,7 @@ import ( "reflect" "testing" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/testutil/require" ) @@ -12,7 +13,7 @@ func TestConvertWspInput(t *testing.T) { name string input string bRoot []byte - epoch uint64 + epoch types.Epoch wantErr bool errStr string }{ diff --git a/beacon-chain/p2p/BUILD.bazel b/beacon-chain/p2p/BUILD.bazel index 10dede6b1c..b6697759e7 100644 --- a/beacon-chain/p2p/BUILD.bazel +++ b/beacon-chain/p2p/BUILD.bazel @@ -159,6 +159,7 @@ go_test( "@com_github_libp2p_go_libp2p_pubsub//pb:go_default_library", "@com_github_libp2p_go_libp2p_swarm//testing:go_default_library", "@com_github_multiformats_go_multiaddr//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", diff --git a/beacon-chain/p2p/fork_test.go b/beacon-chain/p2p/fork_test.go index 32389a90c8..c1c81c62ed 100644 --- a/beacon-chain/p2p/fork_test.go +++ b/beacon-chain/p2p/fork_test.go @@ -13,6 +13,7 @@ import ( "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enr" ma "github.com/multiformats/go-multiaddr" + "github.com/prysmaticlabs/eth2-types" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" @@ -142,7 +143,7 @@ func TestStartDiscv5_SameForkDigests_DifferentNextForkData(t *testing.T) { ipAddr, pkey := createAddrAndPrivKey(t) c := params.BeaconConfig() - nextForkEpoch := uint64(i) + nextForkEpoch := types.Epoch(i) c.NextForkEpoch = nextForkEpoch params.OverrideBeaconConfig(c) @@ -208,11 +209,11 @@ func TestStartDiscv5_SameForkDigests_DifferentNextForkData(t *testing.T) { func TestDiscv5_AddRetrieveForkEntryENR(t *testing.T) { params.SetupTestConfigCleanup(t) c := params.BeaconConfig() - c.ForkVersionSchedule = map[uint64][]byte{ + c.ForkVersionSchedule = map[types.Epoch][]byte{ 0: params.BeaconConfig().GenesisForkVersion, 1: {0, 0, 0, 1}, } - nextForkEpoch := uint64(1) + nextForkEpoch := types.Epoch(1) nextForkVersion := []byte{0, 0, 0, 1} c.NextForkEpoch = nextForkEpoch c.NextForkVersion = nextForkVersion diff --git a/beacon-chain/p2p/peers/BUILD.bazel b/beacon-chain/p2p/peers/BUILD.bazel index 76fd9ee341..58f2482919 100644 --- a/beacon-chain/p2p/peers/BUILD.bazel +++ b/beacon-chain/p2p/peers/BUILD.bazel @@ -19,6 +19,7 @@ go_library( "@com_github_libp2p_go_libp2p_core//peer:go_default_library", "@com_github_multiformats_go_multiaddr//:go_default_library", "@com_github_multiformats_go_multiaddr//net:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", ], ) @@ -44,6 +45,7 @@ go_test( "@com_github_libp2p_go_libp2p_core//network:go_default_library", "@com_github_libp2p_go_libp2p_core//peer:go_default_library", "@com_github_multiformats_go_multiaddr//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", diff --git a/beacon-chain/p2p/peers/status.go b/beacon-chain/p2p/peers/status.go index c96a0ea041..3967d29fbe 100644 --- a/beacon-chain/p2p/peers/status.go +++ b/beacon-chain/p2p/peers/status.go @@ -33,6 +33,7 @@ import ( "github.com/libp2p/go-libp2p-core/peer" ma "github.com/multiformats/go-multiaddr" manet "github.com/multiformats/go-multiaddr/net" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers/peerdata" @@ -545,10 +546,10 @@ func (p *Status) Prune() { // Ideally, all peers would be reporting the same finalized epoch but some may be behind due to their // own latency, or because of their finalized epoch at the time we queried them. // Returns epoch number and list of peers that are at or beyond that epoch. -func (p *Status) BestFinalized(maxPeers int, ourFinalizedEpoch uint64) (uint64, []peer.ID) { +func (p *Status) BestFinalized(maxPeers int, ourFinalizedEpoch types.Epoch) (types.Epoch, []peer.ID) { connected := p.Connected() - finalizedEpochVotes := make(map[uint64]uint64) - pidEpoch := make(map[peer.ID]uint64, len(connected)) + finalizedEpochVotes := make(map[types.Epoch]uint64) + pidEpoch := make(map[peer.ID]types.Epoch, len(connected)) pidHead := make(map[peer.ID]uint64, len(connected)) potentialPIDs := make([]peer.ID, 0, len(connected)) for _, pid := range connected { @@ -562,7 +563,7 @@ func (p *Status) BestFinalized(maxPeers int, ourFinalizedEpoch uint64) (uint64, } // Select the target epoch, which is the epoch most peers agree upon. - var targetEpoch uint64 + var targetEpoch types.Epoch var mostVotes uint64 for epoch, count := range finalizedEpochVotes { if count > mostVotes || (count == mostVotes && epoch > targetEpoch) { @@ -597,14 +598,14 @@ func (p *Status) BestFinalized(maxPeers int, ourFinalizedEpoch uint64) (uint64, // BestNonFinalized returns the highest known epoch, higher than ours, // and is shared by at least minPeers. -func (p *Status) BestNonFinalized(minPeers int, ourHeadEpoch uint64) (uint64, []peer.ID) { +func (p *Status) BestNonFinalized(minPeers int, ourHeadEpoch types.Epoch) (types.Epoch, []peer.ID) { connected := p.Connected() - epochVotes := make(map[uint64]uint64) - pidEpoch := make(map[peer.ID]uint64, len(connected)) + epochVotes := make(map[types.Epoch]uint64) + pidEpoch := make(map[peer.ID]types.Epoch, len(connected)) pidHead := make(map[peer.ID]uint64, len(connected)) potentialPIDs := make([]peer.ID, 0, len(connected)) - ourHeadSlot := ourHeadEpoch * params.BeaconConfig().SlotsPerEpoch + ourHeadSlot := uint64(ourHeadEpoch.Mul(params.BeaconConfig().SlotsPerEpoch)) for _, pid := range connected { peerChainState, err := p.ChainState(pid) if err == nil && peerChainState != nil && peerChainState.HeadSlot > ourHeadSlot { @@ -617,7 +618,7 @@ func (p *Status) BestNonFinalized(minPeers int, ourHeadEpoch uint64) (uint64, [] } // Select the target epoch, which has enough peers' votes (>= minPeers). - var targetEpoch uint64 + var targetEpoch types.Epoch for epoch, votes := range epochVotes { if votes >= uint64(minPeers) && targetEpoch < epoch { targetEpoch = epoch @@ -692,7 +693,7 @@ func (p *Status) PeersToPrune() []peer.ID { } // HighestEpoch returns the highest epoch reported epoch amongst peers. -func (p *Status) HighestEpoch() uint64 { +func (p *Status) HighestEpoch() types.Epoch { p.store.RLock() defer p.store.RUnlock() var highestSlot uint64 diff --git a/beacon-chain/p2p/peers/status_test.go b/beacon-chain/p2p/peers/status_test.go index f74c0580bc..e9490325b1 100644 --- a/beacon-chain/p2p/peers/status_test.go +++ b/beacon-chain/p2p/peers/status_test.go @@ -11,6 +11,7 @@ import ( "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/peer" ma "github.com/multiformats/go-multiaddr" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1" "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers" @@ -286,7 +287,7 @@ func TestPeerChainState(t *testing.T) { oldChainStartLastUpdated, err := p.ChainStateLastUpdated(id) require.NoError(t, err) - finalizedEpoch := uint64(123) + finalizedEpoch := types.Epoch(123) p.SetChainState(id, &pb.Status{FinalizedEpoch: finalizedEpoch}) resChainState, err := p.ChainState(id) @@ -568,7 +569,7 @@ func TestTrimmedOrderedPeers(t *testing.T) { }, }) - expectedTarget := uint64(2) + expectedTarget := types.Epoch(2) maxPeers := 3 mockroot2 := [32]byte{} mockroot3 := [32]byte{} @@ -721,14 +722,14 @@ func TestPrunePeers(t *testing.T) { func TestStatus_BestPeer(t *testing.T) { type peerConfig struct { headSlot uint64 - finalizedEpoch uint64 + finalizedEpoch types.Epoch } tests := []struct { name string peers []*peerConfig limitPeers int - ourFinalizedEpoch uint64 - targetEpoch uint64 + ourFinalizedEpoch types.Epoch + targetEpoch types.Epoch // targetEpochSupport denotes how many peers support returned epoch. targetEpochSupport int }{ @@ -915,7 +916,7 @@ func TestStatus_BestNonFinalized(t *testing.T) { }) } - expectedEpoch := uint64(8) + expectedEpoch := types.Epoch(8) retEpoch, pids := p.BestNonFinalized(3, 5) assert.Equal(t, expectedEpoch, retEpoch, "Incorrect Finalized epoch retrieved") assert.Equal(t, 3, len(pids), "Unexpected number of peers") @@ -947,7 +948,7 @@ func TestStatus_CurrentEpoch(t *testing.T) { HeadSlot: params.BeaconConfig().SlotsPerEpoch * 4, }) - assert.Equal(t, uint64(5), p.HighestEpoch(), "Expected current epoch to be 5") + assert.Equal(t, types.Epoch(5), p.HighestEpoch(), "Expected current epoch to be 5") } func TestInbound(t *testing.T) { diff --git a/beacon-chain/p2p/testing/mock_peersprovider.go b/beacon-chain/p2p/testing/mock_peersprovider.go index 959c714311..b2bbfb083f 100644 --- a/beacon-chain/p2p/testing/mock_peersprovider.go +++ b/beacon-chain/p2p/testing/mock_peersprovider.go @@ -60,7 +60,7 @@ func (m *MockPeersProvider) Peers() *peers.Status { } m.peers.Add(createENR(), id0, ma0, network.DirInbound) m.peers.SetConnectionState(id0, peers.PeerConnected) - m.peers.SetChainState(id0, &pb.Status{FinalizedEpoch: uint64(10)}) + m.peers.SetChainState(id0, &pb.Status{FinalizedEpoch: 10}) id1, err := peer.Decode("16Uiu2HAm4HgJ9N1o222xK61o7LSgToYWoAy1wNTJRkh9gLZapVAy") if err != nil { log.WithError(err).Debug("Cannot decode") @@ -71,7 +71,7 @@ func (m *MockPeersProvider) Peers() *peers.Status { } m.peers.Add(createENR(), id1, ma1, network.DirOutbound) m.peers.SetConnectionState(id1, peers.PeerConnected) - m.peers.SetChainState(id1, &pb.Status{FinalizedEpoch: uint64(11)}) + m.peers.SetChainState(id1, &pb.Status{FinalizedEpoch: 11}) } return m.peers } diff --git a/beacon-chain/rpc/beacon/BUILD.bazel b/beacon-chain/rpc/beacon/BUILD.bazel index 6a89369e2b..1d10519eaa 100644 --- a/beacon-chain/rpc/beacon/BUILD.bazel +++ b/beacon-chain/rpc/beacon/BUILD.bazel @@ -53,6 +53,7 @@ go_library( "@com_github_patrickmn_go_cache//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prometheus_client_golang//prometheus/promauto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@org_golang_google_grpc//codes:go_default_library", @@ -107,6 +108,7 @@ go_test( "@com_github_gogo_protobuf//proto:go_default_library", "@com_github_gogo_protobuf//types:go_default_library", "@com_github_golang_mock//gomock:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@in_gopkg_d4l3k_messagediff_v1//:go_default_library", diff --git a/beacon-chain/rpc/beacon/assignments.go b/beacon-chain/rpc/beacon/assignments.go index 1f443031b4..92635db47e 100644 --- a/beacon-chain/rpc/beacon/assignments.go +++ b/beacon-chain/rpc/beacon/assignments.go @@ -4,6 +4,7 @@ import ( "context" "strconv" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/shared/bytesutil" @@ -30,7 +31,7 @@ func (bs *Server) ListValidatorAssignments( var res []*ethpb.ValidatorAssignments_CommitteeAssignment filtered := map[uint64]bool{} // track filtered validators to prevent duplication in the response. filteredIndices := make([]uint64, 0) - var requestedEpoch uint64 + var requestedEpoch types.Epoch switch q := req.QueryFilter.(type) { case *ethpb.ListValidatorAssignmentsRequest_Genesis: if q.Genesis { diff --git a/beacon-chain/rpc/beacon/attestations_test.go b/beacon-chain/rpc/beacon/attestations_test.go index ed03c4235a..82001f9f56 100644 --- a/beacon-chain/rpc/beacon/attestations_test.go +++ b/beacon-chain/rpc/beacon/attestations_test.go @@ -11,6 +11,7 @@ import ( "github.com/gogo/protobuf/proto" ptypes "github.com/gogo/protobuf/types" "github.com/golang/mock/gomock" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" chainMock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" @@ -150,9 +151,9 @@ func TestServer_ListAttestations_FiltersCorrectly(t *testing.T) { someRoot := [32]byte{1, 2, 3} sourceRoot := [32]byte{4, 5, 6} - sourceEpoch := uint64(5) + sourceEpoch := types.Epoch(5) targetRoot := [32]byte{7, 8, 9} - targetEpoch := uint64(7) + targetEpoch := types.Epoch(7) blocks := []*ethpb.SignedBeaconBlock{ testutil.HydrateSignedBeaconBlock(ðpb.SignedBeaconBlock{ @@ -600,7 +601,7 @@ func TestServer_ListIndexedAttestations_OldEpoch(t *testing.T) { blockRoot := bytesutil.ToBytes32([]byte("root")) count := params.BeaconConfig().SlotsPerEpoch atts := make([]*ethpb.Attestation, 0, count) - epoch := uint64(50) + epoch := types.Epoch(50) startSlot, err := helpers.StartSlot(epoch) require.NoError(t, err) @@ -660,7 +661,7 @@ func TestServer_ListIndexedAttestations_OldEpoch(t *testing.T) { } err = db.SaveStateSummary(ctx, &pbp2p.StateSummary{ Root: blockRoot[:], - Slot: epoch * params.BeaconConfig().SlotsPerEpoch, + Slot: uint64(epoch) * params.BeaconConfig().SlotsPerEpoch, }) require.NoError(t, err) require.NoError(t, db.SaveState(ctx, state, bytesutil.ToBytes32([]byte("root")))) @@ -857,10 +858,10 @@ func TestServer_StreamIndexedAttestations_OK(t *testing.T) { activeIndices, err := helpers.ActiveValidatorIndices(headState, 0) require.NoError(t, err) - epoch := uint64(0) + epoch := types.Epoch(0) attesterSeed, err := helpers.Seed(headState, epoch, params.BeaconConfig().DomainBeaconAttester) require.NoError(t, err) - committees, err := computeCommittees(epoch*params.BeaconConfig().SlotsPerEpoch, activeIndices, attesterSeed) + committees, err := computeCommittees(uint64(epoch)*params.BeaconConfig().SlotsPerEpoch, activeIndices, attesterSeed) require.NoError(t, err) count := params.BeaconConfig().SlotsPerEpoch diff --git a/beacon-chain/rpc/beacon/blocks_test.go b/beacon-chain/rpc/beacon/blocks_test.go index e3de961697..11db0dd986 100644 --- a/beacon-chain/rpc/beacon/blocks_test.go +++ b/beacon-chain/rpc/beacon/blocks_test.go @@ -9,6 +9,7 @@ import ( "github.com/gogo/protobuf/proto" ptypes "github.com/gogo/protobuf/types" "github.com/golang/mock/gomock" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" chainMock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" @@ -411,9 +412,9 @@ func TestServer_GetChainHead(t *testing.T) { head, err := bs.GetChainHead(context.Background(), nil) require.NoError(t, err) - assert.Equal(t, uint64(3), head.PreviousJustifiedEpoch, "Unexpected PreviousJustifiedEpoch") - assert.Equal(t, uint64(2), head.JustifiedEpoch, "Unexpected JustifiedEpoch") - assert.Equal(t, uint64(1), head.FinalizedEpoch, "Unexpected FinalizedEpoch") + assert.Equal(t, types.Epoch(3), head.PreviousJustifiedEpoch, "Unexpected PreviousJustifiedEpoch") + assert.Equal(t, types.Epoch(2), head.JustifiedEpoch, "Unexpected JustifiedEpoch") + assert.Equal(t, types.Epoch(1), head.FinalizedEpoch, "Unexpected FinalizedEpoch") assert.Equal(t, uint64(24), head.PreviousJustifiedSlot, "Unexpected PreviousJustifiedSlot") assert.Equal(t, uint64(16), head.JustifiedSlot, "Unexpected JustifiedSlot") assert.Equal(t, uint64(8), head.FinalizedSlot, "Unexpected FinalizedSlot") @@ -696,9 +697,9 @@ func TestServer_GetWeakSubjectivityCheckpoint(t *testing.T) { c, err := server.GetWeakSubjectivityCheckpoint(ctx, &ptypes.Empty{}) require.NoError(t, err) - e := uint64(256) + e := types.Epoch(256) require.Equal(t, e, c.Epoch) - wsState, err := server.StateGen.StateBySlot(ctx, e*params.BeaconConfig().SlotsPerEpoch) + wsState, err := server.StateGen.StateBySlot(ctx, uint64(e)*params.BeaconConfig().SlotsPerEpoch) require.NoError(t, err) sRoot, err := wsState.HashTreeRoot(ctx) require.NoError(t, err) diff --git a/beacon-chain/rpc/beacon/committees.go b/beacon-chain/rpc/beacon/committees.go index 086f0808e7..049286bcb8 100644 --- a/beacon-chain/rpc/beacon/committees.go +++ b/beacon-chain/rpc/beacon/committees.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/shared/bytesutil" @@ -65,7 +66,7 @@ func (bs *Server) ListBeaconCommittees( func (bs *Server) retrieveCommitteesForEpoch( ctx context.Context, - epoch uint64, + epoch types.Epoch, ) (map[uint64]*ethpb.BeaconCommittees_CommitteesList, []uint64, error) { startSlot, err := helpers.StartSlot(epoch) if err != nil { diff --git a/beacon-chain/rpc/beacon/validators.go b/beacon-chain/rpc/beacon/validators.go index 5470b1cc4b..64a747409c 100644 --- a/beacon-chain/rpc/beacon/validators.go +++ b/beacon-chain/rpc/beacon/validators.go @@ -8,6 +8,7 @@ import ( "time" ptypes "github.com/gogo/protobuf/types" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" @@ -388,7 +389,7 @@ func (bs *Server) GetValidatorActiveSetChanges( ) (*ethpb.ActiveSetChanges, error) { currentEpoch := helpers.SlotToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) - var requestedEpoch uint64 + var requestedEpoch types.Epoch switch q := req.QueryFilter.(type) { case *ethpb.GetValidatorActiveSetChangesRequest_Genesis: requestedEpoch = 0 @@ -474,7 +475,7 @@ func (bs *Server) GetValidatorParticipation( currentSlot := bs.GenesisTimeFetcher.CurrentSlot() currentEpoch := helpers.SlotToEpoch(currentSlot) - var requestedEpoch uint64 + var requestedEpoch types.Epoch switch q := req.QueryFilter.(type) { case *ethpb.GetValidatorParticipationRequest_Genesis: requestedEpoch = 0 @@ -561,7 +562,7 @@ func (bs *Server) GetValidatorQueue( // Queue the validators whose eligible to activate and sort them by activation eligibility epoch number. // Additionally, determine those validators queued to exit awaitingExit := make([]uint64, 0) - exitEpochs := make([]uint64, 0) + exitEpochs := make([]types.Epoch, 0) activationQ := make([]uint64, 0) vals := headState.Validators() for idx, validator := range vals { @@ -592,7 +593,7 @@ func (bs *Server) GetValidatorQueue( return nil, status.Errorf(codes.Internal, "Could not compute churn limit: %v", err) } - exitQueueEpoch := uint64(0) + exitQueueEpoch := types.Epoch(0) for _, i := range exitEpochs { if exitQueueEpoch < i { exitQueueEpoch = i @@ -877,7 +878,7 @@ func (bs *Server) isSlotCanonical(ctx context.Context, slot uint64) (bool, error } // Determines whether a validator has already exited. -func validatorHasExited(validator *ethpb.Validator, currentEpoch uint64) bool { +func validatorHasExited(validator *ethpb.Validator, currentEpoch types.Epoch) bool { farFutureEpoch := params.BeaconConfig().FarFutureEpoch if currentEpoch < validator.ActivationEligibilityEpoch { return false @@ -897,7 +898,7 @@ func validatorHasExited(validator *ethpb.Validator, currentEpoch uint64) bool { return true } -func validatorStatus(validator *ethpb.Validator, epoch uint64) ethpb.ValidatorStatus { +func validatorStatus(validator *ethpb.Validator, epoch types.Epoch) ethpb.ValidatorStatus { farFutureEpoch := params.BeaconConfig().FarFutureEpoch if validator == nil { return ethpb.ValidatorStatus_UNKNOWN_STATUS diff --git a/beacon-chain/rpc/beacon/validators_stream.go b/beacon-chain/rpc/beacon/validators_stream.go index 5c5862a97c..1b6d0a686f 100644 --- a/beacon-chain/rpc/beacon/validators_stream.go +++ b/beacon-chain/rpc/beacon/validators_stream.go @@ -13,6 +13,7 @@ import ( "github.com/patrickmn/go-cache" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/blockchain" "github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache" @@ -44,7 +45,7 @@ type infostream struct { eth1DepositsMutex *sync.RWMutex eth1Blocktimes *cache.Cache eth1BlocktimesMutex *sync.RWMutex - currentEpoch uint64 + currentEpoch types.Epoch stream ethpb.BeaconChain_StreamValidatorsInfoServer genesisTime uint64 } @@ -117,7 +118,7 @@ func (bs *Server) StreamValidatorsInfo(stream ethpb.BeaconChain_StreamValidators eth1DepositsMutex: &sync.RWMutex{}, eth1Blocktimes: cache.New(epochDuration*12, epochDuration*24), eth1BlocktimesMutex: &sync.RWMutex{}, - currentEpoch: headState.Slot() / params.BeaconConfig().SlotsPerEpoch, + currentEpoch: types.Epoch(headState.Slot() / params.BeaconConfig().SlotsPerEpoch), stream: stream, genesisTime: headState.GenesisTime(), } @@ -262,7 +263,7 @@ func (is *infostream) generateValidatorsInfo(pubKeys [][]byte) ([]*ethpb.Validat if headState == nil { return nil, status.Error(codes.Internal, "Not ready to serve information") } - epoch := headState.Slot() / params.BeaconConfig().SlotsPerEpoch + epoch := types.Epoch(headState.Slot() / params.BeaconConfig().SlotsPerEpoch) if epoch == 0 { // Not reporting, but no error. return nil, nil @@ -297,7 +298,7 @@ func (is *infostream) generateValidatorsInfo(pubKeys [][]byte) ([]*ethpb.Validat } // generateValidatorInfo generates the validator info for a public key. -func (is *infostream) generateValidatorInfo(pubKey []byte, validator state.ReadOnlyValidator, headState *state.BeaconState, epoch uint64) (*ethpb.ValidatorInfo, error) { +func (is *infostream) generateValidatorInfo(pubKey []byte, validator state.ReadOnlyValidator, headState *state.BeaconState, epoch types.Epoch) (*ethpb.ValidatorInfo, error) { info := ðpb.ValidatorInfo{ PublicKey: pubKey, Epoch: epoch, @@ -367,7 +368,7 @@ func (is *infostream) generatePendingValidatorInfo(info *ethpb.ValidatorInfo) (* return info, nil } -func (is *infostream) calculateActivationTimeForPendingValidators(res []*ethpb.ValidatorInfo, headState *state.BeaconState, epoch uint64) error { +func (is *infostream) calculateActivationTimeForPendingValidators(res []*ethpb.ValidatorInfo, headState *state.BeaconState, epoch types.Epoch) error { // pendingValidatorsMap is map from the validator pubkey to the index in our return array pendingValidatorsMap := make(map[[48]byte]int) for i, info := range res { @@ -448,7 +449,7 @@ func (is *infostream) handleBlockProcessed() { // We aren't ready to serve information return } - blockEpoch := headState.Slot() / params.BeaconConfig().SlotsPerEpoch + blockEpoch := types.Epoch(headState.Slot() / params.BeaconConfig().SlotsPerEpoch) if blockEpoch == is.currentEpoch { // Epoch hasn't changed, nothing to report yet. return @@ -470,7 +471,7 @@ func (s indicesSorter) Less(i, j int) bool { return s.indices[i] < s.indices[j] } -func (is *infostream) calculateStatusAndTransition(validator state.ReadOnlyValidator, currentEpoch uint64) (ethpb.ValidatorStatus, uint64) { +func (is *infostream) calculateStatusAndTransition(validator state.ReadOnlyValidator, currentEpoch types.Epoch) (ethpb.ValidatorStatus, uint64) { farFutureEpoch := params.BeaconConfig().FarFutureEpoch if validator.IsNil() { @@ -499,8 +500,8 @@ func (is *infostream) calculateStatusAndTransition(validator state.ReadOnlyValid } // epochToTimestamp converts an epoch number to a timestamp. -func (is *infostream) epochToTimestamp(epoch uint64) uint64 { - return is.genesisTime + epoch*params.BeaconConfig().SecondsPerSlot*params.BeaconConfig().SlotsPerEpoch +func (is *infostream) epochToTimestamp(epoch types.Epoch) uint64 { + return is.genesisTime + uint64(epoch)*params.BeaconConfig().SecondsPerSlot*params.BeaconConfig().SlotsPerEpoch } // depositQueueTimestamp calculates the timestamp for exit of the validator from the deposit queue. @@ -531,7 +532,7 @@ func (is *infostream) depositQueueTimestamp(eth1BlockNumber *big.Int) (uint64, e followTime := time.Duration(params.BeaconConfig().Eth1FollowDistance*params.BeaconConfig().SecondsPerETH1Block) * time.Second eth1UnixTime := time.Unix(int64(blockTimestamp), 0).Add(followTime) - period := params.BeaconConfig().SlotsPerEpoch * params.BeaconConfig().EpochsPerEth1VotingPeriod + period := uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod.Mul(params.BeaconConfig().SlotsPerEpoch)) votingPeriod := time.Duration(period*params.BeaconConfig().SecondsPerSlot) * time.Second activationTime := eth1UnixTime.Add(votingPeriod) eth2Genesis := time.Unix(int64(is.genesisTime), 0) diff --git a/beacon-chain/rpc/beacon/validators_stream_test.go b/beacon-chain/rpc/beacon/validators_stream_test.go index 332d567d24..10b3b2ada5 100644 --- a/beacon-chain/rpc/beacon/validators_stream_test.go +++ b/beacon-chain/rpc/beacon/validators_stream_test.go @@ -4,6 +4,7 @@ import ( "sync" "testing" + "github.com/prysmaticlabs/eth2-types" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/testutil" @@ -16,7 +17,7 @@ func TestInfostream_EpochToTimestamp(t *testing.T) { params.OverrideBeaconConfig(params.MainnetConfig()) tests := []struct { name string - epoch uint64 + epoch types.Epoch timestamp uint64 }{ { diff --git a/beacon-chain/rpc/beacon/validators_test.go b/beacon-chain/rpc/beacon/validators_test.go index a9de98e422..8f6f6a1ca0 100644 --- a/beacon-chain/rpc/beacon/validators_test.go +++ b/beacon-chain/rpc/beacon/validators_test.go @@ -11,6 +11,7 @@ import ( "github.com/gogo/protobuf/proto" ptypes "github.com/gogo/protobuf/types" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" @@ -968,11 +969,11 @@ func TestServer_ListValidators_FromOldEpoch(t *testing.T) { beaconDB := dbTest.SetupDB(t) ctx := context.Background() - numEpochs := 30 + numEpochs := types.Epoch(30) validators := make([]*ethpb.Validator, numEpochs) - for i := 0; i < numEpochs; i++ { + for i := types.Epoch(0); i < numEpochs; i++ { validators[i] = ðpb.Validator{ - ActivationEpoch: uint64(i), + ActivationEpoch: i, PublicKey: make([]byte, 48), WithdrawalCredentials: make([]byte, 32), } @@ -1089,11 +1090,11 @@ func TestServer_ListValidators_ProcessHeadStateSlots(t *testing.T) { } func TestServer_GetValidator(t *testing.T) { - count := 30 + count := types.Epoch(30) validators := make([]*ethpb.Validator, count) - for i := 0; i < count; i++ { + for i := types.Epoch(0); i < count; i++ { validators[i] = ðpb.Validator{ - ActivationEpoch: uint64(i), + ActivationEpoch: i, PublicKey: pubKey(uint64(i)), WithdrawalCredentials: make([]byte, 32), } @@ -1359,7 +1360,7 @@ func TestServer_GetValidatorQueue_ExitedValidatorLeavesQueue(t *testing.T) { // Now, we move the state.slot past the exit epoch of the validator, and now // the validator should no longer exist in the queue. - require.NoError(t, headState.SetSlot((validators[1].ExitEpoch+1)*params.BeaconConfig().SlotsPerEpoch)) + require.NoError(t, headState.SetSlot(uint64(validators[1].ExitEpoch+1)*params.BeaconConfig().SlotsPerEpoch)) res, err = bs.GetValidatorQueue(context.Background(), &ptypes.Empty{}) require.NoError(t, err) assert.Equal(t, 0, len(res.ExitPublicKeys)) @@ -1451,8 +1452,8 @@ func TestServer_GetValidatorParticipation_UnknownState(t *testing.T) { headState, err := testutil.NewBeaconState() require.NoError(t, err) require.NoError(t, headState.SetSlot(0)) - epoch := uint64(50) - slots := epoch * params.BeaconConfig().SlotsPerEpoch + epoch := types.Epoch(50) + slots := uint64(epoch) * params.BeaconConfig().SlotsPerEpoch bs := &Server{ BeaconDB: beaconDB, HeadFetcher: &mock.ChainService{ @@ -1642,10 +1643,10 @@ func TestGetValidatorPerformance_Syncing(t *testing.T) { func TestGetValidatorPerformance_OK(t *testing.T) { ctx := context.Background() - epoch := uint64(1) + epoch := types.Epoch(1) headState, err := testutil.NewBeaconState() require.NoError(t, err) - require.NoError(t, headState.SetSlot((epoch+1)*params.BeaconConfig().SlotsPerEpoch)) + require.NoError(t, headState.SetSlot(uint64(epoch+1)*params.BeaconConfig().SlotsPerEpoch)) atts := make([]*pb.PendingAttestation, 3) for i := 0; i < len(atts); i++ { atts[i] = &pb.PendingAttestation{ @@ -1693,7 +1694,7 @@ func TestGetValidatorPerformance_OK(t *testing.T) { GenesisTimeFetcher: &mock.ChainService{Genesis: time.Now().Add(time.Duration(-1*int64(headState.Slot()*params.BeaconConfig().SecondsPerSlot)) * time.Second)}, SyncChecker: &mockSync.Sync{IsSyncing: false}, } - farFuture := params.BeaconConfig().FarFutureEpoch + farFuture := uint64(params.BeaconConfig().FarFutureEpoch) want := ðpb.ValidatorPerformanceResponse{ PublicKeys: [][]byte{publicKey2[:], publicKey3[:]}, CurrentEffectiveBalances: []uint64{params.BeaconConfig().MaxEffectiveBalance, params.BeaconConfig().MaxEffectiveBalance}, @@ -1718,12 +1719,12 @@ func TestGetValidatorPerformance_OK(t *testing.T) { func TestGetValidatorPerformance_Indices(t *testing.T) { ctx := context.Background() - epoch := uint64(1) + epoch := types.Epoch(1) defaultBal := params.BeaconConfig().MaxEffectiveBalance extraBal := params.BeaconConfig().MaxEffectiveBalance + params.BeaconConfig().GweiPerEth headState, err := testutil.NewBeaconState() require.NoError(t, err) - require.NoError(t, headState.SetSlot((epoch+1)*params.BeaconConfig().SlotsPerEpoch)) + require.NoError(t, headState.SetSlot(uint64(epoch+1)*params.BeaconConfig().SlotsPerEpoch)) balances := []uint64{defaultBal, extraBal, extraBal + params.BeaconConfig().GweiPerEth} require.NoError(t, headState.SetBalances(balances)) publicKey1 := bytesutil.ToBytes48([]byte{1}) @@ -1764,7 +1765,7 @@ func TestGetValidatorPerformance_Indices(t *testing.T) { require.NoError(t, err) _, err = precompute.ProcessRewardsAndPenaltiesPrecompute(c, bp, vp) require.NoError(t, err) - farFuture := params.BeaconConfig().FarFutureEpoch + farFuture := uint64(params.BeaconConfig().FarFutureEpoch) want := ðpb.ValidatorPerformanceResponse{ PublicKeys: [][]byte{publicKey2[:], publicKey3[:]}, CurrentEffectiveBalances: []uint64{params.BeaconConfig().MaxEffectiveBalance, params.BeaconConfig().MaxEffectiveBalance}, @@ -1789,12 +1790,12 @@ func TestGetValidatorPerformance_Indices(t *testing.T) { func TestGetValidatorPerformance_IndicesPubkeys(t *testing.T) { ctx := context.Background() - epoch := uint64(1) + epoch := types.Epoch(1) defaultBal := params.BeaconConfig().MaxEffectiveBalance extraBal := params.BeaconConfig().MaxEffectiveBalance + params.BeaconConfig().GweiPerEth headState, err := testutil.NewBeaconState() require.NoError(t, err) - require.NoError(t, headState.SetSlot((epoch+1)*params.BeaconConfig().SlotsPerEpoch)) + require.NoError(t, headState.SetSlot(uint64(epoch+1)*params.BeaconConfig().SlotsPerEpoch)) balances := []uint64{defaultBal, extraBal, extraBal + params.BeaconConfig().GweiPerEth} require.NoError(t, headState.SetBalances(balances)) publicKey1 := bytesutil.ToBytes48([]byte{1}) @@ -1836,7 +1837,7 @@ func TestGetValidatorPerformance_IndicesPubkeys(t *testing.T) { require.NoError(t, err) _, err = precompute.ProcessRewardsAndPenaltiesPrecompute(c, bp, vp) require.NoError(t, err) - farFuture := params.BeaconConfig().FarFutureEpoch + farFuture := uint64(params.BeaconConfig().FarFutureEpoch) want := ðpb.ValidatorPerformanceResponse{ PublicKeys: [][]byte{publicKey2[:], publicKey3[:]}, CurrentEffectiveBalances: []uint64{params.BeaconConfig().MaxEffectiveBalance, params.BeaconConfig().MaxEffectiveBalance}, @@ -2040,10 +2041,24 @@ func TestServer_GetIndividualVotes_Working(t *testing.T) { require.NoError(t, err) wanted := ðpb.IndividualVotesRespond{ IndividualVotes: []*ethpb.IndividualVotesRespond_IndividualVote{ - {ValidatorIndex: 0, PublicKey: beaconState.Validators()[0].PublicKey, IsActiveInCurrentEpoch: true, IsActiveInPreviousEpoch: true, - CurrentEpochEffectiveBalanceGwei: params.BeaconConfig().MaxEffectiveBalance, InclusionSlot: params.BeaconConfig().FarFutureEpoch, InclusionDistance: params.BeaconConfig().FarFutureEpoch}, - {ValidatorIndex: 1, PublicKey: beaconState.Validators()[1].PublicKey, IsActiveInCurrentEpoch: true, IsActiveInPreviousEpoch: true, - CurrentEpochEffectiveBalanceGwei: params.BeaconConfig().MaxEffectiveBalance, InclusionSlot: params.BeaconConfig().FarFutureEpoch, InclusionDistance: params.BeaconConfig().FarFutureEpoch}, + { + ValidatorIndex: 0, + PublicKey: beaconState.Validators()[0].PublicKey, + IsActiveInCurrentEpoch: true, + IsActiveInPreviousEpoch: true, + CurrentEpochEffectiveBalanceGwei: params.BeaconConfig().MaxEffectiveBalance, + InclusionSlot: uint64(params.BeaconConfig().FarFutureEpoch), + InclusionDistance: uint64(params.BeaconConfig().FarFutureEpoch), + }, + { + ValidatorIndex: 1, + PublicKey: beaconState.Validators()[1].PublicKey, + IsActiveInCurrentEpoch: true, + IsActiveInPreviousEpoch: true, + CurrentEpochEffectiveBalanceGwei: params.BeaconConfig().MaxEffectiveBalance, + InclusionSlot: uint64(params.BeaconConfig().FarFutureEpoch), + InclusionDistance: uint64(params.BeaconConfig().FarFutureEpoch), + }, }, } assert.DeepEqual(t, wanted, res, "Unexpected response") @@ -2053,7 +2068,7 @@ func Test_validatorStatus(t *testing.T) { tests := []struct { name string validator *ethpb.Validator - epoch uint64 + epoch types.Epoch want ethpb.ValidatorStatus }{ { @@ -2065,7 +2080,7 @@ func Test_validatorStatus(t *testing.T) { { name: "Deposited", validator: ðpb.Validator{ - ActivationEligibilityEpoch: uint64(1), + ActivationEligibilityEpoch: 1, }, epoch: 0, want: ethpb.ValidatorStatus_DEPOSITED, @@ -2073,8 +2088,8 @@ func Test_validatorStatus(t *testing.T) { { name: "Pending", validator: ðpb.Validator{ - ActivationEligibilityEpoch: uint64(0), - ActivationEpoch: uint64(1), + ActivationEligibilityEpoch: 0, + ActivationEpoch: 1, }, epoch: 0, want: ethpb.ValidatorStatus_PENDING, @@ -2082,8 +2097,8 @@ func Test_validatorStatus(t *testing.T) { { name: "Active", validator: ðpb.Validator{ - ActivationEligibilityEpoch: uint64(0), - ActivationEpoch: uint64(0), + ActivationEligibilityEpoch: 0, + ActivationEpoch: 0, ExitEpoch: params.BeaconConfig().FarFutureEpoch, }, epoch: 0, @@ -2092,9 +2107,9 @@ func Test_validatorStatus(t *testing.T) { { name: "Slashed", validator: ðpb.Validator{ - ActivationEligibilityEpoch: uint64(0), - ActivationEpoch: uint64(0), - ExitEpoch: uint64(5), + ActivationEligibilityEpoch: 0, + ActivationEpoch: 0, + ExitEpoch: 5, Slashed: true, }, epoch: 4, @@ -2103,9 +2118,9 @@ func Test_validatorStatus(t *testing.T) { { name: "Exiting", validator: ðpb.Validator{ - ActivationEligibilityEpoch: uint64(0), - ActivationEpoch: uint64(0), - ExitEpoch: uint64(5), + ActivationEligibilityEpoch: 0, + ActivationEpoch: 0, + ExitEpoch: 5, Slashed: false, }, epoch: 4, @@ -2114,9 +2129,9 @@ func Test_validatorStatus(t *testing.T) { { name: "Exiting", validator: ðpb.Validator{ - ActivationEligibilityEpoch: uint64(0), - ActivationEpoch: uint64(0), - ExitEpoch: uint64(3), + ActivationEligibilityEpoch: 0, + ActivationEpoch: 0, + ExitEpoch: 3, Slashed: false, }, epoch: 4, diff --git a/beacon-chain/rpc/beaconv1/BUILD.bazel b/beacon-chain/rpc/beaconv1/BUILD.bazel index 13d83d7104..444f5bd131 100644 --- a/beacon-chain/rpc/beaconv1/BUILD.bazel +++ b/beacon-chain/rpc/beaconv1/BUILD.bazel @@ -36,6 +36,7 @@ go_library( "@com_github_ethereum_go_ethereum//common/hexutil:go_default_library", "@com_github_gogo_protobuf//types:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", @@ -68,6 +69,7 @@ go_test( "//shared/testutil/assert:go_default_library", "//shared/testutil/require:go_default_library", "@com_github_gogo_protobuf//types:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", ], diff --git a/beacon-chain/rpc/beaconv1/config.go b/beacon-chain/rpc/beaconv1/config.go index 2f81cf3092..2379bdd4d7 100644 --- a/beacon-chain/rpc/beaconv1/config.go +++ b/beacon-chain/rpc/beaconv1/config.go @@ -10,6 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" ptypes "github.com/gogo/protobuf/types" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1" "github.com/prysmaticlabs/prysm/shared/params" "go.opencensus.io/trace" @@ -79,8 +80,8 @@ func (bs *Server) GetDepositContract(ctx context.Context, _ *ptypes.Empty) (*eth }, nil } -func sortedEpochs(forkSchedule map[uint64][]byte) []uint64 { - sortedEpochs := make([]uint64, len(forkSchedule)) +func sortedEpochs(forkSchedule map[types.Epoch][]byte) []types.Epoch { + sortedEpochs := make([]types.Epoch, len(forkSchedule)) i := 0 for k := range forkSchedule { sortedEpochs[i] = k diff --git a/beacon-chain/rpc/beaconv1/config_test.go b/beacon-chain/rpc/beaconv1/config_test.go index 5dad81fb6c..3756955b22 100644 --- a/beacon-chain/rpc/beaconv1/config_test.go +++ b/beacon-chain/rpc/beaconv1/config_test.go @@ -4,7 +4,8 @@ import ( "context" "testing" - "github.com/gogo/protobuf/types" + pbtypes "github.com/gogo/protobuf/types" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/require" @@ -93,7 +94,7 @@ func TestGetSpec(t *testing.T) { params.OverrideBeaconConfig(config) server := &Server{} - resp, err := server.GetSpec(context.Background(), &types.Empty{}) + resp, err := server.GetSpec(context.Background(), &pbtypes.Empty{}) require.NoError(t, err) assert.Equal(t, 60, len(resp.Data)) @@ -235,7 +236,7 @@ func TestGetDepositContract(t *testing.T) { params.OverrideBeaconConfig(config) s := Server{} - resp, err := s.GetDepositContract(context.Background(), &types.Empty{}) + resp, err := s.GetDepositContract(context.Background(), &pbtypes.Empty{}) require.NoError(t, err) assert.Equal(t, uint64(chainId), resp.Data.ChainId) assert.Equal(t, address, resp.Data.Address) @@ -243,15 +244,15 @@ func TestGetDepositContract(t *testing.T) { func TestForkSchedule_Ok(t *testing.T) { genesisForkVersion := []byte("Genesis") - firstForkVersion, firstForkEpoch := []byte("First"), uint64(100) - secondForkVersion, secondForkEpoch := []byte("Second"), uint64(200) - thirdForkVersion, thirdForkEpoch := []byte("Third"), uint64(300) + firstForkVersion, firstForkEpoch := []byte("First"), types.Epoch(100) + secondForkVersion, secondForkEpoch := []byte("Second"), types.Epoch(200) + thirdForkVersion, thirdForkEpoch := []byte("Third"), types.Epoch(300) params.SetupTestConfigCleanup(t) config := params.BeaconConfig() config.GenesisForkVersion = genesisForkVersion // Create fork schedule adding keys in non-sorted order. - schedule := make(map[uint64][]byte, 3) + schedule := make(map[types.Epoch][]byte, 3) schedule[secondForkEpoch] = secondForkVersion schedule[firstForkEpoch] = firstForkVersion schedule[thirdForkEpoch] = thirdForkVersion @@ -259,7 +260,7 @@ func TestForkSchedule_Ok(t *testing.T) { params.OverrideBeaconConfig(config) s := &Server{} - resp, err := s.GetForkSchedule(context.Background(), &types.Empty{}) + resp, err := s.GetForkSchedule(context.Background(), &pbtypes.Empty{}) require.NoError(t, err) require.Equal(t, 3, len(resp.Data)) fork := resp.Data[0] @@ -278,7 +279,7 @@ func TestForkSchedule_Ok(t *testing.T) { func TestForkSchedule_NoForks(t *testing.T) { s := &Server{} - resp, err := s.GetForkSchedule(context.Background(), &types.Empty{}) + resp, err := s.GetForkSchedule(context.Background(), &pbtypes.Empty{}) require.NoError(t, err) assert.Equal(t, 0, len(resp.Data)) } diff --git a/beacon-chain/rpc/beaconv1/state.go b/beacon-chain/rpc/beaconv1/state.go index e632ef3846..35f88d0417 100644 --- a/beacon-chain/rpc/beaconv1/state.go +++ b/beacon-chain/rpc/beaconv1/state.go @@ -29,12 +29,15 @@ func (bs *Server) GetGenesis(ctx context.Context, _ *ptypes.Empty) (*ethpb.Genes forkVersion := params.BeaconConfig().GenesisForkVersion return ðpb.GenesisResponse{ - GenesisTime: &ptypes.Timestamp{ - Seconds: genesisTime.Unix(), - Nanos: 0, + Data: ðpb.GenesisResponse_Genesis{ + + GenesisTime: &ptypes.Timestamp{ + Seconds: genesisTime.Unix(), + Nanos: 0, + }, + GenesisValidatorsRoot: validatorRoot[:], + GenesisForkVersion: forkVersion, }, - GenesisValidatorsRoot: validatorRoot[:], - GenesisForkVersion: forkVersion, }, nil } diff --git a/beacon-chain/rpc/beaconv1/state_test.go b/beacon-chain/rpc/beaconv1/state_test.go index f7e895ec3c..6539f9f1eb 100644 --- a/beacon-chain/rpc/beaconv1/state_test.go +++ b/beacon-chain/rpc/beaconv1/state_test.go @@ -31,10 +31,10 @@ func TestGetGenesis(t *testing.T) { } resp, err := s.GetGenesis(context.Background(), &ptypes.Empty{}) require.NoError(t, err) - assert.Equal(t, genesis.Unix(), resp.GenesisTime.Seconds) - assert.Equal(t, int32(0), resp.GenesisTime.Nanos) - assert.DeepEqual(t, validatorsRoot[:], resp.GenesisValidatorsRoot) - assert.DeepEqual(t, []byte("genesis"), resp.GenesisForkVersion) + assert.Equal(t, genesis.Unix(), resp.Data.GenesisTime.Seconds) + assert.Equal(t, int32(0), resp.Data.GenesisTime.Nanos) + assert.DeepEqual(t, validatorsRoot[:], resp.Data.GenesisValidatorsRoot) + assert.DeepEqual(t, []byte("genesis"), resp.Data.GenesisForkVersion) }) t.Run("No genesis time", func(t *testing.T) { diff --git a/beacon-chain/rpc/debug/block_test.go b/beacon-chain/rpc/debug/block_test.go index 002202d251..f2fb82a23c 100644 --- a/beacon-chain/rpc/debug/block_test.go +++ b/beacon-chain/rpc/debug/block_test.go @@ -82,5 +82,5 @@ func TestServer_GetAttestationInclusionSlot(t *testing.T) { require.Equal(t, b.Block.Slot, res.Slot) res, err = bs.GetInclusionSlot(ctx, &pbrpc.InclusionSlotRequest{Slot: 1, Id: 9999999}) require.NoError(t, err) - require.Equal(t, params.BeaconConfig().FarFutureEpoch, res.Slot) + require.Equal(t, uint64(params.BeaconConfig().FarFutureEpoch), res.Slot) } diff --git a/beacon-chain/rpc/validator/BUILD.bazel b/beacon-chain/rpc/validator/BUILD.bazel index 57a1e58722..2c39964bea 100644 --- a/beacon-chain/rpc/validator/BUILD.bazel +++ b/beacon-chain/rpc/validator/BUILD.bazel @@ -54,6 +54,7 @@ go_library( "@com_github_ferranbt_fastssz//:go_default_library", "@com_github_gogo_protobuf//types:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@io_opencensus_go//trace:go_default_library", @@ -114,6 +115,7 @@ go_test( "@com_github_gogo_protobuf//proto:go_default_library", "@com_github_gogo_protobuf//types:go_default_library", "@com_github_golang_mock//gomock:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", diff --git a/beacon-chain/rpc/validator/assignments.go b/beacon-chain/rpc/validator/assignments.go index eb5f0aa445..5f9eb6dc8d 100644 --- a/beacon-chain/rpc/validator/assignments.go +++ b/beacon-chain/rpc/validator/assignments.go @@ -4,6 +4,7 @@ import ( "context" "time" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/cache" "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" @@ -42,7 +43,7 @@ func (vs *Server) StreamDuties(req *ethpb.DutiesRequest, stream ethpb.BeaconNode if genesisTime.IsZero() { return status.Error(codes.Unavailable, "genesis time is not set") } - var currentEpoch uint64 + var currentEpoch types.Epoch if genesisTime.Before(timeutils.Now()) { currentEpoch = slotutil.EpochsSinceGenesis(vs.TimeFetcher.GenesisTime()) } @@ -65,8 +66,8 @@ func (vs *Server) StreamDuties(req *ethpb.DutiesRequest, stream ethpb.BeaconNode for { select { // Ticks every epoch to submit assignments to connected validator clients. - case epoch := <-epochTicker.C(): - req.Epoch = epoch + case slot := <-epochTicker.C(): + req.Epoch = types.Epoch(slot) res, err := vs.duties(stream.Context(), req) if err != nil { return status.Errorf(codes.Internal, "Could not compute validator duties: %v", err) diff --git a/beacon-chain/rpc/validator/assignments_test.go b/beacon-chain/rpc/validator/assignments_test.go index e8d3d5f244..422ed72634 100644 --- a/beacon-chain/rpc/validator/assignments_test.go +++ b/beacon-chain/rpc/validator/assignments_test.go @@ -7,6 +7,7 @@ import ( "time" "github.com/golang/mock/gomock" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" mockChain "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/cache" @@ -109,7 +110,7 @@ func TestGetDuties_SlotOutOfUpperBound(t *testing.T) { TimeFetcher: chain, } req := ðpb.DutiesRequest{ - Epoch: chain.CurrentSlot()/params.BeaconConfig().SlotsPerEpoch + 2, + Epoch: types.Epoch(chain.CurrentSlot()/params.BeaconConfig().SlotsPerEpoch + 2), } _, err := vs.duties(context.Background(), req) require.ErrorContains(t, "can not be greater than next epoch", err) diff --git a/beacon-chain/rpc/validator/exit_test.go b/beacon-chain/rpc/validator/exit_test.go index 9b68dcda94..7cd5e307c2 100644 --- a/beacon-chain/rpc/validator/exit_test.go +++ b/beacon-chain/rpc/validator/exit_test.go @@ -5,6 +5,7 @@ import ( "testing" "time" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" mockChain "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/feed" @@ -30,8 +31,8 @@ func TestProposeExit_Notification(t *testing.T) { require.NoError(t, err) beaconState, err := state.GenesisBeaconState(deposits, 0, ðpb.Eth1Data{BlockHash: make([]byte, 32)}) require.NoError(t, err) - epoch := uint64(2048) - require.NoError(t, beaconState.SetSlot(epoch*params.BeaconConfig().SlotsPerEpoch)) + epoch := types.Epoch(2048) + require.NoError(t, beaconState.SetSlot(uint64(epoch)*params.BeaconConfig().SlotsPerEpoch)) block := testutil.NewBeaconBlock() require.NoError(t, db.SaveBlock(ctx, block), "Could not save genesis block") genesisRoot, err := block.Block.HashTreeRoot() @@ -100,8 +101,8 @@ func TestProposeExit_NoPanic(t *testing.T) { require.NoError(t, err) beaconState, err := state.GenesisBeaconState(deposits, 0, ðpb.Eth1Data{BlockHash: make([]byte, 32)}) require.NoError(t, err) - epoch := uint64(2048) - require.NoError(t, beaconState.SetSlot(epoch*params.BeaconConfig().SlotsPerEpoch)) + epoch := types.Epoch(2048) + require.NoError(t, beaconState.SetSlot(uint64(epoch)*params.BeaconConfig().SlotsPerEpoch)) block := testutil.NewBeaconBlock() require.NoError(t, db.SaveBlock(ctx, block), "Could not save genesis block") genesisRoot, err := block.Block.HashTreeRoot() diff --git a/beacon-chain/rpc/validator/proposer.go b/beacon-chain/rpc/validator/proposer.go index 8f03ddd80d..3bca0e5963 100644 --- a/beacon-chain/rpc/validator/proposer.go +++ b/beacon-chain/rpc/validator/proposer.go @@ -371,13 +371,13 @@ func (vs *Server) mockETH1DataVote(ctx context.Context, slot uint64) (*ethpb.Eth // DepositCount = state.eth1_deposit_index, // BlockHash = hash(hash(current_epoch + slot_in_voting_period)), // ) - slotInVotingPeriod := slot % (params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch) + slotInVotingPeriod := slot % (uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod) * params.BeaconConfig().SlotsPerEpoch) headState, err := vs.HeadFetcher.HeadState(ctx) if err != nil { return nil, err } var enc []byte - enc = fastssz.MarshalUint64(enc, helpers.SlotToEpoch(slot)+slotInVotingPeriod) + enc = fastssz.MarshalUint64(enc, uint64(helpers.SlotToEpoch(slot))+slotInVotingPeriod) depRoot := hashutil.Hash(enc) blockHash := hashutil.Hash(depRoot[:]) return ðpb.Eth1Data{ diff --git a/beacon-chain/rpc/validator/proposer_test.go b/beacon-chain/rpc/validator/proposer_test.go index b84f3a30f0..12bd0afc53 100644 --- a/beacon-chain/rpc/validator/proposer_test.go +++ b/beacon-chain/rpc/validator/proposer_test.go @@ -309,7 +309,7 @@ func TestProposer_PendingDeposits_Eth1DataVoteOK(t *testing.T) { BlockHash: blockHash, DepositCount: 3, } - period := params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch + period := uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod) * params.BeaconConfig().SlotsPerEpoch for i := 0; i <= int(period/2); i++ { votes = append(votes, vote) } @@ -501,7 +501,7 @@ func TestProposer_PendingDeposits_FollowsCorrectEth1Block(t *testing.T) { DepositRoot: make([]byte, 32), DepositCount: 7, } - period := params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch + period := uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod) * params.BeaconConfig().SlotsPerEpoch for i := 0; i <= int(period/2); i++ { votes = append(votes, vote) } @@ -1217,11 +1217,11 @@ func TestProposer_Eth1Data_MockEnabled(t *testing.T) { eth1Data, err := ps.eth1Data(ctx, 100) require.NoError(t, err) - period := params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch + period := uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod) * params.BeaconConfig().SlotsPerEpoch wantedSlot := 100 % period currentEpoch := helpers.SlotToEpoch(100) var enc []byte - enc = fastssz.MarshalUint64(enc, currentEpoch+wantedSlot) + enc = fastssz.MarshalUint64(enc, uint64(currentEpoch)+wantedSlot) depRoot := hashutil.Hash(enc) blockHash := hashutil.Hash(depRoot[:]) want := ðpb.Eth1Data{ @@ -2086,7 +2086,7 @@ func TestProposer_DeleteAttsInPool_Aggregated(t *testing.T) { func majorityVoteBoundaryTime(slot uint64) (uint64, uint64) { slotStartTime := uint64(mockPOW.GenesisTime) + - (slot-(slot%(params.BeaconConfig().EpochsPerEth1VotingPeriod*params.BeaconConfig().SlotsPerEpoch)))* + (slot-(slot%(uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod)*params.BeaconConfig().SlotsPerEpoch)))* params.BeaconConfig().SecondsPerSlot earliestValidTime := slotStartTime - 2*params.BeaconConfig().SecondsPerETH1Block*params.BeaconConfig().Eth1FollowDistance latestValidTime := slotStartTime - params.BeaconConfig().SecondsPerETH1Block*params.BeaconConfig().Eth1FollowDistance diff --git a/beacon-chain/rpc/validator/status_test.go b/beacon-chain/rpc/validator/status_test.go index 5847b3732e..846da502bf 100644 --- a/beacon-chain/rpc/validator/status_test.go +++ b/beacon-chain/rpc/validator/status_test.go @@ -6,6 +6,7 @@ import ( "time" "github.com/gogo/protobuf/proto" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" mockChain "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache" @@ -594,7 +595,7 @@ func TestActivationStatus_OK(t *testing.T) { t.Errorf("Validator with pubkey %#x is not unknown and instead has this status: %s", response[2].PublicKey, response[2].Status.Status.String()) } - if response[2].Index != params.BeaconConfig().FarFutureEpoch { + if response[2].Index != uint64(params.BeaconConfig().FarFutureEpoch) { t.Errorf("Validator with pubkey %#x is expected to have index %d, received %d", response[2].PublicKey, params.BeaconConfig().FarFutureEpoch, response[2].Index) } @@ -648,14 +649,14 @@ func TestValidatorStatus_CorrectActivationQueue(t *testing.T) { WithdrawableEpoch: params.BeaconConfig().FarFutureEpoch, }, { - ActivationEpoch: currentSlot/params.BeaconConfig().SlotsPerEpoch + 1, + ActivationEpoch: types.Epoch(currentSlot/params.BeaconConfig().SlotsPerEpoch + 1), PublicKey: pbKey, WithdrawalCredentials: make([]byte, 32), ExitEpoch: params.BeaconConfig().FarFutureEpoch, WithdrawableEpoch: params.BeaconConfig().FarFutureEpoch, }, { - ActivationEpoch: currentSlot/params.BeaconConfig().SlotsPerEpoch + 4, + ActivationEpoch: types.Epoch(currentSlot/params.BeaconConfig().SlotsPerEpoch + 4), PublicKey: pubKey(5), WithdrawalCredentials: make([]byte, 32), ExitEpoch: params.BeaconConfig().FarFutureEpoch, diff --git a/beacon-chain/state/BUILD.bazel b/beacon-chain/state/BUILD.bazel index 13d75c8d43..555c530a74 100644 --- a/beacon-chain/state/BUILD.bazel +++ b/beacon-chain/state/BUILD.bazel @@ -36,6 +36,7 @@ go_library( "//shared/sliceutil:go_default_library", "@com_github_gogo_protobuf//proto:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@io_opencensus_go//trace:go_default_library", @@ -61,11 +62,11 @@ go_test( "//shared/bytesutil:go_default_library", "//shared/interop:go_default_library", "//shared/params:go_default_library", - "//shared/sszutil:go_default_library", "//shared/testutil:go_default_library", "//shared/testutil/assert:go_default_library", "//shared/testutil/require:go_default_library", "@com_github_gogo_protobuf//proto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", diff --git a/beacon-chain/state/field_trie_test.go b/beacon-chain/state/field_trie_test.go index 8540d22d35..1cfae4b2b6 100644 --- a/beacon-chain/state/field_trie_test.go +++ b/beacon-chain/state/field_trie_test.go @@ -56,7 +56,7 @@ func TestFieldTrie_RecomputeTrie(t *testing.T) { func TestFieldTrie_CopyTrieImmutable(t *testing.T) { newState, _ := testutil.DeterministicGenesisState(t, 32) // 12 represents the enum value of randao mixes. - trie, err := state.NewFieldTrie(13, newState.RandaoMixes(), params.BeaconConfig().EpochsPerHistoricalVector) + trie, err := state.NewFieldTrie(13, newState.RandaoMixes(), uint64(params.BeaconConfig().EpochsPerHistoricalVector)) require.NoError(t, err) newTrie := trie.CopyTrie() diff --git a/beacon-chain/state/getters.go b/beacon-chain/state/getters.go index 0c401fb179..2256044403 100644 --- a/beacon-chain/state/getters.go +++ b/beacon-chain/state/getters.go @@ -5,6 +5,7 @@ import ( "fmt" "time" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/go-bitfield" pbp2p "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" @@ -23,7 +24,7 @@ func (v ReadOnlyValidator) EffectiveBalance() uint64 { // ActivationEligibilityEpoch returns the activation eligibility epoch of the // read only validator. -func (v ReadOnlyValidator) ActivationEligibilityEpoch() uint64 { +func (v ReadOnlyValidator) ActivationEligibilityEpoch() types.Epoch { if v.IsNil() { return 0 } @@ -32,7 +33,7 @@ func (v ReadOnlyValidator) ActivationEligibilityEpoch() uint64 { // ActivationEpoch returns the activation epoch of the // read only validator. -func (v ReadOnlyValidator) ActivationEpoch() uint64 { +func (v ReadOnlyValidator) ActivationEpoch() types.Epoch { if v.IsNil() { return 0 } @@ -41,7 +42,7 @@ func (v ReadOnlyValidator) ActivationEpoch() uint64 { // WithdrawableEpoch returns the withdrawable epoch of the // read only validator. -func (v ReadOnlyValidator) WithdrawableEpoch() uint64 { +func (v ReadOnlyValidator) WithdrawableEpoch() types.Epoch { if v.IsNil() { return 0 } @@ -50,7 +51,7 @@ func (v ReadOnlyValidator) WithdrawableEpoch() uint64 { // ExitEpoch returns the exit epoch of the // read only validator. -func (v ReadOnlyValidator) ExitEpoch() uint64 { +func (v ReadOnlyValidator) ExitEpoch() types.Epoch { if v.IsNil() { return 0 } @@ -1042,7 +1043,7 @@ func (b *BeaconState) finalizedCheckpoint() *ethpb.Checkpoint { } // FinalizedCheckpointEpoch returns the epoch value of the finalized checkpoint. -func (b *BeaconState) FinalizedCheckpointEpoch() uint64 { +func (b *BeaconState) FinalizedCheckpointEpoch() types.Epoch { if !b.HasInnerState() { return 0 } diff --git a/beacon-chain/state/getters_test.go b/beacon-chain/state/getters_test.go index 3560ed1279..5168a42da3 100644 --- a/beacon-chain/state/getters_test.go +++ b/beacon-chain/state/getters_test.go @@ -5,6 +5,7 @@ import ( "sync" "testing" + "github.com/prysmaticlabs/eth2-types" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" "github.com/prysmaticlabs/prysm/shared/testutil/assert" @@ -86,5 +87,5 @@ func TestReadOnlyValidator_NoPanic(t *testing.T) { func TestReadOnlyValidator_ActivationEligibilityEpochNoPanic(t *testing.T) { v := &ReadOnlyValidator{} - assert.Equal(t, uint64(0), v.ActivationEligibilityEpoch(), "Expected 0 and not panic") + assert.Equal(t, types.Epoch(0), v.ActivationEligibilityEpoch(), "Expected 0 and not panic") } diff --git a/beacon-chain/state/state_trie.go b/beacon-chain/state/state_trie.go index 2e5ade99ee..14eb6c8129 100644 --- a/beacon-chain/state/state_trie.go +++ b/beacon-chain/state/state_trie.go @@ -297,7 +297,7 @@ func (b *BeaconState) rootSelector(field fieldIndex) ([32]byte, error) { return stateutil.Eth1Root(hasher, b.state.Eth1Data) case eth1DataVotes: if b.rebuildTrie[field] { - err := b.resetFieldTrie(field, b.state.Eth1DataVotes, params.BeaconConfig().EpochsPerEth1VotingPeriod*params.BeaconConfig().SlotsPerEpoch) + err := b.resetFieldTrie(field, b.state.Eth1DataVotes, uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod.Mul(params.BeaconConfig().SlotsPerEpoch))) if err != nil { return [32]byte{}, err } @@ -321,7 +321,7 @@ func (b *BeaconState) rootSelector(field fieldIndex) ([32]byte, error) { return stateutil.ValidatorBalancesRoot(b.state.Balances) case randaoMixes: if b.rebuildTrie[field] { - err := b.resetFieldTrie(field, b.state.RandaoMixes, params.BeaconConfig().EpochsPerHistoricalVector) + err := b.resetFieldTrie(field, b.state.RandaoMixes, uint64(params.BeaconConfig().EpochsPerHistoricalVector)) if err != nil { return [32]byte{}, err } diff --git a/beacon-chain/state/stateutil/attestations.go b/beacon-chain/state/stateutil/attestations.go index 9eddcd09b3..00b2f24880 100644 --- a/beacon-chain/state/stateutil/attestations.go +++ b/beacon-chain/state/stateutil/attestations.go @@ -67,7 +67,7 @@ func marshalAttestationData(data *ethpb.AttestationData) []byte { // Source epoch and root. if data.Source != nil { sourceEpochBuf := make([]byte, 8) - binary.LittleEndian.PutUint64(sourceEpochBuf, data.Source.Epoch) + binary.LittleEndian.PutUint64(sourceEpochBuf, uint64(data.Source.Epoch)) copy(enc[48:56], sourceEpochBuf) copy(enc[56:88], data.Source.Root) } @@ -75,7 +75,7 @@ func marshalAttestationData(data *ethpb.AttestationData) []byte { // Target. if data.Target != nil { targetEpochBuf := make([]byte, 8) - binary.LittleEndian.PutUint64(targetEpochBuf, data.Target.Epoch) + binary.LittleEndian.PutUint64(targetEpochBuf, uint64(data.Target.Epoch)) copy(enc[88:96], targetEpochBuf) copy(enc[96:128], data.Target.Root) } diff --git a/beacon-chain/state/stateutil/blocks.go b/beacon-chain/state/stateutil/blocks.go index ad56daafc3..ff70c0e079 100644 --- a/beacon-chain/state/stateutil/blocks.go +++ b/beacon-chain/state/stateutil/blocks.go @@ -107,7 +107,7 @@ func Eth1DataVotesRoot(eth1DataVotes []*ethpb.Eth1Data) ([32]byte, error) { hasher, eth1Chunks, uint64(len(eth1Chunks)), - params.BeaconConfig().EpochsPerEth1VotingPeriod*params.BeaconConfig().SlotsPerEpoch, + uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod.Mul(params.BeaconConfig().SlotsPerEpoch)), ) if err != nil { return [32]byte{}, errors.Wrap(err, "could not compute eth1data votes merkleization") diff --git a/beacon-chain/state/stateutil/state_root.go b/beacon-chain/state/stateutil/state_root.go index f992854953..6afe30776c 100644 --- a/beacon-chain/state/stateutil/state_root.go +++ b/beacon-chain/state/stateutil/state_root.go @@ -138,7 +138,7 @@ func (h *stateRootHasher) computeFieldRoots(state *pb.BeaconState) ([][]byte, er fieldRoots[12] = balancesRoot[:] // RandaoMixes array root. - randaoRootsRoot, err := h.arraysRoot(state.RandaoMixes, params.BeaconConfig().EpochsPerHistoricalVector, "RandaoMixes") + randaoRootsRoot, err := h.arraysRoot(state.RandaoMixes, uint64(params.BeaconConfig().EpochsPerHistoricalVector), "RandaoMixes") if err != nil { return nil, errors.Wrap(err, "could not compute randao roots merkleization") } diff --git a/beacon-chain/state/stateutil/validators.go b/beacon-chain/state/stateutil/validators.go index 461838332a..cd113c38c0 100644 --- a/beacon-chain/state/stateutil/validators.go +++ b/beacon-chain/state/stateutil/validators.go @@ -78,16 +78,16 @@ func ValidatorRoot(hasher htrutils.HashFn, validator *ethpb.Validator) ([32]byte slashBuf[0] = uint8(0) } activationEligibilityBuf := [32]byte{} - binary.LittleEndian.PutUint64(activationEligibilityBuf[:8], validator.ActivationEligibilityEpoch) + binary.LittleEndian.PutUint64(activationEligibilityBuf[:8], uint64(validator.ActivationEligibilityEpoch)) activationBuf := [32]byte{} - binary.LittleEndian.PutUint64(activationBuf[:8], validator.ActivationEpoch) + binary.LittleEndian.PutUint64(activationBuf[:8], uint64(validator.ActivationEpoch)) exitBuf := [32]byte{} - binary.LittleEndian.PutUint64(exitBuf[:8], validator.ExitEpoch) + binary.LittleEndian.PutUint64(exitBuf[:8], uint64(validator.ExitEpoch)) withdrawalBuf := [32]byte{} - binary.LittleEndian.PutUint64(withdrawalBuf[:8], validator.WithdrawableEpoch) + binary.LittleEndian.PutUint64(withdrawalBuf[:8], uint64(validator.WithdrawableEpoch)) // Public key. pubKeyChunks, err := htrutils.Pack([][]byte{pubkey[:]}) @@ -164,19 +164,19 @@ func (h *stateRootHasher) validatorRoot(hasher htrutils.HashFn, validator *ethpb enc[88] = uint8(0) } activationEligibilityBuf := [32]byte{} - binary.LittleEndian.PutUint64(activationEligibilityBuf[:8], validator.ActivationEligibilityEpoch) + binary.LittleEndian.PutUint64(activationEligibilityBuf[:8], uint64(validator.ActivationEligibilityEpoch)) copy(enc[89:97], activationEligibilityBuf[:8]) activationBuf := [32]byte{} - binary.LittleEndian.PutUint64(activationBuf[:8], validator.ActivationEpoch) + binary.LittleEndian.PutUint64(activationBuf[:8], uint64(validator.ActivationEpoch)) copy(enc[97:105], activationBuf[:8]) exitBuf := [32]byte{} - binary.LittleEndian.PutUint64(exitBuf[:8], validator.ExitEpoch) + binary.LittleEndian.PutUint64(exitBuf[:8], uint64(validator.ExitEpoch)) copy(enc[105:113], exitBuf[:8]) withdrawalBuf := [32]byte{} - binary.LittleEndian.PutUint64(withdrawalBuf[:8], validator.WithdrawableEpoch) + binary.LittleEndian.PutUint64(withdrawalBuf[:8], uint64(validator.WithdrawableEpoch)) copy(enc[113:121], withdrawalBuf[:8]) // Check if it exists in cache: diff --git a/beacon-chain/state/types_test.go b/beacon-chain/state/types_test.go index 85e551c908..05dfffdb7b 100644 --- a/beacon-chain/state/types_test.go +++ b/beacon-chain/state/types_test.go @@ -13,7 +13,6 @@ import ( "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/interop" "github.com/prysmaticlabs/prysm/shared/params" - "github.com/prysmaticlabs/prysm/shared/sszutil" "github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/require" log "github.com/sirupsen/logrus" @@ -225,7 +224,5 @@ func TestForkManualCopy_OK(t *testing.T) { require.NoError(t, a.SetFork(wantedFork)) newState := a.CloneInnerState() - if !sszutil.DeepEqual(newState.Fork, wantedFork) { - t.Errorf("Wanted %v but got %v", wantedFork, newState.Fork) - } + require.DeepEqual(t, newState.Fork, wantedFork) } diff --git a/beacon-chain/sync/BUILD.bazel b/beacon-chain/sync/BUILD.bazel index 29907f60a6..143a2852e1 100644 --- a/beacon-chain/sync/BUILD.bazel +++ b/beacon-chain/sync/BUILD.bazel @@ -93,6 +93,7 @@ go_library( "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prometheus_client_golang//prometheus/promauto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@com_github_trailofbits_go_mutexasserts//:go_default_library", @@ -177,6 +178,7 @@ go_test( "@com_github_libp2p_go_libp2p_pubsub//:go_default_library", "@com_github_libp2p_go_libp2p_pubsub//pb:go_default_library", "@com_github_patrickmn_go_cache//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", diff --git a/beacon-chain/sync/initial-sync/BUILD.bazel b/beacon-chain/sync/initial-sync/BUILD.bazel index d057b6cb9d..29f392f33e 100644 --- a/beacon-chain/sync/initial-sync/BUILD.bazel +++ b/beacon-chain/sync/initial-sync/BUILD.bazel @@ -41,6 +41,7 @@ go_library( "@com_github_libp2p_go_libp2p_core//peer:go_default_library", "@com_github_paulbellamy_ratecounter//:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@io_opencensus_go//trace:go_default_library", @@ -138,6 +139,7 @@ go_test( "@com_github_libp2p_go_libp2p_core//network:go_default_library", "@com_github_libp2p_go_libp2p_core//peer:go_default_library", "@com_github_paulbellamy_ratecounter//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@com_github_sirupsen_logrus//hooks/test:go_default_library", diff --git a/beacon-chain/sync/initial-sync/blocks_fetcher.go b/beacon-chain/sync/initial-sync/blocks_fetcher.go index de43abcb8a..5973f66ea4 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher.go @@ -259,7 +259,7 @@ func (f *blocksFetcher) handleRequest(ctx context.Context, start, count uint64) // Short circuit start far exceeding the highest finalized epoch in some infinite loop. if f.mode == modeStopOnFinalizedEpoch { - highestFinalizedSlot := (targetEpoch + 1) * params.BeaconConfig().SlotsPerEpoch + highestFinalizedSlot := uint64(targetEpoch+1) * params.BeaconConfig().SlotsPerEpoch if start > highestFinalizedSlot { response.err = fmt.Errorf("%v, slot: %d, highest finalized slot: %d", errSlotIsTooHigh, start, highestFinalizedSlot) diff --git a/beacon-chain/sync/initial-sync/blocks_fetcher_utils.go b/beacon-chain/sync/initial-sync/blocks_fetcher_utils.go index cf5e8f89cc..092171a235 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher_utils.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher_utils.go @@ -7,6 +7,7 @@ import ( "github.com/libp2p/go-libp2p-core/peer" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/flags" @@ -55,7 +56,7 @@ func (f *blocksFetcher) nonSkippedSlotAfter(ctx context.Context, slot uint64) (u // nonSkippedSlotWithPeersTarget traverse peers (supporting a given target epoch), in an attempt // to find non-skipped slot among returned blocks. func (f *blocksFetcher) nonSkippedSlotAfterWithPeersTarget( - ctx context.Context, slot uint64, peers []peer.ID, targetEpoch uint64, + ctx context.Context, slot uint64, peers []peer.ID, targetEpoch types.Epoch, ) (uint64, error) { // Exit early if no peers are ready. if len(peers) == 0 { @@ -288,19 +289,19 @@ func (f *blocksFetcher) findAncestor(ctx context.Context, pid peer.ID, block *et func (f *blocksFetcher) bestFinalizedSlot() uint64 { finalizedEpoch, _ := f.p2p.Peers().BestFinalized( params.BeaconConfig().MaxPeersToSync, f.chain.FinalizedCheckpt().Epoch) - return finalizedEpoch * params.BeaconConfig().SlotsPerEpoch + return uint64(finalizedEpoch) * params.BeaconConfig().SlotsPerEpoch } // bestNonFinalizedSlot returns the highest non-finalized slot of enough number of connected peers. func (f *blocksFetcher) bestNonFinalizedSlot() uint64 { headEpoch := helpers.SlotToEpoch(f.chain.HeadSlot()) targetEpoch, _ := f.p2p.Peers().BestNonFinalized(flags.Get().MinimumSyncPeers*2, headEpoch) - return targetEpoch * params.BeaconConfig().SlotsPerEpoch + return uint64(targetEpoch) * params.BeaconConfig().SlotsPerEpoch } // calculateHeadAndTargetEpochs return node's current head epoch, along with the best known target // epoch. For the latter peers supporting that target epoch are returned as well. -func (f *blocksFetcher) calculateHeadAndTargetEpochs() (headEpoch, targetEpoch uint64, peers []peer.ID) { +func (f *blocksFetcher) calculateHeadAndTargetEpochs() (headEpoch, targetEpoch types.Epoch, peers []peer.ID) { if f.mode == modeStopOnFinalizedEpoch { headEpoch = f.chain.FinalizedCheckpt().Epoch targetEpoch, peers = f.p2p.Peers().BestFinalized(params.BeaconConfig().MaxPeersToSync, headEpoch) 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 460289d4b6..a719bed2e9 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher_utils_test.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher_utils_test.go @@ -8,6 +8,7 @@ import ( "github.com/kevinms/leakybucket-go" "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/peer" + "github.com/prysmaticlabs/eth2-types" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" @@ -470,10 +471,10 @@ func TestBlocksFetcher_currentHeadAndTargetEpochs(t *testing.T) { name string syncMode syncMode peers []*peerData - ourFinalizedEpoch uint64 + ourFinalizedEpoch types.Epoch ourHeadSlot uint64 - expectedHeadEpoch uint64 - targetEpoch uint64 + expectedHeadEpoch types.Epoch + targetEpoch types.Epoch targetEpochSupport int }{ { @@ -568,7 +569,7 @@ func TestBlocksFetcher_currentHeadAndTargetEpochs(t *testing.T) { assert.Equal(t, tt.targetEpochSupport, len(peers), "Unexpected number of peers supporting target epoch") // Best finalized and non-finalized slots. - finalizedSlot := tt.targetEpoch * params.BeaconConfig().SlotsPerEpoch + finalizedSlot := uint64(tt.targetEpoch) * params.BeaconConfig().SlotsPerEpoch if tt.syncMode == modeStopOnFinalizedEpoch { assert.Equal(t, finalizedSlot, fetcher.bestFinalizedSlot(), "Unexpected finalized slot") } else { diff --git a/beacon-chain/sync/initial-sync/blocks_queue.go b/beacon-chain/sync/initial-sync/blocks_queue.go index d1838af7cb..254f218f4c 100644 --- a/beacon-chain/sync/initial-sync/blocks_queue.go +++ b/beacon-chain/sync/initial-sync/blocks_queue.go @@ -6,6 +6,7 @@ import ( "time" "github.com/libp2p/go-libp2p-core/peer" + "github.com/prysmaticlabs/eth2-types" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/db" @@ -81,7 +82,7 @@ type blocksQueue struct { noRequiredPeersErrRetries int } fetchedData chan *blocksQueueFetchedData // output channel for ready blocks - staleEpochs map[uint64]uint8 // counter to keep track of stale FSMs + staleEpochs map[types.Epoch]uint8 // counter to keep track of stale FSMs quit chan struct{} // termination notifier } @@ -124,7 +125,7 @@ func newBlocksQueue(ctx context.Context, cfg *blocksQueueConfig) *blocksQueue { mode: cfg.mode, fetchedData: make(chan *blocksQueueFetchedData, 1), quit: make(chan struct{}), - staleEpochs: make(map[uint64]uint8), + staleEpochs: make(map[types.Epoch]uint8), } // Configure state machines. diff --git a/beacon-chain/sync/initial-sync/fsm_test.go b/beacon-chain/sync/initial-sync/fsm_test.go index ae1ed06c2e..84ccfc7060 100644 --- a/beacon-chain/sync/initial-sync/fsm_test.go +++ b/beacon-chain/sync/initial-sync/fsm_test.go @@ -5,6 +5,7 @@ import ( "fmt" "testing" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/require" ) @@ -95,20 +96,20 @@ func TestStateMachine_trigger(t *testing.T) { type args struct { name eventID returnState stateID - epoch uint64 + epoch types.Epoch data interface{} } tests := []struct { name string events []event - epochs []uint64 + epochs []types.Epoch args args err error }{ { name: "event not found", events: []event{}, - epochs: []uint64{12, 13}, + epochs: []types.Epoch{12, 13}, args: args{name: eventTick, epoch: 12, data: nil, returnState: stateNew}, err: errors.New("no event handlers registered for event: tick, state: new"), }, @@ -117,7 +118,7 @@ func TestStateMachine_trigger(t *testing.T) { events: []event{ {stateNew, eventTick, stateScheduled, false}, }, - epochs: []uint64{12, 13}, + epochs: []types.Epoch{12, 13}, args: args{name: eventTick, epoch: 12, data: nil, returnState: stateScheduled}, err: nil, }, @@ -128,7 +129,7 @@ func TestStateMachine_trigger(t *testing.T) { {stateScheduled, eventTick, stateSent, true}, {stateSent, eventTick, stateSkipped, false}, }, - epochs: []uint64{12, 13}, + epochs: []types.Epoch{12, 13}, args: args{name: eventTick, epoch: 12, data: nil, returnState: stateScheduled}, err: nil, }, @@ -139,7 +140,7 @@ func TestStateMachine_trigger(t *testing.T) { {stateScheduled, eventTick, stateSent, false}, {stateSent, eventTick, stateSkipped, false}, }, - epochs: []uint64{12, 13}, + epochs: []types.Epoch{12, 13}, args: args{name: eventTick, epoch: 12, data: nil, returnState: stateScheduled}, err: nil, }, @@ -150,7 +151,7 @@ func TestStateMachine_trigger(t *testing.T) { {stateScheduled, eventTick, stateSent, false}, {stateNew, eventTick, stateSkipped, false}, }, - epochs: []uint64{12, 13}, + epochs: []types.Epoch{12, 13}, args: args{name: eventTick, epoch: 12, data: nil, returnState: stateScheduled}, err: nil, }, @@ -174,9 +175,9 @@ func TestStateMachine_trigger(t *testing.T) { } } for _, epoch := range tt.epochs { - smm.addStateMachine(epoch * 32) + smm.addStateMachine(uint64(epoch) * 32) } - state := smm.machines[tt.args.epoch*32] + state := smm.machines[uint64(tt.args.epoch)*32] err := state.trigger(tt.args.name, tt.args.data) if tt.err != nil && (err == nil || tt.err.Error() != err.Error()) { t.Errorf("unexpected error = '%v', want '%v'", err, tt.err) @@ -185,7 +186,7 @@ func TestStateMachine_trigger(t *testing.T) { if err != nil && !expectHandlerError { t.Error(err) } - ind := tt.args.epoch * 32 + ind := uint64(tt.args.epoch) * 32 if smm.machines[ind].state != tt.args.returnState { t.Errorf("unexpected final state: %v, want: %v (%v)", smm.machines[ind].state, tt.args.returnState, smm.machines) diff --git a/beacon-chain/sync/initial-sync/initial_sync_test.go b/beacon-chain/sync/initial-sync/initial_sync_test.go index af8382d758..6abea59afe 100644 --- a/beacon-chain/sync/initial-sync/initial_sync_test.go +++ b/beacon-chain/sync/initial-sync/initial_sync_test.go @@ -11,6 +11,7 @@ import ( "github.com/ethereum/go-ethereum/p2p/enr" "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/peer" + "github.com/prysmaticlabs/eth2-types" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" @@ -44,7 +45,7 @@ var cache = &testCache{} type peerData struct { blocks []uint64 // slots that peer has blocks - finalizedEpoch uint64 + finalizedEpoch types.Epoch headSlot uint64 failureSlots []uint64 // slots at which the peer will return an error forkedPeer bool diff --git a/beacon-chain/sync/initial-sync/round_robin.go b/beacon-chain/sync/initial-sync/round_robin.go index c841ae21d4..cecc2b596e 100644 --- a/beacon-chain/sync/initial-sync/round_robin.go +++ b/beacon-chain/sync/initial-sync/round_robin.go @@ -10,6 +10,7 @@ import ( "github.com/libp2p/go-libp2p-core/peer" "github.com/paulbellamy/ratecounter" + "github.com/prysmaticlabs/eth2-types" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/state" @@ -164,8 +165,8 @@ func (s *Service) processFetchedDataRegSync( // highestFinalizedEpoch returns the absolute highest finalized epoch of all connected peers. // Note this can be lower than our finalized epoch if we have no peers or peers that are all behind us. -func (s *Service) highestFinalizedEpoch() uint64 { - highest := uint64(0) +func (s *Service) highestFinalizedEpoch() types.Epoch { + highest := types.Epoch(0) for _, pid := range s.p2p.Peers().Connected() { peerChainState, err := s.p2p.Peers().ChainState(pid) if err == nil && peerChainState != nil && peerChainState.FinalizedEpoch > highest { diff --git a/beacon-chain/sync/rpc_status.go b/beacon-chain/sync/rpc_status.go index fa2484725e..cba3da48ab 100644 --- a/beacon-chain/sync/rpc_status.go +++ b/beacon-chain/sync/rpc_status.go @@ -10,6 +10,7 @@ import ( "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/peer" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/flags" "github.com/prysmaticlabs/prysm/beacon-chain/p2p" @@ -109,7 +110,7 @@ func (s *Service) resyncIfBehind() { func (s *Service) shouldReSync() bool { syncedEpoch := helpers.SlotToEpoch(s.chain.HeadSlot()) currentEpoch := helpers.SlotToEpoch(s.chain.CurrentSlot()) - prevEpoch := uint64(0) + prevEpoch := types.Epoch(0) if currentEpoch > 1 { prevEpoch = currentEpoch - 1 } @@ -284,7 +285,7 @@ func (s *Service) validateStatusMessage(ctx context.Context, msg *pb.Status) err maxEpoch := slotutil.EpochsSinceGenesis(genesis) // It would take a minimum of 2 epochs to finalize a // previous epoch - maxFinalizedEpoch := uint64(0) + maxFinalizedEpoch := types.Epoch(0) if maxEpoch > 2 { maxFinalizedEpoch = maxEpoch - 2 } diff --git a/beacon-chain/sync/rpc_status_test.go b/beacon-chain/sync/rpc_status_test.go index a6b1643733..56fd580ad4 100644 --- a/beacon-chain/sync/rpc_status_test.go +++ b/beacon-chain/sync/rpc_status_test.go @@ -11,6 +11,7 @@ import ( "github.com/kevinms/leakybucket-go" "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/protocol" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/state" @@ -560,10 +561,10 @@ func TestStatusRPCRequest_FinalizedBlockSkippedSlots(t *testing.T) { } tests := []struct { name string - expectedFinalizedEpoch uint64 + expectedFinalizedEpoch types.Epoch expectedFinalizedRoot [32]byte headSlot uint64 - remoteFinalizedEpoch uint64 + remoteFinalizedEpoch types.Epoch remoteFinalizedRoot [32]byte remoteHeadSlot uint64 expectError bool @@ -634,7 +635,7 @@ func TestStatusRPCRequest_FinalizedBlockSkippedSlots(t *testing.T) { } require.NoError(t, db.SaveFinalizedCheckpoint(context.Background(), finalizedCheckpt)) - totalSec := params.BeaconConfig().SlotsPerEpoch * (expectedFinalizedEpoch + 2) * params.BeaconConfig().SecondsPerSlot + totalSec := params.BeaconConfig().SlotsPerEpoch * uint64(expectedFinalizedEpoch+2) * params.BeaconConfig().SecondsPerSlot genTime := time.Now().Unix() - int64(totalSec) r := &Service{ p2p: p1, diff --git a/beacon-chain/sync/subscriber_beacon_attestation.go b/beacon-chain/sync/subscriber_beacon_attestation.go index 6f31a0655f..f4c377eae2 100644 --- a/beacon-chain/sync/subscriber_beacon_attestation.go +++ b/beacon-chain/sync/subscriber_beacon_attestation.go @@ -52,7 +52,7 @@ func (s *Service) persistentSubnetIndices() []uint64 { func (s *Service) aggregatorSubnetIndices(currentSlot uint64) []uint64 { endEpoch := helpers.SlotToEpoch(currentSlot) + 1 - endSlot := endEpoch * params.BeaconConfig().SlotsPerEpoch + endSlot := uint64(endEpoch) * params.BeaconConfig().SlotsPerEpoch var commIds []uint64 for i := currentSlot; i <= endSlot; i++ { commIds = append(commIds, cache.SubnetIDs.GetAggregatorSubnetIDs(i)...) @@ -62,7 +62,7 @@ func (s *Service) aggregatorSubnetIndices(currentSlot uint64) []uint64 { func (s *Service) attesterSubnetIndices(currentSlot uint64) []uint64 { endEpoch := helpers.SlotToEpoch(currentSlot) + 1 - endSlot := endEpoch * params.BeaconConfig().SlotsPerEpoch + endSlot := uint64(endEpoch) * params.BeaconConfig().SlotsPerEpoch var commIds []uint64 for i := currentSlot; i <= endSlot; i++ { commIds = append(commIds, cache.SubnetIDs.GetAttesterSubnetIDs(i)...) diff --git a/beacon-chain/sync/validate_aggregate_proof.go b/beacon-chain/sync/validate_aggregate_proof.go index 3d2f23784a..70eeee70b4 100644 --- a/beacon-chain/sync/validate_aggregate_proof.go +++ b/beacon-chain/sync/validate_aggregate_proof.go @@ -7,6 +7,7 @@ import ( "github.com/libp2p/go-libp2p-core/peer" pubsub "github.com/libp2p/go-libp2p-pubsub" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" @@ -189,19 +190,19 @@ func (s *Service) validateBlockInAttestation(ctx context.Context, satt *ethpb.Si } // Returns true if the node has received aggregate for the aggregator with index and target epoch. -func (s *Service) hasSeenAggregatorIndexEpoch(epoch, aggregatorIndex uint64) bool { +func (s *Service) hasSeenAggregatorIndexEpoch(epoch types.Epoch, aggregatorIndex uint64) bool { s.seenAttestationLock.RLock() defer s.seenAttestationLock.RUnlock() - b := append(bytesutil.Bytes32(epoch), bytesutil.Bytes32(aggregatorIndex)...) + b := append(bytesutil.Bytes32(uint64(epoch)), bytesutil.Bytes32(aggregatorIndex)...) _, seen := s.seenAttestationCache.Get(string(b)) return seen } // Set aggregate's aggregator index target epoch as seen. -func (s *Service) setAggregatorIndexEpochSeen(epoch, aggregatorIndex uint64) { +func (s *Service) setAggregatorIndexEpochSeen(epoch types.Epoch, aggregatorIndex uint64) { s.seenAttestationLock.Lock() defer s.seenAttestationLock.Unlock() - b := append(bytesutil.Bytes32(epoch), bytesutil.Bytes32(aggregatorIndex)...) + b := append(bytesutil.Bytes32(uint64(epoch)), bytesutil.Bytes32(aggregatorIndex)...) s.seenAttestationCache.Add(string(b), true) } diff --git a/beacon-chain/sync/validate_attester_slashing_test.go b/beacon-chain/sync/validate_attester_slashing_test.go index 2d3045de72..eb48504b1e 100644 --- a/beacon-chain/sync/validate_attester_slashing_test.go +++ b/beacon-chain/sync/validate_attester_slashing_test.go @@ -10,6 +10,7 @@ import ( pubsub "github.com/libp2p/go-libp2p-pubsub" pubsubpb "github.com/libp2p/go-libp2p-pubsub/pb" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" @@ -28,7 +29,7 @@ func setupValidAttesterSlashing(t *testing.T) (*ethpb.AttesterSlashing, *stateTr state, privKeys := testutil.DeterministicGenesisState(t, 5) vals := state.Validators() for _, vv := range vals { - vv.WithdrawableEpoch = 1 * params.BeaconConfig().SlotsPerEpoch + vv.WithdrawableEpoch = types.Epoch(1 * params.BeaconConfig().SlotsPerEpoch) } require.NoError(t, state.SetValidators(vals)) diff --git a/beacon-chain/sync/validate_beacon_blocks_test.go b/beacon-chain/sync/validate_beacon_blocks_test.go index 063d138545..d3fbffaada 100644 --- a/beacon-chain/sync/validate_beacon_blocks_test.go +++ b/beacon-chain/sync/validate_beacon_blocks_test.go @@ -253,7 +253,7 @@ func TestValidateBeaconBlockPubSub_WithLookahead(t *testing.T) { require.NoError(t, db.SaveStateSummary(ctx, &pb.StateSummary{Root: bRoot[:]})) copied := beaconState.Copy() // The next block is only 1 epoch ahead so as to not induce a new seed. - blkSlot := params.BeaconConfig().SlotsPerEpoch * helpers.NextEpoch(copied) + blkSlot := params.BeaconConfig().SlotsPerEpoch * uint64(helpers.NextEpoch(copied)) copied, err = state.ProcessSlots(context.Background(), copied, blkSlot) require.NoError(t, err) proposerIdx, err := helpers.BeaconProposerIndex(copied) diff --git a/beacon-chain/sync/validate_voluntary_exit_test.go b/beacon-chain/sync/validate_voluntary_exit_test.go index f23dade4ea..566ebeb528 100644 --- a/beacon-chain/sync/validate_voluntary_exit_test.go +++ b/beacon-chain/sync/validate_voluntary_exit_test.go @@ -46,7 +46,7 @@ func setupValidExit(t *testing.T) (*ethpb.SignedVoluntaryExit, *stateTrie.Beacon Slot: params.BeaconConfig().SlotsPerEpoch * 5, }) require.NoError(t, err) - err = state.SetSlot(state.Slot() + (params.BeaconConfig().ShardCommitteePeriod * params.BeaconConfig().SlotsPerEpoch)) + err = state.SetSlot(state.Slot() + uint64(params.BeaconConfig().ShardCommitteePeriod.Mul(params.BeaconConfig().SlotsPerEpoch))) require.NoError(t, err) priv, err := bls.RandKey() diff --git a/deps.bzl b/deps.bzl index 3c1e07bba8..b0a0619c2a 100644 --- a/deps.bzl +++ b/deps.bzl @@ -2568,13 +2568,18 @@ def prysm_deps(): sum = "h1:If5rVCMTp6W2SiRAQFlbpJNgVlgMEd+U2GZckwK38ic=", version = "v0.10.0", ) - + go_repository( + name = "com_github_prysmaticlabs_eth2_types", + importpath = "github.com/prysmaticlabs/eth2-types", + sum = "h1:n/ZI+/bZfkMoGoV2Rult3YvS5LT4dvpAFOuISq+I+GY=", + version = "v0.0.0-20210127031309-22cbe426eba6", + ) go_repository( name = "com_github_prysmaticlabs_ethereumapis", build_file_generation = "off", importpath = "github.com/prysmaticlabs/ethereumapis", - sum = "h1:W8MMbOp3rkI972HrLaJDBgOzolv8K8S7SUf9reFtqtw=", - version = "v0.0.0-20210127105958-025470485ece", + sum = "h1:PrH+xowCzrpZteDwab4SNgJgL/+z8Tz7lcsKOuwlR1A=", + version = "v0.0.0-20210204190026-013b3e2be070", ) go_repository( name = "com_github_prysmaticlabs_go_bitfield", diff --git a/endtoend/BUILD.bazel b/endtoend/BUILD.bazel index 30e4d6a5d1..4cb74685b9 100644 --- a/endtoend/BUILD.bazel +++ b/endtoend/BUILD.bazel @@ -37,6 +37,7 @@ go_test( "//shared/slotutil:go_default_library", "//shared/testutil:go_default_library", "@com_github_gogo_protobuf//types:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@org_golang_google_grpc//:go_default_library", "//shared/testutil/assert:go_default_library", diff --git a/endtoend/endtoend_test.go b/endtoend/endtoend_test.go index 232128fa17..2dfffcc94e 100644 --- a/endtoend/endtoend_test.go +++ b/endtoend/endtoend_test.go @@ -13,18 +13,18 @@ import ( "time" ptypes "github.com/gogo/protobuf/types" + "github.com/prysmaticlabs/eth2-types" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/state" "github.com/prysmaticlabs/prysm/endtoend/components" ev "github.com/prysmaticlabs/prysm/endtoend/evaluators" "github.com/prysmaticlabs/prysm/endtoend/helpers" e2e "github.com/prysmaticlabs/prysm/endtoend/params" - "github.com/prysmaticlabs/prysm/endtoend/types" + e2etypes "github.com/prysmaticlabs/prysm/endtoend/types" "github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/slotutil" "github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/require" - "google.golang.org/grpc" ) @@ -32,7 +32,7 @@ func init() { state.SkipSlotCache.Disable() } -func runEndToEndTest(t *testing.T, config *types.E2EConfig) { +func runEndToEndTest(t *testing.T, config *e2etypes.E2EConfig) { t.Logf("Shard index: %d\n", e2e.TestParams.TestShardIndex) t.Logf("Starting time: %s\n", time.Now().String()) t.Logf("Log Path: %s\n", e2e.TestParams.LogPath) @@ -101,7 +101,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) { for currentEpoch := range ticker.C() { for _, evaluator := range config.Evaluators { // Only run if the policy says so. - if !evaluator.Policy(currentEpoch) { + if !evaluator.Policy(types.Epoch(currentEpoch)) { continue } t.Run(fmt.Sprintf(evaluator.Name, currentEpoch), func(t *testing.T) { @@ -145,7 +145,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) { // Sleep a slot to make sure the synced state is made. time.Sleep(time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second) - syncEvaluators := []types.Evaluator{ev.FinishedSyncing, ev.AllNodesHaveSameHead} + syncEvaluators := []e2etypes.Evaluator{ev.FinishedSyncing, ev.AllNodesHaveSameHead} for _, evaluator := range syncEvaluators { t.Run(evaluator.Name, func(t *testing.T) { assert.NoError(t, evaluator.Evaluation(conns...), "Evaluation failed for sync node") diff --git a/endtoend/evaluators/BUILD.bazel b/endtoend/evaluators/BUILD.bazel index 5774a29467..10e1b044de 100644 --- a/endtoend/evaluators/BUILD.bazel +++ b/endtoend/evaluators/BUILD.bazel @@ -28,6 +28,7 @@ go_library( "//shared/testutil:go_default_library", "@com_github_gogo_protobuf//types:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@org_golang_google_grpc//:go_default_library", diff --git a/endtoend/evaluators/data.go b/endtoend/evaluators/data.go index 33f3ee3ffa..b6b9c89500 100644 --- a/endtoend/evaluators/data.go +++ b/endtoend/evaluators/data.go @@ -4,17 +4,18 @@ import ( "context" "errors" + "github.com/prysmaticlabs/eth2-types" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" - "github.com/prysmaticlabs/prysm/endtoend/types" + e2etypes "github.com/prysmaticlabs/prysm/endtoend/types" "google.golang.org/grpc" ) const epochToCheck = 50 // must be more than 46 (32 hot states + 16 chkpt interval) // ColdStateCheckpoint checks data from the database using cold state storage. -var ColdStateCheckpoint = types.Evaluator{ +var ColdStateCheckpoint = e2etypes.Evaluator{ Name: "cold_state_assignments_from_epoch_%d", - Policy: func(currentEpoch uint64) bool { + Policy: func(currentEpoch types.Epoch) bool { return currentEpoch == epochToCheck }, Evaluation: checkColdStateCheckpoint, @@ -25,7 +26,7 @@ func checkColdStateCheckpoint(conns ...*grpc.ClientConn) error { ctx := context.Background() client := eth.NewBeaconChainClient(conns[0]) - for i := uint64(0); i < epochToCheck; i++ { + for i := types.Epoch(0); i < epochToCheck; i++ { res, err := client.ListValidatorAssignments(ctx, ð.ListValidatorAssignmentsRequest{ QueryFilter: ð.ListValidatorAssignmentsRequest_Epoch{Epoch: i}, }) diff --git a/endtoend/evaluators/node.go b/endtoend/evaluators/node.go index 62e0c695fb..e50955d0b7 100644 --- a/endtoend/evaluators/node.go +++ b/endtoend/evaluators/node.go @@ -12,10 +12,11 @@ import ( ptypes "github.com/gogo/protobuf/types" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" e2e "github.com/prysmaticlabs/prysm/endtoend/params" "github.com/prysmaticlabs/prysm/endtoend/policies" - "github.com/prysmaticlabs/prysm/endtoend/types" + e2etypes "github.com/prysmaticlabs/prysm/endtoend/types" "google.golang.org/grpc" ) @@ -23,21 +24,21 @@ import ( var connTimeDelay = 50 * time.Millisecond // PeersConnect checks all beacon nodes and returns whether they are connected to each other as peers. -var PeersConnect = types.Evaluator{ +var PeersConnect = e2etypes.Evaluator{ Name: "peers_connect_epoch_%d", Policy: policies.OnEpoch(0), Evaluation: peersConnect, } // HealthzCheck pings healthz and errors if it doesn't have the expected OK status. -var HealthzCheck = types.Evaluator{ +var HealthzCheck = e2etypes.Evaluator{ Name: "healthz_check_epoch_%d", Policy: policies.AfterNthEpoch(0), Evaluation: healthzCheck, } // FinishedSyncing returns whether the beacon node with the given rpc port has finished syncing. -var FinishedSyncing = types.Evaluator{ +var FinishedSyncing = e2etypes.Evaluator{ Name: "finished_syncing", Policy: policies.AllEpochs, Evaluation: finishedSyncing, @@ -45,7 +46,7 @@ var FinishedSyncing = types.Evaluator{ // AllNodesHaveSameHead ensures all nodes have the same head epoch. Checks finality and justification as well. // Not checking head block root as it may change irregularly for the validator connected nodes. -var AllNodesHaveSameHead = types.Evaluator{ +var AllNodesHaveSameHead = e2etypes.Evaluator{ Name: "all_nodes_have_same_head", Policy: policies.AllEpochs, Evaluation: allNodesHaveSameHead, @@ -127,7 +128,7 @@ func finishedSyncing(conns ...*grpc.ClientConn) error { } func allNodesHaveSameHead(conns ...*grpc.ClientConn) error { - headEpochs := make([]uint64, len(conns)) + headEpochs := make([]types.Epoch, len(conns)) justifiedRoots := make([][]byte, len(conns)) prevJustifiedRoots := make([][]byte, len(conns)) finalizedRoots := make([][]byte, len(conns)) diff --git a/endtoend/evaluators/operations.go b/endtoend/evaluators/operations.go index 654a9440c4..fac6777e5e 100644 --- a/endtoend/evaluators/operations.go +++ b/endtoend/evaluators/operations.go @@ -8,12 +8,13 @@ import ( ptypes "github.com/gogo/protobuf/types" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" corehelpers "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/endtoend/helpers" e2e "github.com/prysmaticlabs/prysm/endtoend/params" "github.com/prysmaticlabs/prysm/endtoend/policies" - "github.com/prysmaticlabs/prysm/endtoend/types" + e2etypes "github.com/prysmaticlabs/prysm/endtoend/types" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/testutil" @@ -33,56 +34,56 @@ var churnLimit = uint64(4) var depositValCount = e2e.DepositCount // Deposits should be processed in twice the length of the epochs per eth1 voting period. -var depositsInBlockStart = uint64(math.Floor(float64(params.E2ETestConfig().EpochsPerEth1VotingPeriod) * 2)) +var depositsInBlockStart = types.Epoch(math.Floor(float64(params.E2ETestConfig().EpochsPerEth1VotingPeriod) * 2)) // deposits included + finalization + MaxSeedLookahead for activation. var depositActivationStartEpoch = depositsInBlockStart + 2 + params.E2ETestConfig().MaxSeedLookahead -var depositEndEpoch = depositActivationStartEpoch + uint64(math.Ceil(float64(depositValCount)/float64(churnLimit))) +var depositEndEpoch = depositActivationStartEpoch + types.Epoch(math.Ceil(float64(depositValCount)/float64(churnLimit))) // ProcessesDepositsInBlocks ensures the expected amount of deposits are accepted into blocks. -var ProcessesDepositsInBlocks = types.Evaluator{ +var ProcessesDepositsInBlocks = e2etypes.Evaluator{ Name: "processes_deposits_in_blocks_epoch_%d", Policy: policies.OnEpoch(depositsInBlockStart), // We expect all deposits to enter in one epoch. Evaluation: processesDepositsInBlocks, } // VerifyBlockGraffiti ensures the block graffiti is one of the random list. -var VerifyBlockGraffiti = types.Evaluator{ +var VerifyBlockGraffiti = e2etypes.Evaluator{ Name: "verify_graffiti_in_blocks_epoch_%d", Policy: policies.AfterNthEpoch(0), Evaluation: verifyGraffitiInBlocks, } // ActivatesDepositedValidators ensures the expected amount of validator deposits are activated into the state. -var ActivatesDepositedValidators = types.Evaluator{ +var ActivatesDepositedValidators = e2etypes.Evaluator{ Name: "processes_deposit_validators_epoch_%d", Policy: policies.BetweenEpochs(depositActivationStartEpoch, depositEndEpoch), Evaluation: activatesDepositedValidators, } // DepositedValidatorsAreActive ensures the expected amount of validators are active after their deposits are processed. -var DepositedValidatorsAreActive = types.Evaluator{ +var DepositedValidatorsAreActive = e2etypes.Evaluator{ Name: "deposited_validators_are_active_epoch_%d", Policy: policies.AfterNthEpoch(depositEndEpoch), Evaluation: depositedValidatorsAreActive, } // ProposeVoluntaryExit sends a voluntary exit from randomly selected validator in the genesis set. -var ProposeVoluntaryExit = types.Evaluator{ +var ProposeVoluntaryExit = e2etypes.Evaluator{ Name: "propose_voluntary_exit_epoch_%d", Policy: policies.OnEpoch(7), Evaluation: proposeVoluntaryExit, } // ValidatorHasExited checks the beacon state for the exited validator and ensures its marked as exited. -var ValidatorHasExited = types.Evaluator{ +var ValidatorHasExited = e2etypes.Evaluator{ Name: "voluntary_has_exited_%d", Policy: policies.OnEpoch(8), Evaluation: validatorIsExited, } // ValidatorsVoteWithTheMajority verifies whether validator vote for eth1data using the majority algorithm. -var ValidatorsVoteWithTheMajority = types.Evaluator{ +var ValidatorsVoteWithTheMajority = e2etypes.Evaluator{ Name: "validators_vote_with_the_majority_%d", Policy: policies.AfterNthEpoch(0), Evaluation: validatorsVoteWithTheMajority, @@ -339,7 +340,7 @@ func validatorsVoteWithTheMajority(conns ...*grpc.ClientConn) error { for _, blk := range blks.BlockContainers { slot, vote := blk.Block.Block.Slot, blk.Block.Block.Body.Eth1Data.BlockHash - slotsPerVotingPeriod := params.E2ETestConfig().SlotsPerEpoch * params.E2ETestConfig().EpochsPerEth1VotingPeriod + slotsPerVotingPeriod := uint64(params.E2ETestConfig().EpochsPerEth1VotingPeriod.Mul(params.E2ETestConfig().SlotsPerEpoch)) // We treat epoch 1 differently from other epoch for two reasons: // - this evaluator is not executed for epoch 0 so we have to calculate the first slot differently diff --git a/endtoend/policies/BUILD.bazel b/endtoend/policies/BUILD.bazel index 3632040e9e..31d92bd6fa 100644 --- a/endtoend/policies/BUILD.bazel +++ b/endtoend/policies/BUILD.bazel @@ -5,4 +5,5 @@ go_library( srcs = ["policies.go"], importpath = "github.com/prysmaticlabs/prysm/endtoend/policies", visibility = ["//visibility:public"], + deps = ["@com_github_prysmaticlabs_eth2_types//:go_default_library"], ) diff --git a/endtoend/policies/policies.go b/endtoend/policies/policies.go index 8252444fee..09124688e1 100644 --- a/endtoend/policies/policies.go +++ b/endtoend/policies/policies.go @@ -1,27 +1,29 @@ package policies +import "github.com/prysmaticlabs/eth2-types" + // AfterNthEpoch runs for every epoch after the provided epoch. -func AfterNthEpoch(afterEpoch uint64) func(uint64) bool { - return func(currentEpoch uint64) bool { +func AfterNthEpoch(afterEpoch types.Epoch) func(epoch types.Epoch) bool { + return func(currentEpoch types.Epoch) bool { return currentEpoch > afterEpoch } } // AllEpochs runs for all epochs. -func AllEpochs(_ uint64) bool { +func AllEpochs(_ types.Epoch) bool { return true } // OnEpoch runs only for the provided epoch. -func OnEpoch(epoch uint64) func(uint64) bool { - return func(currentEpoch uint64) bool { +func OnEpoch(epoch types.Epoch) func(types.Epoch) bool { + return func(currentEpoch types.Epoch) bool { return currentEpoch == epoch } } // BetweenEpochs runs for every epoch that is between the provided epochs. -func BetweenEpochs(fromEpoch, toEpoch uint64) func(uint64) bool { - return func(currentEpoch uint64) bool { +func BetweenEpochs(fromEpoch, toEpoch types.Epoch) func(types.Epoch) bool { + return func(currentEpoch types.Epoch) bool { return fromEpoch < currentEpoch && currentEpoch < toEpoch } } diff --git a/endtoend/types/BUILD.bazel b/endtoend/types/BUILD.bazel index cdc7577dfe..a27b6425f4 100644 --- a/endtoend/types/BUILD.bazel +++ b/endtoend/types/BUILD.bazel @@ -6,5 +6,8 @@ go_library( srcs = ["types.go"], importpath = "github.com/prysmaticlabs/prysm/endtoend/types", visibility = ["//endtoend:__subpackages__"], - deps = ["@org_golang_google_grpc//:go_default_library"], + deps = [ + "@com_github_prysmaticlabs_eth2_types//:go_default_library", + "@org_golang_google_grpc//:go_default_library", + ], ) diff --git a/endtoend/types/types.go b/endtoend/types/types.go index 11247edab6..54fd401003 100644 --- a/endtoend/types/types.go +++ b/endtoend/types/types.go @@ -3,6 +3,7 @@ package types import ( + "github.com/prysmaticlabs/eth2-types" "google.golang.org/grpc" ) @@ -22,6 +23,6 @@ type E2EConfig struct { // conduct the current beacon state during the E2E. type Evaluator struct { Name string - Policy func(currentEpoch uint64) bool + Policy func(currentEpoch types.Epoch) bool Evaluation func(conn ...*grpc.ClientConn) error // A variable amount of conns is allowed to be passed in for evaluations to check all nodes if needed. } diff --git a/fuzz/BUILD.bazel b/fuzz/BUILD.bazel index 412dbe5759..f91b3c02fe 100644 --- a/fuzz/BUILD.bazel +++ b/fuzz/BUILD.bazel @@ -16,6 +16,7 @@ ssz_gen_marshal( srcs = ["inputs.go"], includes = [ "//proto/beacon/p2p/v1:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", ], objs = [ diff --git a/go.mod b/go.mod index e4591ca9ae..624ea63096 100644 --- a/go.mod +++ b/go.mod @@ -83,7 +83,8 @@ require ( github.com/prometheus/client_golang v1.9.0 github.com/prometheus/procfs v0.3.0 // indirect github.com/prometheus/tsdb v0.10.0 // indirect - github.com/prysmaticlabs/ethereumapis v0.0.0-20210127105958-025470485ece + github.com/prysmaticlabs/eth2-types v0.0.0-20210127031309-22cbe426eba6 + github.com/prysmaticlabs/ethereumapis v0.0.0-20210204190026-013b3e2be070 github.com/prysmaticlabs/go-bitfield v0.0.0-20210202205921-7fcea7c45dc8 github.com/prysmaticlabs/prombbolt v0.0.0-20210126082820-9b7adba6db7c github.com/rs/cors v1.7.0 diff --git a/go.sum b/go.sum index 430e7fd3a5..ad316aefb4 100644 --- a/go.sum +++ b/go.sum @@ -245,7 +245,6 @@ github.com/fatih/color v1.3.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5Kwzbycv github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= -github.com/ferranbt/fastssz v0.0.0-20200728110133-0b6e349af87a/go.mod h1:DyEu2iuLBnb/T51BlsiO3yLYdJC6UbGMrIkqK1KmQxM= github.com/ferranbt/fastssz v0.0.0-20210120143747-11b9eff30ea9 h1:9VDpsWq096+oGMDTT/SgBD/VgZYf4pTF+KTPmZ+OaKM= github.com/ferranbt/fastssz v0.0.0-20210120143747-11b9eff30ea9/go.mod h1:DyEu2iuLBnb/T51BlsiO3yLYdJC6UbGMrIkqK1KmQxM= github.com/fjl/memsize v0.0.0-20180418122429-ca190fb6ffbc/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0= @@ -1104,8 +1103,10 @@ github.com/prometheus/tsdb v0.10.0 h1:If5rVCMTp6W2SiRAQFlbpJNgVlgMEd+U2GZckwK38i github.com/prometheus/tsdb v0.10.0/go.mod h1:oi49uRhEe9dPUTlS3JRZOwJuVi6tmh10QSgwXEyGCt4= github.com/prysmaticlabs/bazel-go-ethereum v0.0.0-20201126065335-1fb46e307951 h1:Jncuyb/nIJgXbEe0iGz3MN5JmijPVGzwk3G5FR01phI= github.com/prysmaticlabs/bazel-go-ethereum v0.0.0-20201126065335-1fb46e307951/go.mod h1:JIfVb6esrqALTExdz9hRYvrP0xBDf6wCncIu1hNwHpM= -github.com/prysmaticlabs/ethereumapis v0.0.0-20210127105958-025470485ece h1:W8MMbOp3rkI972HrLaJDBgOzolv8K8S7SUf9reFtqtw= -github.com/prysmaticlabs/ethereumapis v0.0.0-20210127105958-025470485ece/go.mod h1:k7b2dxy6RppCG6kmOJkNOXzRpEoTdsPygc2aQhsUsZk= +github.com/prysmaticlabs/eth2-types v0.0.0-20210127031309-22cbe426eba6 h1:n/ZI+/bZfkMoGoV2Rult3YvS5LT4dvpAFOuISq+I+GY= +github.com/prysmaticlabs/eth2-types v0.0.0-20210127031309-22cbe426eba6/go.mod h1:kOmQ/zdobQf7HUohDTifDNFEZfNaSCIY5fkONPL+dWU= +github.com/prysmaticlabs/ethereumapis v0.0.0-20210204190026-013b3e2be070 h1:PrH+xowCzrpZteDwab4SNgJgL/+z8Tz7lcsKOuwlR1A= +github.com/prysmaticlabs/ethereumapis v0.0.0-20210204190026-013b3e2be070/go.mod h1:YS3iOCGE+iVDE007GHWtj+UoPK9hyYA7Fo4mSDNTtiY= github.com/prysmaticlabs/go-bitfield v0.0.0-20200322041314-62c2aee71669 h1:cX6YRZnZ9sgMqM5U14llxUiXVNJ3u07Res1IIjTOgtI= github.com/prysmaticlabs/go-bitfield v0.0.0-20200322041314-62c2aee71669/go.mod h1:hCwmef+4qXWjv0jLDbQdWnL0Ol7cS7/lCSS26WR+u6s= github.com/prysmaticlabs/go-bitfield v0.0.0-20210202205921-7fcea7c45dc8 h1:18+Qqobq3HAUY0hgIhPGSqmLFnaLLocemmU7+Sj2aYQ= diff --git a/proto/beacon/p2p/v1/BUILD.bazel b/proto/beacon/p2p/v1/BUILD.bazel index 8392260602..7e2c288d0a 100644 --- a/proto/beacon/p2p/v1/BUILD.bazel +++ b/proto/beacon/p2p/v1/BUILD.bazel @@ -13,6 +13,7 @@ go_proto_library( proto = ":v1_proto", visibility = ["//visibility:public"], deps = [ + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", ], @@ -22,6 +23,7 @@ ssz_gen_marshal( name = "ssz_generated_files", go_proto = ":v1_go_proto", includes = [ + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", ], objs = [ diff --git a/proto/beacon/p2p/v1/generated.ssz.go b/proto/beacon/p2p/v1/generated.ssz.go index 1808eb334a..a844bd90c1 100755 --- a/proto/beacon/p2p/v1/generated.ssz.go +++ b/proto/beacon/p2p/v1/generated.ssz.go @@ -3,6 +3,7 @@ package ethereum_beacon_p2p_v1 import ( ssz "github.com/ferranbt/fastssz" + github_com_prysmaticlabs_eth2_types "github.com/prysmaticlabs/eth2-types" v1alpha1 "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ) @@ -30,7 +31,7 @@ func (s *Status) MarshalSSZTo(buf []byte) (dst []byte, err error) { dst = append(dst, s.FinalizedRoot...) // Field (2) 'FinalizedEpoch' - dst = ssz.MarshalUint64(dst, s.FinalizedEpoch) + dst = ssz.MarshalUint64(dst, uint64(s.FinalizedEpoch)) // Field (3) 'HeadRoot' if len(s.HeadRoot) != 32 { @@ -66,7 +67,7 @@ func (s *Status) UnmarshalSSZ(buf []byte) error { s.FinalizedRoot = append(s.FinalizedRoot, buf[4:36]...) // Field (2) 'FinalizedEpoch' - s.FinalizedEpoch = ssz.UnmarshallUint64(buf[36:44]) + s.FinalizedEpoch = github_com_prysmaticlabs_eth2_types.Epoch(ssz.UnmarshallUint64(buf[36:44])) // Field (3) 'HeadRoot' if cap(s.HeadRoot) == 0 { @@ -110,7 +111,7 @@ func (s *Status) HashTreeRootWith(hh *ssz.Hasher) (err error) { hh.PutBytes(s.FinalizedRoot) // Field (2) 'FinalizedEpoch' - hh.PutUint64(s.FinalizedEpoch) + hh.PutUint64(uint64(s.FinalizedEpoch)) // Field (3) 'HeadRoot' if len(s.HeadRoot) != 32 { @@ -219,7 +220,7 @@ func (e *ENRForkID) MarshalSSZTo(buf []byte) (dst []byte, err error) { dst = append(dst, e.NextForkVersion...) // Field (2) 'NextForkEpoch' - dst = ssz.MarshalUint64(dst, e.NextForkEpoch) + dst = ssz.MarshalUint64(dst, uint64(e.NextForkEpoch)) return } @@ -245,7 +246,7 @@ func (e *ENRForkID) UnmarshalSSZ(buf []byte) error { e.NextForkVersion = append(e.NextForkVersion, buf[4:8]...) // Field (2) 'NextForkEpoch' - e.NextForkEpoch = ssz.UnmarshallUint64(buf[8:16]) + e.NextForkEpoch = github_com_prysmaticlabs_eth2_types.Epoch(ssz.UnmarshallUint64(buf[8:16])) return err } @@ -280,7 +281,7 @@ func (e *ENRForkID) HashTreeRootWith(hh *ssz.Hasher) (err error) { hh.PutBytes(e.NextForkVersion) // Field (2) 'NextForkEpoch' - hh.PutUint64(e.NextForkEpoch) + hh.PutUint64(uint64(e.NextForkEpoch)) hh.Merkleize(indx) return @@ -1135,7 +1136,7 @@ func (f *Fork) MarshalSSZTo(buf []byte) (dst []byte, err error) { dst = append(dst, f.CurrentVersion...) // Field (2) 'Epoch' - dst = ssz.MarshalUint64(dst, f.Epoch) + dst = ssz.MarshalUint64(dst, uint64(f.Epoch)) return } @@ -1161,7 +1162,7 @@ func (f *Fork) UnmarshalSSZ(buf []byte) error { f.CurrentVersion = append(f.CurrentVersion, buf[4:8]...) // Field (2) 'Epoch' - f.Epoch = ssz.UnmarshallUint64(buf[8:16]) + f.Epoch = github_com_prysmaticlabs_eth2_types.Epoch(ssz.UnmarshallUint64(buf[8:16])) return err } @@ -1196,7 +1197,7 @@ func (f *Fork) HashTreeRootWith(hh *ssz.Hasher) (err error) { hh.PutBytes(f.CurrentVersion) // Field (2) 'Epoch' - hh.PutUint64(f.Epoch) + hh.PutUint64(uint64(f.Epoch)) hh.Merkleize(indx) return diff --git a/proto/beacon/p2p/v1/messages.pb.go b/proto/beacon/p2p/v1/messages.pb.go index 1051069d20..7c69b5b7a9 100755 --- a/proto/beacon/p2p/v1/messages.pb.go +++ b/proto/beacon/p2p/v1/messages.pb.go @@ -7,6 +7,7 @@ import ( fmt "fmt" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" + github_com_prysmaticlabs_eth2_types "github.com/prysmaticlabs/eth2-types" github_com_prysmaticlabs_go_bitfield "github.com/prysmaticlabs/go-bitfield" io "io" math "math" @@ -25,14 +26,14 @@ var _ = math.Inf const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type Status struct { - ForkDigest []byte `protobuf:"bytes,1,opt,name=fork_digest,json=forkDigest,proto3" json:"fork_digest,omitempty" ssz-size:"4"` - FinalizedRoot []byte `protobuf:"bytes,2,opt,name=finalized_root,json=finalizedRoot,proto3" json:"finalized_root,omitempty" ssz-size:"32"` - FinalizedEpoch uint64 `protobuf:"varint,3,opt,name=finalized_epoch,json=finalizedEpoch,proto3" json:"finalized_epoch,omitempty"` - HeadRoot []byte `protobuf:"bytes,4,opt,name=head_root,json=headRoot,proto3" json:"head_root,omitempty" ssz-size:"32"` - HeadSlot uint64 `protobuf:"varint,5,opt,name=head_slot,json=headSlot,proto3" json:"head_slot,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + ForkDigest []byte `protobuf:"bytes,1,opt,name=fork_digest,json=forkDigest,proto3" json:"fork_digest,omitempty" ssz-size:"4"` + FinalizedRoot []byte `protobuf:"bytes,2,opt,name=finalized_root,json=finalizedRoot,proto3" json:"finalized_root,omitempty" ssz-size:"32"` + FinalizedEpoch github_com_prysmaticlabs_eth2_types.Epoch `protobuf:"varint,3,opt,name=finalized_epoch,json=finalizedEpoch,proto3,casttype=github.com/prysmaticlabs/eth2-types.Epoch" json:"finalized_epoch,omitempty"` + HeadRoot []byte `protobuf:"bytes,4,opt,name=head_root,json=headRoot,proto3" json:"head_root,omitempty" ssz-size:"32"` + HeadSlot uint64 `protobuf:"varint,5,opt,name=head_slot,json=headSlot,proto3" json:"head_slot,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Status) Reset() { *m = Status{} } @@ -82,7 +83,7 @@ func (m *Status) GetFinalizedRoot() []byte { return nil } -func (m *Status) GetFinalizedEpoch() uint64 { +func (m *Status) GetFinalizedEpoch() github_com_prysmaticlabs_eth2_types.Epoch { if m != nil { return m.FinalizedEpoch } @@ -167,12 +168,12 @@ func (m *BeaconBlocksByRangeRequest) GetStep() uint64 { } type ENRForkID struct { - CurrentForkDigest []byte `protobuf:"bytes,1,opt,name=current_fork_digest,json=currentForkDigest,proto3" json:"current_fork_digest,omitempty" ssz-size:"4"` - NextForkVersion []byte `protobuf:"bytes,2,opt,name=next_fork_version,json=nextForkVersion,proto3" json:"next_fork_version,omitempty" ssz-size:"4"` - NextForkEpoch uint64 `protobuf:"varint,3,opt,name=next_fork_epoch,json=nextForkEpoch,proto3" json:"next_fork_epoch,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + CurrentForkDigest []byte `protobuf:"bytes,1,opt,name=current_fork_digest,json=currentForkDigest,proto3" json:"current_fork_digest,omitempty" ssz-size:"4"` + NextForkVersion []byte `protobuf:"bytes,2,opt,name=next_fork_version,json=nextForkVersion,proto3" json:"next_fork_version,omitempty" ssz-size:"4"` + NextForkEpoch github_com_prysmaticlabs_eth2_types.Epoch `protobuf:"varint,3,opt,name=next_fork_epoch,json=nextForkEpoch,proto3,casttype=github.com/prysmaticlabs/eth2-types.Epoch" json:"next_fork_epoch,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *ENRForkID) Reset() { *m = ENRForkID{} } @@ -222,7 +223,7 @@ func (m *ENRForkID) GetNextForkVersion() []byte { return nil } -func (m *ENRForkID) GetNextForkEpoch() uint64 { +func (m *ENRForkID) GetNextForkEpoch() github_com_prysmaticlabs_eth2_types.Epoch { if m != nil { return m.NextForkEpoch } @@ -296,38 +297,39 @@ func init() { } var fileDescriptor_a1d590cda035b632 = []byte{ - // 489 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x92, 0xcd, 0x6e, 0xd3, 0x40, - 0x14, 0x85, 0x65, 0x48, 0x4b, 0x33, 0x24, 0x84, 0x0c, 0x08, 0x45, 0x45, 0x24, 0x95, 0x17, 0xd0, - 0x4d, 0x6c, 0x92, 0x56, 0xa8, 0x42, 0x2c, 0x90, 0x95, 0x56, 0x62, 0x41, 0x17, 0xae, 0xc4, 0x92, - 0x68, 0xec, 0xdc, 0x38, 0xa3, 0x38, 0xbe, 0xce, 0xcc, 0x75, 0x44, 0xf3, 0x06, 0x3c, 0x0f, 0x2f, - 0xc1, 0x92, 0x27, 0x88, 0x50, 0xb6, 0xec, 0xba, 0x64, 0x85, 0x3c, 0x76, 0xeb, 0x22, 0x84, 0xd4, - 0xdd, 0xfc, 0x7c, 0xdf, 0xd1, 0x9d, 0xa3, 0x61, 0x76, 0xaa, 0x90, 0xd0, 0x0d, 0x40, 0x84, 0x98, - 0xb8, 0xe9, 0x30, 0x75, 0x57, 0x03, 0x77, 0x01, 0x5a, 0x8b, 0x08, 0xb4, 0x63, 0x2e, 0xf9, 0x33, - 0xa0, 0x19, 0x28, 0xc8, 0x16, 0x4e, 0x81, 0x39, 0xe9, 0x30, 0x75, 0x56, 0x83, 0xfd, 0x7e, 0x24, - 0x69, 0x96, 0x05, 0x4e, 0x88, 0x0b, 0x37, 0xc2, 0x08, 0x5d, 0x83, 0x07, 0xd9, 0xd4, 0xec, 0x8a, - 0xe0, 0x7c, 0x55, 0xc4, 0xd8, 0xbf, 0x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5, 0xfc, 0xc3, 0x88, 0xbf, 0x67, - 0x4f, 0xc2, 0x4c, 0x29, 0x48, 0x68, 0x7c, 0x97, 0x7e, 0xdb, 0x25, 0x7c, 0x56, 0xd5, 0xfc, 0x8e, - 0xb5, 0x13, 0xf8, 0x52, 0xea, 0x2b, 0x50, 0x5a, 0x62, 0x52, 0x36, 0xfd, 0xaf, 0xdf, 0xca, 0xd1, - 0x5c, 0xfe, 0x54, 0x80, 0xfc, 0x25, 0x6b, 0x55, 0xf6, 0xed, 0xaa, 0x9b, 0xd7, 0xa4, 0x69, 0xda, - 0xfe, 0x6a, 0xb1, 0xbd, 0x8f, 0x40, 0x62, 0x24, 0x48, 0x98, 0x2e, 0x60, 0x39, 0x4e, 0xb2, 0x45, - 0x00, 0xea, 0xa6, 0x0b, 0x58, 0x9e, 0x9b, 0x03, 0xfe, 0x99, 0x3d, 0x10, 0x44, 0x09, 0x90, 0x2e, - 0xe7, 0x18, 0xfd, 0x3d, 0xc7, 0x89, 0xfd, 0x7b, 0xd3, 0x7b, 0x7d, 0xeb, 0x2b, 0xa6, 0xea, 0x52, - 0x2f, 0x04, 0xc9, 0x30, 0x16, 0x81, 0x76, 0x23, 0xec, 0x07, 0x92, 0xa6, 0x12, 0xe2, 0x89, 0xe3, - 0x49, 0x5a, 0x41, 0x48, 0xa8, 0xde, 0x1c, 0xfb, 0xd7, 0xa1, 0x5e, 0xe3, 0xfb, 0xb6, 0x6b, 0xfd, - 0xd8, 0x76, 0xad, 0x9f, 0xdb, 0xae, 0x15, 0xec, 0x9a, 0xbf, 0x7a, 0xf4, 0x27, 0x00, 0x00, 0xff, - 0xff, 0xf7, 0x8d, 0xaf, 0xcc, 0x18, 0x03, 0x00, 0x00, + // 510 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0xc1, 0x6e, 0xd3, 0x40, + 0x10, 0x86, 0xe5, 0x92, 0x96, 0x66, 0x49, 0x08, 0x59, 0x10, 0x8a, 0x8a, 0x48, 0x2a, 0x9f, 0xca, + 0x21, 0x36, 0x49, 0x2b, 0x54, 0x21, 0x0e, 0xc8, 0x4a, 0x2b, 0x71, 0xa0, 0x07, 0x57, 0xf4, 0x48, + 0xb4, 0x76, 0x26, 0xce, 0x2a, 0x8e, 0xc7, 0xd9, 0x1d, 0x47, 0x24, 0x6f, 0xc0, 0x2b, 0xf0, 0x44, + 0x1c, 0x79, 0x82, 0x08, 0xe5, 0x11, 0x7a, 0xec, 0x09, 0x79, 0xed, 0x36, 0x20, 0x54, 0x09, 0x89, + 0xdb, 0xce, 0xee, 0xff, 0x8d, 0xff, 0x99, 0x5f, 0x66, 0x76, 0xaa, 0x90, 0xd0, 0x0d, 0x40, 0x84, + 0x98, 0xb8, 0x69, 0x3f, 0x75, 0x17, 0x3d, 0x77, 0x06, 0x5a, 0x8b, 0x08, 0xb4, 0x63, 0x1e, 0xf9, + 0x73, 0xa0, 0x09, 0x28, 0xc8, 0x66, 0x4e, 0x21, 0x73, 0xd2, 0x7e, 0xea, 0x2c, 0x7a, 0x07, 0xdd, + 0x48, 0xd2, 0x24, 0x0b, 0x9c, 0x10, 0x67, 0x6e, 0x84, 0x11, 0xba, 0x46, 0x1e, 0x64, 0x63, 0x53, + 0x15, 0x8d, 0xf3, 0x53, 0xd1, 0xc6, 0xfe, 0xb6, 0xc3, 0xf6, 0x2e, 0x49, 0x50, 0xa6, 0x79, 0x8f, + 0x3d, 0x1a, 0xa3, 0x9a, 0x0e, 0x47, 0x32, 0x02, 0x4d, 0x2d, 0xeb, 0xd0, 0x3a, 0xaa, 0x79, 0x4f, + 0xae, 0xd7, 0x9d, 0x9a, 0xd6, 0xab, 0xae, 0x96, 0x2b, 0x78, 0x6b, 0x9f, 0xd8, 0x3e, 0xcb, 0x45, + 0x03, 0xa3, 0xe1, 0xa7, 0xec, 0xf1, 0x58, 0x26, 0x22, 0x96, 0x2b, 0x18, 0x0d, 0x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0x00, 0xa5, 0x25, 0x26, 0x65, 0x30, 0x7f, 0xf3, 0x8d, 0x5c, 0x9a, 0xc3, + 0x57, 0x85, 0x90, 0x7f, 0x62, 0x8d, 0x2d, 0xfd, 0x1f, 0xc9, 0xd4, 0x6f, 0x1b, 0x9b, 0xd2, 0xfe, + 0x6a, 0xb1, 0xfd, 0x8f, 0x40, 0x62, 0x20, 0x48, 0x98, 0xd5, 0xc1, 0x7c, 0x98, 0x64, 0xb3, 0x00, + 0xd4, 0xdd, 0xea, 0x60, 0x7e, 0x61, 0x2e, 0xf8, 0x67, 0xf6, 0x50, 0x10, 0x25, 0x40, 0xba, 0xb4, + 0x3d, 0xf8, 0xd3, 0xf6, 0xa9, 0x7d, 0xb3, 0xee, 0xbc, 0xbe, 0xd7, 0x4a, 0x84, 0xdd, 0x40, 0xd2, + 0x58, 0x42, 0x3c, 0x72, 0x3c, 0x49, 0x0b, 0x08, 0x09, 0xd5, 0x9b, 0x13, 0xff, 0xb6, 0xa9, 0x57, + 0xfb, 0xbe, 0x69, 0x5b, 0x3f, 0x36, 0x6d, 0xeb, 0xe7, 0xa6, 0x6d, 0x05, 0x7b, 0xe6, 0x4f, 0x38, + 0xfe, 0x15, 0x00, 0x00, 0xff, 0xff, 0x26, 0xdc, 0x54, 0x71, 0x76, 0x03, 0x00, 0x00, } func (m *Status) Marshal() (dAtA []byte, err error) { @@ -736,7 +738,7 @@ func (m *Status) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.FinalizedEpoch |= uint64(b&0x7F) << shift + m.FinalizedEpoch |= github_com_prysmaticlabs_eth2_types.Epoch(b&0x7F) << shift if b < 0x80 { break } @@ -1035,7 +1037,7 @@ func (m *ENRForkID) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.NextForkEpoch |= uint64(b&0x7F) << shift + m.NextForkEpoch |= github_com_prysmaticlabs_eth2_types.Epoch(b&0x7F) << shift if b < 0x80 { break } diff --git a/proto/beacon/p2p/v1/messages.proto b/proto/beacon/p2p/v1/messages.proto index 76d138c2b0..d564100f89 100644 --- a/proto/beacon/p2p/v1/messages.proto +++ b/proto/beacon/p2p/v1/messages.proto @@ -7,7 +7,7 @@ import "github.com/gogo/protobuf/gogoproto/gogo.proto"; message Status { bytes fork_digest = 1 [(gogoproto.moretags) = "ssz-size:\"4\""]; bytes finalized_root = 2 [(gogoproto.moretags) = "ssz-size:\"32\""]; - uint64 finalized_epoch = 3; + uint64 finalized_epoch = 3 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Epoch"]; bytes head_root = 4 [(gogoproto.moretags) = "ssz-size:\"32\""]; uint64 head_slot = 5; } @@ -21,7 +21,7 @@ message BeaconBlocksByRangeRequest { message ENRForkID { bytes current_fork_digest = 1 [(gogoproto.moretags) = "ssz-size:\"4\""]; bytes next_fork_version = 2 [(gogoproto.moretags) = "ssz-size:\"4\""]; - uint64 next_fork_epoch = 3; + uint64 next_fork_epoch = 3 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Epoch"]; } /* Spec Definition: diff --git a/proto/beacon/p2p/v1/types.pb.go b/proto/beacon/p2p/v1/types.pb.go index 448e68df78..c7573b733e 100755 --- a/proto/beacon/p2p/v1/types.pb.go +++ b/proto/beacon/p2p/v1/types.pb.go @@ -7,6 +7,7 @@ import ( fmt "fmt" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" + github_com_prysmaticlabs_eth2_types "github.com/prysmaticlabs/eth2-types" v1alpha1 "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" github_com_prysmaticlabs_go_bitfield "github.com/prysmaticlabs/go-bitfield" io "io" @@ -233,12 +234,12 @@ func (m *BeaconState) GetFinalizedCheckpoint() *v1alpha1.Checkpoint { } type Fork struct { - PreviousVersion []byte `protobuf:"bytes,1,opt,name=previous_version,json=previousVersion,proto3" json:"previous_version,omitempty" ssz-size:"4"` - CurrentVersion []byte `protobuf:"bytes,2,opt,name=current_version,json=currentVersion,proto3" json:"current_version,omitempty" ssz-size:"4"` - Epoch uint64 `protobuf:"varint,3,opt,name=epoch,proto3" json:"epoch,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + PreviousVersion []byte `protobuf:"bytes,1,opt,name=previous_version,json=previousVersion,proto3" json:"previous_version,omitempty" ssz-size:"4"` + CurrentVersion []byte `protobuf:"bytes,2,opt,name=current_version,json=currentVersion,proto3" json:"current_version,omitempty" ssz-size:"4"` + Epoch github_com_prysmaticlabs_eth2_types.Epoch `protobuf:"varint,3,opt,name=epoch,proto3,casttype=github.com/prysmaticlabs/eth2-types.Epoch" json:"epoch,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Fork) Reset() { *m = Fork{} } @@ -288,7 +289,7 @@ func (m *Fork) GetCurrentVersion() []byte { return nil } -func (m *Fork) GetEpoch() uint64 { +func (m *Fork) GetEpoch() github_com_prysmaticlabs_eth2_types.Epoch { if m != nil { return m.Epoch } @@ -743,91 +744,92 @@ func init() { func init() { proto.RegisterFile("proto/beacon/p2p/v1/types.proto", fileDescriptor_e719e7d82cfa7b0d) } var fileDescriptor_e719e7d82cfa7b0d = []byte{ - // 1338 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0xcb, 0x6f, 0x1b, 0x45, - 0x18, 0x97, 0x13, 0xb7, 0x4d, 0xc7, 0x4e, 0x9c, 0x4e, 0x4a, 0xb2, 0x7d, 0x90, 0x75, 0x57, 0xf4, - 0x01, 0x6a, 0xec, 0xd8, 0x4d, 0xed, 0x24, 0x15, 0x45, 0x38, 0x2d, 0x6a, 0x5a, 0x55, 0xaa, 0xb6, - 0x50, 0x09, 0x09, 0xb1, 0x9a, 0xdd, 0x1d, 0x7b, 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, 0xdf, 0x8e, - 0x94, 0x73, 0x17, 0xf2, 0x7a, 0x21, 0x36, 0xbe, 0x4e, 0xba, 0x18, 0xde, 0x04, 0x2b, 0x09, 0x26, - 0x8d, 0xce, 0x8c, 0x80, 0x52, 0xae, 0xfc, 0x2e, 0xe0, 0xc5, 0xd6, 0xb1, 0xe1, 0x40, 0x9d, 0x67, - 0xec, 0xd1, 0x1a, 0x23, 0x8f, 0xf0, 0xb6, 0x76, 0xa9, 0xae, 0xe9, 0xcf, 0xc5, 0x94, 0x7b, 0x29, - 0x43, 0xa7, 0x94, 0xc3, 0x25, 0x90, 0x67, 0x2e, 0xe5, 0xca, 0x1f, 0x51, 0x1c, 0xb9, 0x80, 0x35, - 0x90, 0x6f, 0xd3, 0x60, 0x4f, 0xf9, 0x53, 0x18, 0x0b, 0xf5, 0xd3, 0x95, 0x83, 0xa5, 0xac, 0xbc, - 0x46, 0x83, 0x3d, 0x5d, 0x42, 0xe1, 0x9b, 0x60, 0xc9, 0x45, 0x42, 0xca, 0x48, 0x2a, 0xc3, 0xc1, - 0xc8, 0xc6, 0x81, 0xf2, 0x43, 0x49, 0x7a, 0xb8, 0x90, 0x79, 0xc0, 0xdc, 0xa9, 0x24, 0xe2, 0x55, - 0xa2, 0x9b, 0xb7, 0x04, 0xe3, 0x86, 0x24, 0xe8, 0xc7, 0x22, 0x2f, 0x23, 0x26, 0xb8, 0x09, 0x0a, - 0x91, 0x4f, 0x71, 0x43, 0xa6, 0xfc, 0x58, 0x2a, 0xcf, 0x5e, 0x28, 0xb6, 0x96, 0x87, 0x03, 0x15, - 0x66, 0x57, 0xdc, 0xac, 0x6d, 0xd5, 0x2f, 0x8a, 0x7b, 0x02, 0x89, 0x15, 0x77, 0x63, 0x82, 0x29, - 0x72, 0x8b, 0x63, 0xe6, 0x4f, 0xff, 0xc2, 0x94, 0xd8, 0x88, 0xa9, 0x83, 0x45, 0x87, 0x30, 0x4e, - 0x03, 0x62, 0x21, 0x37, 0xa6, 0xff, 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 0x0c, 0x00, 0x00, + // 1358 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0x4b, 0x6f, 0xdb, 0xc6, + 0x16, 0x86, 0x6c, 0x25, 0x71, 0x46, 0xb2, 0xe5, 0x8c, 0xef, 0xb5, 0x99, 0xc7, 0x35, 0x15, 0xe2, + 0xe6, 0x55, 0x44, 0x92, 0xa5, 0x38, 0x92, 0xed, 0xa0, 0x29, 0x2a, 0x27, 0x45, 0x9c, 0x20, 0x40, + 0xc0, 0xb4, 0x01, 0x0a, 0x14, 0x25, 0x86, 0xe4, 0x48, 0x9c, 0x98, 0xe2, 0x10, 0x9c, 0x91, 0x12, + 0x05, 0x28, 0xba, 0xe8, 0xaa, 0xab, 0xf6, 0x2f, 0xb4, 0x7f, 0xa2, 0xaf, 0x55, 0x9b, 0x2e, 0xba, + 0xec, 0x6b, 0x93, 0x2e, 0x84, 0x22, 0xbb, 0x3e, 0x36, 0xd5, 0x32, 0xab, 0x62, 0x66, 0x48, 0x51, + 0x6a, 0xac, 0x54, 0x05, 0xba, 0x23, 0xcf, 0x7c, 0xdf, 0x39, 0x33, 0xdf, 0x39, 0x73, 0xe6, 0x00, + 0x3d, 0x8c, 0x28, 0xa7, 0x15, 0x1b, 0x23, 0x87, 0x06, 0x95, 0xb0, 0x16, 0x56, 0x7a, 0xd5, 0x0a, + 0xef, 0x87, 0x98, 0x95, 0xe5, 0x0a, 0x5c, 0xc5, 0xdc, 0xc3, 0x11, 0xee, 0x76, 0xca, 0x0a, 0x53, + 0x0e, 0x6b, 0x61, 0xb9, 0x57, 0x3d, 0xb1, 0x8e, 0xb9, 0x57, 0xe9, 0x55, 0x91, 0x1f, 0x7a, 0xa8, + 0x5a, 0x41, 0x9c, 0x63, 0xc6, 0x11, 0x27, 0x02, 0x20, 0x78, 0x27, 0xf4, 0x89, 0x75, 0xc5, 0xb5, + 0x6c, 0x9f, 0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84, 0xba, 0x0b, 0x0e, + 0xc9, 0x8a, 0xd4, 0xe6, 0x45, 0x1b, 0x69, 0x96, 0x9e, 0x0d, 0xf4, 0x0b, 0x53, 0x93, 0x8f, 0xb9, + 0x57, 0x2b, 0xa9, 0x07, 0x5c, 0x16, 0x99, 0xa9, 0xb8, 0xc6, 0x07, 0x73, 0x00, 0x3e, 0x5f, 0xa4, + 0xb0, 0x03, 0x96, 0x51, 0xbb, 0x1d, 0xe1, 0xf6, 0x58, 0xd1, 0xa9, 0x33, 0x35, 0x9f, 0xef, 0x76, + 0xcf, 0x06, 0xfa, 0xc5, 0x59, 0xab, 0xce, 0x27, 0x8c, 0x9b, 0x85, 0x31, 0xdf, 0xb2, 0xe0, 0x76, + 0x40, 0x56, 0xf6, 0xed, 0x39, 0x99, 0x91, 0xb3, 0x53, 0x32, 0x32, 0xb6, 0x41, 0xd9, 0xbd, 0x25, + 0x07, 0x9e, 0x03, 0x05, 0x12, 0x38, 0x7e, 0x57, 0x68, 0x62, 0xb9, 0xd8, 0x47, 0x7d, 0x25, 0x88, + 0xb9, 0x34, 0x32, 0x5f, 0x13, 0x56, 0x78, 0x06, 0x2c, 0x85, 0x11, 0x0d, 0x29, 0xc3, 0x51, 0xdc, + 0x80, 0xb3, 0x12, 0xb7, 0x98, 0x58, 0x65, 0xf3, 0x35, 0xde, 0xcb, 0x80, 0xc2, 0x8d, 0xd1, 0xe3, + 0xd2, 0x44, 0xdc, 0xf1, 0x60, 0x63, 0xf2, 0x91, 0xcc, 0xcc, 0xfc, 0x46, 0x36, 0x26, 0xdf, 0xc8, + 0xb9, 0x59, 0x9f, 0x48, 0xa3, 0x0e, 0xf2, 0x72, 0x64, 0xb9, 0xdb, 0xed, 0x74, 0x50, 0xd4, 0x87, + 0x30, 0x9e, 0x24, 0x32, 0x63, 0x83, 0x04, 0x04, 0x59, 0x39, 0x96, 0xc8, 0x82, 0x31, 0xe5, 0xb7, + 0xe1, 0x83, 0xdc, 0x5d, 0xd2, 0x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0xe3, 0xbe, 0x61, + 0x1e, 0x55, 0xbc, 0x5b, 0xb8, 0x0f, 0x6f, 0x80, 0xd5, 0x07, 0x84, 0x7b, 0x6e, 0x84, 0x1e, 0x20, + 0xdf, 0x72, 0x22, 0xec, 0xe2, 0x80, 0x13, 0xe4, 0xb3, 0x17, 0x88, 0x9b, 0x12, 0x76, 0x53, 0x3c, + 0x5c, 0x05, 0x87, 0x51, 0x87, 0x76, 0x03, 0x1e, 0x5f, 0xb1, 0xf8, 0xaf, 0x99, 0xff, 0xe6, 0xe9, + 0x7a, 0xe6, 0xdb, 0xa7, 0xeb, 0x99, 0x9f, 0x9f, 0xae, 0x67, 0xec, 0xc3, 0x72, 0xf8, 0xbe, 0xf4, + 0x67, 0x00, 0x00, 0x00, 0xff, 0xff, 0xc5, 0xb4, 0xbb, 0x92, 0x45, 0x0c, 0x00, 0x00, } func (m *BeaconState) Marshal() (dAtA []byte, err error) { @@ -2791,7 +2793,7 @@ func (m *Fork) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.Epoch |= uint64(b&0x7F) << shift + m.Epoch |= github_com_prysmaticlabs_eth2_types.Epoch(b&0x7F) << shift if b < 0x80 { break } diff --git a/proto/beacon/p2p/v1/types.proto b/proto/beacon/p2p/v1/types.proto index aa77b3c0ae..5f5db49180 100644 --- a/proto/beacon/p2p/v1/types.proto +++ b/proto/beacon/p2p/v1/types.proto @@ -49,7 +49,7 @@ message BeaconState { message Fork { bytes previous_version = 1 [(gogoproto.moretags) = "ssz-size:\"4\""]; bytes current_version = 2 [(gogoproto.moretags) = "ssz-size:\"4\""]; - uint64 epoch = 3; + uint64 epoch = 3 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Epoch"]; } message PendingAttestation { diff --git a/proto/beacon/rpc/v1/BUILD.bazel b/proto/beacon/rpc/v1/BUILD.bazel index 7e54d03df8..72ce5abc08 100644 --- a/proto/beacon/rpc/v1/BUILD.bazel +++ b/proto/beacon/rpc/v1/BUILD.bazel @@ -15,10 +15,12 @@ go_proto_library( visibility = ["//visibility:public"], deps = [ "//proto/beacon/p2p/v1:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_golang_protobuf//descriptor:go_default_library", "@com_github_golang_protobuf//ptypes/empty:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@go_googleapis//google/api:annotations_go_proto", + "@com_github_gogo_protobuf//gogoproto:go_default_library", ], ) @@ -30,6 +32,7 @@ go_proto_library( visibility = ["//visibility:public"], deps = [ "//proto/beacon/p2p/v1:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_golang_protobuf//ptypes/empty:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@go_googleapis//google/api:annotations_go_proto", @@ -52,5 +55,6 @@ proto_library( "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:proto", "@com_google_protobuf//:empty_proto", "@go_googleapis//google/api:annotations_proto", + "@gogo_special_proto//github.com/gogo/protobuf/gogoproto", ], ) diff --git a/proto/beacon/rpc/v1/debug.pb.go b/proto/beacon/rpc/v1/debug.pb.go index c74e7610c2..869209a84d 100755 --- a/proto/beacon/rpc/v1/debug.pb.go +++ b/proto/beacon/rpc/v1/debug.pb.go @@ -7,8 +7,10 @@ import ( context "context" encoding_binary "encoding/binary" fmt "fmt" + _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" types "github.com/gogo/protobuf/types" + github_com_prysmaticlabs_eth2_types "github.com/prysmaticlabs/eth2-types" v1alpha1 "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" v1 "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" _ "google.golang.org/genproto/googleapis/api/annotations" @@ -391,14 +393,14 @@ func (m *LoggingLevelRequest) GetLevel() LoggingLevelRequest_Level { } type ProtoArrayForkChoiceResponse struct { - PruneThreshold uint64 `protobuf:"varint,1,opt,name=prune_threshold,json=pruneThreshold,proto3" json:"prune_threshold,omitempty"` - JustifiedEpoch uint64 `protobuf:"varint,2,opt,name=justified_epoch,json=justifiedEpoch,proto3" json:"justified_epoch,omitempty"` - FinalizedEpoch uint64 `protobuf:"varint,3,opt,name=finalized_epoch,json=finalizedEpoch,proto3" json:"finalized_epoch,omitempty"` - ProtoArrayNodes []*ProtoArrayNode `protobuf:"bytes,4,rep,name=proto_array_nodes,json=protoArrayNodes,proto3" json:"proto_array_nodes,omitempty"` - Indices map[string]uint64 `protobuf:"bytes,5,rep,name=indices,proto3" json:"indices,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + PruneThreshold uint64 `protobuf:"varint,1,opt,name=prune_threshold,json=pruneThreshold,proto3" json:"prune_threshold,omitempty"` + JustifiedEpoch github_com_prysmaticlabs_eth2_types.Epoch `protobuf:"varint,2,opt,name=justified_epoch,json=justifiedEpoch,proto3,casttype=github.com/prysmaticlabs/eth2-types.Epoch" json:"justified_epoch,omitempty"` + FinalizedEpoch github_com_prysmaticlabs_eth2_types.Epoch `protobuf:"varint,3,opt,name=finalized_epoch,json=finalizedEpoch,proto3,casttype=github.com/prysmaticlabs/eth2-types.Epoch" json:"finalized_epoch,omitempty"` + ProtoArrayNodes []*ProtoArrayNode `protobuf:"bytes,4,rep,name=proto_array_nodes,json=protoArrayNodes,proto3" json:"proto_array_nodes,omitempty"` + Indices map[string]uint64 `protobuf:"bytes,5,rep,name=indices,proto3" json:"indices,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *ProtoArrayForkChoiceResponse) Reset() { *m = ProtoArrayForkChoiceResponse{} } @@ -441,14 +443,14 @@ func (m *ProtoArrayForkChoiceResponse) GetPruneThreshold() uint64 { return 0 } -func (m *ProtoArrayForkChoiceResponse) GetJustifiedEpoch() uint64 { +func (m *ProtoArrayForkChoiceResponse) GetJustifiedEpoch() github_com_prysmaticlabs_eth2_types.Epoch { if m != nil { return m.JustifiedEpoch } return 0 } -func (m *ProtoArrayForkChoiceResponse) GetFinalizedEpoch() uint64 { +func (m *ProtoArrayForkChoiceResponse) GetFinalizedEpoch() github_com_prysmaticlabs_eth2_types.Epoch { if m != nil { return m.FinalizedEpoch } @@ -470,17 +472,17 @@ func (m *ProtoArrayForkChoiceResponse) GetIndices() map[string]uint64 { } type ProtoArrayNode struct { - Slot uint64 `protobuf:"varint,1,opt,name=slot,proto3" json:"slot,omitempty"` - Root []byte `protobuf:"bytes,2,opt,name=root,proto3" json:"root,omitempty"` - Parent uint64 `protobuf:"varint,3,opt,name=parent,proto3" json:"parent,omitempty"` - JustifiedEpoch uint64 `protobuf:"varint,4,opt,name=justified_epoch,json=justifiedEpoch,proto3" json:"justified_epoch,omitempty"` - FinalizedEpoch uint64 `protobuf:"varint,5,opt,name=finalized_epoch,json=finalizedEpoch,proto3" json:"finalized_epoch,omitempty"` - Weight uint64 `protobuf:"varint,6,opt,name=weight,proto3" json:"weight,omitempty"` - BestChild uint64 `protobuf:"varint,7,opt,name=best_child,json=bestChild,proto3" json:"best_child,omitempty"` - BestDescendant uint64 `protobuf:"varint,8,opt,name=best_descendant,json=bestDescendant,proto3" json:"best_descendant,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Slot uint64 `protobuf:"varint,1,opt,name=slot,proto3" json:"slot,omitempty"` + Root []byte `protobuf:"bytes,2,opt,name=root,proto3" json:"root,omitempty"` + Parent uint64 `protobuf:"varint,3,opt,name=parent,proto3" json:"parent,omitempty"` + JustifiedEpoch github_com_prysmaticlabs_eth2_types.Epoch `protobuf:"varint,4,opt,name=justified_epoch,json=justifiedEpoch,proto3,casttype=github.com/prysmaticlabs/eth2-types.Epoch" json:"justified_epoch,omitempty"` + FinalizedEpoch github_com_prysmaticlabs_eth2_types.Epoch `protobuf:"varint,5,opt,name=finalized_epoch,json=finalizedEpoch,proto3,casttype=github.com/prysmaticlabs/eth2-types.Epoch" json:"finalized_epoch,omitempty"` + Weight uint64 `protobuf:"varint,6,opt,name=weight,proto3" json:"weight,omitempty"` + BestChild uint64 `protobuf:"varint,7,opt,name=best_child,json=bestChild,proto3" json:"best_child,omitempty"` + BestDescendant uint64 `protobuf:"varint,8,opt,name=best_descendant,json=bestDescendant,proto3" json:"best_descendant,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *ProtoArrayNode) Reset() { *m = ProtoArrayNode{} } @@ -537,14 +539,14 @@ func (m *ProtoArrayNode) GetParent() uint64 { return 0 } -func (m *ProtoArrayNode) GetJustifiedEpoch() uint64 { +func (m *ProtoArrayNode) GetJustifiedEpoch() github_com_prysmaticlabs_eth2_types.Epoch { if m != nil { return m.JustifiedEpoch } return 0 } -func (m *ProtoArrayNode) GetFinalizedEpoch() uint64 { +func (m *ProtoArrayNode) GetFinalizedEpoch() github_com_prysmaticlabs_eth2_types.Epoch { if m != nil { return m.FinalizedEpoch } @@ -1005,101 +1007,105 @@ func init() { func init() { proto.RegisterFile("proto/beacon/rpc/v1/debug.proto", fileDescriptor_851e5cb2de3d61dd) } var fileDescriptor_851e5cb2de3d61dd = []byte{ - // 1504 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x57, 0x4b, 0x6f, 0x1b, 0xc9, - 0x11, 0x36, 0x29, 0x51, 0xd2, 0x14, 0x19, 0x8a, 0x6e, 0xcb, 0x12, 0x43, 0xdb, 0x7a, 0x8c, 0x1d, - 0x3f, 0x63, 0x32, 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0x00, 0xff, 0xff, 0x48, 0xd6, 0xf7, 0x7c, 0xb3, 0x0e, 0x00, 0x00, + // 1568 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x57, 0x5f, 0x6f, 0x1b, 0xc7, + 0x11, 0x37, 0x29, 0x51, 0xd2, 0x0d, 0x59, 0x8a, 0xde, 0x38, 0x32, 0x4b, 0xdb, 0x92, 0x7c, 0x4e, + 0xe3, 0x38, 0xae, 0x8e, 0x15, 0x5b, 0x14, 0x81, 0x11, 0xa0, 0xb1, 0xfe, 0x44, 0x11, 0x60, 0x27, + 0xee, 0xc9, 0xce, 0x43, 0x83, 0xe2, 0xb0, 0xba, 0x1b, 0xf2, 0x36, 0x3e, 0xde, 0x5e, 0x76, 0x97, + 0x6c, 0x99, 0xbe, 0x15, 0x05, 0xfa, 0xd8, 0x87, 0x02, 0x7d, 0xee, 0xc7, 0x29, 0xd0, 0x97, 0x02, + 0x7d, 0x2f, 0x02, 0x23, 0xe8, 0x87, 0xf0, 0x53, 0xb1, 0xbb, 0x77, 0x47, 0x32, 0x24, 0x13, 0x37, + 0x70, 0xde, 0x76, 0x7e, 0x33, 0xf3, 0x9b, 0xb9, 0x99, 0xd9, 0x3f, 0x07, 0x7b, 0x99, 0xe0, 0x8a, + 0x77, 0x2f, 0x91, 0x86, 0x3c, 0xed, 0x8a, 0x2c, 0xec, 0x8e, 0x0f, 0xbb, 0x11, 0x5e, 0x8e, 0x06, + 0x9e, 0xd1, 0x90, 0x1d, 0x54, 0x31, 0x0a, 0x1c, 0x0d, 0x3d, 0x6b, 0xe3, 0x89, 0x2c, 0xf4, 0xc6, + 0x87, 0x9d, 0xeb, 0xa8, 0xe2, 0xee, 0xf8, 0x90, 0x26, 0x59, 0x4c, 0x0f, 0xbb, 0x29, 0x8f, 0xd0, + 0x3a, 0x74, 0xdc, 0x39, 0xc6, 0xac, 0x97, 0x69, 0xc6, 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x30, 0xcf, 0x32, 0xd4, 0x53, 0x1f, 0x05, 0xe6, 0x8a, 0x96, + 0xf9, 0xb1, 0xb8, 0x5d, 0xe2, 0xe6, 0x6e, 0x97, 0xe4, 0x67, 0x70, 0xcd, 0xde, 0xea, 0x99, 0xe0, + 0x63, 0x16, 0xe9, 0x51, 0x30, 0xb4, 0x6b, 0x86, 0x96, 0x18, 0xdd, 0x93, 0x5c, 0x65, 0xc9, 0x9f, + 0x41, 0x43, 0xf1, 0x8c, 0x85, 0xd6, 0xb0, 0xb8, 0x36, 0x7a, 0xdf, 0xd9, 0x50, 0xef, 0xa9, 0xf6, + 0x32, 0x62, 0x7e, 0xba, 0xd7, 0xd5, 0x14, 0xd1, 0x95, 0x18, 0x70, 0x29, 0x59, 0x96, 0x27, 0x50, + 0x33, 0x09, 0xd4, 0x2d, 0x66, 0x23, 0xdf, 0x87, 0xab, 0x97, 0x18, 0xd3, 0x31, 0xe3, 0x23, 0x11, + 0x64, 0x98, 0xd2, 0x44, 0xd9, 0x8a, 0x55, 0xfd, 0x56, 0xa9, 0x78, 0x62, 0x71, 0x5d, 0x83, 0x31, + 0x4d, 0x58, 0x64, 0x5e, 0x79, 0x01, 0x0a, 0xc1, 0x85, 0x19, 0x6f, 0xc7, 0xdf, 0x9e, 0xe2, 0xa7, + 0x1a, 0xee, 0x7c, 0x0e, 0xad, 0x6f, 0xe6, 0xb6, 0xe4, 0x82, 0xf9, 0x60, 0xf6, 0x82, 0xa9, 0xf7, + 0xde, 0x5d, 0xf5, 0xc1, 0x53, 0xaa, 0x8b, 0x94, 0x66, 0x32, 0xe6, 0x6a, 0xf6, 0x32, 0xfa, 0x6f, + 0x05, 0xc8, 0xa2, 0x05, 0xd9, 0x87, 0x86, 0x62, 0x43, 0xbd, 0x45, 0x82, 0x21, 0xca, 0x38, 0xbf, + 0x98, 0x40, 0x63, 0xe7, 0xe9, 0x63, 0x94, 0x31, 0x79, 0x0f, 0xda, 0x7d, 0x26, 0xa4, 0x0a, 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, 0xa4, 0xb3, 0x4f, 0x76, 0x97, 0xa5, 0xd3, 0xe7, 0xe2, 0x79, 0x68, 0xa3, 0x0a, 0x70, + 0x1e, 0x31, 0xa9, 0xf4, 0x81, 0x2e, 0x57, 0xa6, 0xf0, 0xee, 0x2b, 0x5f, 0x6b, 0xf2, 0xdb, 0x5b, + 0x90, 0x99, 0x30, 0x5f, 0xc2, 0xa6, 0x2e, 0x02, 0xa2, 0x20, 0xee, 0xb7, 0x5c, 0xf9, 0x45, 0xc5, + 0x5f, 0xfd, 0x99, 0xe2, 0xee, 0x9b, 0xe0, 0x1d, 0xd2, 0x5e, 0x15, 0x9c, 0xfc, 0xad, 0x02, 0xad, + 0x33, 0x54, 0x73, 0xbf, 0x75, 0xe4, 0xa7, 0xab, 0x22, 0x2c, 0xfb, 0x73, 0xec, 0x1c, 0xbc, 0xa2, + 0x75, 0x9e, 0xd3, 0x4f, 0x4c, 0x4e, 0x7b, 0xe4, 0xd6, 0xb2, 0x9c, 0x58, 0xe1, 0x72, 0xd4, 0xf8, + 0xc7, 0x8b, 0xdd, 0xca, 0xbf, 0x5e, 0xec, 0x56, 0xbe, 0x7a, 0xb1, 0x5b, 0xb9, 0xdc, 0x30, 0x1d, + 0xf8, 0xf9, 0xff, 0x02, 0x00, 0x00, 0xff, 0xff, 0x84, 0xeb, 0x52, 0x3a, 0x9e, 0x0f, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -3065,7 +3071,7 @@ func (m *ProtoArrayForkChoiceResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.JustifiedEpoch |= uint64(b&0x7F) << shift + m.JustifiedEpoch |= github_com_prysmaticlabs_eth2_types.Epoch(b&0x7F) << shift if b < 0x80 { break } @@ -3084,7 +3090,7 @@ func (m *ProtoArrayForkChoiceResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.FinalizedEpoch |= uint64(b&0x7F) << shift + m.FinalizedEpoch |= github_com_prysmaticlabs_eth2_types.Epoch(b&0x7F) << shift if b < 0x80 { break } @@ -3373,7 +3379,7 @@ func (m *ProtoArrayNode) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.JustifiedEpoch |= uint64(b&0x7F) << shift + m.JustifiedEpoch |= github_com_prysmaticlabs_eth2_types.Epoch(b&0x7F) << shift if b < 0x80 { break } @@ -3392,7 +3398,7 @@ func (m *ProtoArrayNode) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.FinalizedEpoch |= uint64(b&0x7F) << shift + m.FinalizedEpoch |= github_com_prysmaticlabs_eth2_types.Epoch(b&0x7F) << shift if b < 0x80 { break } diff --git a/proto/beacon/rpc/v1/debug.proto b/proto/beacon/rpc/v1/debug.proto index b49836e374..9ae1be0e85 100644 --- a/proto/beacon/rpc/v1/debug.proto +++ b/proto/beacon/rpc/v1/debug.proto @@ -6,6 +6,7 @@ import "eth/v1alpha1/node.proto"; import "proto/beacon/p2p/v1/messages.proto"; import "google/api/annotations.proto"; import "google/protobuf/empty.proto"; +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; // Debug service API // @@ -99,9 +100,9 @@ message ProtoArrayForkChoiceResponse { // The prune threshold of how many nodes allowed in proto array store. uint64 prune_threshold = 1; // Latest justified epoch in proto array store. - uint64 justified_epoch = 2; + uint64 justified_epoch = 2 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Epoch"]; // Latest finalized epoch in proto array store. - uint64 finalized_epoch = 3; + uint64 finalized_epoch = 3 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Epoch"]; // The list of the proto array nodes in store. repeated ProtoArrayNode proto_array_nodes = 4; // Root to indices mapping of the proto array nodes in store. @@ -116,9 +117,9 @@ message ProtoArrayNode { // Parent of the proto array node. uint64 parent = 3; // Justified epoch of the current proto array node. - uint64 justified_epoch = 4; + uint64 justified_epoch = 4 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Epoch"]; // finalized epoch of the current proto array node. - uint64 finalized_epoch = 5; + uint64 finalized_epoch = 5 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Epoch"]; // Current weight of the current proto array node. uint64 weight = 6; // Best child of the current proto array node. diff --git a/proto/slashing/BUILD.bazel b/proto/slashing/BUILD.bazel index b3d3f54200..7a1d1ea87c 100644 --- a/proto/slashing/BUILD.bazel +++ b/proto/slashing/BUILD.bazel @@ -22,6 +22,7 @@ go_proto_library( proto = ":ethereum_slashing_proto", visibility = ["//visibility:public"], deps = [ + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_gogo_protobuf//gogoproto:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", diff --git a/proto/slashing/slashing.pb.go b/proto/slashing/slashing.pb.go index 9ba51e552a..b0cd4ca917 100755 --- a/proto/slashing/slashing.pb.go +++ b/proto/slashing/slashing.pb.go @@ -12,6 +12,7 @@ import ( _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" + github_com_prysmaticlabs_eth2_types "github.com/prysmaticlabs/eth2-types" v1alpha1 "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" github_com_prysmaticlabs_go_bitfield "github.com/prysmaticlabs/go-bitfield" grpc "google.golang.org/grpc" @@ -125,12 +126,12 @@ func (m *HighestAttestationResponse) GetAttestations() []*HighestAttestation { } type HighestAttestation struct { - ValidatorId uint64 `protobuf:"varint,1,opt,name=validator_id,json=validatorId,proto3" json:"validator_id,omitempty"` - HighestSourceEpoch uint64 `protobuf:"varint,2,opt,name=highest_source_epoch,json=highestSourceEpoch,proto3" json:"highest_source_epoch,omitempty"` - HighestTargetEpoch uint64 `protobuf:"varint,3,opt,name=highest_target_epoch,json=highestTargetEpoch,proto3" json:"highest_target_epoch,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + ValidatorId uint64 `protobuf:"varint,1,opt,name=validator_id,json=validatorId,proto3" json:"validator_id,omitempty"` + HighestSourceEpoch github_com_prysmaticlabs_eth2_types.Epoch `protobuf:"varint,2,opt,name=highest_source_epoch,json=highestSourceEpoch,proto3,casttype=github.com/prysmaticlabs/eth2-types.Epoch" json:"highest_source_epoch,omitempty"` + HighestTargetEpoch github_com_prysmaticlabs_eth2_types.Epoch `protobuf:"varint,3,opt,name=highest_target_epoch,json=highestTargetEpoch,proto3,casttype=github.com/prysmaticlabs/eth2-types.Epoch" json:"highest_target_epoch,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *HighestAttestation) Reset() { *m = HighestAttestation{} } @@ -173,14 +174,14 @@ func (m *HighestAttestation) GetValidatorId() uint64 { return 0 } -func (m *HighestAttestation) GetHighestSourceEpoch() uint64 { +func (m *HighestAttestation) GetHighestSourceEpoch() github_com_prysmaticlabs_eth2_types.Epoch { if m != nil { return m.HighestSourceEpoch } return 0 } -func (m *HighestAttestation) GetHighestTargetEpoch() uint64 { +func (m *HighestAttestation) GetHighestTargetEpoch() github_com_prysmaticlabs_eth2_types.Epoch { if m != nil { return m.HighestTargetEpoch } @@ -330,7 +331,7 @@ func (m *AttesterSlashingResponse) GetAttesterSlashing() []*v1alpha1.AttesterSla type ProposalHistory struct { EpochBits github_com_prysmaticlabs_go_bitfield.Bitlist `protobuf:"bytes,1,opt,name=epoch_bits,json=epochBits,proto3,casttype=github.com/prysmaticlabs/go-bitfield.Bitlist" json:"epoch_bits,omitempty"` - LatestEpochWritten uint64 `protobuf:"varint,2,opt,name=latest_epoch_written,json=latestEpochWritten,proto3" json:"latest_epoch_written,omitempty"` + LatestEpochWritten github_com_prysmaticlabs_eth2_types.Epoch `protobuf:"varint,2,opt,name=latest_epoch_written,json=latestEpochWritten,proto3,casttype=github.com/prysmaticlabs/eth2-types.Epoch" json:"latest_epoch_written,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` @@ -376,7 +377,7 @@ func (m *ProposalHistory) GetEpochBits() github_com_prysmaticlabs_go_bitfield.Bi return nil } -func (m *ProposalHistory) GetLatestEpochWritten() uint64 { +func (m *ProposalHistory) GetLatestEpochWritten() github_com_prysmaticlabs_eth2_types.Epoch { if m != nil { return m.LatestEpochWritten } @@ -384,11 +385,11 @@ func (m *ProposalHistory) GetLatestEpochWritten() uint64 { } type AttestationHistory struct { - TargetToSource map[uint64]uint64 `protobuf:"bytes,1,rep,name=target_to_source,json=targetToSource,proto3" json:"target_to_source,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` - LatestEpochWritten uint64 `protobuf:"varint,2,opt,name=latest_epoch_written,json=latestEpochWritten,proto3" json:"latest_epoch_written,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + TargetToSource map[uint64]uint64 `protobuf:"bytes,1,rep,name=target_to_source,json=targetToSource,proto3" json:"target_to_source,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` + LatestEpochWritten github_com_prysmaticlabs_eth2_types.Epoch `protobuf:"varint,2,opt,name=latest_epoch_written,json=latestEpochWritten,proto3,casttype=github.com/prysmaticlabs/eth2-types.Epoch" json:"latest_epoch_written,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *AttestationHistory) Reset() { *m = AttestationHistory{} } @@ -431,7 +432,7 @@ func (m *AttestationHistory) GetTargetToSource() map[uint64]uint64 { return nil } -func (m *AttestationHistory) GetLatestEpochWritten() uint64 { +func (m *AttestationHistory) GetLatestEpochWritten() github_com_prysmaticlabs_eth2_types.Epoch { if m != nil { return m.LatestEpochWritten } @@ -453,49 +454,50 @@ func init() { func init() { proto.RegisterFile("proto/slashing/slashing.proto", fileDescriptor_da7e95107d0081b4) } var fileDescriptor_da7e95107d0081b4 = []byte{ - // 661 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x55, 0xdd, 0x4e, 0xd4, 0x40, - 0x14, 0x4e, 0x01, 0x7f, 0x18, 0x56, 0x5d, 0x06, 0x62, 0xd6, 0x0d, 0x2e, 0x58, 0x63, 0x84, 0x08, - 0x5d, 0xc0, 0x1b, 0xf5, 0x4a, 0x36, 0x31, 0x61, 0x6f, 0xd4, 0x2c, 0x18, 0x2f, 0x9b, 0x69, 0x7b, - 0x68, 0x27, 0x94, 0x4e, 0x9d, 0x39, 0x8b, 0xee, 0x7b, 0x78, 0xe7, 0x43, 0xf8, 0x1a, 0x5e, 0xfa, - 0x04, 0xc6, 0xf0, 0x00, 0x3e, 0x80, 0x57, 0xa6, 0x33, 0xed, 0x6e, 0xa1, 0x5d, 0xb3, 0xdc, 0x4d, - 0xcf, 0xdf, 0x77, 0xce, 0x77, 0xbe, 0x99, 0x92, 0x87, 0xa9, 0x14, 0x28, 0xba, 0x2a, 0x66, 0x2a, - 0xe2, 0x49, 0x38, 0x3e, 0x38, 0xda, 0x4e, 0x97, 0x01, 0x23, 0x90, 0x30, 0x3c, 0x73, 0x0a, 0x47, - 0x7b, 0x1d, 0x30, 0xea, 0x9e, 0xef, 0xb1, 0x38, 0x8d, 0xd8, 0x5e, 0xd7, 0x03, 0xe6, 0x8b, 0xc4, - 0xf5, 0x62, 0xe1, 0x9f, 0x9a, 0x9c, 0xf6, 0x4e, 0xc8, 0x31, 0x1a, 0x7a, 0x8e, 0x2f, 0xce, 0xba, - 0xa1, 0x08, 0x45, 0x57, 0x9b, 0xbd, 0xe1, 0x89, 0xfe, 0x32, 0x78, 0xd9, 0xc9, 0x84, 0xdb, 0xaf, - 0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92, - 0x29, 0xdf, 0xa1, 0xad, 0x29, 0x8b, 0xee, 0x27, 0x01, 0x7c, 0x81, 0xa0, 0x14, 0xda, 0x7e, 0x36, - 0x95, 0x90, 0x1a, 0x6d, 0x09, 0xd2, 0x2c, 0x21, 0xf6, 0xb2, 0x67, 0x8a, 0x3a, 0x53, 0xb0, 0x8e, - 0x78, 0x98, 0x40, 0xd0, 0xd3, 0x2f, 0x9a, 0x8e, 0x3c, 0x04, 0x16, 0x80, 0xac, 0x05, 0x9c, 0x7a, - 0xd3, 0x38, 0xe9, 0xd4, 0x8f, 0xf8, 0x56, 0x7c, 0x48, 0x03, 0x86, 0x70, 0x9d, 0x51, 0xd7, 0x6a, - 0x90, 0x27, 0x37, 0xce, 0x23, 0xad, 0xab, 0xb3, 0x8d, 0x41, 0x36, 0xa7, 0x80, 0x54, 0xa7, 0xfb, - 0x3f, 0x86, 0x24, 0x2b, 0xd5, 0x17, 0x4f, 0xd1, 0xed, 0xd9, 0x9e, 0x4f, 0xf3, 0x8a, 0xb7, 0x77, - 0x66, 0x8c, 0x36, 0x14, 0xf6, 0x1a, 0x3f, 0x2e, 0x3a, 0xd6, 0xcf, 0x8b, 0x8e, 0xf5, 0xfb, 0xa2, - 0x63, 0x79, 0x37, 0xf5, 0x6f, 0xe2, 0xf9, 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xe6, 0x5a, 0x08, - 0xcf, 0xaa, 0x06, 0x00, 0x00, + // 685 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x55, 0xcd, 0x6e, 0xd3, 0x4c, + 0x14, 0x95, 0xdb, 0x7e, 0x3f, 0x9d, 0xe6, 0xfb, 0x48, 0xa7, 0x15, 0x0a, 0x51, 0x49, 0x4b, 0x10, + 0xa2, 0x15, 0x8d, 0x43, 0xcb, 0x06, 0x58, 0x51, 0x4b, 0x48, 0xcd, 0x06, 0x90, 0x5b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0x20, 0x97, 0x8e, 0x76, 0xbf, 0x59, 0x84, 0x56, 0x93, 0xe8, 0x1d, + 0xd2, 0x28, 0x17, 0xd9, 0xb2, 0x36, 0xac, 0xcd, 0x05, 0x77, 0xa9, 0x54, 0x23, 0xf5, 0xc8, 0x6a, + 0x6c, 0x0e, 0x7a, 0x4a, 0x0c, 0x65, 0x00, 0x1e, 0x64, 0x22, 0x88, 0x5b, 0x73, 0x79, 0xaa, 0xd3, + 0xbb, 0x38, 0x5b, 0xdf, 0x2a, 0xa9, 0x96, 0xc9, 0x91, 0x3a, 0x61, 0xc8, 0x83, 0x84, 0xf9, 0xaa, + 0x0f, 0x18, 0xef, 0xf6, 0x70, 0x94, 0x81, 0xb2, 0x9f, 0xe7, 0x87, 0x5c, 0x5a, 0x40, 0x1d, 0x68, + 0x24, 0x1d, 0x2b, 0x13, 0x20, 0x93, 0x11, 0x60, 0x41, 0x30, 0xff, 0x3b, 0x04, 0x87, 0x1a, 0x49, + 0xc7, 0xba, 0x19, 0x69, 0xbd, 0x92, 0x22, 0x13, 0x0a, 0xe4, 0x41, 0x21, 0xd8, 0x44, 0xe2, 0x43, + 0xb2, 0x9c, 0x15, 0xdf, 0xbc, 0xb1, 0x9a, 0x85, 0xce, 0xf7, 0xa7, 0x3a, 0x03, 0xc6, 0xf6, 0xd8, + 0x37, 0x76, 0x05, 0xab, 0x99, 0x5d, 0x89, 0x74, 0xb7, 0xc8, 0xa2, 0x5e, 0x33, 0x3f, 0x01, 0xba, + 0x46, 0x16, 0xd5, 0x78, 0xa3, 0x05, 0xfe, 0xd7, 0x9d, 0x06, 0xf2, 0xe2, 0xcc, 0x85, 0xd4, 0x17, + 0xc7, 0x8a, 0x6f, 0xd7, 0x2d, 0xae, 0x82, 0xd5, 0x64, 0x57, 0x22, 0xdd, 0x4f, 0x16, 0xb9, 0x61, + 0x7a, 0x60, 0xc9, 0x3e, 0x57, 0x28, 0xe4, 0x88, 0xbe, 0x24, 0x44, 0x8b, 0xee, 0x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59, 0x4b, 0x38, 0x73, 0x8e, 0x39, 0xe9, 0xd4, 0xb7, 0xf8, 0x42, 0xbc, + 0xce, 0x42, 0x86, 0xf0, 0x33, 0xad, 0xae, 0xd5, 0x30, 0x4f, 0xe7, 0xd9, 0x27, 0xad, 0xab, 0xbd, + 0x4d, 0x48, 0x36, 0x67, 0x90, 0x54, 0xbb, 0xfb, 0x31, 0x87, 0x24, 0x2b, 0xd5, 0xd7, 0x5a, 0xd1, + 0xed, 0xeb, 0x3d, 0xfd, 0xe6, 0x0f, 0xd4, 0xee, 0x5d, 0x33, 0xdb, 0x48, 0xe8, 0x34, 0x3e, 0x9f, + 0x77, 0xac, 0x2f, 0xe7, 0x1d, 0xeb, 0xeb, 0x79, 0xc7, 0xf2, 0xff, 0xd6, 0xbf, 0xb8, 0x47, 0xdf, + 0x03, 0x00, 0x00, 0xff, 0xff, 0x0a, 0x8e, 0xba, 0x2f, 0x66, 0x07, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -1497,7 +1499,7 @@ func (m *HighestAttestation) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.HighestSourceEpoch |= uint64(b&0x7F) << shift + m.HighestSourceEpoch |= github_com_prysmaticlabs_eth2_types.Epoch(b&0x7F) << shift if b < 0x80 { break } @@ -1516,7 +1518,7 @@ func (m *HighestAttestation) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.HighestTargetEpoch |= uint64(b&0x7F) << shift + m.HighestTargetEpoch |= github_com_prysmaticlabs_eth2_types.Epoch(b&0x7F) << shift if b < 0x80 { break } @@ -1861,7 +1863,7 @@ func (m *ProposalHistory) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.LatestEpochWritten |= uint64(b&0x7F) << shift + m.LatestEpochWritten |= github_com_prysmaticlabs_eth2_types.Epoch(b&0x7F) << shift if b < 0x80 { break } @@ -2030,7 +2032,7 @@ func (m *AttestationHistory) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.LatestEpochWritten |= uint64(b&0x7F) << shift + m.LatestEpochWritten |= github_com_prysmaticlabs_eth2_types.Epoch(b&0x7F) << shift if b < 0x80 { break } diff --git a/proto/slashing/slashing.proto b/proto/slashing/slashing.proto index cc6554f031..98d7ddae17 100644 --- a/proto/slashing/slashing.proto +++ b/proto/slashing/slashing.proto @@ -41,8 +41,8 @@ message HighestAttestationResponse { message HighestAttestation { uint64 validator_id = 1; - uint64 highest_source_epoch = 2; - uint64 highest_target_epoch = 3; + uint64 highest_source_epoch = 2 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Epoch"]; + uint64 highest_target_epoch = 3 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Epoch"]; } message ProposerSlashingResponse { @@ -63,7 +63,7 @@ message AttesterSlashingResponse { // a block for while pruning the older data. message ProposalHistory { bytes epoch_bits = 1 [(gogoproto.casttype) = "github.com/prysmaticlabs/go-bitfield.Bitlist"]; - uint64 latest_epoch_written = 2; + uint64 latest_epoch_written = 2 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Epoch"]; } // AttestationHistory defines the structure for recording a validator's historical attestation. @@ -73,5 +73,5 @@ message ProposalHistory { // the history is updated. message AttestationHistory { map target_to_source = 1; - uint64 latest_epoch_written = 2; + uint64 latest_epoch_written = 2 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Epoch"]; } diff --git a/proto/validator/accounts/v2/BUILD.bazel b/proto/validator/accounts/v2/BUILD.bazel index f7a02a28e3..50c413dfc7 100644 --- a/proto/validator/accounts/v2/BUILD.bazel +++ b/proto/validator/accounts/v2/BUILD.bazel @@ -30,6 +30,7 @@ go_proto_library( visibility = ["//visibility:public"], deps = [ "//proto/beacon/rpc/v1:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_golang_protobuf//descriptor:go_default_library", "@com_github_golang_protobuf//ptypes/empty:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", @@ -48,6 +49,7 @@ go_proto_library( visibility = ["//visibility:public"], deps = [ "//proto/beacon/rpc/v1:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@go_googleapis//google/api:annotations_go_proto", ], diff --git a/proto/validator/accounts/v2/keymanager.pb.go b/proto/validator/accounts/v2/keymanager.pb.go index 55665f28d4..1bf7bfd486 100755 --- a/proto/validator/accounts/v2/keymanager.pb.go +++ b/proto/validator/accounts/v2/keymanager.pb.go @@ -6,8 +6,10 @@ package ethereum_validator_accounts_v2 import ( context "context" fmt "fmt" + _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" types "github.com/gogo/protobuf/types" + github_com_prysmaticlabs_eth2_types "github.com/prysmaticlabs/eth2-types" v1alpha1 "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" @@ -179,7 +181,7 @@ type SignRequest_Slot struct { Slot uint64 `protobuf:"varint,105,opt,name=slot,proto3,oneof" json:"slot,omitempty"` } type SignRequest_Epoch struct { - Epoch uint64 `protobuf:"varint,106,opt,name=epoch,proto3,oneof" json:"epoch,omitempty"` + Epoch github_com_prysmaticlabs_eth2_types.Epoch `protobuf:"varint,106,opt,name=epoch,proto3,oneof,casttype=github.com/prysmaticlabs/eth2-types.Epoch" json:"epoch,omitempty"` } func (*SignRequest_Block) isSignRequest_Object() {} @@ -252,7 +254,7 @@ func (m *SignRequest) GetSlot() uint64 { return 0 } -func (m *SignRequest) GetEpoch() uint64 { +func (m *SignRequest) GetEpoch() github_com_prysmaticlabs_eth2_types.Epoch { if x, ok := m.GetObject().(*SignRequest_Epoch); ok { return x.Epoch } @@ -338,49 +340,53 @@ func init() { } var fileDescriptor_795e98bd0a473d79 = []byte{ - // 671 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b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38, 0x3a, 0x31, 0x3b, 0xe5, 0x5c, 0xeb, 0x53, 0x16, 0x95, - 0x2c, 0x18, 0x33, 0x0e, 0xa2, 0x07, 0x84, 0xf8, 0x83, 0x82, 0x54, 0x71, 0x1b, 0xe7, 0x2b, 0xde, - 0x39, 0xae, 0xe8, 0xc9, 0x55, 0xe9, 0xb3, 0xab, 0xd2, 0x4d, 0x71, 0x55, 0xd5, 0xe7, 0x7f, 0xfa, - 0x03, 0xab, 0xaf, 0x4d, 0xdb, 0x7e, 0xf7, 0xed, 0xc7, 0xc7, 0x6c, 0x1d, 0xd7, 0x6e, 0x7d, 0x4a, - 0x42, 0x39, 0xcf, 0x1c, 0xc2, 0xef, 0x15, 0x94, 0x17, 0xd3, 0xe1, 0xa7, 0x7f, 0xe7, 0x93, 0xbc, - 0xc1, 0xea, 0xce, 0xbf, 0x98, 0xaa, 0x35, 0xe4, 0x24, 0x55, 0x4d, 0x5d, 0x35, 0x89, 0xd8, 0x5c, - 0xbb, 0xf4, 0xe5, 0xa6, 0xae, 0x7c, 0xbd, 0xa9, 0x2b, 0xdf, 0x6f, 0xea, 0xca, 0xa0, 0x20, 0x1d, - 0xd8, 0xfb, 0x15, 0x00, 0x00, 0xff, 0xff, 0x8e, 0x70, 0x82, 0xe4, 0x14, 0x05, 0x00, 0x00, + // 727 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0xcd, 0x6a, 0xdb, 0x4a, + 0x14, 0xb6, 0x1c, 0xc7, 0xf7, 0x66, 0xec, 0x7b, 0x63, 0x86, 0x10, 0x84, 0xeb, 0x3a, 0xae, 0x08, + 0xc5, 0xa1, 0x89, 0x44, 0x9c, 0xd2, 0x45, 0xe8, 0x26, 0x8e, 0x55, 0x1c, 0x12, 0xdc, 0x20, 0x93, + 0x74, 0x69, 0x46, 0xf2, 0x44, 0x56, 0x22, 0x6b, 0x54, 0xcd, 0x91, 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cc, 0x56, 0x69, 0xa9, 0xf1, 0x3e, 0x8b, 0x8a, 0x16, 0x1d, 0x32, 0xa0, 0xa2, 0x06, 0x8d, 0xf0, + 0x5b, 0x05, 0xa9, 0xc2, 0x4a, 0xe7, 0x0b, 0x6c, 0x81, 0xd7, 0xf5, 0xc4, 0xb3, 0xfa, 0xc4, 0x8d, + 0xba, 0x29, 0x3c, 0x5b, 0x7e, 0xf2, 0xbb, 0x07, 0x2c, 0x36, 0xa7, 0xb6, 0xf9, 0xfa, 0xcb, 0xf7, + 0x77, 0xd9, 0x2a, 0xae, 0xdc, 0xfa, 0x51, 0x45, 0xf2, 0x3e, 0x53, 0x08, 0xbf, 0x51, 0x50, 0x4e, + 0xdc, 0x0e, 0x3f, 0xfa, 0xb3, 0x3e, 0x49, 0xcb, 0x96, 0xb7, 0xff, 0xa6, 0xa9, 0x5a, 0x4d, 0xde, + 0xa4, 0xac, 0xa9, 0x8b, 0x6e, 0x22, 0x26, 0xd7, 0x2c, 0x7e, 0xba, 0xa9, 0x2a, 0x9f, 0x6f, 0xaa, + 0xca, 0xb7, 0x9b, 0xaa, 0x62, 0xe7, 0x65, 0x07, 0xf6, 0x7e, 0x06, 0x00, 0x00, 0xff, 0xff, 0x11, + 0xba, 0xb9, 0xca, 0x72, 0x05, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -1276,7 +1282,7 @@ func (m *SignRequest) Unmarshal(dAtA []byte) error { if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Epoch", wireType) } - var v uint64 + var v github_com_prysmaticlabs_eth2_types.Epoch for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowKeymanager @@ -1286,7 +1292,7 @@ func (m *SignRequest) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - v |= uint64(b&0x7F) << shift + v |= github_com_prysmaticlabs_eth2_types.Epoch(b&0x7F) << shift if b < 0x80 { break } diff --git a/proto/validator/accounts/v2/keymanager.proto b/proto/validator/accounts/v2/keymanager.proto index c6c652af31..380a8d7287 100644 --- a/proto/validator/accounts/v2/keymanager.proto +++ b/proto/validator/accounts/v2/keymanager.proto @@ -5,6 +5,7 @@ import "eth/v1alpha1/attestation.proto"; import "eth/v1alpha1/beacon_block.proto"; import "google/api/annotations.proto"; import "google/protobuf/empty.proto"; +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; // RemoteSigner service API. // @@ -56,7 +57,7 @@ message SignRequest { ethereum.eth.v1alpha1.AggregateAttestationAndProof aggregate_attestation_and_proof = 103; ethereum.eth.v1alpha1.VoluntaryExit exit = 104; uint64 slot = 105; - uint64 epoch = 106; + uint64 epoch = 106 [(gogoproto.casttype) = "github.com/prysmaticlabs/eth2-types.Epoch"]; } } diff --git a/shared/bytesutil/BUILD.bazel b/shared/bytesutil/BUILD.bazel index 9b4b703820..f10e42acb3 100644 --- a/shared/bytesutil/BUILD.bazel +++ b/shared/bytesutil/BUILD.bazel @@ -6,6 +6,7 @@ go_library( srcs = ["bytes.go"], importpath = "github.com/prysmaticlabs/prysm/shared/bytesutil", visibility = ["//visibility:public"], + deps = ["@com_github_prysmaticlabs_eth2_types//:go_default_library"], ) go_test( diff --git a/shared/bytesutil/bytes.go b/shared/bytesutil/bytes.go index a5fe6f12e2..896516cac3 100644 --- a/shared/bytesutil/bytes.go +++ b/shared/bytesutil/bytes.go @@ -5,6 +5,8 @@ import ( "encoding/binary" "errors" "math/bits" + + "github.com/prysmaticlabs/eth2-types" ) // ToBytes returns integer x to bytes in little-endian format at the specified length. @@ -306,3 +308,18 @@ func BytesToUint64BigEndian(b []byte) uint64 { } return binary.BigEndian.Uint64(b) } + +// EpochToBytesLittleEndian conversion. +func EpochToBytesLittleEndian(i types.Epoch) []byte { + return Uint64ToBytesLittleEndian(uint64(i)) +} + +// EpochToBytesBigEndian conversion. +func EpochToBytesBigEndian(i types.Epoch) []byte { + return Uint64ToBytesBigEndian(uint64(i)) +} + +// BytesToEpochBigEndian conversion. +func BytesToEpochBigEndian(b []byte) types.Epoch { + return types.Epoch(BytesToUint64BigEndian(b)) +} diff --git a/shared/htrutils/htrutils.go b/shared/htrutils/htrutils.go index c8e6ea75ba..f628f7dab0 100644 --- a/shared/htrutils/htrutils.go +++ b/shared/htrutils/htrutils.go @@ -34,7 +34,7 @@ func ForkRoot(fork *pb.Fork) ([32]byte, error) { currRoot := bytesutil.ToBytes32(fork.CurrentVersion) fieldRoots[1] = currRoot[:] forkEpochBuf := make([]byte, 8) - binary.LittleEndian.PutUint64(forkEpochBuf, fork.Epoch) + binary.LittleEndian.PutUint64(forkEpochBuf, uint64(fork.Epoch)) epochRoot := bytesutil.ToBytes32(forkEpochBuf) fieldRoots[2] = epochRoot[:] } @@ -48,7 +48,7 @@ func CheckpointRoot(hasher HashFn, checkpoint *ethpb.Checkpoint) ([32]byte, erro fieldRoots := make([][]byte, 2) if checkpoint != nil { epochBuf := make([]byte, 8) - binary.LittleEndian.PutUint64(epochBuf, checkpoint.Epoch) + binary.LittleEndian.PutUint64(epochBuf, uint64(checkpoint.Epoch)) epochRoot := bytesutil.ToBytes32(epochBuf) fieldRoots[0] = epochRoot[:] ckpRoot := bytesutil.ToBytes32(checkpoint.Root) diff --git a/shared/htrutils/htrutils_test.go b/shared/htrutils/htrutils_test.go index 7818097be8..08e4bf08f2 100644 --- a/shared/htrutils/htrutils_test.go +++ b/shared/htrutils/htrutils_test.go @@ -23,7 +23,7 @@ func TestForkRoot(t *testing.T) { testFork := pb.Fork{ PreviousVersion: []byte{123}, CurrentVersion: []byte{124}, - Epoch: uint64(1234567890), + Epoch: 1234567890, } expected := [32]byte{19, 46, 77, 103, 92, 175, 247, 33, 100, 64, 17, 111, 199, 145, 69, 38, 217, 112, 6, 16, 149, 201, 225, 144, 192, 228, 197, 172, 157, 78, 114, 140} @@ -35,7 +35,7 @@ func TestForkRoot(t *testing.T) { func TestCheckPointRoot(t *testing.T) { testHasher := hashutil.CustomSHA256Hasher() testCheckpoint := ethpb.Checkpoint{ - Epoch: uint64(1234567890), + Epoch: 1234567890, Root: []byte{222}, } expected := [32]byte{228, 65, 39, 109, 183, 249, 167, 232, 125, 239, 25, 155, 207, 4, 84, 174, 176, 229, 175, 224, 62, 33, 215, 254, 170, 220, 132, 65, 246, 128, 68, 194} diff --git a/shared/p2putils/BUILD.bazel b/shared/p2putils/BUILD.bazel index c7548f7308..d8ebe08366 100644 --- a/shared/p2putils/BUILD.bazel +++ b/shared/p2putils/BUILD.bazel @@ -10,5 +10,6 @@ go_library( "//proto/beacon/p2p/v1:go_default_library", "//shared/params:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", ], ) diff --git a/shared/p2putils/fork.go b/shared/p2putils/fork.go index e0b98274b8..eb815ab11a 100644 --- a/shared/p2putils/fork.go +++ b/shared/p2putils/fork.go @@ -5,6 +5,7 @@ import ( "time" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1" "github.com/prysmaticlabs/prysm/shared/params" @@ -41,7 +42,7 @@ func CreateForkDigest( // Fork given a target epoch, // returns the active fork version during this epoch. func Fork( - targetEpoch uint64, + targetEpoch types.Epoch, ) (*pb.Fork, error) { // We retrieve a list of scheduled forks by epoch. // We loop through the keys in this map to determine the current @@ -49,7 +50,7 @@ func Fork( retrievedForkVersion := params.BeaconConfig().GenesisForkVersion previousForkVersion := params.BeaconConfig().GenesisForkVersion scheduledForks := params.BeaconConfig().ForkVersionSchedule - forkEpoch := uint64(0) + forkEpoch := types.Epoch(0) for epoch, forkVersion := range scheduledForks { if epoch <= targetEpoch { previousForkVersion = retrievedForkVersion diff --git a/shared/params/BUILD.bazel b/shared/params/BUILD.bazel index d557cdcfd8..fd9abccfc1 100644 --- a/shared/params/BUILD.bazel +++ b/shared/params/BUILD.bazel @@ -23,6 +23,7 @@ go_library( deps = [ "//shared/bytesutil:go_default_library", "@com_github_mohae_deepcopy//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@in_gopkg_yaml_v2//:go_default_library", ], diff --git a/shared/params/config.go b/shared/params/config.go index e0c2a0579c..c5c7f679ff 100644 --- a/shared/params/config.go +++ b/shared/params/config.go @@ -3,17 +3,19 @@ package params import ( "time" + + "github.com/prysmaticlabs/eth2-types" ) // BeaconChainConfig contains constant configs for node to participate in beacon chain. type BeaconChainConfig struct { // Constants (non-configurable) - GenesisSlot uint64 `yaml:"GENESIS_SLOT"` // GenesisSlot represents the first canonical slot number of the beacon chain. - GenesisEpoch uint64 `yaml:"GENESIS_EPOCH"` // GenesisEpoch represents the first canonical epoch number of the beacon chain. - FarFutureEpoch uint64 `yaml:"FAR_FUTURE_EPOCH"` // FarFutureEpoch represents a epoch extremely far away in the future used as the default penalization slot for validators. - BaseRewardsPerEpoch uint64 `yaml:"BASE_REWARDS_PER_EPOCH"` // BaseRewardsPerEpoch is used to calculate the per epoch rewards. - DepositContractTreeDepth uint64 `yaml:"DEPOSIT_CONTRACT_TREE_DEPTH"` // DepositContractTreeDepth depth of the Merkle trie of deposits in the validator deposit contract on the PoW chain. - JustificationBitsLength uint64 `yaml:"JUSTIFICATION_BITS_LENGTH"` // JustificationBitsLength defines number of epochs to track when implementing k-finality in Casper FFG. + GenesisSlot uint64 `yaml:"GENESIS_SLOT"` // GenesisSlot represents the first canonical slot number of the beacon chain. + GenesisEpoch types.Epoch `yaml:"GENESIS_EPOCH"` // GenesisEpoch represents the first canonical epoch number of the beacon chain. + FarFutureEpoch types.Epoch `yaml:"FAR_FUTURE_EPOCH"` // FarFutureEpoch represents a epoch extremely far away in the future used as the default penalization slot for validators. + BaseRewardsPerEpoch uint64 `yaml:"BASE_REWARDS_PER_EPOCH"` // BaseRewardsPerEpoch is used to calculate the per epoch rewards. + DepositContractTreeDepth uint64 `yaml:"DEPOSIT_CONTRACT_TREE_DEPTH"` // DepositContractTreeDepth depth of the Merkle trie of deposits in the validator deposit contract on the PoW chain. + JustificationBitsLength uint64 `yaml:"JUSTIFICATION_BITS_LENGTH"` // JustificationBitsLength defines number of epochs to track when implementing k-finality in Casper FFG. // Misc constants. ConfigName string `yaml:"CONFIG_NAME" spec:"true"` // ConfigName for allowing an easy human-readable way of knowing what chain is being used. @@ -41,20 +43,20 @@ type BeaconChainConfig struct { ZeroHash [32]byte // ZeroHash is used to represent a zeroed out 32 byte array. // Time parameters constants. - GenesisDelay uint64 `yaml:"GENESIS_DELAY" spec:"true"` // GenesisDelay is the minimum number of seconds to delay starting the ETH2 genesis. Must be at least 1 second. - MinAttestationInclusionDelay uint64 `yaml:"MIN_ATTESTATION_INCLUSION_DELAY" spec:"true"` // MinAttestationInclusionDelay defines how many slots validator has to wait to include attestation for beacon block. - SecondsPerSlot uint64 `yaml:"SECONDS_PER_SLOT" spec:"true"` // SecondsPerSlot is how many seconds are in a single slot. - SlotsPerEpoch uint64 `yaml:"SLOTS_PER_EPOCH" spec:"true"` // SlotsPerEpoch is the number of slots in an epoch. - MinSeedLookahead uint64 `yaml:"MIN_SEED_LOOKAHEAD" spec:"true"` // MinSeedLookahead is the duration of randao look ahead seed. - MaxSeedLookahead uint64 `yaml:"MAX_SEED_LOOKAHEAD" spec:"true"` // MaxSeedLookahead is the duration a validator has to wait for entry and exit in epoch. - EpochsPerEth1VotingPeriod uint64 `yaml:"EPOCHS_PER_ETH1_VOTING_PERIOD" spec:"true"` // EpochsPerEth1VotingPeriod defines how often the merkle root of deposit receipts get updated in beacon node on per epoch basis. - SlotsPerHistoricalRoot uint64 `yaml:"SLOTS_PER_HISTORICAL_ROOT" spec:"true"` // SlotsPerHistoricalRoot defines how often the historical root is saved. - MinValidatorWithdrawabilityDelay uint64 `yaml:"MIN_VALIDATOR_WITHDRAWABILITY_DELAY" spec:"true"` // MinValidatorWithdrawabilityDelay is the shortest amount of time a validator has to wait to withdraw. - ShardCommitteePeriod uint64 `yaml:"SHARD_COMMITTEE_PERIOD" spec:"true"` // ShardCommitteePeriod is the minimum amount of epochs a validator must participate before exiting. - MinEpochsToInactivityPenalty uint64 `yaml:"MIN_EPOCHS_TO_INACTIVITY_PENALTY" spec:"true"` // MinEpochsToInactivityPenalty defines the minimum amount of epochs since finality to begin penalizing inactivity. - Eth1FollowDistance uint64 `yaml:"ETH1_FOLLOW_DISTANCE" spec:"true"` // Eth1FollowDistance is the number of eth1.0 blocks to wait before considering a new deposit for voting. This only applies after the chain as been started. - SafeSlotsToUpdateJustified uint64 `yaml:"SAFE_SLOTS_TO_UPDATE_JUSTIFIED" spec:"true"` // SafeSlotsToUpdateJustified is the minimal slots needed to update justified check point. - SecondsPerETH1Block uint64 `yaml:"SECONDS_PER_ETH1_BLOCK" spec:"true"` // SecondsPerETH1Block is the approximate time for a single eth1 block to be produced. + GenesisDelay uint64 `yaml:"GENESIS_DELAY" spec:"true"` // GenesisDelay is the minimum number of seconds to delay starting the ETH2 genesis. Must be at least 1 second. + MinAttestationInclusionDelay uint64 `yaml:"MIN_ATTESTATION_INCLUSION_DELAY" spec:"true"` // MinAttestationInclusionDelay defines how many slots validator has to wait to include attestation for beacon block. + SecondsPerSlot uint64 `yaml:"SECONDS_PER_SLOT" spec:"true"` // SecondsPerSlot is how many seconds are in a single slot. + SlotsPerEpoch uint64 `yaml:"SLOTS_PER_EPOCH" spec:"true"` // SlotsPerEpoch is the number of slots in an epoch. + MinSeedLookahead types.Epoch `yaml:"MIN_SEED_LOOKAHEAD" spec:"true"` // MinSeedLookahead is the duration of randao look ahead seed. + MaxSeedLookahead types.Epoch `yaml:"MAX_SEED_LOOKAHEAD" spec:"true"` // MaxSeedLookahead is the duration a validator has to wait for entry and exit in epoch. + EpochsPerEth1VotingPeriod types.Epoch `yaml:"EPOCHS_PER_ETH1_VOTING_PERIOD" spec:"true"` // EpochsPerEth1VotingPeriod defines how often the merkle root of deposit receipts get updated in beacon node on per epoch basis. + SlotsPerHistoricalRoot uint64 `yaml:"SLOTS_PER_HISTORICAL_ROOT" spec:"true"` // SlotsPerHistoricalRoot defines how often the historical root is saved. + MinValidatorWithdrawabilityDelay types.Epoch `yaml:"MIN_VALIDATOR_WITHDRAWABILITY_DELAY" spec:"true"` // MinValidatorWithdrawabilityDelay is the shortest amount of time a validator has to wait to withdraw. + ShardCommitteePeriod types.Epoch `yaml:"SHARD_COMMITTEE_PERIOD" spec:"true"` // ShardCommitteePeriod is the minimum amount of epochs a validator must participate before exiting. + MinEpochsToInactivityPenalty types.Epoch `yaml:"MIN_EPOCHS_TO_INACTIVITY_PENALTY" spec:"true"` // MinEpochsToInactivityPenalty defines the minimum amount of epochs since finality to begin penalizing inactivity. + Eth1FollowDistance uint64 `yaml:"ETH1_FOLLOW_DISTANCE" spec:"true"` // Eth1FollowDistance is the number of eth1.0 blocks to wait before considering a new deposit for voting. This only applies after the chain as been started. + SafeSlotsToUpdateJustified uint64 `yaml:"SAFE_SLOTS_TO_UPDATE_JUSTIFIED" spec:"true"` // SafeSlotsToUpdateJustified is the minimal slots needed to update justified check point. + SecondsPerETH1Block uint64 `yaml:"SECONDS_PER_ETH1_BLOCK" spec:"true"` // SecondsPerETH1Block is the approximate time for a single eth1 block to be produced. // Ethereum PoW parameters. DepositChainID uint64 `yaml:"DEPOSIT_CHAIN_ID" spec:"true"` // DepositChainID of the eth1 network. This used for replay protection. @@ -66,10 +68,10 @@ type BeaconChainConfig struct { EpochsPerRandomSubnetSubscription uint64 `yaml:"EPOCHS_PER_RANDOM_SUBNET_SUBSCRIPTION" spec:"true"` // EpochsPerRandomSubnetSubscription specifies the minimum duration a validator is connected to their subnet. // State list lengths - EpochsPerHistoricalVector uint64 `yaml:"EPOCHS_PER_HISTORICAL_VECTOR" spec:"true"` // EpochsPerHistoricalVector defines max length in epoch to store old historical stats in beacon state. - EpochsPerSlashingsVector uint64 `yaml:"EPOCHS_PER_SLASHINGS_VECTOR" spec:"true"` // EpochsPerSlashingsVector defines max length in epoch to store old stats to recompute slashing witness. - HistoricalRootsLimit uint64 `yaml:"HISTORICAL_ROOTS_LIMIT" spec:"true"` // HistoricalRootsLimit defines max historical roots that can be saved in state before roll over. - ValidatorRegistryLimit uint64 `yaml:"VALIDATOR_REGISTRY_LIMIT" spec:"true"` // ValidatorRegistryLimit defines the upper bound of validators can participate in eth2. + EpochsPerHistoricalVector types.Epoch `yaml:"EPOCHS_PER_HISTORICAL_VECTOR" spec:"true"` // EpochsPerHistoricalVector defines max length in epoch to store old historical stats in beacon state. + EpochsPerSlashingsVector types.Epoch `yaml:"EPOCHS_PER_SLASHINGS_VECTOR" spec:"true"` // EpochsPerSlashingsVector defines max length in epoch to store old stats to recompute slashing witness. + HistoricalRootsLimit uint64 `yaml:"HISTORICAL_ROOTS_LIMIT" spec:"true"` // HistoricalRootsLimit defines max historical roots that can be saved in state before roll over. + ValidatorRegistryLimit uint64 `yaml:"VALIDATOR_REGISTRY_LIMIT" spec:"true"` // ValidatorRegistryLimit defines the upper bound of validators can participate in eth2. // Reward and penalty quotients constants. BaseRewardFactor uint64 `yaml:"BASE_REWARD_FACTOR" spec:"true"` // BaseRewardFactor is used to calculate validator per-slot interest rate. @@ -112,14 +114,14 @@ type BeaconChainConfig struct { BeaconStateFieldCount int // BeaconStateFieldCount defines how many fields are in beacon state. // Slasher constants. - WeakSubjectivityPeriod uint64 // WeakSubjectivityPeriod defines the time period expressed in number of epochs were proof of stake network should validate block headers and attestations for slashable events. - PruneSlasherStoragePeriod uint64 // PruneSlasherStoragePeriod defines the time period expressed in number of epochs were proof of stake network should prune attestation and block header store. + WeakSubjectivityPeriod types.Epoch // WeakSubjectivityPeriod defines the time period expressed in number of epochs were proof of stake network should validate block headers and attestations for slashable events. + PruneSlasherStoragePeriod types.Epoch // PruneSlasherStoragePeriod defines the time period expressed in number of epochs were proof of stake network should prune attestation and block header store. // Fork-related values. - GenesisForkVersion []byte `yaml:"GENESIS_FORK_VERSION" spec:"true"` // GenesisForkVersion is used to track fork version between state transitions. - NextForkVersion []byte `yaml:"NEXT_FORK_VERSION"` // NextForkVersion is used to track the upcoming fork version, if any. - NextForkEpoch uint64 `yaml:"NEXT_FORK_EPOCH"` // NextForkEpoch is used to track the epoch of the next fork, if any. - ForkVersionSchedule map[uint64][]byte // Schedule of fork versions by epoch number. + GenesisForkVersion []byte `yaml:"GENESIS_FORK_VERSION" spec:"true"` // GenesisForkVersion is used to track fork version between state transitions. + NextForkVersion []byte `yaml:"NEXT_FORK_VERSION"` // NextForkVersion is used to track the upcoming fork version, if any. + NextForkEpoch types.Epoch `yaml:"NEXT_FORK_EPOCH"` // NextForkEpoch is used to track the epoch of the next fork, if any. + ForkVersionSchedule map[types.Epoch][]byte // Schedule of fork versions by epoch number. // Weak subjectivity values. SafetyDecay uint64 // SafetyDecay is defined as the loss in the 1/3 consensus safety margin of the casper FFG mechanism. diff --git a/shared/params/mainnet_config.go b/shared/params/mainnet_config.go index 357f8bcf35..6ad20085ba 100644 --- a/shared/params/mainnet_config.go +++ b/shared/params/mainnet_config.go @@ -3,6 +3,7 @@ package params import ( "time" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bytesutil" ) @@ -171,7 +172,7 @@ var mainnetBeaconConfig = &BeaconChainConfig{ GenesisForkVersion: []byte{0, 0, 0, 0}, NextForkVersion: []byte{0, 0, 0, 0}, // Set to GenesisForkVersion unless there is a scheduled fork NextForkEpoch: 1<<64 - 1, // Set to FarFutureEpoch unless there is a scheduled fork. - ForkVersionSchedule: map[uint64][]byte{ + ForkVersionSchedule: map[types.Epoch][]byte{ // Any further forks must be specified here by their epoch number. }, } diff --git a/shared/slashutil/BUILD.bazel b/shared/slashutil/BUILD.bazel index 16ada194e9..cff01a1ecc 100644 --- a/shared/slashutil/BUILD.bazel +++ b/shared/slashutil/BUILD.bazel @@ -24,6 +24,7 @@ go_test( embed = [":go_default_library"], deps = [ "//shared/params:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", ], ) diff --git a/shared/slashutil/surround_votes_test.go b/shared/slashutil/surround_votes_test.go index 484096c373..a836cdc902 100644 --- a/shared/slashutil/surround_votes_test.go +++ b/shared/slashutil/surround_votes_test.go @@ -3,6 +3,7 @@ package slashutil import ( "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ) @@ -82,7 +83,7 @@ func TestIsSurround(t *testing.T) { } } -func createAttestation(source, target uint64) *ethpb.IndexedAttestation { +func createAttestation(source, target types.Epoch) *ethpb.IndexedAttestation { return ðpb.IndexedAttestation{ Data: ðpb.AttestationData{ Source: ðpb.Checkpoint{Epoch: source}, diff --git a/shared/slotutil/BUILD.bazel b/shared/slotutil/BUILD.bazel index 9318f4968b..13c2b019a2 100644 --- a/shared/slotutil/BUILD.bazel +++ b/shared/slotutil/BUILD.bazel @@ -13,6 +13,7 @@ go_library( deps = [ "//shared/params:go_default_library", "//shared/timeutils:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", ], ) diff --git a/shared/slotutil/slottime.go b/shared/slotutil/slottime.go index b3888688e9..873bc93537 100644 --- a/shared/slotutil/slottime.go +++ b/shared/slotutil/slottime.go @@ -3,6 +3,7 @@ package slotutil import ( "time" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/timeutils" ) @@ -26,8 +27,8 @@ func SlotsSinceGenesis(genesis time.Time) uint64 { // EpochsSinceGenesis returns the number of slots since // the provided genesis time. -func EpochsSinceGenesis(genesis time.Time) uint64 { - return SlotsSinceGenesis(genesis) / params.BeaconConfig().SlotsPerEpoch +func EpochsSinceGenesis(genesis time.Time) types.Epoch { + return types.Epoch(SlotsSinceGenesis(genesis) / params.BeaconConfig().SlotsPerEpoch) } // DivideSlotBy divides the SECONDS_PER_SLOT configuration diff --git a/shared/sszutil/BUILD.bazel b/shared/sszutil/BUILD.bazel index ee1ed50224..31ceeced6f 100644 --- a/shared/sszutil/BUILD.bazel +++ b/shared/sszutil/BUILD.bazel @@ -6,6 +6,7 @@ go_library( srcs = ["deep_equal.go"], importpath = "github.com/prysmaticlabs/prysm/shared/sszutil", visibility = ["//visibility:public"], + deps = ["@com_github_prysmaticlabs_eth2_types//:go_default_library"], ) go_test( diff --git a/shared/sszutil/deep_equal.go b/shared/sszutil/deep_equal.go index 9d37e26eba..091066fb6f 100644 --- a/shared/sszutil/deep_equal.go +++ b/shared/sszutil/deep_equal.go @@ -3,6 +3,8 @@ package sszutil import ( "reflect" "unsafe" + + "github.com/prysmaticlabs/eth2-types" ) // During deepValueEqual, must keep track of checks that are @@ -115,6 +117,12 @@ func deepValueEqual(v1, v2 reflect.Value, visited map[visit]bool, depth int) boo } return true case reflect.Uint64: + switch v1.Type().Name() { + case "Epoch": + return v1.Interface().(types.Epoch) == v2.Interface().(types.Epoch) + case "Slot": + return v1.Interface().(types.Slot) == v2.Interface().(types.Slot) + } return v1.Interface().(uint64) == v2.Interface().(uint64) case reflect.Uint32: return v1.Interface().(uint32) == v2.Interface().(uint32) diff --git a/shared/sszutil/deep_equal_test.go b/shared/sszutil/deep_equal_test.go index 794a147229..7ce4ae1e19 100644 --- a/shared/sszutil/deep_equal_test.go +++ b/shared/sszutil/deep_equal_test.go @@ -64,22 +64,22 @@ func TestDeepEqualProto(t *testing.T) { fork1 = pb.Fork{ PreviousVersion: []byte{123}, CurrentVersion: []byte{124}, - Epoch: uint64(1234567890), + Epoch: 1234567890, } fork2 = pb.Fork{ PreviousVersion: []byte{123}, CurrentVersion: []byte{125}, - Epoch: uint64(1234567890), + Epoch: 1234567890, } assert.Equal(t, true, sszutil.DeepEqual(fork1, fork1)) assert.Equal(t, false, sszutil.DeepEqual(fork1, fork2)) checkpoint1 := ethpb.Checkpoint{ - Epoch: uint64(1234567890), + Epoch: 1234567890, Root: []byte{}, } checkpoint2 := ethpb.Checkpoint{ - Epoch: uint64(1234567890), + Epoch: 1234567890, Root: nil, } assert.Equal(t, true, sszutil.DeepEqual(checkpoint1, checkpoint2)) diff --git a/shared/testutil/BUILD.bazel b/shared/testutil/BUILD.bazel index 5dc8ed5f66..134d2283c2 100644 --- a/shared/testutil/BUILD.bazel +++ b/shared/testutil/BUILD.bazel @@ -33,6 +33,7 @@ go_library( "@com_github_gogo_protobuf//proto:go_default_library", "@com_github_json_iterator_go//:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", diff --git a/shared/testutil/block_test.go b/shared/testutil/block_test.go index 63979a4a1b..ac17b1ce79 100644 --- a/shared/testutil/block_test.go +++ b/shared/testutil/block_test.go @@ -153,7 +153,7 @@ func TestGenerateFullBlock_ValidDeposits(t *testing.T) { func TestGenerateFullBlock_ValidVoluntaryExits(t *testing.T) { beaconState, privs := DeterministicGenesisState(t, 256) // Moving the state 2048 epochs forward due to PERSISTENT_COMMITTEE_PERIOD. - err := beaconState.SetSlot(3 + params.BeaconConfig().ShardCommitteePeriod*params.BeaconConfig().SlotsPerEpoch) + err := beaconState.SetSlot(uint64(params.BeaconConfig().ShardCommitteePeriod.Mul(params.BeaconConfig().SlotsPerEpoch).Add(3))) require.NoError(t, err) conf := &BlockGenConfig{ NumVoluntaryExits: 1, diff --git a/shared/testutil/helpers.go b/shared/testutil/helpers.go index ebf87d8eff..22a542c4a5 100644 --- a/shared/testutil/helpers.go +++ b/shared/testutil/helpers.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/state" @@ -17,14 +18,14 @@ import ( ) // RandaoReveal returns a signature of the requested epoch using the beacon proposer private key. -func RandaoReveal(beaconState *stateTrie.BeaconState, epoch uint64, privKeys []bls.SecretKey) ([]byte, error) { +func RandaoReveal(beaconState *stateTrie.BeaconState, epoch types.Epoch, privKeys []bls.SecretKey) ([]byte, error) { // We fetch the proposer's index as that is whom the RANDAO will be verified against. proposerIdx, err := helpers.BeaconProposerIndex(beaconState) if err != nil { return []byte{}, errors.Wrap(err, "could not get beacon proposer index") } buf := make([]byte, 32) - binary.LittleEndian.PutUint64(buf, epoch) + binary.LittleEndian.PutUint64(buf, uint64(epoch)) // We make the previous validator's index sign the message instead of the proposer. sszEpoch := p2ptypes.SSZUint64(epoch) diff --git a/shared/testutil/helpers_test.go b/shared/testutil/helpers_test.go index ce6cd486f5..a093f3a723 100644 --- a/shared/testutil/helpers_test.go +++ b/shared/testutil/helpers_test.go @@ -44,7 +44,7 @@ func TestRandaoReveal(t *testing.T) { proposerIdx, err := helpers.BeaconProposerIndex(beaconState) assert.NoError(t, err) buf := make([]byte, 32) - binary.LittleEndian.PutUint64(buf, epoch) + binary.LittleEndian.PutUint64(buf, uint64(epoch)) // We make the previous validator's index sign the message instead of the proposer. sszUint := p2ptypes.SSZUint64(epoch) epochSignature, err := helpers.ComputeDomainAndSign(beaconState, epoch, &sszUint, params.BeaconConfig().DomainRandao, privKeys[proposerIdx]) diff --git a/shared/testutil/state.go b/shared/testutil/state.go index 99524d48ca..a15ed575ea 100644 --- a/shared/testutil/state.go +++ b/shared/testutil/state.go @@ -14,7 +14,7 @@ func NewBeaconState(options ...func(state *pb.BeaconState)) (*stateTrie.BeaconSt BlockRoots: filledByteSlice2D(params.MainnetConfig().SlotsPerHistoricalRoot, 32), StateRoots: filledByteSlice2D(params.MainnetConfig().SlotsPerHistoricalRoot, 32), Slashings: make([]uint64, params.MainnetConfig().EpochsPerSlashingsVector), - RandaoMixes: filledByteSlice2D(params.MainnetConfig().EpochsPerHistoricalVector, 32), + RandaoMixes: filledByteSlice2D(uint64(params.MainnetConfig().EpochsPerHistoricalVector), 32), Validators: make([]*ethpb.Validator, 0), CurrentJustifiedCheckpoint: ðpb.Checkpoint{Root: make([]byte, 32)}, Eth1Data: ðpb.Eth1Data{ diff --git a/slasher/beaconclient/BUILD.bazel b/slasher/beaconclient/BUILD.bazel index 37a8869f6e..c6c9421bf2 100644 --- a/slasher/beaconclient/BUILD.bazel +++ b/slasher/beaconclient/BUILD.bazel @@ -33,6 +33,7 @@ go_library( "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prometheus_client_golang//prometheus/promauto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@io_opencensus_go//plugin/ocgrpc:go_default_library", diff --git a/slasher/beaconclient/historical_data_retrieval.go b/slasher/beaconclient/historical_data_retrieval.go index 11eef6bd15..3a0bd8328a 100644 --- a/slasher/beaconclient/historical_data_retrieval.go +++ b/slasher/beaconclient/historical_data_retrieval.go @@ -3,6 +3,7 @@ package beaconclient import ( "context" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/cmd" "go.opencensus.io/trace" @@ -12,7 +13,7 @@ import ( // given epoch from a beacon node via gRPC. func (s *Service) RequestHistoricalAttestations( ctx context.Context, - epoch uint64, + epoch types.Epoch, ) ([]*ethpb.IndexedAttestation, error) { ctx, span := trace.StartSpan(ctx, "beaconclient.RequestHistoricalAttestations") defer span.End() diff --git a/slasher/cache/BUILD.bazel b/slasher/cache/BUILD.bazel index e101173c80..6ec2338a5f 100644 --- a/slasher/cache/BUILD.bazel +++ b/slasher/cache/BUILD.bazel @@ -19,6 +19,7 @@ go_library( "@com_github_hashicorp_golang_lru//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prometheus_client_golang//prometheus/promauto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", ], ) @@ -30,5 +31,6 @@ go_test( deps = [ "//proto/slashing:go_default_library", "//shared/testutil/require:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", ], ) diff --git a/slasher/cache/flat_span_cache.go b/slasher/cache/flat_span_cache.go index a8fc515db2..8af3e15680 100644 --- a/slasher/cache/flat_span_cache.go +++ b/slasher/cache/flat_span_cache.go @@ -2,7 +2,8 @@ package cache import ( lru "github.com/hashicorp/golang-lru" - "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" + "github.com/prysmaticlabs/eth2-types" + slashertypes "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" ) // EpochFlatSpansCache is used to store the spans needed on a per-epoch basis for slashing detection. @@ -23,25 +24,25 @@ func NewEpochFlatSpansCache(size int, onEvicted func(key interface{}, value inte } // Get returns an ok bool and the cached value for the requested epoch key, if any. -func (c *EpochFlatSpansCache) Get(epoch uint64) (*types.EpochStore, bool) { +func (c *EpochFlatSpansCache) Get(epoch types.Epoch) (*slashertypes.EpochStore, bool) { item, exists := c.cache.Get(epoch) if exists && item != nil { epochSpansCacheHit.Inc() - return item.(*types.EpochStore), true + return item.(*slashertypes.EpochStore), true } epochSpansCacheMiss.Inc() - return &types.EpochStore{}, false + return &slashertypes.EpochStore{}, false } // Set the response in the cache. -func (c *EpochFlatSpansCache) Set(epoch uint64, epochSpans *types.EpochStore) { +func (c *EpochFlatSpansCache) Set(epoch types.Epoch, epochSpans *slashertypes.EpochStore) { _ = c.cache.Add(epoch, epochSpans) } // Delete removes an epoch from the cache and returns if it existed or not. // Performs the onEviction function before removal. -func (c *EpochFlatSpansCache) Delete(epoch uint64) bool { +func (c *EpochFlatSpansCache) Delete(epoch types.Epoch) bool { return c.cache.Remove(epoch) } @@ -55,7 +56,7 @@ func (c *EpochFlatSpansCache) PruneOldest() uint64 { } // Has returns true if the key exists in the cache. -func (c *EpochFlatSpansCache) Has(epoch uint64) bool { +func (c *EpochFlatSpansCache) Has(epoch types.Epoch) bool { return c.cache.Contains(epoch) } diff --git a/slasher/cache/highest_attestation_cache_test.go b/slasher/cache/highest_attestation_cache_test.go index 8ef66b0f56..8840699fac 100644 --- a/slasher/cache/highest_attestation_cache_test.go +++ b/slasher/cache/highest_attestation_cache_test.go @@ -3,8 +3,8 @@ package cache import ( "testing" + "github.com/prysmaticlabs/eth2-types" ethereum_slashing "github.com/prysmaticlabs/prysm/proto/slashing" - "github.com/prysmaticlabs/prysm/shared/testutil/require" ) @@ -26,8 +26,8 @@ func TestStoringAndFetching(t *testing.T) { res, b := cache.Get(1) require.Equal(t, true, b) require.Equal(t, uint64(1), res[1].ValidatorId) - require.Equal(t, uint64(2), res[1].HighestSourceEpoch) - require.Equal(t, uint64(3), res[1].HighestTargetEpoch) + require.Equal(t, types.Epoch(2), res[1].HighestSourceEpoch) + require.Equal(t, types.Epoch(3), res[1].HighestTargetEpoch) // Delete it. require.Equal(t, true, cache.Delete(1)) diff --git a/slasher/db/iface/BUILD.bazel b/slasher/db/iface/BUILD.bazel index e47170323c..b474bd7594 100644 --- a/slasher/db/iface/BUILD.bazel +++ b/slasher/db/iface/BUILD.bazel @@ -10,6 +10,7 @@ go_library( "//shared/backuputil:go_default_library", "//slasher/db/types:go_default_library", "//slasher/detection/attestations/types:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", ], ) diff --git a/slasher/db/iface/interface.go b/slasher/db/iface/interface.go index 5cc5e2bc2e..7436feb30f 100644 --- a/slasher/db/iface/interface.go +++ b/slasher/db/iface/interface.go @@ -7,20 +7,21 @@ import ( "context" "io" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" slashpb "github.com/prysmaticlabs/prysm/proto/slashing" "github.com/prysmaticlabs/prysm/shared/backuputil" - "github.com/prysmaticlabs/prysm/slasher/db/types" - detectionTypes "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" + dbtypes "github.com/prysmaticlabs/prysm/slasher/db/types" + slashertypes "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" ) // ReadOnlyDatabase represents a read only database with functions that do not modify the DB. type ReadOnlyDatabase interface { // AttesterSlashing related methods. - AttesterSlashings(ctx context.Context, status types.SlashingStatus) ([]*ethpb.AttesterSlashing, error) + AttesterSlashings(ctx context.Context, status dbtypes.SlashingStatus) ([]*ethpb.AttesterSlashing, error) DeleteAttesterSlashing(ctx context.Context, attesterSlashing *ethpb.AttesterSlashing) error - HasAttesterSlashing(ctx context.Context, slashing *ethpb.AttesterSlashing) (bool, types.SlashingStatus, error) - GetLatestEpochDetected(ctx context.Context) (uint64, error) + HasAttesterSlashing(ctx context.Context, slashing *ethpb.AttesterSlashing) (bool, dbtypes.SlashingStatus, error) + GetLatestEpochDetected(ctx context.Context) (types.Epoch, error) // BlockHeader related methods. BlockHeaders(ctx context.Context, slot uint64, validatorID uint64) ([]*ethpb.SignedBeaconBlockHeader, error) @@ -28,19 +29,19 @@ type ReadOnlyDatabase interface { // IndexedAttestations related methods. HasIndexedAttestation(ctx context.Context, att *ethpb.IndexedAttestation) (bool, error) - IndexedAttestationsForTarget(ctx context.Context, targetEpoch uint64) ([]*ethpb.IndexedAttestation, error) - IndexedAttestationsWithPrefix(ctx context.Context, targetEpoch uint64, sigBytes []byte) ([]*ethpb.IndexedAttestation, error) + IndexedAttestationsForTarget(ctx context.Context, targetEpoch types.Epoch) ([]*ethpb.IndexedAttestation, error) + IndexedAttestationsWithPrefix(ctx context.Context, targetEpoch types.Epoch, sigBytes []byte) ([]*ethpb.IndexedAttestation, error) LatestIndexedAttestationsTargetEpoch(ctx context.Context) (uint64, error) // Highest Attestation related methods. HighestAttestation(ctx context.Context, validatorID uint64) (*slashpb.HighestAttestation, error) // MinMaxSpan related methods. - EpochSpans(ctx context.Context, epoch uint64, fromCache bool) (*detectionTypes.EpochStore, error) + EpochSpans(ctx context.Context, epoch types.Epoch, fromCache bool) (*slashertypes.EpochStore, error) // ProposerSlashing related methods. - ProposalSlashingsByStatus(ctx context.Context, status types.SlashingStatus) ([]*ethpb.ProposerSlashing, error) - HasProposerSlashing(ctx context.Context, slashing *ethpb.ProposerSlashing) (bool, types.SlashingStatus, error) + ProposalSlashingsByStatus(ctx context.Context, status dbtypes.SlashingStatus) ([]*ethpb.ProposerSlashing, error) + HasProposerSlashing(ctx context.Context, slashing *ethpb.ProposerSlashing) (bool, dbtypes.SlashingStatus, error) // Validator Index -> Pubkey related methods. ValidatorPubKey(ctx context.Context, validatorID uint64) ([]byte, error) @@ -55,31 +56,31 @@ type ReadOnlyDatabase interface { // WriteAccessDatabase represents a write access database with only functions that can modify the DB. type WriteAccessDatabase interface { // AttesterSlashing related methods. - SaveAttesterSlashing(ctx context.Context, status types.SlashingStatus, slashing *ethpb.AttesterSlashing) error - SaveAttesterSlashings(ctx context.Context, status types.SlashingStatus, slashings []*ethpb.AttesterSlashing) error - SetLatestEpochDetected(ctx context.Context, epoch uint64) error + SaveAttesterSlashing(ctx context.Context, status dbtypes.SlashingStatus, slashing *ethpb.AttesterSlashing) error + SaveAttesterSlashings(ctx context.Context, status dbtypes.SlashingStatus, slashings []*ethpb.AttesterSlashing) error + SetLatestEpochDetected(ctx context.Context, epoch types.Epoch) error // BlockHeader related methods. SaveBlockHeader(ctx context.Context, blockHeader *ethpb.SignedBeaconBlockHeader) error DeleteBlockHeader(ctx context.Context, blockHeader *ethpb.SignedBeaconBlockHeader) error - PruneBlockHistory(ctx context.Context, currentEpoch uint64, pruningEpochAge uint64) error + PruneBlockHistory(ctx context.Context, currentEpoch, pruningEpochAge types.Epoch) error // IndexedAttestations related methods. SaveIndexedAttestation(ctx context.Context, idxAttestation *ethpb.IndexedAttestation) error SaveIndexedAttestations(ctx context.Context, idxAttestations []*ethpb.IndexedAttestation) error DeleteIndexedAttestation(ctx context.Context, idxAttestation *ethpb.IndexedAttestation) error - PruneAttHistory(ctx context.Context, currentEpoch uint64, pruningEpochAge uint64) error + PruneAttHistory(ctx context.Context, currentEpoch, pruningEpochAge types.Epoch) error // Highest Attestation related methods. SaveHighestAttestation(ctx context.Context, highest *slashpb.HighestAttestation) error // MinMaxSpan related methods. - SaveEpochSpans(ctx context.Context, epoch uint64, spans *detectionTypes.EpochStore, toCache bool) error + SaveEpochSpans(ctx context.Context, epoch types.Epoch, spans *slashertypes.EpochStore, toCache bool) error // ProposerSlashing related methods. DeleteProposerSlashing(ctx context.Context, slashing *ethpb.ProposerSlashing) error - SaveProposerSlashing(ctx context.Context, status types.SlashingStatus, slashing *ethpb.ProposerSlashing) error - SaveProposerSlashings(ctx context.Context, status types.SlashingStatus, slashings []*ethpb.ProposerSlashing) error + SaveProposerSlashing(ctx context.Context, status dbtypes.SlashingStatus, slashing *ethpb.ProposerSlashing) error + SaveProposerSlashings(ctx context.Context, status dbtypes.SlashingStatus, slashings []*ethpb.ProposerSlashing) error // Validator Index -> Pubkey related methods. SavePubKey(ctx context.Context, validatorID uint64, pubKey []byte) error @@ -106,6 +107,6 @@ type Database interface { // EpochSpansStore represents a data access layer for marshaling and unmarshaling validator spans for each validator per epoch. type EpochSpansStore interface { - SetValidatorSpan(ctx context.Context, idx uint64, newSpan detectionTypes.Span) error - GetValidatorSpan(ctx context.Context, idx uint64) (detectionTypes.Span, error) + SetValidatorSpan(ctx context.Context, idx uint64, newSpan slashertypes.Span) error + GetValidatorSpan(ctx context.Context, idx uint64) (slashertypes.Span, error) } diff --git a/slasher/db/kv/BUILD.bazel b/slasher/db/kv/BUILD.bazel index 6b77d64df3..6e97455b11 100644 --- a/slasher/db/kv/BUILD.bazel +++ b/slasher/db/kv/BUILD.bazel @@ -33,6 +33,7 @@ go_library( "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prometheus_client_golang//prometheus/promauto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@io_etcd_go_bbolt//:go_default_library", @@ -66,6 +67,7 @@ go_test( "//shared/testutil/require:go_default_library", "//slasher/db/types:go_default_library", "//slasher/detection/attestations/types:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@in_gopkg_d4l3k_messagediff_v1//:go_default_library", diff --git a/slasher/db/kv/attester_slashings.go b/slasher/db/kv/attester_slashings.go index 412296dfac..cd897490c3 100644 --- a/slasher/db/kv/attester_slashings.go +++ b/slasher/db/kv/attester_slashings.go @@ -6,10 +6,11 @@ import ( "github.com/gogo/protobuf/proto" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/hashutil" - "github.com/prysmaticlabs/prysm/slasher/db/types" + slashertypes "github.com/prysmaticlabs/prysm/slasher/db/types" bolt "go.etcd.io/bbolt" "go.opencensus.io/trace" ) @@ -37,13 +38,13 @@ func unmarshalAttSlashings(encoded [][]byte) ([]*ethpb.AttesterSlashing, error) // AttesterSlashings accepts a status and returns all slashings with this status. // returns empty []*ethpb.AttesterSlashing if no slashing has been found with this status. -func (s *Store) AttesterSlashings(ctx context.Context, status types.SlashingStatus) ([]*ethpb.AttesterSlashing, error) { +func (s *Store) AttesterSlashings(ctx context.Context, status slashertypes.SlashingStatus) ([]*ethpb.AttesterSlashing, error) { ctx, span := trace.StartSpan(ctx, "slasherDB.AttesterSlashings") defer span.End() encoded := make([][]byte, 0) err := s.view(func(tx *bolt.Tx) error { c := tx.Bucket(slashingBucket).Cursor() - prefix := encodeType(types.SlashingType(types.Attestation)) + prefix := encodeType(slashertypes.SlashingType(slashertypes.Attestation)) for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() { if v[0] == byte(status) { encoded = append(encoded, v[1:]) @@ -67,7 +68,7 @@ func (s *Store) DeleteAttesterSlashing(ctx context.Context, attesterSlashing *et } return s.update(func(tx *bolt.Tx) error { bucket := tx.Bucket(slashingBucket) - k := encodeTypeRoot(types.SlashingType(types.Attestation), root) + k := encodeTypeRoot(slashertypes.SlashingType(slashertypes.Attestation), root) if err != nil { return errors.Wrap(err, "failed to get key for for attester slashing.") } @@ -79,22 +80,22 @@ func (s *Store) DeleteAttesterSlashing(ctx context.Context, attesterSlashing *et } // HasAttesterSlashing returns true and slashing status if a slashing is found in the db. -func (s *Store) HasAttesterSlashing(ctx context.Context, slashing *ethpb.AttesterSlashing) (bool, types.SlashingStatus, error) { +func (s *Store) HasAttesterSlashing(ctx context.Context, slashing *ethpb.AttesterSlashing) (bool, slashertypes.SlashingStatus, error) { ctx, span := trace.StartSpan(ctx, "slasherDB.HasAttesterSlashing") defer span.End() - var status types.SlashingStatus + var status slashertypes.SlashingStatus var found bool root, err := hashutil.HashProto(slashing) if err != nil { return found, status, errors.Wrap(err, "failed to get hash root of attesterSlashing") } - key := encodeTypeRoot(types.SlashingType(types.Attestation), root) + key := encodeTypeRoot(slashertypes.SlashingType(slashertypes.Attestation), root) err = s.view(func(tx *bolt.Tx) error { b := tx.Bucket(slashingBucket) enc := b.Get(key) if enc != nil { found = true - status = types.SlashingStatus(enc[0]) + status = slashertypes.SlashingStatus(enc[0]) } return nil }) @@ -102,7 +103,7 @@ func (s *Store) HasAttesterSlashing(ctx context.Context, slashing *ethpb.Atteste } // SaveAttesterSlashing accepts a slashing proof and its status and writes it to disk. -func (s *Store) SaveAttesterSlashing(ctx context.Context, status types.SlashingStatus, slashing *ethpb.AttesterSlashing) error { +func (s *Store) SaveAttesterSlashing(ctx context.Context, status slashertypes.SlashingStatus, slashing *ethpb.AttesterSlashing) error { ctx, span := trace.StartSpan(ctx, "slasherDB.SaveAttesterSlashing") defer span.End() enc, err := proto.Marshal(slashing) @@ -113,7 +114,7 @@ func (s *Store) SaveAttesterSlashing(ctx context.Context, status types.SlashingS if err != nil { return err } - key := encodeTypeRoot(types.SlashingType(types.Attestation), root) + key := encodeTypeRoot(slashertypes.SlashingType(slashertypes.Attestation), root) return s.update(func(tx *bolt.Tx) error { b := tx.Bucket(slashingBucket) e := b.Put(key, append([]byte{byte(status)}, enc...)) @@ -122,7 +123,7 @@ func (s *Store) SaveAttesterSlashing(ctx context.Context, status types.SlashingS } // SaveAttesterSlashings accepts a slice of slashing proof and its status and writes it to disk. -func (s *Store) SaveAttesterSlashings(ctx context.Context, status types.SlashingStatus, slashings []*ethpb.AttesterSlashing) error { +func (s *Store) SaveAttesterSlashings(ctx context.Context, status slashertypes.SlashingStatus, slashings []*ethpb.AttesterSlashing) error { ctx, span := trace.StartSpan(ctx, "slasherDB.SaveAttesterSlashings") defer span.End() enc := make([][]byte, len(slashings)) @@ -137,7 +138,7 @@ func (s *Store) SaveAttesterSlashings(ctx context.Context, status types.Slashing if err != nil { return err } - key[i] = encodeTypeRoot(types.SlashingType(types.Attestation), root) + key[i] = encodeTypeRoot(slashertypes.SlashingType(slashertypes.Attestation), root) } return s.update(func(tx *bolt.Tx) error { @@ -153,10 +154,10 @@ func (s *Store) SaveAttesterSlashings(ctx context.Context, status types.Slashing } // GetLatestEpochDetected returns the latest detected epoch from db. -func (s *Store) GetLatestEpochDetected(ctx context.Context) (uint64, error) { +func (s *Store) GetLatestEpochDetected(ctx context.Context) (types.Epoch, error) { ctx, span := trace.StartSpan(ctx, "slasherDB.GetLatestEpochDetected") defer span.End() - var epoch uint64 + var epoch types.Epoch err := s.view(func(tx *bolt.Tx) error { b := tx.Bucket(slashingBucket) enc := b.Get([]byte(latestEpochKey)) @@ -164,19 +165,19 @@ func (s *Store) GetLatestEpochDetected(ctx context.Context) (uint64, error) { epoch = 0 return nil } - epoch = bytesutil.FromBytes8(enc) + epoch = types.Epoch(bytesutil.FromBytes8(enc)) return nil }) return epoch, err } // SetLatestEpochDetected sets the latest slashing detected epoch in db. -func (s *Store) SetLatestEpochDetected(ctx context.Context, epoch uint64) error { +func (s *Store) SetLatestEpochDetected(ctx context.Context, epoch types.Epoch) error { ctx, span := trace.StartSpan(ctx, "slasherDB.SetLatestEpochDetected") defer span.End() return s.update(func(tx *bolt.Tx) error { b := tx.Bucket(slashingBucket) - err := b.Put([]byte(latestEpochKey), bytesutil.Bytes8(epoch)) + err := b.Put([]byte(latestEpochKey), bytesutil.Bytes8(uint64(epoch))) return err }) } diff --git a/slasher/db/kv/attester_slashings_test.go b/slasher/db/kv/attester_slashings_test.go index 3986c71349..20617cf820 100644 --- a/slasher/db/kv/attester_slashings_test.go +++ b/slasher/db/kv/attester_slashings_test.go @@ -5,11 +5,12 @@ import ( "sort" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil/require" - "github.com/prysmaticlabs/prysm/slasher/db/types" + dbtypes "github.com/prysmaticlabs/prysm/slasher/db/types" ) func TestStore_AttesterSlashingNilBucket(t *testing.T) { @@ -28,7 +29,7 @@ func TestStore_AttesterSlashingNilBucket(t *testing.T) { require.NoError(t, err, "HasAttesterSlashing should not return error") require.Equal(t, false, has) - p, err := db.AttesterSlashings(ctx, types.SlashingStatus(types.Active)) + p, err := db.AttesterSlashings(ctx, dbtypes.SlashingStatus(dbtypes.Active)) require.NoError(t, err, "Failed to get attester slashing") require.NotNil(t, p, "Get should return empty attester slashing array for a non existent key") require.Equal(t, 0, len(p), "Get should return empty attester slashing array for a non existent key") @@ -41,19 +42,19 @@ func TestStore_SaveAttesterSlashing(t *testing.T) { data := testutil.HydrateAttestationData(ðpb.AttestationData{}) att := ðpb.IndexedAttestation{Data: data, Signature: make([]byte, 96)} tests := []struct { - ss types.SlashingStatus + ss dbtypes.SlashingStatus as *ethpb.AttesterSlashing }{ { - ss: types.Active, + ss: dbtypes.Active, as: ðpb.AttesterSlashing{Attestation_1: ðpb.IndexedAttestation{Data: data, Signature: bytesutil.PadTo([]byte("hello"), 96)}, Attestation_2: att}, }, { - ss: types.Included, + ss: dbtypes.Included, as: ðpb.AttesterSlashing{Attestation_1: ðpb.IndexedAttestation{Data: data, Signature: bytesutil.PadTo([]byte("hello2"), 96)}, Attestation_2: att}, }, { - ss: types.Reverted, + ss: dbtypes.Reverted, as: ðpb.AttesterSlashing{Attestation_1: ðpb.IndexedAttestation{Data: data, Signature: bytesutil.PadTo([]byte("hello3"), 96)}, Attestation_2: att}, }, } @@ -81,9 +82,9 @@ func TestStore_SaveAttesterSlashings(t *testing.T) { {Attestation_1: ðpb.IndexedAttestation{Signature: bytesutil.PadTo([]byte("2"), 96), Data: data}, Attestation_2: att}, {Attestation_1: ðpb.IndexedAttestation{Signature: bytesutil.PadTo([]byte("3"), 96), Data: data}, Attestation_2: att}, } - err := db.SaveAttesterSlashings(ctx, types.Active, as) + err := db.SaveAttesterSlashings(ctx, dbtypes.Active, as) require.NoError(t, err, "Save attester slashing failed") - attesterSlashings, err := db.AttesterSlashings(ctx, types.Active) + attesterSlashings, err := db.AttesterSlashings(ctx, dbtypes.Active) require.NoError(t, err, "Failed to get attester slashings") sort.SliceStable(attesterSlashings, func(i, j int) bool { return attesterSlashings[i].Attestation_1.Signature[0] < attesterSlashings[j].Attestation_1.Signature[0] @@ -99,25 +100,25 @@ func TestStore_UpdateAttesterSlashingStatus(t *testing.T) { data := testutil.HydrateAttestationData(ðpb.AttestationData{}) tests := []struct { - ss types.SlashingStatus + ss dbtypes.SlashingStatus as *ethpb.AttesterSlashing }{ { - ss: types.Active, + ss: dbtypes.Active, as: ðpb.AttesterSlashing{ Attestation_1: ðpb.IndexedAttestation{Data: data, Signature: bytesutil.PadTo([]byte("hello"), 96)}, Attestation_2: ðpb.IndexedAttestation{Data: data, Signature: bytesutil.PadTo([]byte("hello"), 96)}, }, }, { - ss: types.Active, + ss: dbtypes.Active, as: ðpb.AttesterSlashing{ Attestation_1: ðpb.IndexedAttestation{Data: data, Signature: bytesutil.PadTo([]byte("hello2"), 96)}, Attestation_2: ðpb.IndexedAttestation{Data: data, Signature: bytesutil.PadTo([]byte("hello2"), 96)}, }, }, { - ss: types.Active, + ss: dbtypes.Active, as: ðpb.AttesterSlashing{ Attestation_1: ðpb.IndexedAttestation{Data: data, Signature: bytesutil.PadTo([]byte("hello3"), 96)}, Attestation_2: ðpb.IndexedAttestation{Data: data, Signature: bytesutil.PadTo([]byte("hello2"), 96)}, @@ -136,12 +137,12 @@ func TestStore_UpdateAttesterSlashingStatus(t *testing.T) { require.Equal(t, true, has, "Failed to find attester slashing: %v", tt.as) require.Equal(t, tt.ss, st, "Failed to find attester slashing with the correct status: %v", tt.as) - err = db.SaveAttesterSlashing(ctx, types.SlashingStatus(types.Included), tt.as) + err = db.SaveAttesterSlashing(ctx, dbtypes.SlashingStatus(dbtypes.Included), tt.as) require.NoError(t, err) has, st, err = db.HasAttesterSlashing(ctx, tt.as) require.NoError(t, err, "Failed to get attester slashing") require.Equal(t, true, has, "Failed to find attester slashing: %v", tt.as) - require.Equal(t, types.SlashingStatus(types.Included), st, "Failed to find attester slashing with the correct status: %v", tt.as) + require.Equal(t, dbtypes.SlashingStatus(dbtypes.Included), st, "Failed to find attester slashing with the correct status: %v", tt.as) } } @@ -151,8 +152,8 @@ func TestStore_LatestEpochDetected(t *testing.T) { e, err := db.GetLatestEpochDetected(ctx) require.NoError(t, err, "Get latest epoch detected failed") - require.Equal(t, uint64(0), e, "Latest epoch detected should have been 0 before setting got: %d", e) - epoch := uint64(1) + require.Equal(t, types.Epoch(0), e, "Latest epoch detected should have been 0 before setting got: %d", e) + epoch := types.Epoch(1) err = db.SetLatestEpochDetected(ctx, epoch) require.NoError(t, err, "Set latest epoch detected failed") e, err = db.GetLatestEpochDetected(ctx) diff --git a/slasher/db/kv/benchmark_test.go b/slasher/db/kv/benchmark_test.go index da7271f11a..2f01ac1393 100644 --- a/slasher/db/kv/benchmark_test.go +++ b/slasher/db/kv/benchmark_test.go @@ -4,9 +4,10 @@ import ( "context" "testing" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/require" - "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" + slashertypes "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" ) const ( @@ -17,18 +18,18 @@ func BenchmarkStore_SaveEpochSpans(b *testing.B) { ctx := context.Background() sigBytes := [2]byte{} db := setupDB(b) - es := &types.EpochStore{} + es := &slashertypes.EpochStore{} - es, err := es.SetValidatorSpan(benchmarkValidator, types.Span{MinSpan: 1, MaxSpan: 2, SigBytes: sigBytes, HasAttested: true}) + es, err := es.SetValidatorSpan(benchmarkValidator, slashertypes.Span{MinSpan: 1, MaxSpan: 2, SigBytes: sigBytes, HasAttested: true}) assert.NoError(b, err) for i := 0; i < benchmarkValidator; i++ { - es, err = es.SetValidatorSpan(uint64(i), types.Span{MinSpan: 1, MaxSpan: 2, SigBytes: sigBytes, HasAttested: true}) + es, err = es.SetValidatorSpan(uint64(i), slashertypes.Span{MinSpan: 1, MaxSpan: 2, SigBytes: sigBytes, HasAttested: true}) assert.NoError(b, err) } b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { - err := db.SaveEpochSpans(ctx, uint64(i%54000), es, false) + err := db.SaveEpochSpans(ctx, types.Epoch(i%54000), es, false) require.NoError(b, err, "Save validator span map failed") } } @@ -37,34 +38,34 @@ func BenchmarkStore_EpochSpans(b *testing.B) { db := setupDB(b) ctx := context.Background() sigBytes := [2]byte{} - es := &types.EpochStore{} - es, err := es.SetValidatorSpan(benchmarkValidator, types.Span{MinSpan: 1, MaxSpan: 2, SigBytes: sigBytes, HasAttested: true}) + es := &slashertypes.EpochStore{} + es, err := es.SetValidatorSpan(benchmarkValidator, slashertypes.Span{MinSpan: 1, MaxSpan: 2, SigBytes: sigBytes, HasAttested: true}) assert.NoError(b, err) for i := 0; i < benchmarkValidator; i++ { - es, err = es.SetValidatorSpan(uint64(i), types.Span{MinSpan: 1, MaxSpan: 2, SigBytes: sigBytes, HasAttested: true}) + es, err = es.SetValidatorSpan(uint64(i), slashertypes.Span{MinSpan: 1, MaxSpan: 2, SigBytes: sigBytes, HasAttested: true}) assert.NoError(b, err) } b.Log(len(es.Bytes())) for i := 0; i < 200; i++ { - err := db.SaveEpochSpans(ctx, uint64(i), es, false) + err := db.SaveEpochSpans(ctx, types.Epoch(i), es, false) require.NoError(b, err, "Save validator span map failed") } b.Log(db.db.Info()) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { - _, err := db.EpochSpans(ctx, uint64(i%200), false) + _, err := db.EpochSpans(ctx, types.Epoch(i%200), false) require.NoError(b, err, "Read validator span map failed") } } func BenchmarkStore_GetValidatorSpan(b *testing.B) { sigBytes := [2]byte{} - es := &types.EpochStore{} - es, err := es.SetValidatorSpan(benchmarkValidator, types.Span{MinSpan: 1, MaxSpan: 2, SigBytes: sigBytes, HasAttested: true}) + es := &slashertypes.EpochStore{} + es, err := es.SetValidatorSpan(benchmarkValidator, slashertypes.Span{MinSpan: 1, MaxSpan: 2, SigBytes: sigBytes, HasAttested: true}) assert.NoError(b, err) for i := 0; i < benchmarkValidator; i++ { - es, err = es.SetValidatorSpan(uint64(i), types.Span{MinSpan: uint16(i), MaxSpan: uint16(benchmarkValidator - i), SigBytes: sigBytes, HasAttested: true}) + es, err = es.SetValidatorSpan(uint64(i), slashertypes.Span{MinSpan: uint16(i), MaxSpan: uint16(benchmarkValidator - i), SigBytes: sigBytes, HasAttested: true}) assert.NoError(b, err) } b.Log(len(es.Bytes())) @@ -80,19 +81,19 @@ func BenchmarkStore_GetValidatorSpan(b *testing.B) { func BenchmarkStore_SetValidatorSpan(b *testing.B) { sigBytes := [2]byte{} var err error - es := &types.EpochStore{} - es, err = es.SetValidatorSpan(benchmarkValidator, types.Span{MinSpan: 1, MaxSpan: 2, SigBytes: sigBytes, HasAttested: true}) + es := &slashertypes.EpochStore{} + es, err = es.SetValidatorSpan(benchmarkValidator, slashertypes.Span{MinSpan: 1, MaxSpan: 2, SigBytes: sigBytes, HasAttested: true}) assert.NoError(b, err) for i := 0; i < benchmarkValidator; i++ { - es, err = es.SetValidatorSpan(uint64(i), types.Span{MinSpan: uint16(i), MaxSpan: uint16(benchmarkValidator - i), SigBytes: sigBytes, HasAttested: true}) + es, err = es.SetValidatorSpan(uint64(i), slashertypes.Span{MinSpan: uint16(i), MaxSpan: uint16(benchmarkValidator - i), SigBytes: sigBytes, HasAttested: true}) assert.NoError(b, err) } b.Log(len(es.Bytes())) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { - es, err = es.SetValidatorSpan(uint64(i%benchmarkValidator), types.Span{MinSpan: uint16(i), MaxSpan: uint16(benchmarkValidator - i), SigBytes: sigBytes, HasAttested: true}) + es, err = es.SetValidatorSpan(uint64(i%benchmarkValidator), slashertypes.Span{MinSpan: uint16(i), MaxSpan: uint16(benchmarkValidator - i), SigBytes: sigBytes, HasAttested: true}) require.NoError(b, err, "Read validator span map failed") } } diff --git a/slasher/db/kv/block_header.go b/slasher/db/kv/block_header.go index 616d2989d0..0df4ee1acb 100644 --- a/slasher/db/kv/block_header.go +++ b/slasher/db/kv/block_header.go @@ -6,6 +6,7 @@ import ( "github.com/gogo/protobuf/proto" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/shared/bytesutil" @@ -112,7 +113,7 @@ func (s *Store) DeleteBlockHeader(ctx context.Context, blockHeader *ethpb.Signed } // PruneBlockHistory leaves only records younger then history size. -func (s *Store) PruneBlockHistory(ctx context.Context, currentEpoch, pruningEpochAge uint64) error { +func (s *Store) PruneBlockHistory(ctx context.Context, currentEpoch, pruningEpochAge types.Epoch) error { ctx, span := trace.StartSpan(ctx, "slasherDB.pruneBlockHistory") defer span.End() pruneTill := int64(currentEpoch) - int64(pruningEpochAge) diff --git a/slasher/db/kv/block_header_test.go b/slasher/db/kv/block_header_test.go index 11857e5f9f..eaa57907a6 100644 --- a/slasher/db/kv/block_header_test.go +++ b/slasher/db/kv/block_header_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/shared/bytesutil" @@ -162,8 +163,8 @@ func TestPruneHistoryBlkHdr(t *testing.T) { require.NotNil(t, bha) require.DeepEqual(t, tt.bh, bha[0], "Should return bh") } - currentEpoch := uint64(3) - historyToKeep := uint64(2) + currentEpoch := types.Epoch(3) + historyToKeep := types.Epoch(2) err := db.PruneBlockHistory(ctx, currentEpoch, historyToKeep) require.NoError(t, err, "Failed to prune") diff --git a/slasher/db/kv/indexed_attestations.go b/slasher/db/kv/indexed_attestations.go index bcfabbba8b..d8fbde2331 100644 --- a/slasher/db/kv/indexed_attestations.go +++ b/slasher/db/kv/indexed_attestations.go @@ -6,6 +6,7 @@ import ( "github.com/gogo/protobuf/proto" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/bytesutil" bolt "go.etcd.io/bbolt" @@ -26,11 +27,11 @@ func unmarshalIndexedAttestation(ctx context.Context, enc []byte) (*ethpb.Indexe // IndexedAttestationsForTarget accepts a target epoch and returns a list of // indexed attestations. // Returns nil if the indexed attestation does not exist with that target epoch. -func (s *Store) IndexedAttestationsForTarget(ctx context.Context, targetEpoch uint64) ([]*ethpb.IndexedAttestation, error) { +func (s *Store) IndexedAttestationsForTarget(ctx context.Context, targetEpoch types.Epoch) ([]*ethpb.IndexedAttestation, error) { ctx, span := trace.StartSpan(ctx, "slasherDB.IndexedAttestationsForTarget") defer span.End() var idxAtts []*ethpb.IndexedAttestation - key := bytesutil.Bytes8(targetEpoch) + key := bytesutil.Bytes8(uint64(targetEpoch)) err := s.view(func(tx *bolt.Tx) error { c := tx.Bucket(historicIndexedAttestationsBucket).Cursor() for k, enc := c.Seek(key); k != nil && bytes.Equal(k[:8], key); k, enc = c.Next() { @@ -47,7 +48,7 @@ func (s *Store) IndexedAttestationsForTarget(ctx context.Context, targetEpoch ui // IndexedAttestationsWithPrefix accepts a target epoch and signature bytes to find all attestations with the requested prefix. // Returns nil if the indexed attestation does not exist with that target epoch. -func (s *Store) IndexedAttestationsWithPrefix(ctx context.Context, targetEpoch uint64, sigBytes []byte) ([]*ethpb.IndexedAttestation, error) { +func (s *Store) IndexedAttestationsWithPrefix(ctx context.Context, targetEpoch types.Epoch, sigBytes []byte) ([]*ethpb.IndexedAttestation, error) { ctx, span := trace.StartSpan(ctx, "slasherDB.IndexedAttestationsWithPrefix") defer span.End() var idxAtts []*ethpb.IndexedAttestation @@ -162,7 +163,7 @@ func (s *Store) DeleteIndexedAttestation(ctx context.Context, idxAttestation *et } // PruneAttHistory removes all attestations from the DB older than the pruning epoch age. -func (s *Store) PruneAttHistory(ctx context.Context, currentEpoch, pruningEpochAge uint64) error { +func (s *Store) PruneAttHistory(ctx context.Context, currentEpoch, pruningEpochAge types.Epoch) error { ctx, span := trace.StartSpan(ctx, "slasherDB.pruneAttHistory") defer span.End() pruneFromEpoch := int64(currentEpoch) - int64(pruningEpochAge) diff --git a/slasher/db/kv/indexed_attestations_test.go b/slasher/db/kv/indexed_attestations_test.go index 8a8422d2b7..3bca7df169 100644 --- a/slasher/db/kv/indexed_attestations_test.go +++ b/slasher/db/kv/indexed_attestations_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/testutil/require" ) @@ -85,7 +86,7 @@ func TestIndexedAttestationsWithPrefix(t *testing.T) { type prefixTestStruct struct { name string attsInDB []*ethpb.IndexedAttestation - targetEpoch uint64 + targetEpoch types.Epoch searchPrefix []byte expectedResult []*ethpb.IndexedAttestation } @@ -326,7 +327,7 @@ func TestIndexedAttestationsForTarget(t *testing.T) { type prefixTestStruct struct { name string attsInDB []*ethpb.IndexedAttestation - targetEpoch uint64 + targetEpoch types.Epoch expectedResult []*ethpb.IndexedAttestation } prefixTests := []prefixTestStruct{ @@ -695,8 +696,8 @@ func TestPruneHistoryIndexedAttestation(t *testing.T) { require.NoError(t, err, "Failed to get indexed attestation") require.Equal(t, true, found, "Expected to find attestation in DB") } - currentEpoch := uint64(2) - historyToKeep := uint64(1) + currentEpoch := types.Epoch(2) + historyToKeep := types.Epoch(1) require.NoError(t, db.PruneAttHistory(ctx, currentEpoch, historyToKeep), "Failed to prune") for _, tt := range tests { diff --git a/slasher/db/kv/schema.go b/slasher/db/kv/schema.go index 5778f099f4..2aaf28da3c 100644 --- a/slasher/db/kv/schema.go +++ b/slasher/db/kv/schema.go @@ -1,8 +1,9 @@ package kv import ( + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bytesutil" - "github.com/prysmaticlabs/prysm/slasher/db/types" + dbtypes "github.com/prysmaticlabs/prysm/slasher/db/types" ) const ( @@ -36,12 +37,12 @@ func encodeSlotValidatorIDSig(slot, validatorID uint64, sig []byte) []byte { return append(append(bytesutil.Bytes8(slot), bytesutil.Bytes8(validatorID)...), sig...) } -func encodeEpochSig(targetEpoch uint64, sig []byte) []byte { - return append(bytesutil.Bytes8(targetEpoch), sig...) +func encodeEpochSig(targetEpoch types.Epoch, sig []byte) []byte { + return append(bytesutil.Bytes8(uint64(targetEpoch)), sig...) } -func encodeType(st types.SlashingType) []byte { +func encodeType(st dbtypes.SlashingType) []byte { return []byte{byte(st)} } -func encodeTypeRoot(st types.SlashingType, root [32]byte) []byte { +func encodeTypeRoot(st dbtypes.SlashingType, root [32]byte) []byte { return append([]byte{byte(st)}, root[:]...) } diff --git a/slasher/db/kv/spanner_new.go b/slasher/db/kv/spanner_new.go index 842e838016..9a54ab4d79 100644 --- a/slasher/db/kv/spanner_new.go +++ b/slasher/db/kv/spanner_new.go @@ -6,9 +6,10 @@ import ( "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/params" - "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" + slashertypes "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" bolt "go.etcd.io/bbolt" "go.opencensus.io/trace" ) @@ -16,7 +17,7 @@ import ( // Tracks the highest and lowest observed epochs from the validator span maps // used for attester slashing detection. This value is purely used // as a cache key and only needs to be maintained in memory. -var highestObservedEpoch uint64 +var highestObservedEpoch types.Epoch var lowestObservedEpoch = params.BeaconConfig().FarFutureEpoch var ( @@ -46,7 +47,7 @@ func persistFlatSpanMapsOnEviction(db *Store) func(key interface{}, value interf log.Tracef("Evicting flat span map for epoch: %d", key) err := db.update(func(tx *bolt.Tx) error { epoch, keyOK := key.(uint64) - epochStore, valueOK := value.(*types.EpochStore) + epochStore, valueOK := value.(*slashertypes.EpochStore) if !keyOK || !valueOK { return errors.New("could not cast key and value into needed types") } @@ -68,7 +69,7 @@ func persistFlatSpanMapsOnEviction(db *Store) func(key interface{}, value interf // for slashing detection. // Returns span byte array, and error in case of db error. // returns empty byte array if no entry for this epoch exists in db. -func (s *Store) EpochSpans(_ context.Context, epoch uint64, fromCache bool) (*types.EpochStore, error) { +func (s *Store) EpochSpans(_ context.Context, epoch types.Epoch, fromCache bool) (*slashertypes.EpochStore, error) { // Get from the cache if it exists or is requested, if not, go to DB. if fromCache && s.flatSpanCache.Has(epoch) || s.flatSpanCache.Has(epoch) { spans, _ := s.flatSpanCache.Get(epoch) @@ -81,24 +82,24 @@ func (s *Store) EpochSpans(_ context.Context, epoch uint64, fromCache bool) (*ty if b == nil { return nil } - spans := b.Get(bytesutil.Bytes8(epoch)) + spans := b.Get(bytesutil.Bytes8(uint64(epoch))) copiedSpans = make([]byte, len(spans)) copy(copiedSpans, spans) return nil }) if err != nil { - return &types.EpochStore{}, err + return &slashertypes.EpochStore{}, err } if copiedSpans == nil { copiedSpans = []byte{} } - return types.NewEpochStore(copiedSpans) + return slashertypes.NewEpochStore(copiedSpans) } // SaveEpochSpans accepts a epoch and span byte array and writes it to disk. -func (s *Store) SaveEpochSpans(ctx context.Context, epoch uint64, es *types.EpochStore, toCache bool) error { - if len(es.Bytes())%int(types.SpannerEncodedLength) != 0 { - return types.ErrWrongSize +func (s *Store) SaveEpochSpans(ctx context.Context, epoch types.Epoch, es *slashertypes.EpochStore, toCache bool) error { + if len(es.Bytes())%int(slashertypes.SpannerEncodedLength) != 0 { + return slashertypes.ErrWrongSize } // Also prune indexed attestations older then weak subjectivity period. if err := s.setObservedEpochs(ctx, epoch); err != nil { @@ -117,7 +118,7 @@ func (s *Store) SaveEpochSpans(ctx context.Context, epoch uint64, es *types.Epoc if err != nil { return err } - return b.Put(bytesutil.Bytes8(epoch), es.Bytes()) + return b.Put(bytesutil.Bytes8(uint64(epoch)), es.Bytes()) }) } @@ -135,7 +136,7 @@ func (s *Store) EnableSpanCache(enable bool) { s.spanCacheEnabled = enable } -func (s *Store) setObservedEpochs(ctx context.Context, epoch uint64) error { +func (s *Store) setObservedEpochs(ctx context.Context, epoch types.Epoch) error { var err error if epoch > highestObservedEpoch { slasherHighestObservedEpoch.Set(float64(epoch)) diff --git a/slasher/db/kv/spanner_new_test.go b/slasher/db/kv/spanner_new_test.go index b983b2abb9..9243664bfc 100644 --- a/slasher/db/kv/spanner_new_test.go +++ b/slasher/db/kv/spanner_new_test.go @@ -5,18 +5,19 @@ import ( "encoding/hex" "testing" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/testutil/require" - dbTypes "github.com/prysmaticlabs/prysm/slasher/db/types" - "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" + dbtypes "github.com/prysmaticlabs/prysm/slasher/db/types" + slashertypes "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" ) type spansTestStruct struct { name string - epoch uint64 + epoch types.Epoch spansHex string spansResultHex string - validator1Span types.Span + validator1Span slashertypes.Span err error } @@ -29,15 +30,15 @@ func init() { epoch: 1, spansHex: "00000000", spansResultHex: "", - validator1Span: types.Span{}, - err: types.ErrWrongSize, + validator1Span: slashertypes.Span{}, + err: slashertypes.ErrWrongSize, }, { name: "no validator 1 in spans", epoch: 2, spansHex: "00000000000000", spansResultHex: "00000000000000", - validator1Span: types.Span{}, + validator1Span: slashertypes.Span{}, err: nil, }, { @@ -45,7 +46,7 @@ func init() { epoch: 3, spansHex: "0000000000000001000000000000", spansResultHex: "0000000000000001000000000000", - validator1Span: types.Span{MinSpan: 1}, + validator1Span: slashertypes.Span{MinSpan: 1}, err: nil, }, } @@ -58,9 +59,9 @@ func TestValidatorSpans_NilDB(t *testing.T) { ctx := context.Background() validatorIdx := uint64(1) - es, err := db.EpochSpans(ctx, validatorIdx, false) + es, err := db.EpochSpans(ctx, types.Epoch(validatorIdx), false) require.NoError(t, err, "Nil EpochSpansMap should not return error") - cleanStore, err := types.NewEpochStore([]byte{}) + cleanStore, err := slashertypes.NewEpochStore([]byte{}) require.NoError(t, err) require.DeepEqual(t, es, cleanStore, "EpochSpans should return empty byte array if no record exists in the db") } @@ -74,7 +75,7 @@ func TestStore_SaveReadEpochSpans(t *testing.T) { t.Run(tt.name, func(t *testing.T) { spans, err := hex.DecodeString(tt.spansHex) require.NoError(t, err) - es, err := types.NewEpochStore(spans) + es, err := slashertypes.NewEpochStore(spans) if tt.err != nil { require.ErrorContains(t, tt.err.Error(), err) } else { @@ -85,7 +86,7 @@ func TestStore_SaveReadEpochSpans(t *testing.T) { require.NoError(t, err, "Failed to get validator spans") spansResult, err := hex.DecodeString(tt.spansResultHex) require.NoError(t, err) - esr, err := types.NewEpochStore(spansResult) + esr, err := slashertypes.NewEpochStore(spansResult) require.NoError(t, err) require.DeepEqual(t, sm, esr, "Get should return validator spans: %v", spansResult) @@ -101,7 +102,7 @@ func TestStore_SaveEpochSpans_ToCache(t *testing.T) { db := setupDB(t) ctx := context.Background() - spansToSave := map[uint64]types.Span{ + spansToSave := map[uint64]slashertypes.Span{ 0: {MinSpan: 5, MaxSpan: 69, SigBytes: [2]byte{40, 219}, HasAttested: false}, 10: {MinSpan: 43, MaxSpan: 32, SigBytes: [2]byte{10, 13}, HasAttested: true}, 1000: {MinSpan: 40, MaxSpan: 36, SigBytes: [2]byte{61, 151}, HasAttested: false}, @@ -109,17 +110,17 @@ func TestStore_SaveEpochSpans_ToCache(t *testing.T) { 50000: {MinSpan: 40, MaxSpan: 64, SigBytes: [2]byte{190, 215}, HasAttested: true}, 100: {MinSpan: 49, MaxSpan: 96, SigBytes: [2]byte{11, 98}, HasAttested: true}, } - epochStore, err := types.EpochStoreFromMap(spansToSave) + epochStore, err := slashertypes.EpochStoreFromMap(spansToSave) require.NoError(t, err) - epoch := uint64(9) - require.NoError(t, db.SaveEpochSpans(ctx, epoch, epochStore, dbTypes.UseCache)) + epoch := types.Epoch(9) + require.NoError(t, db.SaveEpochSpans(ctx, epoch, epochStore, dbtypes.UseCache)) - esFromCache, err := db.EpochSpans(ctx, epoch, dbTypes.UseCache) + esFromCache, err := db.EpochSpans(ctx, epoch, dbtypes.UseCache) require.NoError(t, err) require.DeepEqual(t, epochStore.Bytes(), esFromCache.Bytes()) - esFromDB, err := db.EpochSpans(ctx, epoch, dbTypes.UseDB) + esFromDB, err := db.EpochSpans(ctx, epoch, dbtypes.UseDB) require.NoError(t, err) require.DeepEqual(t, esFromDB.Bytes(), esFromCache.Bytes()) } @@ -129,7 +130,7 @@ func TestStore_SaveEpochSpans_ToDB(t *testing.T) { db := setupDB(t) ctx := context.Background() - spansToSave := map[uint64]types.Span{ + spansToSave := map[uint64]slashertypes.Span{ 0: {MinSpan: 5, MaxSpan: 69, SigBytes: [2]byte{40, 219}, HasAttested: false}, 10: {MinSpan: 43, MaxSpan: 32, SigBytes: [2]byte{10, 13}, HasAttested: true}, 1000: {MinSpan: 40, MaxSpan: 36, SigBytes: [2]byte{61, 151}, HasAttested: false}, @@ -137,18 +138,18 @@ func TestStore_SaveEpochSpans_ToDB(t *testing.T) { 100000: {MinSpan: 20, MaxSpan: 64, SigBytes: [2]byte{170, 215}, HasAttested: false}, 100: {MinSpan: 49, MaxSpan: 96, SigBytes: [2]byte{11, 98}, HasAttested: true}, } - epochStore, err := types.EpochStoreFromMap(spansToSave) + epochStore, err := slashertypes.EpochStoreFromMap(spansToSave) require.NoError(t, err) - epoch := uint64(9) - require.NoError(t, db.SaveEpochSpans(ctx, epoch, epochStore, dbTypes.UseDB)) + epoch := types.Epoch(9) + require.NoError(t, db.SaveEpochSpans(ctx, epoch, epochStore, dbtypes.UseDB)) // Expect cache to retrieve from DB if its not in cache. - esFromCache, err := db.EpochSpans(ctx, epoch, dbTypes.UseCache) + esFromCache, err := db.EpochSpans(ctx, epoch, dbtypes.UseCache) require.NoError(t, err) require.DeepEqual(t, esFromCache.Bytes(), epochStore.Bytes()) - esFromDB, err := db.EpochSpans(ctx, epoch, dbTypes.UseDB) + esFromDB, err := db.EpochSpans(ctx, epoch, dbtypes.UseDB) require.NoError(t, err) require.DeepEqual(t, epochStore.Bytes(), esFromDB.Bytes()) } diff --git a/slasher/detection/BUILD.bazel b/slasher/detection/BUILD.bazel index 9a047d1a0c..0d5ecb5d9c 100644 --- a/slasher/detection/BUILD.bazel +++ b/slasher/detection/BUILD.bazel @@ -32,6 +32,7 @@ go_library( "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prometheus_client_golang//prometheus/promauto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@io_opencensus_go//trace:go_default_library", diff --git a/slasher/detection/attestations/BUILD.bazel b/slasher/detection/attestations/BUILD.bazel index 5a8edd0b89..8ea8c0cf65 100644 --- a/slasher/detection/attestations/BUILD.bazel +++ b/slasher/detection/attestations/BUILD.bazel @@ -19,6 +19,7 @@ go_library( "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prometheus_client_golang//prometheus/promauto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@io_opencensus_go//trace:go_default_library", ], @@ -39,6 +40,7 @@ go_test( "//slasher/db/testing:go_default_library", "//slasher/db/types:go_default_library", "//slasher/detection/attestations/types:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", ], diff --git a/slasher/detection/attestations/spanner.go b/slasher/detection/attestations/spanner.go index b2533c6c67..d24fba29a2 100644 --- a/slasher/detection/attestations/spanner.go +++ b/slasher/detection/attestations/spanner.go @@ -9,13 +9,14 @@ import ( "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/featureconfig" "github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/slasher/db" - dbTypes "github.com/prysmaticlabs/prysm/slasher/db/types" + dbtypes "github.com/prysmaticlabs/prysm/slasher/db/types" "github.com/prysmaticlabs/prysm/slasher/detection/attestations/iface" - "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" + slashertypes "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" "go.opencensus.io/trace" ) @@ -37,7 +38,7 @@ var ( // We look back 128 epochs when updating min/max spans // for incoming attestations. // TODO(#5040): Remove lookback and handle min spans properly. -const epochLookback = 128 +const epochLookback = types.Epoch(128) var _ iface.SpanDetector = (*SpanDetector)(nil) @@ -63,7 +64,7 @@ func NewSpanDetector(db db.Database) *SpanDetector { func (s *SpanDetector) DetectSlashingsForAttestation( ctx context.Context, att *ethpb.IndexedAttestation, -) ([]*types.DetectionResult, error) { +) ([]*slashertypes.DetectionResult, error) { ctx, traceSpan := trace.StartSpan(ctx, "spanner.DetectSlashingsForAttestation") defer traceSpan.End() sourceEpoch := att.Data.Source.Epoch @@ -84,16 +85,16 @@ func (s *SpanDetector) DetectSlashingsForAttestation( ) } - spanMap, err := s.slasherDB.EpochSpans(ctx, sourceEpoch, dbTypes.UseCache) + spanMap, err := s.slasherDB.EpochSpans(ctx, sourceEpoch, dbtypes.UseCache) if err != nil { return nil, err } - targetSpanMap, err := s.slasherDB.EpochSpans(ctx, targetEpoch, dbTypes.UseCache) + targetSpanMap, err := s.slasherDB.EpochSpans(ctx, targetEpoch, dbtypes.UseCache) if err != nil { return nil, err } - var detections []*types.DetectionResult + var detections []*slashertypes.DetectionResult distance := uint16(dis) for _, idx := range att.AttestingIndices { if ctx.Err() != nil { @@ -105,8 +106,8 @@ func (s *SpanDetector) DetectSlashingsForAttestation( } minSpan := span.MinSpan if minSpan > 0 && minSpan < distance { - slashableEpoch := sourceEpoch + uint64(minSpan) - targetSpans, err := s.slasherDB.EpochSpans(ctx, slashableEpoch, dbTypes.UseCache) + slashableEpoch := sourceEpoch + types.Epoch(minSpan) + targetSpans, err := s.slasherDB.EpochSpans(ctx, slashableEpoch, dbtypes.UseCache) if err != nil { return nil, err } @@ -114,9 +115,9 @@ func (s *SpanDetector) DetectSlashingsForAttestation( if err != nil { return nil, err } - detections = append(detections, &types.DetectionResult{ + detections = append(detections, &slashertypes.DetectionResult{ ValidatorIndex: idx, - Kind: types.SurroundVote, + Kind: slashertypes.SurroundVote, SlashableEpoch: slashableEpoch, SigBytes: valSpan.SigBytes, }) @@ -125,8 +126,8 @@ func (s *SpanDetector) DetectSlashingsForAttestation( maxSpan := span.MaxSpan if maxSpan > distance { - slashableEpoch := sourceEpoch + uint64(maxSpan) - targetSpans, err := s.slasherDB.EpochSpans(ctx, slashableEpoch, dbTypes.UseCache) + slashableEpoch := sourceEpoch + types.Epoch(maxSpan) + targetSpans, err := s.slasherDB.EpochSpans(ctx, slashableEpoch, dbtypes.UseCache) if err != nil { return nil, err } @@ -134,9 +135,9 @@ func (s *SpanDetector) DetectSlashingsForAttestation( if err != nil { return nil, err } - detections = append(detections, &types.DetectionResult{ + detections = append(detections, &slashertypes.DetectionResult{ ValidatorIndex: idx, - Kind: types.SurroundVote, + Kind: slashertypes.SurroundVote, SlashableEpoch: slashableEpoch, SigBytes: valSpan.SigBytes, }) @@ -149,9 +150,9 @@ func (s *SpanDetector) DetectSlashingsForAttestation( } // Check if the validator has attested for this epoch or not. if targetSpan.HasAttested { - detections = append(detections, &types.DetectionResult{ + detections = append(detections, &slashertypes.DetectionResult{ ValidatorIndex: idx, - Kind: types.DoubleVote, + Kind: slashertypes.DoubleVote, SlashableEpoch: targetEpoch, SigBytes: targetSpan.SigBytes, }) @@ -188,7 +189,7 @@ func (s *SpanDetector) saveSigBytes(ctx context.Context, att *ethpb.IndexedAttes if source > target { target = source } - spanMap, err := s.slasherDB.EpochSpans(ctx, target, dbTypes.UseCache) + spanMap, err := s.slasherDB.EpochSpans(ctx, target, dbtypes.UseCache) if err != nil { return err } @@ -213,7 +214,7 @@ func (s *SpanDetector) saveSigBytes(ctx context.Context, att *ethpb.IndexedAttes sigBytes = [2]byte{att.Signature[0], att.Signature[1]} } // Save the signature bytes into the span for this epoch. - newSpan := types.Span{ + newSpan := slashertypes.Span{ MinSpan: span.MinSpan, MaxSpan: span.MaxSpan, HasAttested: true, @@ -224,7 +225,7 @@ func (s *SpanDetector) saveSigBytes(ctx context.Context, att *ethpb.IndexedAttes return err } } - return s.slasherDB.SaveEpochSpans(ctx, target, spanMap, dbTypes.UseCache) + return s.slasherDB.SaveEpochSpans(ctx, target, spanMap, dbtypes.UseCache) } // Updates a min span for a validator index given a source and target epoch @@ -248,7 +249,7 @@ func (s *SpanDetector) updateMinSpan(ctx context.Context, att *ethpb.IndexedAtte // the for loop tries to update min span using cache for as long as there // is a relevant cached epoch. when there is no such epoch in cache batch // db read and write is used. - var spanMap *types.EpochStore + var spanMap *slashertypes.EpochStore epoch := source - 1 lookbackEpoch := epoch - epochLookback // prevent underflow @@ -260,12 +261,12 @@ func (s *SpanDetector) updateMinSpan(ctx context.Context, att *ethpb.IndexedAtte untilEpoch = 0 } var err error - dbOrCache := dbTypes.UseCache + dbOrCache := dbtypes.UseCache for ; epoch >= untilEpoch; epoch-- { if ctx.Err() != nil { return errors.Wrap(ctx.Err(), "could not update min spans") } - spanMap, err = s.slasherDB.EpochSpans(ctx, epoch, dbTypes.UseCache) + spanMap, err = s.slasherDB.EpochSpans(ctx, epoch, dbtypes.UseCache) if err != nil { return err } @@ -277,7 +278,7 @@ func (s *SpanDetector) updateMinSpan(ctx context.Context, att *ethpb.IndexedAtte } newMinSpan := uint16(target - epoch) if span.MinSpan == 0 || span.MinSpan > newMinSpan { - span = types.Span{ + span = slashertypes.Span{ MinSpan: newMinSpan, MaxSpan: span.MaxSpan, SigBytes: span.SigBytes, @@ -290,8 +291,8 @@ func (s *SpanDetector) updateMinSpan(ctx context.Context, att *ethpb.IndexedAtte indices = append(indices, idx) } } - if epoch <= lookbackEpoch && dbOrCache == dbTypes.UseCache { - dbOrCache = dbTypes.UseDB + if epoch <= lookbackEpoch && dbOrCache == dbtypes.UseCache { + dbOrCache = dbtypes.UseDB } if err := s.slasherDB.SaveEpochSpans(ctx, epoch, spanMap, dbOrCache); err != nil { return err @@ -324,7 +325,7 @@ func (s *SpanDetector) updateMaxSpan(ctx context.Context, att *ethpb.IndexedAtte if ctx.Err() != nil { return errors.Wrap(ctx.Err(), "could not update max spans") } - spanMap, err := s.slasherDB.EpochSpans(ctx, epoch, dbTypes.UseCache) + spanMap, err := s.slasherDB.EpochSpans(ctx, epoch, dbtypes.UseCache) if err != nil { return err } @@ -336,7 +337,7 @@ func (s *SpanDetector) updateMaxSpan(ctx context.Context, att *ethpb.IndexedAtte } newMaxSpan := uint16(target - epoch) if newMaxSpan > span.MaxSpan { - span = types.Span{ + span = slashertypes.Span{ MinSpan: span.MinSpan, MaxSpan: newMaxSpan, SigBytes: span.SigBytes, @@ -349,7 +350,7 @@ func (s *SpanDetector) updateMaxSpan(ctx context.Context, att *ethpb.IndexedAtte indices = append(indices, idx) } } - if err := s.slasherDB.SaveEpochSpans(ctx, epoch, spanMap, dbTypes.UseCache); err != nil { + if err := s.slasherDB.SaveEpochSpans(ctx, epoch, spanMap, dbtypes.UseCache); err != nil { return err } if len(indices) == 0 { diff --git a/slasher/detection/attestations/spanner_test.go b/slasher/detection/attestations/spanner_test.go index c6e788945c..862357133b 100644 --- a/slasher/detection/attestations/spanner_test.go +++ b/slasher/detection/attestations/spanner_test.go @@ -5,17 +5,18 @@ import ( "reflect" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/featureconfig" "github.com/prysmaticlabs/prysm/shared/sliceutil" "github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/require" testDB "github.com/prysmaticlabs/prysm/slasher/db/testing" - dbTypes "github.com/prysmaticlabs/prysm/slasher/db/types" - "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" + dbtypes "github.com/prysmaticlabs/prysm/slasher/db/types" + slashertypes "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" ) -func indexedAttestation(source, target uint64, indices []uint64) *ethpb.IndexedAttestation { +func indexedAttestation(source, target types.Epoch, indices []uint64) *ethpb.IndexedAttestation { return ðpb.IndexedAttestation{ AttestingIndices: indices, Data: ðpb.AttestationData{ @@ -250,12 +251,12 @@ func TestSpanDetector_DetectSlashingsForAttestation_Double(t *testing.T) { res, err := sd.DetectSlashingsForAttestation(ctx, tt.incomingAtt) require.NoError(t, err) - var want []*types.DetectionResult + var want []*slashertypes.DetectionResult if tt.slashCount > 0 { for _, indice := range sliceutil.IntersectionUint64(tt.att.AttestingIndices, tt.incomingAtt.AttestingIndices) { - want = append(want, &types.DetectionResult{ + want = append(want, &slashertypes.DetectionResult{ ValidatorIndex: indice, - Kind: types.DoubleVote, + Kind: slashertypes.DoubleVote, SlashableEpoch: tt.incomingAtt.Data.Target.Epoch, SigBytes: [2]byte{1, 2}, }) @@ -270,11 +271,11 @@ func TestSpanDetector_DetectSlashingsForAttestation_Double(t *testing.T) { func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { type testStruct struct { name string - sourceEpoch uint64 - targetEpoch uint64 - slashableEpoch uint64 + sourceEpoch types.Epoch + targetEpoch types.Epoch + slashableEpoch types.Epoch shouldSlash bool - spansByEpochForValidator map[uint64][3]uint16 + spansByEpochForValidator map[types.Epoch][3]uint16 } tests := []testStruct{ { @@ -285,7 +286,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { shouldSlash: true, // Given a distance of (6 - 3) = 3, we want the validator at epoch 3 to have // committed a slashable offense by having a max span of 4 > distance. - spansByEpochForValidator: map[uint64][3]uint16{ + spansByEpochForValidator: map[types.Epoch][3]uint16{ 3: {0, 4}, }, }, @@ -296,7 +297,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { // Given a distance of (6 - 3) = 3, we want the validator at epoch 3 to NOT // have committed slashable offense by having a max span of 1 < distance. shouldSlash: false, - spansByEpochForValidator: map[uint64][3]uint16{ + spansByEpochForValidator: map[types.Epoch][3]uint16{ 3: {0, 1}, }, }, @@ -307,7 +308,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { // Given a distance of (6 - 3) = 3, we want the validator at epoch 3 to NOT // have committed slashable offense by having a max span of 3 == distance. shouldSlash: false, - spansByEpochForValidator: map[uint64][3]uint16{ + spansByEpochForValidator: map[types.Epoch][3]uint16{ 3: {0, 3}, }, }, @@ -318,7 +319,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { // Given a min span of 0 and no max span slashing, we want validator to NOT // have committed a slashable offense if min span == 0. shouldSlash: false, - spansByEpochForValidator: map[uint64][3]uint16{ + spansByEpochForValidator: map[types.Epoch][3]uint16{ 3: {0, 1}, }, }, @@ -330,7 +331,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { // committed a slashable offense by having a min span of 1 < distance. shouldSlash: true, slashableEpoch: 4, - spansByEpochForValidator: map[uint64][3]uint16{ + spansByEpochForValidator: map[types.Epoch][3]uint16{ 3: {1, 0}, }, }, @@ -340,7 +341,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { sourceEpoch: 8, targetEpoch: 18, shouldSlash: false, - spansByEpochForValidator: map[uint64][3]uint16{ + spansByEpochForValidator: map[types.Epoch][3]uint16{ 0: {4, 0}, 1: {2, 0}, 2: {1, 0}, @@ -354,7 +355,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { targetEpoch: 12, shouldSlash: false, slashableEpoch: 0, - spansByEpochForValidator: map[uint64][3]uint16{ + spansByEpochForValidator: map[types.Epoch][3]uint16{ 4: {14, 2}, 5: {13, 1}, 6: {12, 0}, @@ -376,7 +377,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { targetEpoch: 15, shouldSlash: true, slashableEpoch: 18, - spansByEpochForValidator: map[uint64][3]uint16{ + spansByEpochForValidator: map[types.Epoch][3]uint16{ 4: {14, 2}, 5: {13, 7}, 6: {12, 6}, @@ -399,7 +400,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { sourceEpoch: 4, targetEpoch: 6, shouldSlash: false, - spansByEpochForValidator: map[uint64][3]uint16{ + spansByEpochForValidator: map[types.Epoch][3]uint16{ 1: {5, 0}, 2: {4, 0}, 3: {3, 0}, @@ -410,7 +411,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { sourceEpoch: 11, targetEpoch: 15, shouldSlash: false, - spansByEpochForValidator: map[uint64][3]uint16{ + spansByEpochForValidator: map[types.Epoch][3]uint16{ 1: {5, 0}, 2: {4, 0}, 3: {3, 0}, @@ -435,7 +436,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { targetEpoch: 19, shouldSlash: true, slashableEpoch: 14, - spansByEpochForValidator: map[uint64][3]uint16{ + spansByEpochForValidator: map[types.Epoch][3]uint16{ 0: {5, 0}, 1: {4, 0}, 2: {3, 0}, @@ -464,7 +465,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { shouldSlash: true, // Given a distance of (6 - 3) = 3, we want the validator at epoch 3 to have // committed a slashable offense by having a max span of 4 > distance. - spansByEpochForValidator: map[uint64][3]uint16{ + spansByEpochForValidator: map[types.Epoch][3]uint16{ 3: {0, 4}, }, }, @@ -475,7 +476,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { shouldSlash: false, // Given a distance of (6 - 3) = 3, we want the validator at epoch 3 to NOT // have committed slashable offense by having a max span of 1 < distance. - spansByEpochForValidator: map[uint64][3]uint16{ + spansByEpochForValidator: map[types.Epoch][3]uint16{ 3: {0, 1}, }, }, @@ -491,15 +492,15 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { // We only care about validator index 0 for these tests for simplicity. validatorIndex := uint64(0) for k, v := range tt.spansByEpochForValidator { - epochStore, err := types.NewEpochStore([]byte{}) + epochStore, err := slashertypes.NewEpochStore([]byte{}) require.NoError(t, err) - span := types.Span{ + span := slashertypes.Span{ MinSpan: v[0], MaxSpan: v[1], } epochStore, err = epochStore.SetValidatorSpan(validatorIndex, span) require.NoError(t, err) - require.NoError(t, sd.slasherDB.SaveEpochSpans(ctx, k, epochStore, dbTypes.UseDB), "Failed to save to slasherDB") + require.NoError(t, sd.slasherDB.SaveEpochSpans(ctx, k, epochStore, dbtypes.UseDB), "Failed to save to slasherDB") } att := ðpb.IndexedAttestation{ @@ -517,9 +518,9 @@ func TestSpanDetector_DetectSlashingsForAttestation_Surround(t *testing.T) { require.NoError(t, err) require.Equal(t, false, !tt.shouldSlash && res != nil, "Did not want validator to be slashed but found slashable offense: %v", res) if tt.shouldSlash { - want := []*types.DetectionResult{ + want := []*slashertypes.DetectionResult{ { - Kind: types.SurroundVote, + Kind: slashertypes.SurroundVote, SlashableEpoch: tt.slashableEpoch, }, } @@ -533,7 +534,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_MultipleValidators(t *testin type testStruct struct { name string incomingAtt *ethpb.IndexedAttestation - slashableEpochs []uint64 + slashableEpochs []types.Epoch shouldSlash []bool atts []*ethpb.IndexedAttestation } @@ -554,7 +555,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_MultipleValidators(t *testin }, Signature: []byte{1, 2}, }, - slashableEpochs: []uint64{6, 7, 5, 0}, + slashableEpochs: []types.Epoch{6, 7, 5, 0}, // Detections - double, surround, surrounded, none. shouldSlash: []bool{true, true, true, false}, // Atts in map: (src, epoch) - 0: (3, 6), 1: (2, 7), 2: (4, 5), 3: (5, 7) @@ -581,7 +582,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_MultipleValidators(t *testin }, Signature: []byte{1, 2}, }, - slashableEpochs: []uint64{8, 9, 10, 0}, + slashableEpochs: []types.Epoch{8, 9, 10, 0}, // Detections - surround, surround, surround, none. shouldSlash: []bool{true, true, true, false}, // Atts in map: (src, epoch) - 0: (1, 8), 1: (3, 9), 2: (2, 10), 3: (4, 6) @@ -608,7 +609,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_MultipleValidators(t *testin }, Signature: []byte{1, 2}, }, - slashableEpochs: []uint64{8, 8, 7, 0}, + slashableEpochs: []types.Epoch{8, 8, 7, 0}, // Detections - surround, surround, surround, none. shouldSlash: []bool{true, true, true, false}, // Atts in map: (src, epoch) - 0: (5, 8), 1: (3, 8), 2: (4, 7), 3: (1, 5) @@ -635,7 +636,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_MultipleValidators(t *testin }, Signature: []byte{1, 2}, }, - slashableEpochs: []uint64{7, 7, 7, 0}, + slashableEpochs: []types.Epoch{7, 7, 7, 0}, // Detections - surround, surround, surround, none. shouldSlash: []bool{true, true, true, false}, // Atts in map: (src, epoch) - 0: (2, 7), 1: (3, 7), 2: (6, 7), 3: (1, 5) @@ -662,7 +663,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_MultipleValidators(t *testin }, Signature: []byte{1, 2}, }, - slashableEpochs: []uint64{8, 9, 10, 0}, + slashableEpochs: []types.Epoch{8, 9, 10, 0}, // Detections - surround, surround, surround, none. shouldSlash: []bool{true, true, true, false}, // Atts in map: (src, epoch) - 0: (1, 8), 1: (3, 9), 2: (2, 10), 3: (4, 6) @@ -689,7 +690,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_MultipleValidators(t *testin }, Signature: []byte{1, 2}, }, - slashableEpochs: []uint64{8, 8, 7, 0}, + slashableEpochs: []types.Epoch{8, 8, 7, 0}, // Detections - surround, surround, surround, none. shouldSlash: []bool{true, true, true, false}, // Atts in map: (src, epoch) - 0: (5, 8), 1: (3, 8), 2: (4, 7), 3: (1, 5) @@ -716,7 +717,7 @@ func TestSpanDetector_DetectSlashingsForAttestation_MultipleValidators(t *testin }, Signature: []byte{1, 2}, }, - slashableEpochs: []uint64{8, 8, 7, 0}, + slashableEpochs: []types.Epoch{8, 8, 7, 0}, // Detections - surround, surround, surround, none. shouldSlash: []bool{true, true, true, false}, // Atts in map: (src, epoch) - 0: (5, 8), 1: (3, 8), 2: (4, 7), 3: (1, 5) @@ -747,20 +748,20 @@ func TestSpanDetector_DetectSlashingsForAttestation_MultipleValidators(t *testin } res, err := spanDetector.DetectSlashingsForAttestation(ctx, tt.incomingAtt) require.NoError(t, err) - var want []*types.DetectionResult + var want []*slashertypes.DetectionResult for i := 0; i < len(tt.incomingAtt.AttestingIndices); i++ { if tt.shouldSlash[i] { if tt.slashableEpochs[i] == tt.incomingAtt.Data.Target.Epoch { - want = append(want, &types.DetectionResult{ + want = append(want, &slashertypes.DetectionResult{ ValidatorIndex: uint64(i), - Kind: types.DoubleVote, + Kind: slashertypes.DoubleVote, SlashableEpoch: tt.slashableEpochs[i], SigBytes: [2]byte{1, 2}, }) } else { - want = append(want, &types.DetectionResult{ + want = append(want, &slashertypes.DetectionResult{ ValidatorIndex: uint64(i), - Kind: types.SurroundVote, + Kind: slashertypes.SurroundVote, SlashableEpoch: tt.slashableEpochs[i], SigBytes: [2]byte{1, 2}, }) @@ -784,7 +785,7 @@ func TestNewSpanDetector_UpdateSpans(t *testing.T) { type testStruct struct { name string att *ethpb.IndexedAttestation - want []map[uint64]types.Span + want []map[uint64]slashertypes.Span } tests := []testStruct{ { @@ -802,7 +803,7 @@ func TestNewSpanDetector_UpdateSpans(t *testing.T) { }, Signature: []byte{1, 2}, }, - want: []map[uint64]types.Span{ + want: []map[uint64]slashertypes.Span{ // Epoch 0. { 0: {MinSpan: 4, MaxSpan: 0, SigBytes: [2]byte{0, 0}, HasAttested: false}, @@ -849,7 +850,7 @@ func TestNewSpanDetector_UpdateSpans(t *testing.T) { }, Signature: []byte{1, 2}, }, - want: []map[uint64]types.Span{ + want: []map[uint64]slashertypes.Span{ // Epoch 0. {}, // Epoch 1. @@ -903,7 +904,7 @@ func TestNewSpanDetector_UpdateSpans(t *testing.T) { } require.NoError(t, sd.UpdateSpans(ctx, tt.att)) for epoch := range tt.want { - sm, err := sd.slasherDB.EpochSpans(ctx, uint64(epoch), dbTypes.UseDB) + sm, err := sd.slasherDB.EpochSpans(ctx, types.Epoch(epoch), dbtypes.UseDB) require.NoError(t, err, "Failed to read from slasherDB") resMap, err := sm.ToMap() require.NoError(t, err) @@ -944,5 +945,5 @@ func TestSpanDetector_UpdateMinSpansCheckCacheSize(t *testing.T) { slasherDB: db, } require.NoError(t, sd.updateMinSpan(ctx, att)) - require.Equal(t, epochLookback, db.CacheLength(ctx), "Unexpected cache length") + require.Equal(t, int(epochLookback), db.CacheLength(ctx), "Unexpected cache length") } diff --git a/slasher/detection/attestations/types/BUILD.bazel b/slasher/detection/attestations/types/BUILD.bazel index 48e9231786..f54667b7f2 100644 --- a/slasher/detection/attestations/types/BUILD.bazel +++ b/slasher/detection/attestations/types/BUILD.bazel @@ -12,6 +12,7 @@ go_library( deps = [ "//shared/bytesutil:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", ], ) diff --git a/slasher/detection/attestations/types/types.go b/slasher/detection/attestations/types/types.go index 3b4411595a..e470064097 100644 --- a/slasher/detection/attestations/types/types.go +++ b/slasher/detection/attestations/types/types.go @@ -5,6 +5,7 @@ package types import ( "errors" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bytesutil" ) @@ -31,14 +32,14 @@ const ( // finding the attestation for the slashing proof. type DetectionResult struct { ValidatorIndex uint64 - SlashableEpoch uint64 + SlashableEpoch types.Epoch Kind DetectionKind SigBytes [2]byte } // Marshal the result into bytes, used for removing duplicates. func (r *DetectionResult) Marshal() []byte { - numBytes := bytesutil.ToBytes(r.SlashableEpoch, 8) + numBytes := bytesutil.ToBytes(uint64(r.SlashableEpoch), 8) var resultBytes []byte resultBytes = append(resultBytes, uint8(r.Kind)) resultBytes = append(resultBytes, r.SigBytes[:]...) diff --git a/slasher/detection/detect.go b/slasher/detection/detect.go index fd3f2f5abb..84ae9e7586 100644 --- a/slasher/detection/detect.go +++ b/slasher/detection/detect.go @@ -197,7 +197,7 @@ func (s *Service) mapResultsToAtts(ctx context.Context, results []*types.Detecti } func resultHash(result *types.DetectionResult) [32]byte { - resultBytes := append(bytesutil.Bytes8(result.SlashableEpoch), result.SigBytes[:]...) + resultBytes := append(bytesutil.Bytes8(uint64(result.SlashableEpoch)), result.SigBytes[:]...) return hashutil.Hash(resultBytes) } diff --git a/slasher/detection/service.go b/slasher/detection/service.go index fed5ded2f0..32476fe0fa 100644 --- a/slasher/detection/service.go +++ b/slasher/detection/service.go @@ -4,6 +4,7 @@ import ( "context" "errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/event" "github.com/prysmaticlabs/prysm/slasher/beaconclient" @@ -152,7 +153,7 @@ func (s *Service) detectHistoricalChainData(ctx context.Context) { log.WithError(err).Error("Cannot retrieve chain head from beacon node") return } - var latestStoredEpoch uint64 + var latestStoredEpoch types.Epoch if latestStoredHead != nil { latestStoredEpoch = latestStoredHead.HeadEpoch } @@ -162,7 +163,7 @@ func (s *Service) detectHistoricalChainData(ctx context.Context) { // slasher DB up to the current beacon node's head epoch we retrieved via gRPC. // If no data was persisted from previous sessions, we request data starting from // the genesis epoch. - var storedEpoch uint64 + var storedEpoch types.Epoch for epoch := latestStoredEpoch; epoch < currentChainHead.HeadEpoch; epoch++ { if ctx.Err() != nil { log.WithError(err).Errorf("Could not fetch attestations for epoch: %d", epoch) diff --git a/tools/forkchecker/BUILD.bazel b/tools/forkchecker/BUILD.bazel index 31001f9e73..9d04517724 100644 --- a/tools/forkchecker/BUILD.bazel +++ b/tools/forkchecker/BUILD.bazel @@ -9,6 +9,7 @@ go_library( deps = [ "//shared/params:go_default_library", "@com_github_gogo_protobuf//types:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@org_golang_google_grpc//:go_default_library", diff --git a/tools/forkchecker/forkchecker.go b/tools/forkchecker/forkchecker.go index 62db877676..db42f4cefb 100644 --- a/tools/forkchecker/forkchecker.go +++ b/tools/forkchecker/forkchecker.go @@ -17,6 +17,7 @@ import ( "time" ptypes "github.com/gogo/protobuf/types" + "github.com/prysmaticlabs/eth2-types" pb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/params" "github.com/sirupsen/logrus" @@ -106,7 +107,7 @@ func compareHeads(clients map[string]pb.BeaconChainClient) { if (head1.HeadSlot+1)%params.BeaconConfig().SlotsPerEpoch == 0 { p, err := clients[endpt2].GetValidatorParticipation(context.Background(), &pb.GetValidatorParticipationRequest{ QueryFilter: &pb.GetValidatorParticipationRequest_Epoch{ - Epoch: head2.HeadSlot / params.BeaconConfig().SlotsPerEpoch, + Epoch: types.Epoch(head2.HeadSlot / params.BeaconConfig().SlotsPerEpoch), }, }) if err != nil { diff --git a/validator/client/BUILD.bazel b/validator/client/BUILD.bazel index 706f0dd1c9..cdb947138a 100644 --- a/validator/client/BUILD.bazel +++ b/validator/client/BUILD.bazel @@ -57,6 +57,7 @@ go_library( "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prometheus_client_golang//prometheus/promauto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", @@ -118,6 +119,7 @@ go_test( "@com_github_golang_mock//gomock:go_default_library", "@com_github_hashicorp_golang_lru//:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_go_bitfield//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", diff --git a/validator/client/attest_protect_test.go b/validator/client/attest_protect_test.go index 989315a836..654f8bb92b 100644 --- a/validator/client/attest_protect_test.go +++ b/validator/client/attest_protect_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/golang/mock/gomock" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/featureconfig" @@ -92,11 +93,11 @@ func Test_slashableAttestationCheck_UpdatesLowestSignedEpochs(t *testing.T) { e, exists, err := validator.db.LowestSignedSourceEpoch(context.Background(), pubKey) require.NoError(t, err) require.Equal(t, true, exists) - require.Equal(t, uint64(4), e) + require.Equal(t, types.Epoch(4), e) e, exists, err = validator.db.LowestSignedTargetEpoch(context.Background(), pubKey) require.NoError(t, err) require.Equal(t, true, exists) - require.Equal(t, uint64(10), e) + require.Equal(t, types.Epoch(10), e) } func Test_slashableAttestationCheck_OK(t *testing.T) { @@ -161,9 +162,9 @@ func Test_slashableAttestationCheck_GenesisEpoch(t *testing.T) { e, exists, err := validator.db.LowestSignedSourceEpoch(context.Background(), fakePubkey) require.NoError(t, err) require.Equal(t, true, exists) - require.Equal(t, uint64(0), e) + require.Equal(t, types.Epoch(0), e) e, exists, err = validator.db.LowestSignedTargetEpoch(context.Background(), fakePubkey) require.NoError(t, err) require.Equal(t, true, exists) - require.Equal(t, uint64(0), e) + require.Equal(t, types.Epoch(0), e) } diff --git a/validator/client/metrics.go b/validator/client/metrics.go index 9ab20d7a03..95134b6c69 100644 --- a/validator/client/metrics.go +++ b/validator/client/metrics.go @@ -6,6 +6,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/shared/bytesutil" @@ -209,10 +210,10 @@ func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot uint64) } } - prevEpoch := uint64(0) + prevEpoch := types.Epoch(0) if slot >= params.BeaconConfig().SlotsPerEpoch { - prevEpoch = (slot / params.BeaconConfig().SlotsPerEpoch) - 1 - if v.voteStats.startEpoch == ^uint64(0) { // Handles unknown first epoch. + prevEpoch = types.Epoch(slot/params.BeaconConfig().SlotsPerEpoch) - 1 + if uint64(v.voteStats.startEpoch) == ^uint64(0) { // Handles unknown first epoch. v.voteStats.startEpoch = prevEpoch } } @@ -281,7 +282,7 @@ func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot uint64) // UpdateLogAggregateStats updates and logs the voteStats struct of a validator using the RPC response obtained from LogValidatorGainsAndLosses. func (v *validator) UpdateLogAggregateStats(resp *ethpb.ValidatorPerformanceResponse, slot uint64) { summary := &v.voteStats - currentEpoch := slot / params.BeaconConfig().SlotsPerEpoch + currentEpoch := types.Epoch(slot / params.BeaconConfig().SlotsPerEpoch) var included uint64 var correctSource, correctTarget, correctHead int diff --git a/validator/client/propose.go b/validator/client/propose.go index 5cc70979ba..9fc27a2732 100644 --- a/validator/client/propose.go +++ b/validator/client/propose.go @@ -6,8 +6,9 @@ import ( "fmt" "time" - "github.com/gogo/protobuf/types" + pbtypes "github.com/gogo/protobuf/types" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" p2ptypes "github.com/prysmaticlabs/prysm/beacon-chain/p2p/types" @@ -49,7 +50,7 @@ func (v *validator) ProposeBlock(ctx context.Context, slot uint64, pubKey [48]by log := log.WithField("pubKey", fmt.Sprintf("%#x", bytesutil.Trunc(pubKey[:]))) // Sign randao reveal, it's used to request block from beacon node - epoch := slot / params.BeaconConfig().SlotsPerEpoch + epoch := types.Epoch(slot / params.BeaconConfig().SlotsPerEpoch) randaoReveal, err := v.signRandaoReveal(ctx, pubKey, epoch) if err != nil { log.WithError(err).Error("Failed to sign randao reveal") @@ -164,12 +165,12 @@ func ProposeExit( if err != nil { return errors.Wrap(err, "gRPC call to get validator index failed") } - genesisResponse, err := nodeClient.GetGenesis(ctx, &types.Empty{}) + genesisResponse, err := nodeClient.GetGenesis(ctx, &pbtypes.Empty{}) if err != nil { return errors.Wrap(err, "gRPC call to get genesis time failed") } totalSecondsPassed := timeutils.Now().Unix() - genesisResponse.GenesisTime.Seconds - currentEpoch := uint64(totalSecondsPassed) / (params.BeaconConfig().SecondsPerSlot * params.BeaconConfig().SlotsPerEpoch) + currentEpoch := types.Epoch(uint64(totalSecondsPassed) / (params.BeaconConfig().SecondsPerSlot * params.BeaconConfig().SlotsPerEpoch)) exit := ðpb.VoluntaryExit{Epoch: currentEpoch, ValidatorIndex: indexResponse.Index} sig, err := signVoluntaryExit(ctx, validatorClient, signer, pubKey, exit) @@ -191,7 +192,7 @@ func ProposeExit( } // Sign randao reveal with randao domain and private key. -func (v *validator) signRandaoReveal(ctx context.Context, pubKey [48]byte, epoch uint64) ([]byte, error) { +func (v *validator) signRandaoReveal(ctx context.Context, pubKey [48]byte, epoch types.Epoch) ([]byte, error) { domain, err := v.domainData(ctx, epoch, params.BeaconConfig().DomainRandao[:]) if err != nil { return nil, errors.Wrap(err, domainDataErr) @@ -219,7 +220,7 @@ func (v *validator) signRandaoReveal(ctx context.Context, pubKey [48]byte, epoch } // Sign block with proposer domain and private key. -func (v *validator) signBlock(ctx context.Context, pubKey [48]byte, epoch uint64, b *ethpb.BeaconBlock) ([]byte, *ethpb.DomainResponse, error) { +func (v *validator) signBlock(ctx context.Context, pubKey [48]byte, epoch types.Epoch, b *ethpb.BeaconBlock) ([]byte, *ethpb.DomainResponse, error) { domain, err := v.domainData(ctx, epoch, params.BeaconConfig().DomainBeaconProposer[:]) if err != nil { return nil, nil, errors.Wrap(err, domainDataErr) diff --git a/validator/client/propose_test.go b/validator/client/propose_test.go index 5618a28a44..5590440833 100644 --- a/validator/client/propose_test.go +++ b/validator/client/propose_test.go @@ -249,7 +249,7 @@ func TestProposeBlock_BlocksDoubleProposal_After54KEpochs(t *testing.T) { ).Times(1).Return(ðpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/) testBlock := testutil.NewBeaconBlock() - farFuture := (params.BeaconConfig().WeakSubjectivityPeriod + 9) * params.BeaconConfig().SlotsPerEpoch + farFuture := uint64(params.BeaconConfig().WeakSubjectivityPeriod+9) * params.BeaconConfig().SlotsPerEpoch testBlock.Block.Slot = farFuture m.validatorClient.EXPECT().GetBlock( gomock.Any(), // ctx @@ -299,7 +299,7 @@ func TestProposeBlock_AllowsPastProposals(t *testing.T) { gomock.Any(), // epoch ).Times(2).Return(ðpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/) - farAhead := (params.BeaconConfig().WeakSubjectivityPeriod + 9) * params.BeaconConfig().SlotsPerEpoch + farAhead := uint64(params.BeaconConfig().WeakSubjectivityPeriod+9) * params.BeaconConfig().SlotsPerEpoch blk := testutil.NewBeaconBlock() blk.Block.Slot = farAhead m.validatorClient.EXPECT().GetBlock( @@ -320,7 +320,7 @@ func TestProposeBlock_AllowsPastProposals(t *testing.T) { validator.ProposeBlock(context.Background(), farAhead, pubKey) require.LogsDoNotContain(t, hook, failedPreBlockSignLocalErr) - past := (params.BeaconConfig().WeakSubjectivityPeriod - 400) * params.BeaconConfig().SlotsPerEpoch + past := uint64(params.BeaconConfig().WeakSubjectivityPeriod-400) * params.BeaconConfig().SlotsPerEpoch blk2 := testutil.NewBeaconBlock() blk2.Block.Slot = past m.validatorClient.EXPECT().GetBlock( @@ -347,7 +347,7 @@ func TestProposeBlock_AllowsSameEpoch(t *testing.T) { gomock.Any(), // epoch ).Times(2).Return(ðpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/) - farAhead := (params.BeaconConfig().WeakSubjectivityPeriod + 9) * params.BeaconConfig().SlotsPerEpoch + farAhead := uint64(params.BeaconConfig().WeakSubjectivityPeriod+9) * params.BeaconConfig().SlotsPerEpoch blk := testutil.NewBeaconBlock() blk.Block.Slot = farAhead m.validatorClient.EXPECT().GetBlock( diff --git a/validator/client/service.go b/validator/client/service.go index 5c02892c24..f4d2a63d0e 100644 --- a/validator/client/service.go +++ b/validator/client/service.go @@ -14,6 +14,7 @@ import ( grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus" lru "github.com/hashicorp/golang-lru" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/event" @@ -189,7 +190,7 @@ func (v *ValidatorService) Start() { domainDataCache: cache, aggregatedSlotCommitteeIDCache: aggregatedSlotCommitteeIDCache, protector: v.protector, - voteStats: voteStats{startEpoch: ^uint64(0)}, + voteStats: voteStats{startEpoch: types.Epoch(^uint64(0))}, useWeb: v.useWeb, walletInitializedFeed: v.walletInitializedFeed, blockFeed: new(event.Feed), diff --git a/validator/client/slashing_protection_interchange_test.go b/validator/client/slashing_protection_interchange_test.go index aab67f9d4a..5709a8966b 100644 --- a/validator/client/slashing_protection_interchange_test.go +++ b/validator/client/slashing_protection_interchange_test.go @@ -149,9 +149,9 @@ func TestEIP3076SpecTests(t *testing.T) { // This loops through a list of attestation signings to attempt after importing the interchange data above. for _, sa := range step.Attestations { - target, err := interchangeformat.Uint64FromString(sa.TargetEpoch) + target, err := interchangeformat.EpochFromString(sa.TargetEpoch) require.NoError(t, err) - source, err := interchangeformat.Uint64FromString(sa.SourceEpoch) + source, err := interchangeformat.EpochFromString(sa.SourceEpoch) require.NoError(t, err) pk, err := interchangeformat.PubKeyFromHex(sa.Pubkey) require.NoError(t, err) diff --git a/validator/client/validator.go b/validator/client/validator.go index 3d6c819fda..2b97ee01fa 100644 --- a/validator/client/validator.go +++ b/validator/client/validator.go @@ -19,6 +19,7 @@ import ( ptypes "github.com/gogo/protobuf/types" lru "github.com/hashicorp/golang-lru" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/shared/bytesutil" @@ -390,7 +391,7 @@ func (v *validator) UpdateDuties(ctx context.Context, slot uint64) error { v.slashableKeysLock.RUnlock() req := ðpb.DutiesRequest{ - Epoch: slot / params.BeaconConfig().SlotsPerEpoch, + Epoch: types.Epoch(slot / params.BeaconConfig().SlotsPerEpoch), PublicKeys: bytesutil.FromBytes48Array(filteredKeys), } @@ -590,7 +591,7 @@ func (v *validator) AllValidatorsAreExited(ctx context.Context) (bool, error) { return true, nil } -func (v *validator) domainData(ctx context.Context, epoch uint64, domain []byte) (*ethpb.DomainResponse, error) { +func (v *validator) domainData(ctx context.Context, epoch types.Epoch, domain []byte) (*ethpb.DomainResponse, error) { v.domainDataLock.Lock() defer v.domainDataLock.Unlock() @@ -599,7 +600,7 @@ func (v *validator) domainData(ctx context.Context, epoch uint64, domain []byte) Domain: domain, } - key := strings.Join([]string{strconv.FormatUint(req.Epoch, 10), hex.EncodeToString(req.Domain)}, ",") + key := strings.Join([]string{strconv.FormatUint(uint64(req.Epoch), 10), hex.EncodeToString(req.Domain)}, ",") if val, ok := v.domainDataCache.Get(key); ok { return proto.Clone(val.(proto.Message)).(*ethpb.DomainResponse), nil @@ -677,7 +678,7 @@ func validatorSubscribeKey(slot, committeeID uint64) [64]byte { // This tracks all validators' voting status. type voteStats struct { - startEpoch uint64 + startEpoch types.Epoch includedAttestedCount uint64 totalAttestedCount uint64 totalDistance uint64 diff --git a/validator/db/iface/BUILD.bazel b/validator/db/iface/BUILD.bazel index daed7f3ca1..39335e251f 100644 --- a/validator/db/iface/BUILD.bazel +++ b/validator/db/iface/BUILD.bazel @@ -9,6 +9,7 @@ go_library( deps = [ "//shared/backuputil:go_default_library", "//validator/db/kv:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", ], ) diff --git a/validator/db/iface/interface.go b/validator/db/iface/interface.go index bf25c999a3..0fce699cc2 100644 --- a/validator/db/iface/interface.go +++ b/validator/db/iface/interface.go @@ -5,6 +5,7 @@ import ( "context" "io" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/backuputil" "github.com/prysmaticlabs/prysm/validator/db/kv" @@ -40,9 +41,9 @@ type ValidatorDB interface { // slashing protection imports. EIPImportBlacklistedPublicKeys(ctx context.Context) ([][48]byte, error) SaveEIPImportBlacklistedPublicKeys(ctx context.Context, publicKeys [][48]byte) error - SigningRootAtTargetEpoch(ctx context.Context, publicKey [48]byte, target uint64) ([32]byte, error) - LowestSignedTargetEpoch(ctx context.Context, publicKey [48]byte) (uint64, bool, error) - LowestSignedSourceEpoch(ctx context.Context, publicKey [48]byte) (uint64, bool, error) + SigningRootAtTargetEpoch(ctx context.Context, publicKey [48]byte, target types.Epoch) ([32]byte, error) + LowestSignedTargetEpoch(ctx context.Context, publicKey [48]byte) (types.Epoch, bool, error) + LowestSignedSourceEpoch(ctx context.Context, publicKey [48]byte) (types.Epoch, bool, error) AttestedPublicKeys(ctx context.Context) ([][48]byte, error) CheckSlashableAttestation( ctx context.Context, pubKey [48]byte, signingRoot [32]byte, att *ethpb.IndexedAttestation, diff --git a/validator/db/kv/BUILD.bazel b/validator/db/kv/BUILD.bazel index fb60a573f6..420b75177d 100644 --- a/validator/db/kv/BUILD.bazel +++ b/validator/db/kv/BUILD.bazel @@ -29,6 +29,7 @@ go_library( "//shared/slashutil:go_default_library", "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_prombbolt//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", @@ -56,6 +57,7 @@ go_test( "//shared/params:go_default_library", "//shared/testutil/assert:go_default_library", "//shared/testutil/require:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@com_github_sirupsen_logrus//hooks/test:go_default_library", diff --git a/validator/db/kv/attester_protection.go b/validator/db/kv/attester_protection.go index dcd8a92314..0b84ccffe2 100644 --- a/validator/db/kv/attester_protection.go +++ b/validator/db/kv/attester_protection.go @@ -6,6 +6,7 @@ import ( "time" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/slashutil" @@ -20,8 +21,8 @@ type SlashingKind int // for manipulation by database methods. type AttestationRecord struct { PubKey [48]byte - Source uint64 - Target uint64 + Source types.Epoch + Target types.Epoch SigningRoot [32]byte } @@ -64,18 +65,18 @@ func (s *Store) AttestationHistoryForPubKey(ctx context.Context, pubKey [48]byte sourceEpochsBucket := pkBucket.Bucket(attestationSourceEpochsBucket) return sourceEpochsBucket.ForEach(func(sourceBytes, targetEpochsList []byte) error { - targetEpochs := make([]uint64, 0) + targetEpochs := make([]types.Epoch, 0) for i := 0; i < len(targetEpochsList); i += 8 { - epoch := bytesutil.BytesToUint64BigEndian(targetEpochsList[i : i+8]) + epoch := bytesutil.BytesToEpochBigEndian(targetEpochsList[i : i+8]) targetEpochs = append(targetEpochs, epoch) } - sourceEpoch := bytesutil.BytesToUint64BigEndian(sourceBytes) + sourceEpoch := bytesutil.BytesToEpochBigEndian(sourceBytes) for _, targetEpoch := range targetEpochs { record := &AttestationRecord{ Source: sourceEpoch, Target: targetEpoch, } - signingRoot := signingRootsBucket.Get(bytesutil.Uint64ToBytesBigEndian(targetEpoch)) + signingRoot := signingRootsBucket.Get(bytesutil.EpochToBytesBigEndian(targetEpoch)) if signingRoot != nil { copy(record.SigningRoot[:], signingRoot) } @@ -105,7 +106,7 @@ func (s *Store) CheckSlashableAttestation( // First we check for double votes. signingRootsBucket := pkBucket.Bucket(attestationSigningRootsBucket) if signingRootsBucket != nil { - targetEpochBytes := bytesutil.Uint64ToBytesBigEndian(att.Data.Target.Epoch) + targetEpochBytes := bytesutil.EpochToBytesBigEndian(att.Data.Target.Epoch) existingSigningRoot := signingRootsBucket.Get(targetEpochBytes) if existingSigningRoot != nil { var existing [32]byte @@ -123,12 +124,12 @@ func (s *Store) CheckSlashableAttestation( } // Check for surround votes. return sourceEpochsBucket.ForEach(func(sourceEpochBytes []byte, targetEpochsBytes []byte) error { - existingSourceEpoch := bytesutil.BytesToUint64BigEndian(sourceEpochBytes) + existingSourceEpoch := bytesutil.BytesToEpochBigEndian(sourceEpochBytes) // There can be multiple target epochs attested per source epoch. - attestedTargetEpochs := make([]uint64, 0) + attestedTargetEpochs := make([]types.Epoch, 0) for i := 0; i < len(targetEpochsBytes); i += 8 { - targetEpoch := bytesutil.BytesToUint64BigEndian(targetEpochsBytes[i : i+8]) + targetEpoch := bytesutil.BytesToEpochBigEndian(targetEpochsBytes[i : i+8]) attestedTargetEpochs = append(attestedTargetEpochs, targetEpoch) } @@ -285,8 +286,8 @@ func (s *Store) saveAttestationRecords(ctx context.Context, atts []*AttestationR if err != nil { return errors.Wrap(err, "could not create public key bucket") } - sourceEpochBytes := bytesutil.Uint64ToBytesBigEndian(att.Source) - targetEpochBytes := bytesutil.Uint64ToBytesBigEndian(att.Target) + sourceEpochBytes := bytesutil.EpochToBytesBigEndian(att.Source) + targetEpochBytes := bytesutil.EpochToBytesBigEndian(att.Target) signingRootsBucket, err := pkBucket.CreateBucketIfNotExists(attestationSigningRootsBucket) if err != nil { @@ -325,13 +326,13 @@ func (s *Store) saveAttestationRecords(ctx context.Context, atts []*AttestationR // If the incoming source epoch is lower than the lowest signed source epoch, override. lowestSignedSourceBytes := lowestSourceBucket.Get(att.PubKey[:]) - var lowestSignedSourceEpoch uint64 + var lowestSignedSourceEpoch types.Epoch if len(lowestSignedSourceBytes) >= 8 { - lowestSignedSourceEpoch = bytesutil.BytesToUint64BigEndian(lowestSignedSourceBytes) + lowestSignedSourceEpoch = bytesutil.BytesToEpochBigEndian(lowestSignedSourceBytes) } if len(lowestSignedSourceBytes) == 0 || att.Source < lowestSignedSourceEpoch { if err := lowestSourceBucket.Put( - att.PubKey[:], bytesutil.Uint64ToBytesBigEndian(att.Source), + att.PubKey[:], bytesutil.EpochToBytesBigEndian(att.Source), ); err != nil { return err } @@ -339,13 +340,13 @@ func (s *Store) saveAttestationRecords(ctx context.Context, atts []*AttestationR // If the incoming target epoch is lower than the lowest signed target epoch, override. lowestSignedTargetBytes := lowestTargetBucket.Get(att.PubKey[:]) - var lowestSignedTargetEpoch uint64 + var lowestSignedTargetEpoch types.Epoch if len(lowestSignedTargetBytes) >= 8 { - lowestSignedTargetEpoch = bytesutil.BytesToUint64BigEndian(lowestSignedTargetBytes) + lowestSignedTargetEpoch = bytesutil.BytesToEpochBigEndian(lowestSignedTargetBytes) } if len(lowestSignedTargetBytes) == 0 || att.Target < lowestSignedTargetEpoch { if err := lowestTargetBucket.Put( - att.PubKey[:], bytesutil.Uint64ToBytesBigEndian(att.Target), + att.PubKey[:], bytesutil.EpochToBytesBigEndian(att.Target), ); err != nil { return err } @@ -375,7 +376,7 @@ func (s *Store) AttestedPublicKeys(ctx context.Context) ([][48]byte, error) { // SigningRootAtTargetEpoch checks for an existing signing root at a specified // target epoch for a given validator public key. -func (s *Store) SigningRootAtTargetEpoch(ctx context.Context, pubKey [48]byte, target uint64) ([32]byte, error) { +func (s *Store) SigningRootAtTargetEpoch(ctx context.Context, pubKey [48]byte, target types.Epoch) ([32]byte, error) { ctx, span := trace.StartSpan(ctx, "Validator.SigningRootAtTargetEpoch") defer span.End() var signingRoot [32]byte @@ -389,7 +390,7 @@ func (s *Store) SigningRootAtTargetEpoch(ctx context.Context, pubKey [48]byte, t if signingRootsBucket == nil { return nil } - sr := signingRootsBucket.Get(bytesutil.Uint64ToBytesBigEndian(target)) + sr := signingRootsBucket.Get(bytesutil.EpochToBytesBigEndian(target)) copy(signingRoot[:], sr) return nil }) @@ -398,22 +399,22 @@ func (s *Store) SigningRootAtTargetEpoch(ctx context.Context, pubKey [48]byte, t // LowestSignedSourceEpoch returns the lowest signed source epoch for a validator public key. // If no data exists, returning 0 is a sensible default. -func (s *Store) LowestSignedSourceEpoch(ctx context.Context, publicKey [48]byte) (uint64, bool, error) { +func (s *Store) LowestSignedSourceEpoch(ctx context.Context, publicKey [48]byte) (types.Epoch, bool, error) { ctx, span := trace.StartSpan(ctx, "Validator.LowestSignedSourceEpoch") defer span.End() var err error - var lowestSignedSourceEpoch uint64 + var lowestSignedSourceEpoch types.Epoch var exists bool err = s.view(func(tx *bolt.Tx) error { bucket := tx.Bucket(lowestSignedSourceBucket) lowestSignedSourceBytes := bucket.Get(publicKey[:]) - // 8 because bytesutil.BytesToUint64BigEndian will return 0 if input is less than 8 bytes. + // 8 because bytesutil.BytesToEpochBigEndian will return 0 if input is less than 8 bytes. if len(lowestSignedSourceBytes) < 8 { return nil } exists = true - lowestSignedSourceEpoch = bytesutil.BytesToUint64BigEndian(lowestSignedSourceBytes) + lowestSignedSourceEpoch = bytesutil.BytesToEpochBigEndian(lowestSignedSourceBytes) return nil }) return lowestSignedSourceEpoch, exists, err @@ -421,22 +422,22 @@ func (s *Store) LowestSignedSourceEpoch(ctx context.Context, publicKey [48]byte) // LowestSignedTargetEpoch returns the lowest signed target epoch for a validator public key. // If no data exists, returning 0 is a sensible default. -func (s *Store) LowestSignedTargetEpoch(ctx context.Context, publicKey [48]byte) (uint64, bool, error) { +func (s *Store) LowestSignedTargetEpoch(ctx context.Context, publicKey [48]byte) (types.Epoch, bool, error) { ctx, span := trace.StartSpan(ctx, "Validator.LowestSignedTargetEpoch") defer span.End() var err error - var lowestSignedTargetEpoch uint64 + var lowestSignedTargetEpoch types.Epoch var exists bool err = s.view(func(tx *bolt.Tx) error { bucket := tx.Bucket(lowestSignedTargetBucket) lowestSignedTargetBytes := bucket.Get(publicKey[:]) - // 8 because bytesutil.BytesToUint64BigEndian will return 0 if input is less than 8 bytes. + // 8 because bytesutil.BytesToEpochBigEndian will return 0 if input is less than 8 bytes. if len(lowestSignedTargetBytes) < 8 { return nil } exists = true - lowestSignedTargetEpoch = bytesutil.BytesToUint64BigEndian(lowestSignedTargetBytes) + lowestSignedTargetEpoch = bytesutil.BytesToEpochBigEndian(lowestSignedTargetBytes) return nil }) return lowestSignedTargetEpoch, exists, err diff --git a/validator/db/kv/attester_protection_test.go b/validator/db/kv/attester_protection_test.go index c708af88f7..ed4cc1e7f0 100644 --- a/validator/db/kv/attester_protection_test.go +++ b/validator/db/kv/attester_protection_test.go @@ -8,6 +8,7 @@ import ( "sync" "testing" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/testutil/assert" @@ -115,7 +116,7 @@ func TestStore_CheckSlashableAttestation_SurroundVote_MultipleTargetsPerSource(t func TestStore_CheckSlashableAttestation_SurroundVote_54kEpochs(t *testing.T) { ctx := context.Background() numValidators := 1 - numEpochs := uint64(54000) + numEpochs := types.Epoch(54000) pubKeys := make([][48]byte, numValidators) validatorDB := setupDB(t, pubKeys) @@ -131,10 +132,10 @@ func TestStore_CheckSlashableAttestation_SurroundVote_54kEpochs(t *testing.T) { if err != nil { return err } - for epoch := uint64(1); epoch < numEpochs; epoch++ { + for epoch := types.Epoch(1); epoch < numEpochs; epoch++ { att := createAttestation(epoch-1, epoch) - sourceEpoch := bytesutil.Uint64ToBytesBigEndian(att.Data.Source.Epoch) - targetEpoch := bytesutil.Uint64ToBytesBigEndian(att.Data.Target.Epoch) + sourceEpoch := bytesutil.EpochToBytesBigEndian(att.Data.Source.Epoch) + targetEpoch := bytesutil.EpochToBytesBigEndian(att.Data.Target.Epoch) if err := sourceEpochsBucket.Put(sourceEpoch, targetEpoch); err != nil { return err } @@ -206,10 +207,10 @@ func TestLowestSignedSourceEpoch_SaveRetrieve(t *testing.T) { ) got, _, err := validatorDB.LowestSignedSourceEpoch(ctx, p0) require.NoError(t, err) - require.Equal(t, uint64(100), got) + require.Equal(t, types.Epoch(100), got) got, _, err = validatorDB.LowestSignedSourceEpoch(ctx, p1) require.NoError(t, err) - require.Equal(t, uint64(200), got) + require.Equal(t, types.Epoch(200), got) // Can replace. require.NoError( @@ -222,10 +223,10 @@ func TestLowestSignedSourceEpoch_SaveRetrieve(t *testing.T) { ) got, _, err = validatorDB.LowestSignedSourceEpoch(ctx, p0) require.NoError(t, err) - require.Equal(t, uint64(99), got) + require.Equal(t, types.Epoch(99), got) got, _, err = validatorDB.LowestSignedSourceEpoch(ctx, p1) require.NoError(t, err) - require.Equal(t, uint64(199), got) + require.Equal(t, types.Epoch(199), got) // Can not replace. require.NoError( @@ -238,10 +239,10 @@ func TestLowestSignedSourceEpoch_SaveRetrieve(t *testing.T) { ) got, _, err = validatorDB.LowestSignedSourceEpoch(ctx, p0) require.NoError(t, err) - require.Equal(t, uint64(99), got) + require.Equal(t, types.Epoch(99), got) got, _, err = validatorDB.LowestSignedSourceEpoch(ctx, p1) require.NoError(t, err) - require.Equal(t, uint64(199), got) + require.Equal(t, types.Epoch(199), got) } func TestLowestSignedTargetEpoch_SaveRetrieveReplace(t *testing.T) { @@ -265,10 +266,10 @@ func TestLowestSignedTargetEpoch_SaveRetrieveReplace(t *testing.T) { ) got, _, err := validatorDB.LowestSignedTargetEpoch(ctx, p0) require.NoError(t, err) - require.Equal(t, uint64(100), got) + require.Equal(t, types.Epoch(100), got) got, _, err = validatorDB.LowestSignedTargetEpoch(ctx, p1) require.NoError(t, err) - require.Equal(t, uint64(200), got) + require.Equal(t, types.Epoch(200), got) // Can replace. require.NoError( @@ -281,10 +282,10 @@ func TestLowestSignedTargetEpoch_SaveRetrieveReplace(t *testing.T) { ) got, _, err = validatorDB.LowestSignedTargetEpoch(ctx, p0) require.NoError(t, err) - require.Equal(t, uint64(99), got) + require.Equal(t, types.Epoch(99), got) got, _, err = validatorDB.LowestSignedTargetEpoch(ctx, p1) require.NoError(t, err) - require.Equal(t, uint64(199), got) + require.Equal(t, types.Epoch(199), got) // Can not replace. require.NoError( @@ -297,10 +298,10 @@ func TestLowestSignedTargetEpoch_SaveRetrieveReplace(t *testing.T) { ) got, _, err = validatorDB.LowestSignedTargetEpoch(ctx, p0) require.NoError(t, err) - require.Equal(t, uint64(99), got) + require.Equal(t, types.Epoch(99), got) got, _, err = validatorDB.LowestSignedTargetEpoch(ctx, p1) require.NoError(t, err) - require.Equal(t, uint64(199), got) + require.Equal(t, types.Epoch(199), got) } func TestStore_SaveAttestationsForPubKey(t *testing.T) { @@ -310,8 +311,8 @@ func TestStore_SaveAttestationsForPubKey(t *testing.T) { validatorDB := setupDB(t, pubKeys) atts := make([]*ethpb.IndexedAttestation, 0) signingRoots := make([][32]byte, 0) - for i := 1; i < 10; i++ { - atts = append(atts, createAttestation(uint64(i-1), uint64(i))) + for i := types.Epoch(1); i < 10; i++ { + atts = append(atts, createAttestation(i-1, i)) var sr [32]byte copy(sr[:], fmt.Sprintf("%d", i)) signingRoots = append(signingRoots, sr) @@ -355,14 +356,14 @@ func TestSaveAttestationForPubKey_BatchWrites_FullCapacity(t *testing.T) { var wg sync.WaitGroup for i, pubKey := range pubKeys { wg.Add(1) - go func(j int, pk [48]byte, w *sync.WaitGroup) { + go func(j types.Epoch, pk [48]byte, w *sync.WaitGroup) { defer w.Done() var signingRoot [32]byte copy(signingRoot[:], fmt.Sprintf("%d", j)) - att := createAttestation(uint64(j), uint64(j)+1) + att := createAttestation(j, j+1) err := validatorDB.SaveAttestationForPubKey(ctx, pk, signingRoot, att) require.NoError(t, err) - }(i, pubKey, &wg) + }(types.Epoch(i), pubKey, &wg) } wg.Wait() @@ -412,14 +413,14 @@ func TestSaveAttestationForPubKey_BatchWrites_LowCapacity_TimerReached(t *testin var wg sync.WaitGroup for i, pubKey := range pubKeys { wg.Add(1) - go func(j int, pk [48]byte, w *sync.WaitGroup) { + go func(j types.Epoch, pk [48]byte, w *sync.WaitGroup) { defer w.Done() var signingRoot [32]byte copy(signingRoot[:], fmt.Sprintf("%d", j)) - att := createAttestation(uint64(j), uint64(j)+1) + att := createAttestation(j, j+1) err := validatorDB.SaveAttestationForPubKey(ctx, pk, signingRoot, att) require.NoError(t, err) - }(i, pubKey, &wg) + }(types.Epoch(i), pubKey, &wg) } wg.Wait() @@ -455,14 +456,14 @@ func TestSaveAttestationForPubKey_BatchWrites_LowCapacity_TimerReached(t *testin func BenchmarkStore_CheckSlashableAttestation_Surround_SafeAttestation_54kEpochs(b *testing.B) { numValidators := 1 - numEpochs := uint64(54000) + numEpochs := types.Epoch(54000) pubKeys := make([][48]byte, numValidators) benchCheckSurroundVote(b, pubKeys, numEpochs, false /* surround */) } func BenchmarkStore_CheckSurroundVote_Surround_Slashable_54kEpochs(b *testing.B) { numValidators := 1 - numEpochs := uint64(54000) + numEpochs := types.Epoch(54000) pubKeys := make([][48]byte, numValidators) benchCheckSurroundVote(b, pubKeys, numEpochs, true /* surround */) } @@ -470,7 +471,7 @@ func BenchmarkStore_CheckSurroundVote_Surround_Slashable_54kEpochs(b *testing.B) func benchCheckSurroundVote( b *testing.B, pubKeys [][48]byte, - numEpochs uint64, + numEpochs types.Epoch, shouldSurround bool, ) { ctx := context.Background() @@ -493,10 +494,10 @@ func benchCheckSurroundVote( if err != nil { return err } - for epoch := uint64(1); epoch < numEpochs; epoch++ { + for epoch := types.Epoch(1); epoch < numEpochs; epoch++ { att := createAttestation(epoch-1, epoch) - sourceEpoch := bytesutil.Uint64ToBytesBigEndian(att.Data.Source.Epoch) - targetEpoch := bytesutil.Uint64ToBytesBigEndian(att.Data.Target.Epoch) + sourceEpoch := bytesutil.EpochToBytesBigEndian(att.Data.Source.Epoch) + targetEpoch := bytesutil.EpochToBytesBigEndian(att.Data.Target.Epoch) if err := sourceEpochsBucket.Put(sourceEpoch, targetEpoch); err != nil { return err } @@ -527,7 +528,7 @@ func benchCheckSurroundVote( } } -func createAttestation(source, target uint64) *ethpb.IndexedAttestation { +func createAttestation(source, target types.Epoch) *ethpb.IndexedAttestation { return ðpb.IndexedAttestation{ Data: ðpb.AttestationData{ Source: ðpb.Checkpoint{ diff --git a/validator/db/kv/deprecated_attester_protection.go b/validator/db/kv/deprecated_attester_protection.go index 598f6b1f46..769e9e6ff7 100644 --- a/validator/db/kv/deprecated_attester_protection.go +++ b/validator/db/kv/deprecated_attester_protection.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/params" ) @@ -22,7 +23,7 @@ const ( // deprecatedHistoryData stores the needed data to confirm if an attestation is slashable // or repeated. type deprecatedHistoryData struct { - Source uint64 + Source types.Epoch SigningRoot []byte } @@ -56,15 +57,15 @@ func emptyHistoryData() *deprecatedHistoryData { // newDeprecatedAttestingHistory creates a new encapsulated attestation history byte array // sized by the latest epoch written. -func newDeprecatedAttestingHistory(target uint64) deprecatedEncodedAttestingHistory { - relativeTarget := target % params.BeaconConfig().WeakSubjectivityPeriod +func newDeprecatedAttestingHistory(target types.Epoch) deprecatedEncodedAttestingHistory { + relativeTarget := types.Epoch(target % params.BeaconConfig().WeakSubjectivityPeriod) historyDataSize := (relativeTarget + 1) * historySize arraySize := latestEpochWrittenSize + historyDataSize en := make(deprecatedEncodedAttestingHistory, arraySize) enc := en ctx := context.Background() var err error - for i := uint64(0); i <= target%params.BeaconConfig().WeakSubjectivityPeriod; i++ { + for i := types.Epoch(0); i <= target%params.BeaconConfig().WeakSubjectivityPeriod; i++ { enc, err = enc.setTargetData(ctx, i, emptyHistoryData()) if err != nil { log.WithError(err).Error("Failed to set empty target data") @@ -73,40 +74,40 @@ func newDeprecatedAttestingHistory(target uint64) deprecatedEncodedAttestingHist return enc } -func (dh deprecatedEncodedAttestingHistory) getLatestEpochWritten(ctx context.Context) (uint64, error) { +func (dh deprecatedEncodedAttestingHistory) getLatestEpochWritten(ctx context.Context) (types.Epoch, error) { if err := dh.assertSize(); err != nil { return 0, err } - return bytesutil.FromBytes8(dh[:latestEpochWrittenSize]), nil + return types.Epoch(bytesutil.FromBytes8(dh[:latestEpochWrittenSize])), nil } -func (dh deprecatedEncodedAttestingHistory) setLatestEpochWritten(ctx context.Context, latestEpochWritten uint64) (deprecatedEncodedAttestingHistory, error) { +func (dh deprecatedEncodedAttestingHistory) setLatestEpochWritten(ctx context.Context, latestEpochWritten types.Epoch) (deprecatedEncodedAttestingHistory, error) { if err := dh.assertSize(); err != nil { return nil, err } - copy(dh[:latestEpochWrittenSize], bytesutil.Uint64ToBytesLittleEndian(latestEpochWritten)) + copy(dh[:latestEpochWrittenSize], bytesutil.EpochToBytesLittleEndian(latestEpochWritten)) return dh, nil } -func (dh deprecatedEncodedAttestingHistory) getTargetData(ctx context.Context, target uint64) (*deprecatedHistoryData, error) { +func (dh deprecatedEncodedAttestingHistory) getTargetData(ctx context.Context, target types.Epoch) (*deprecatedHistoryData, error) { if err := dh.assertSize(); err != nil { return nil, err } // Cursor for the location to read target epoch from. // Modulus of target epoch X weak subjectivity period in order to have maximum size to the encapsulated data array. cursor := (target%params.BeaconConfig().WeakSubjectivityPeriod)*historySize + latestEpochWrittenSize - if uint64(len(dh)) < cursor+historySize { + if uint64(len(dh)) < uint64(cursor+historySize) { return nil, nil } history := &deprecatedHistoryData{} - history.Source = bytesutil.FromBytes8(dh[cursor : cursor+sourceSize]) + history.Source = types.Epoch(bytesutil.FromBytes8(dh[cursor : cursor+sourceSize])) sr := make([]byte, 32) copy(sr, dh[cursor+sourceSize:cursor+historySize]) history.SigningRoot = sr return history, nil } -func (dh deprecatedEncodedAttestingHistory) setTargetData(ctx context.Context, target uint64, historyData *deprecatedHistoryData) (deprecatedEncodedAttestingHistory, error) { +func (dh deprecatedEncodedAttestingHistory) setTargetData(ctx context.Context, target types.Epoch, historyData *deprecatedHistoryData) (deprecatedEncodedAttestingHistory, error) { if err := dh.assertSize(); err != nil { return nil, err } @@ -114,11 +115,11 @@ func (dh deprecatedEncodedAttestingHistory) setTargetData(ctx context.Context, t // Modulus of target epoch X weak subjectivity period in order to have maximum size to the encapsulated data array. cursor := latestEpochWrittenSize + (target%params.BeaconConfig().WeakSubjectivityPeriod)*historySize - if uint64(len(dh)) < cursor+historySize { - ext := make([]byte, cursor+historySize-uint64(len(dh))) + if uint64(len(dh)) < uint64(cursor+historySize) { + ext := make([]byte, uint64(cursor+historySize)-uint64(len(dh))) dh = append(dh, ext...) } - copy(dh[cursor:cursor+sourceSize], bytesutil.Uint64ToBytesLittleEndian(historyData.Source)) + copy(dh[cursor:cursor+sourceSize], bytesutil.EpochToBytesLittleEndian(historyData.Source)) copy(dh[cursor+sourceSize:cursor+sourceSize+signingRootSize], historyData.SigningRoot) return dh, nil diff --git a/validator/db/kv/deprecated_attester_protection_test.go b/validator/db/kv/deprecated_attester_protection_test.go index df7740186e..a77d8f5e90 100644 --- a/validator/db/kv/deprecated_attester_protection_test.go +++ b/validator/db/kv/deprecated_attester_protection_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/testutil/assert" @@ -14,7 +15,7 @@ func TestNewAttestationHistoryArray(t *testing.T) { ba := newDeprecatedAttestingHistory(0) assert.Equal(t, latestEpochWrittenSize+historySize, len(ba)) ba = newDeprecatedAttestingHistory(params.BeaconConfig().WeakSubjectivityPeriod - 1) - assert.Equal(t, latestEpochWrittenSize+historySize*params.BeaconConfig().WeakSubjectivityPeriod, uint64(len(ba))) + assert.Equal(t, latestEpochWrittenSize+historySize*params.BeaconConfig().WeakSubjectivityPeriod, types.Epoch(len(ba))) ba = newDeprecatedAttestingHistory(params.BeaconConfig().WeakSubjectivityPeriod) assert.Equal(t, latestEpochWrittenSize+historySize, len(ba)) ba = newDeprecatedAttestingHistory(params.BeaconConfig().WeakSubjectivityPeriod + 1) @@ -38,7 +39,7 @@ func TestGetLatestEpochWritten(t *testing.T) { ha[0] = 28 lew, err := ha.getLatestEpochWritten(ctx) require.NoError(t, err) - assert.Equal(t, uint64(28), lew) + assert.Equal(t, types.Epoch(28), lew) } func TestSetLatestEpochWritten(t *testing.T) { @@ -67,8 +68,8 @@ func TestSetTargetData(t *testing.T) { type testStruct struct { name string enc deprecatedEncodedAttestingHistory - target uint64 - source uint64 + target types.Epoch + source types.Epoch signingRoot []byte expected deprecatedEncodedAttestingHistory error string diff --git a/validator/db/kv/migration_optimal_attester_protection.go b/validator/db/kv/migration_optimal_attester_protection.go index 3fb6e9963c..1609299a96 100644 --- a/validator/db/kv/migration_optimal_attester_protection.go +++ b/validator/db/kv/migration_optimal_attester_protection.go @@ -4,6 +4,7 @@ import ( "bytes" "context" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/progressutil" @@ -80,7 +81,7 @@ func (s *Store) migrateOptimalAttesterProtectionUp(ctx context.Context) error { } // For every epoch since genesis up to the highest epoch written, we then // extract historical data and insert it into the new schema. - for targetEpoch := uint64(0); targetEpoch <= latestEpochWritten; targetEpoch++ { + for targetEpoch := types.Epoch(0); targetEpoch <= latestEpochWritten; targetEpoch++ { historicalAtt, err := attestingHistory.getTargetData(ctx, targetEpoch) if err != nil { return err @@ -88,8 +89,8 @@ func (s *Store) migrateOptimalAttesterProtectionUp(ctx context.Context) error { if historicalAtt.isEmpty() { continue } - targetEpochBytes := bytesutil.Uint64ToBytesBigEndian(targetEpoch) - sourceEpochBytes := bytesutil.Uint64ToBytesBigEndian(historicalAtt.Source) + targetEpochBytes := bytesutil.EpochToBytesBigEndian(targetEpoch) + sourceEpochBytes := bytesutil.EpochToBytesBigEndian(historicalAtt.Source) if err := sourceEpochsBucket.Put(sourceEpochBytes, targetEpochBytes); err != nil { return err } @@ -143,8 +144,8 @@ func (s *Store) migrateOptimalAttesterProtectionDown(ctx context.Context) error // Next up, we extract the data for attested epochs and signing roots // from the optimized db schema into maps we can use later. - signingRootsByTarget := make(map[uint64][]byte) - targetEpochsBySource := make(map[uint64][]uint64) + signingRootsByTarget := make(map[types.Epoch][]byte) + targetEpochsBySource := make(map[types.Epoch][]types.Epoch) err = s.view(func(tx *bolt.Tx) error { bkt := tx.Bucket(pubKeysBucket) if bkt == nil { @@ -161,18 +162,18 @@ func (s *Store) migrateOptimalAttesterProtectionDown(ctx context.Context) error if err := signingRootsBucket.ForEach(func(targetBytes, signingRoot []byte) error { var sr [32]byte copy(sr[:], signingRoot) - signingRootsByTarget[bytesutil.BytesToUint64BigEndian(targetBytes)] = sr[:] + signingRootsByTarget[bytesutil.BytesToEpochBigEndian(targetBytes)] = sr[:] return nil }); err != nil { return err } // Next up, extract the target epochs by source. if err := sourceEpochsBucket.ForEach(func(sourceBytes, targetEpochsBytes []byte) error { - targetEpochs := make([]uint64, 0) + targetEpochs := make([]types.Epoch, 0) for i := 0; i < len(targetEpochsBytes); i += 8 { - targetEpochs = append(targetEpochs, bytesutil.BytesToUint64BigEndian(targetEpochsBytes[i:i+8])) + targetEpochs = append(targetEpochs, bytesutil.BytesToEpochBigEndian(targetEpochsBytes[i:i+8])) } - targetEpochsBySource[bytesutil.BytesToUint64BigEndian(sourceBytes)] = targetEpochs + targetEpochsBySource[bytesutil.BytesToEpochBigEndian(sourceBytes)] = targetEpochs return nil }); err != nil { return err @@ -197,7 +198,7 @@ func (s *Store) migrateOptimalAttesterProtectionDown(ctx context.Context) error // Now we write the attesting history using the data we extracted // from the buckets accordingly. history := newDeprecatedAttestingHistory(0) - var maxTargetWritten uint64 + var maxTargetWritten types.Epoch for source, targetEpochs := range targetEpochsBySource { for _, target := range targetEpochs { signingRoot := params.BeaconConfig().ZeroHash[:] diff --git a/validator/db/kv/migration_optimal_attester_protection_test.go b/validator/db/kv/migration_optimal_attester_protection_test.go index 26ba6b4bea..86088ba803 100644 --- a/validator/db/kv/migration_optimal_attester_protection_test.go +++ b/validator/db/kv/migration_optimal_attester_protection_test.go @@ -5,6 +5,7 @@ import ( "fmt" "testing" + "github.com/prysmaticlabs/eth2-types" bolt "go.etcd.io/bbolt" "github.com/prysmaticlabs/prysm/shared/bytesutil" @@ -41,8 +42,8 @@ func Test_migrateOptimalAttesterProtectionUp(t *testing.T) { pubKey := [48]byte{1} history := newDeprecatedAttestingHistory(0) // Attest all epochs from genesis to 50. - numEpochs := uint64(50) - for i := uint64(1); i <= numEpochs; i++ { + numEpochs := types.Epoch(50) + for i := types.Epoch(1); i <= numEpochs; i++ { var sr [32]byte copy(sr[:], fmt.Sprintf("%d", i)) newHist, err := history.setTargetData(ctx, i, &deprecatedHistoryData{ @@ -100,8 +101,8 @@ func Test_migrateOptimalAttesterProtectionUp(t *testing.T) { pubKey := [48]byte{1} history := newDeprecatedAttestingHistory(0) // Attest all epochs from genesis to 50. - numEpochs := uint64(50) - for i := uint64(1); i <= numEpochs; i++ { + numEpochs := types.Epoch(50) + for i := types.Epoch(1); i <= numEpochs; i++ { var sr [32]byte copy(sr[:], fmt.Sprintf("%d", i)) newHist, err := history.setTargetData(ctx, i, &deprecatedHistoryData{ @@ -282,7 +283,7 @@ func Test_migrateOptimalAttesterProtectionDown(t *testing.T) { highestEpoch, err := attestingHistory.getLatestEpochWritten(ctx) require.NoError(t, err) // Verify the highest epoch written is 50 from the setup stage. - require.Equal(t, uint64(50), highestEpoch) + require.Equal(t, types.Epoch(50), highestEpoch) } return nil }) diff --git a/validator/db/kv/proposer_protection_test.go b/validator/db/kv/proposer_protection_test.go index a07042ab38..266fb1c304 100644 --- a/validator/db/kv/proposer_protection_test.go +++ b/validator/db/kv/proposer_protection_test.go @@ -117,8 +117,8 @@ func TestPruneProposalHistoryBySlot_OK(t *testing.T) { }{ { // Go 2 epochs past pruning point. - slots: []uint64{slotsPerEpoch / 2, slotsPerEpoch*5 + 6, (wsPeriod+3)*slotsPerEpoch + 8}, - storedSlots: []uint64{slotsPerEpoch*5 + 6, (wsPeriod+3)*slotsPerEpoch + 8}, + slots: []uint64{slotsPerEpoch / 2, slotsPerEpoch*5 + 6, uint64(wsPeriod+3)*slotsPerEpoch + 8}, + storedSlots: []uint64{slotsPerEpoch*5 + 6, uint64(wsPeriod+3)*slotsPerEpoch + 8}, removedSlots: []uint64{slotsPerEpoch / 2}, }, { @@ -129,9 +129,9 @@ func TestPruneProposalHistoryBySlot_OK(t *testing.T) { slotsPerEpoch * 3, slotsPerEpoch * 4, slotsPerEpoch * 5, - (wsPeriod+10)*slotsPerEpoch + 8, + uint64(wsPeriod+10)*slotsPerEpoch + 8, }, - storedSlots: []uint64{(wsPeriod+10)*slotsPerEpoch + 8}, + storedSlots: []uint64{uint64(wsPeriod+10)*slotsPerEpoch + 8}, removedSlots: []uint64{ slotsPerEpoch + 4, slotsPerEpoch * 2, diff --git a/validator/db/kv/prune_attester_protection.go b/validator/db/kv/prune_attester_protection.go index 767600c4c3..df5646fa22 100644 --- a/validator/db/kv/prune_attester_protection.go +++ b/validator/db/kv/prune_attester_protection.go @@ -3,6 +3,7 @@ package kv import ( "context" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/params" bolt "go.etcd.io/bbolt" @@ -41,7 +42,7 @@ func pruneSourceEpochsBucket(bucket *bolt.Bucket) error { // Then, we obtain the corresponding target epoch for that source epoch. highestSourceEpochBytes, _ := sourceEpochsBucket.Cursor().Last() highestTargetEpochBytes := sourceEpochsBucket.Get(highestSourceEpochBytes) - highestTargetEpoch := bytesutil.BytesToUint64BigEndian(highestTargetEpochBytes) + highestTargetEpoch := bytesutil.BytesToEpochBigEndian(highestTargetEpochBytes) // No need to prune if the highest epoch we've written is still // before the first weak subjectivity period. @@ -50,7 +51,7 @@ func pruneSourceEpochsBucket(bucket *bolt.Bucket) error { } return sourceEpochsBucket.ForEach(func(k []byte, v []byte) error { - targetEpoch := bytesutil.BytesToUint64BigEndian(v) + targetEpoch := bytesutil.BytesToEpochBigEndian(v) // For each source epoch we find, we check // if its associated target epoch is less than the weak @@ -72,7 +73,7 @@ func pruneSigningRootsBucket(bucket *bolt.Bucket) error { // We obtain the highest target epoch from the signing roots bucket. highestTargetEpochBytes, _ := signingRootsBucket.Cursor().Last() - highestTargetEpoch := bytesutil.BytesToUint64BigEndian(highestTargetEpochBytes) + highestTargetEpoch := bytesutil.BytesToEpochBigEndian(highestTargetEpochBytes) // No need to prune if the highest epoch we've written is still // before the first weak subjectivity period. @@ -81,7 +82,7 @@ func pruneSigningRootsBucket(bucket *bolt.Bucket) error { } return signingRootsBucket.ForEach(func(k []byte, v []byte) error { - targetEpoch := bytesutil.BytesToUint64BigEndian(k) + targetEpoch := bytesutil.BytesToEpochBigEndian(k) // For each target epoch we find in the bucket, we check // if it less than the weak subjectivity period of the // highest written target epoch in the bucket and delete if so. @@ -92,7 +93,7 @@ func pruneSigningRootsBucket(bucket *bolt.Bucket) error { }) } -func olderThanCurrentWeakSubjectivityPeriod(epoch, highestEpoch uint64) bool { +func olderThanCurrentWeakSubjectivityPeriod(epoch, highestEpoch types.Epoch) bool { wssPeriod := params.BeaconConfig().WeakSubjectivityPeriod // Number of weak subjectivity periods that have passed. currentWeakSubjectivityPeriod := highestEpoch / wssPeriod diff --git a/validator/db/kv/prune_attester_protection_test.go b/validator/db/kv/prune_attester_protection_test.go index 3c68d68837..8b62307bd5 100644 --- a/validator/db/kv/prune_attester_protection_test.go +++ b/validator/db/kv/prune_attester_protection_test.go @@ -5,6 +5,7 @@ import ( "fmt" "testing" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/testutil/require" @@ -49,8 +50,8 @@ func TestPruneAttestationsOlderThanCurrentWeakSubjectivity_AfterFirstWeakSubject pkBucket := bucket.Bucket(pubKey[:]) sourceEpochsBkt := pkBucket.Bucket(attestationSourceEpochsBucket) signingRootsBkt := pkBucket.Bucket(attestationSigningRootsBucket) - targetEpochBytes := bytesutil.Uint64ToBytesBigEndian(numEpochs + 1) - sourceEpochBytes := bytesutil.Uint64ToBytesBigEndian(numEpochs) + targetEpochBytes := bytesutil.EpochToBytesBigEndian(numEpochs + 1) + sourceEpochBytes := bytesutil.EpochToBytesBigEndian(numEpochs) if err := sourceEpochsBkt.Put(sourceEpochBytes, targetEpochBytes); err != nil { return err } @@ -76,11 +77,11 @@ func TestPruneAttestationsOlderThanCurrentWeakSubjectivity_AfterFirstWeakSubject sourceEpochsBkt := pkBucket.Bucket(attestationSourceEpochsBucket) signingRootsBkt := pkBucket.Bucket(attestationSigningRootsBucket) - targetEpochBytes := bytesutil.Uint64ToBytesBigEndian(numEpochs + 1) - sourceEpochBytes := bytesutil.Uint64ToBytesBigEndian(numEpochs) + targetEpochBytes := bytesutil.EpochToBytesBigEndian(numEpochs + 1) + sourceEpochBytes := bytesutil.EpochToBytesBigEndian(numEpochs) storedTargetEpoch := sourceEpochsBkt.Get(sourceEpochBytes) - require.DeepEqual(t, numEpochs+1, bytesutil.BytesToUint64BigEndian(storedTargetEpoch)) + require.DeepEqual(t, numEpochs+1, bytesutil.BytesToEpochBigEndian(storedTargetEpoch)) var expectedSigningRoot [32]byte copy(expectedSigningRoot[:], fmt.Sprintf("%d", targetEpochBytes)) @@ -94,7 +95,7 @@ func TestPruneAttestationsOlderThanCurrentWeakSubjectivity_AfterFirstWeakSubject } func TestPruneAttestationsOlderThanCurrentWeakSubjectivity_AfterMultipleWeakSubjectivity(t *testing.T) { - numWeakSubjectivityPeriods := uint64(5) + numWeakSubjectivityPeriods := types.Epoch(5) pubKeys := [][48]byte{{1}} validatorDB := setupDB(t, pubKeys) @@ -113,11 +114,11 @@ func TestPruneAttestationsOlderThanCurrentWeakSubjectivity_AfterMultipleWeakSubj if err != nil { return err } - for i := uint64(1); i <= numWeakSubjectivityPeriods; i++ { + for i := types.Epoch(1); i <= numWeakSubjectivityPeriods; i++ { targetEpoch := (i * params.BeaconConfig().WeakSubjectivityPeriod) + 1 - targetEpochBytes := bytesutil.Uint64ToBytesBigEndian(targetEpoch) + targetEpochBytes := bytesutil.EpochToBytesBigEndian(targetEpoch) sourceEpoch := targetEpoch - 1 - sourceEpochBytes := bytesutil.Uint64ToBytesBigEndian(sourceEpoch) + sourceEpochBytes := bytesutil.EpochToBytesBigEndian(sourceEpoch) if err := sourceEpochsBkt.Put(sourceEpochBytes, targetEpochBytes); err != nil { return err } @@ -146,11 +147,11 @@ func TestPruneAttestationsOlderThanCurrentWeakSubjectivity_AfterMultipleWeakSubj // We check everything except for the highest weak subjectivity period // has been pruned from the bucket. - for i := uint64(1); i <= numWeakSubjectivityPeriods-1; i++ { + for i := types.Epoch(1); i <= numWeakSubjectivityPeriods-1; i++ { targetEpoch := (i * params.BeaconConfig().WeakSubjectivityPeriod) + 1 sourceEpoch := targetEpoch - 1 - sourceEpochBytes := bytesutil.Uint64ToBytesBigEndian(sourceEpoch) - targetEpochBytes := bytesutil.Uint64ToBytesBigEndian(targetEpoch) + sourceEpochBytes := bytesutil.EpochToBytesBigEndian(sourceEpoch) + targetEpochBytes := bytesutil.EpochToBytesBigEndian(targetEpoch) storedTargetEpoch := sourceEpochsBkt.Get(sourceEpochBytes) signingRoot := signingRootsBkt.Get(targetEpochBytes) @@ -161,8 +162,8 @@ func TestPruneAttestationsOlderThanCurrentWeakSubjectivity_AfterMultipleWeakSubj targetEpoch := (numWeakSubjectivityPeriods * params.BeaconConfig().WeakSubjectivityPeriod) + 1 sourceEpoch := targetEpoch - 1 - targetEpochBytes := bytesutil.Uint64ToBytesBigEndian(targetEpoch) - sourceEpochBytes := bytesutil.Uint64ToBytesBigEndian(sourceEpoch) + targetEpochBytes := bytesutil.EpochToBytesBigEndian(targetEpoch) + sourceEpochBytes := bytesutil.EpochToBytesBigEndian(sourceEpoch) var expectedSigningRoot [32]byte copy(expectedSigningRoot[:], fmt.Sprintf("%d", targetEpochBytes)) signingRoot := signingRootsBkt.Get(targetEpochBytes) @@ -178,7 +179,7 @@ func TestPruneAttestationsOlderThanCurrentWeakSubjectivity_AfterMultipleWeakSubj // Saves attesting history for every (source, target = source + 1) pairs since genesis // up to a given number of epochs for a validator public key. -func setupAttestationsForEveryEpoch(t testing.TB, validatorDB *Store, pubKey [48]byte, numEpochs uint64) error { +func setupAttestationsForEveryEpoch(t testing.TB, validatorDB *Store, pubKey [48]byte, numEpochs types.Epoch) error { return validatorDB.update(func(tx *bolt.Tx) error { bucket := tx.Bucket(pubKeysBucket) pkBucket, err := bucket.CreateBucketIfNotExists(pubKey[:]) @@ -193,9 +194,9 @@ func setupAttestationsForEveryEpoch(t testing.TB, validatorDB *Store, pubKey [48 if err != nil { return err } - for targetEpoch := uint64(1); targetEpoch < numEpochs; targetEpoch++ { - targetEpochBytes := bytesutil.Uint64ToBytesBigEndian(targetEpoch) - sourceEpochBytes := bytesutil.Uint64ToBytesBigEndian(targetEpoch - 1) + for targetEpoch := types.Epoch(1); targetEpoch < numEpochs; targetEpoch++ { + targetEpochBytes := bytesutil.EpochToBytesBigEndian(targetEpoch) + sourceEpochBytes := bytesutil.EpochToBytesBigEndian(targetEpoch - 1) // Save (source epoch, target epoch) pairs. if err := sourceEpochsBucket.Put(sourceEpochBytes, targetEpochBytes); err != nil { return err @@ -214,16 +215,16 @@ func setupAttestationsForEveryEpoch(t testing.TB, validatorDB *Store, pubKey [48 // Verifies, based on a boolean input argument, whether or not we should have // pruned all attesting history since genesis up to a specified number of epochs. func checkAttestingHistoryAfterPruning( - t testing.TB, validatorDB *Store, pubKey [48]byte, numEpochs uint64, shouldBePruned bool, + t testing.TB, validatorDB *Store, pubKey [48]byte, numEpochs types.Epoch, shouldBePruned bool, ) error { return validatorDB.view(func(tx *bolt.Tx) error { bucket := tx.Bucket(pubKeysBucket) pkBkt := bucket.Bucket(pubKey[:]) signingRootsBkt := pkBkt.Bucket(attestationSigningRootsBucket) sourceEpochsBkt := pkBkt.Bucket(attestationSourceEpochsBucket) - for targetEpoch := uint64(1); targetEpoch < numEpochs; targetEpoch++ { - targetEpochBytes := bytesutil.Uint64ToBytesBigEndian(targetEpoch) - sourceEpochBytes := bytesutil.Uint64ToBytesBigEndian(targetEpoch - 1) + for targetEpoch := types.Epoch(1); targetEpoch < numEpochs; targetEpoch++ { + targetEpochBytes := bytesutil.EpochToBytesBigEndian(targetEpoch) + sourceEpochBytes := bytesutil.EpochToBytesBigEndian(targetEpoch - 1) storedTargetEpoch := sourceEpochsBkt.Get(sourceEpochBytes) signingRoot := signingRootsBkt.Get(targetEpochBytes) @@ -247,8 +248,8 @@ func checkAttestingHistoryAfterPruning( func Test_olderThanCurrentWeakSubjectivityPeriod(t *testing.T) { wssPeriod := params.BeaconConfig().WeakSubjectivityPeriod type args struct { - epoch uint64 - highestEpoch uint64 + epoch types.Epoch + highestEpoch types.Epoch } tests := []struct { name string diff --git a/validator/slashing-protection/local/standard-protection-format/BUILD.bazel b/validator/slashing-protection/local/standard-protection-format/BUILD.bazel index 7c301efbca..e69eee2d13 100644 --- a/validator/slashing-protection/local/standard-protection-format/BUILD.bazel +++ b/validator/slashing-protection/local/standard-protection-format/BUILD.bazel @@ -21,6 +21,7 @@ go_library( "//validator/slashing-protection/local/standard-protection-format/format:go_default_library", "@com_github_k0kubun_go_ansi//:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_schollz_progressbar_v3//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", @@ -43,6 +44,7 @@ go_test( "//validator/db/testing:go_default_library", "//validator/slashing-protection/local/standard-protection-format/format:go_default_library", "//validator/testing:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_sirupsen_logrus//hooks/test:go_default_library", ], diff --git a/validator/slashing-protection/local/standard-protection-format/export_test.go b/validator/slashing-protection/local/standard-protection-format/export_test.go index 7b6e9b3013..8a8ce0212a 100644 --- a/validator/slashing-protection/local/standard-protection-format/export_test.go +++ b/validator/slashing-protection/local/standard-protection-format/export_test.go @@ -5,6 +5,7 @@ import ( "fmt" "testing" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/require" dbtest "github.com/prysmaticlabs/prysm/validator/db/testing" @@ -24,8 +25,8 @@ func Test_getSignedAttestationsByPubKey(t *testing.T) { assert.Equal(t, 0, len(signedAttestations)) // We write a real attesting history to disk for the public key. - lowestSourceEpoch := uint64(0) - lowestTargetEpoch := uint64(4) + lowestSourceEpoch := types.Epoch(0) + lowestTargetEpoch := types.Epoch(4) require.NoError(t, validatorDB.SaveAttestationForPubKey(ctx, pubKeys[0], [32]byte{4}, createAttestation( lowestSourceEpoch, diff --git a/validator/slashing-protection/local/standard-protection-format/helpers.go b/validator/slashing-protection/local/standard-protection-format/helpers.go index da0e64e781..83dd67554b 100644 --- a/validator/slashing-protection/local/standard-protection-format/helpers.go +++ b/validator/slashing-protection/local/standard-protection-format/helpers.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/k0kubun/go-ansi" + "github.com/prysmaticlabs/eth2-types" "github.com/schollz/progressbar/v3" ) @@ -33,6 +34,15 @@ func Uint64FromString(str string) (uint64, error) { return strconv.ParseUint(str, 10, 64) } +// Uint64FromString converts a string into a uint64 representation. +func EpochFromString(str string) (types.Epoch, error) { + e, err := strconv.ParseUint(str, 10, 64) + if err != nil { + return 0, err + } + return types.Epoch(e), nil +} + // PubKeyFromHex takes in a hex string, verifies its length as 48 bytes, and converts that representation. func PubKeyFromHex(str string) ([48]byte, error) { pubKeyBytes, err := hex.DecodeString(strings.TrimPrefix(str, "0x")) diff --git a/validator/slashing-protection/local/standard-protection-format/import.go b/validator/slashing-protection/local/standard-protection-format/import.go index 56dc2fc352..e4c57500ca 100644 --- a/validator/slashing-protection/local/standard-protection-format/import.go +++ b/validator/slashing-protection/local/standard-protection-format/import.go @@ -9,6 +9,7 @@ import ( "io/ioutil" "github.com/pkg/errors" + "github.com/prysmaticlabs/eth2-types" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/slashutil" @@ -266,8 +267,8 @@ func filterSlashablePubKeysFromAttestations( // First we need to find attestations that are slashable with respect to other // attestations within the same JSON import. for pubKey, signedAtts := range signedAttsByPubKey { - signingRootsByTarget := make(map[uint64][32]byte) - targetEpochsBySource := make(map[uint64][]uint64) + signingRootsByTarget := make(map[types.Epoch][32]byte) + targetEpochsBySource := make(map[types.Epoch][]types.Epoch) Loop: for _, att := range signedAtts { // Check for double votes. @@ -338,11 +339,11 @@ func transformSignedBlocks(ctx context.Context, signedBlocks []*format.SignedBlo func transformSignedAttestations(pubKey [48]byte, atts []*format.SignedAttestation) ([]*kv.AttestationRecord, error) { historicalAtts := make([]*kv.AttestationRecord, 0) for _, attestation := range atts { - target, err := Uint64FromString(attestation.TargetEpoch) + target, err := EpochFromString(attestation.TargetEpoch) if err != nil { return nil, fmt.Errorf("%d is not a valid epoch: %v", target, err) } - source, err := Uint64FromString(attestation.SourceEpoch) + source, err := EpochFromString(attestation.SourceEpoch) if err != nil { return nil, fmt.Errorf("%d is not a valid epoch: %v", source, err) } @@ -364,7 +365,7 @@ func transformSignedAttestations(pubKey [48]byte, atts []*format.SignedAttestati return historicalAtts, nil } -func createAttestation(source, target uint64) *ethpb.IndexedAttestation { +func createAttestation(source, target types.Epoch) *ethpb.IndexedAttestation { return ðpb.IndexedAttestation{ Data: ðpb.AttestationData{ Source: ðpb.Checkpoint{ diff --git a/validator/testing/BUILD.bazel b/validator/testing/BUILD.bazel index 9b727d18b2..6b81e70311 100644 --- a/validator/testing/BUILD.bazel +++ b/validator/testing/BUILD.bazel @@ -19,6 +19,7 @@ go_library( "//validator/db/kv:go_default_library", "//validator/slashing-protection/local/standard-protection-format/format:go_default_library", "@com_github_golang_protobuf//proto:go_default_library", + "@com_github_prysmaticlabs_eth2_types//:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@org_golang_google_grpc//:go_default_library", ], diff --git a/validator/testing/protection_history.go b/validator/testing/protection_history.go index 4830d95a59..4b45ba0d9c 100644 --- a/validator/testing/protection_history.go +++ b/validator/testing/protection_history.go @@ -3,6 +3,7 @@ package testing import ( "fmt" + "github.com/prysmaticlabs/eth2-types" "github.com/prysmaticlabs/prysm/shared/bls" "github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/params" @@ -56,7 +57,7 @@ func MockAttestingAndProposalHistories(numValidators int) ([][]*kv.AttestationRe proposalData := make([]kv.ProposalHistoryForPubkey, numValidators) gen := rand.NewGenerator() for v := 0; v < numValidators; v++ { - latestTarget := gen.Intn(int(params.BeaconConfig().WeakSubjectivityPeriod) / 1000) + latestTarget := types.Epoch(gen.Intn(int(params.BeaconConfig().WeakSubjectivityPeriod) / 1000)) // If 0, we change the value to 1 as the we compute source by doing (target-1) // to prevent any underflows in this setup helper. if latestTarget == 0 { @@ -64,17 +65,17 @@ func MockAttestingAndProposalHistories(numValidators int) ([][]*kv.AttestationRe } historicalAtts := make([]*kv.AttestationRecord, 0) proposals := make([]kv.Proposal, 0) - for i := 1; i < latestTarget; i++ { + for i := types.Epoch(1); i < latestTarget; i++ { signingRoot := [32]byte{} signingRootStr := fmt.Sprintf("%d", i) copy(signingRoot[:], signingRootStr) historicalAtts = append(historicalAtts, &kv.AttestationRecord{ - Source: uint64(i - 1), - Target: uint64(i), + Source: i - 1, + Target: i, SigningRoot: signingRoot, }) } - for i := 1; i <= latestTarget; i++ { + for i := types.Epoch(1); i <= latestTarget; i++ { signingRoot := [32]byte{} signingRootStr := fmt.Sprintf("%d", i) copy(signingRoot[:], signingRootStr)