From 77d3ccb9ad8b28656452456d2d25437f5fc53d88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Kapka?= Date: Thu, 26 Jan 2023 15:40:12 +0100 Subject: [PATCH] Clean up state types (#11916) * Clean up state types * rename package --- api/client/beacon/checkpoint.go | 8 +- api/client/beacon/checkpoint_test.go | 8 +- api/client/beacon/client.go | 10 +- api/client/builder/client.go | 10 +- api/client/builder/testing/mock.go | 4 +- beacon-chain/blockchain/chain_info.go | 26 +- beacon-chain/blockchain/chain_info_test.go | 16 +- beacon-chain/blockchain/execution_engine.go | 4 +- .../blockchain/execution_engine_test.go | 18 +- beacon-chain/blockchain/head.go | 12 +- .../blockchain/head_sync_committee_info.go | 30 +- .../head_sync_committee_info_test.go | 14 +- beacon-chain/blockchain/head_test.go | 8 +- beacon-chain/blockchain/metrics.go | 8 +- beacon-chain/blockchain/pow_block.go | 4 +- .../blockchain/process_attestation_helpers.go | 6 +- .../blockchain/process_attestation_test.go | 4 +- beacon-chain/blockchain/process_block.go | 4 +- .../blockchain/process_block_helpers.go | 10 +- beacon-chain/blockchain/process_block_test.go | 82 ++--- .../blockchain/receive_attestation_test.go | 6 +- beacon-chain/blockchain/receive_block.go | 6 +- beacon-chain/blockchain/receive_block_test.go | 12 +- beacon-chain/blockchain/service.go | 4 +- .../blockchain/state_balance_cache_test.go | 30 +- beacon-chain/blockchain/testing/mock.go | 34 +- .../blockchain/weak_subjectivity_checks.go | 8 +- .../weak_subjectivity_checks_test.go | 4 +- beacon-chain/builder/service.go | 8 +- beacon-chain/builder/testing/mock.go | 4 +- beacon-chain/cache/active_balance.go | 4 +- beacon-chain/cache/active_balance_test.go | 4 +- beacon-chain/cache/checkpoint_state_test.go | 6 +- beacon-chain/cache/committee.go | 6 +- beacon-chain/cache/committee_disabled.go | 10 +- beacon-chain/cache/committee_test.go | 20 +- beacon-chain/cache/committees.go | 6 +- beacon-chain/cache/payload_id.go | 14 +- beacon-chain/cache/payload_id_test.go | 24 +- beacon-chain/cache/proposer_indices.go | 4 +- .../cache/proposer_indices_disabled.go | 4 +- beacon-chain/cache/proposer_indices_test.go | 6 +- beacon-chain/cache/proposer_indices_type.go | 4 +- beacon-chain/cache/subnet_ids.go | 10 +- beacon-chain/cache/subnet_ids_test.go | 4 +- beacon-chain/cache/sync_committee.go | 28 +- beacon-chain/cache/sync_committee_disabled.go | 6 +- .../cache/sync_committee_head_state.go | 6 +- .../cache/sync_committee_head_state_test.go | 36 +- beacon-chain/cache/sync_committee_test.go | 30 +- beacon-chain/cache/sync_subnet_ids.go | 14 +- beacon-chain/core/altair/attestation.go | 8 +- beacon-chain/core/altair/attestation_test.go | 10 +- beacon-chain/core/altair/block_test.go | 8 +- .../core/altair/epoch_precompute_test.go | 4 +- beacon-chain/core/altair/epoch_spec_test.go | 6 +- beacon-chain/core/altair/reward.go | 6 +- beacon-chain/core/altair/reward_test.go | 6 +- beacon-chain/core/altair/sync_committee.go | 12 +- .../core/altair/sync_committee_test.go | 14 +- beacon-chain/core/altair/upgrade_test.go | 4 +- beacon-chain/core/blocks/attestation.go | 4 +- beacon-chain/core/blocks/attestation_test.go | 4 +- beacon-chain/core/blocks/attester_slashing.go | 6 +- .../core/blocks/attester_slashing_test.go | 14 +- .../core/blocks/block_operations_fuzz_test.go | 4 +- .../core/blocks/block_regression_test.go | 4 +- beacon-chain/core/blocks/deposit_test.go | 8 +- beacon-chain/core/blocks/eth1_data_test.go | 4 +- beacon-chain/core/blocks/exit.go | 6 +- beacon-chain/core/blocks/exit_test.go | 8 +- beacon-chain/core/blocks/header.go | 4 +- beacon-chain/core/blocks/proposer_slashing.go | 4 +- .../core/blocks/proposer_slashing_test.go | 18 +- beacon-chain/core/blocks/randao_test.go | 4 +- beacon-chain/core/blocks/signature.go | 8 +- beacon-chain/core/blocks/withdrawals.go | 10 +- beacon-chain/core/blocks/withdrawals_test.go | 68 ++-- beacon-chain/core/capella/upgrade_test.go | 4 +- beacon-chain/core/epoch/epoch_processing.go | 20 +- .../core/epoch/epoch_processing_test.go | 8 +- .../core/epoch/precompute/attestation.go | 6 +- .../justification_finalization_test.go | 30 +- .../core/epoch/precompute/reward_penalty.go | 4 +- .../epoch/precompute/reward_penalty_test.go | 20 +- .../core/epoch/precompute/slashing.go | 4 +- beacon-chain/core/epoch/precompute/type.go | 8 +- beacon-chain/core/feed/state/events.go | 4 +- beacon-chain/core/helpers/attestation.go | 12 +- beacon-chain/core/helpers/attestation_test.go | 4 +- beacon-chain/core/helpers/beacon_committee.go | 56 +-- .../core/helpers/beacon_committee_test.go | 46 +-- beacon-chain/core/helpers/block.go | 8 +- beacon-chain/core/helpers/block_test.go | 10 +- beacon-chain/core/helpers/randao.go | 6 +- beacon-chain/core/helpers/randao_test.go | 6 +- .../core/helpers/rewards_penalties.go | 12 +- .../core/helpers/rewards_penalties_test.go | 22 +- beacon-chain/core/helpers/shuffle.go | 24 +- beacon-chain/core/helpers/shuffle_test.go | 42 +-- beacon-chain/core/helpers/sync_committee.go | 20 +- .../core/helpers/sync_committee_test.go | 20 +- beacon-chain/core/helpers/validators.go | 34 +- beacon-chain/core/helpers/validators_test.go | 52 +-- .../core/helpers/weak_subjectivity.go | 12 +- .../core/helpers/weak_subjectivity_test.go | 28 +- beacon-chain/core/signing/domain.go | 4 +- beacon-chain/core/signing/domain_test.go | 4 +- beacon-chain/core/signing/signing_root.go | 6 +- beacon-chain/core/time/slot_epoch.go | 16 +- beacon-chain/core/time/slot_epoch_test.go | 44 +-- beacon-chain/core/transition/state_test.go | 16 +- .../stateutils/validator_index_map.go | 8 +- .../stateutils/validator_index_map_test.go | 4 +- .../trailing_slot_state_cache_test.go | 6 +- beacon-chain/core/transition/transition.go | 8 +- .../core/transition/transition_fuzz_test.go | 4 +- .../core/transition/transition_test.go | 18 +- beacon-chain/core/validators/validator.go | 46 +-- .../core/validators/validator_test.go | 38 +- beacon-chain/db/filters/filter.go | 14 +- beacon-chain/db/filters/filter_test.go | 6 +- beacon-chain/db/iface/interface.go | 40 +-- beacon-chain/db/kv/archived_point.go | 10 +- beacon-chain/db/kv/archived_point_test.go | 8 +- beacon-chain/db/kv/backup_test.go | 4 +- beacon-chain/db/kv/blocks.go | 28 +- beacon-chain/db/kv/blocks_test.go | 78 ++-- .../db/kv/finalized_block_roots_test.go | 6 +- .../db/kv/migration_archived_index.go | 4 +- beacon-chain/db/kv/state.go | 10 +- beacon-chain/db/kv/state_summary_test.go | 4 +- beacon-chain/db/kv/state_test.go | 28 +- beacon-chain/db/kv/wss.go | 4 +- beacon-chain/db/restore_test.go | 4 +- beacon-chain/db/slasherkv/pruning.go | 18 +- beacon-chain/db/slasherkv/pruning_test.go | 34 +- beacon-chain/db/slasherkv/slasher.go | 28 +- beacon-chain/db/slasherkv/slasher_test.go | 48 +-- beacon-chain/deterministic-genesis/service.go | 4 +- beacon-chain/execution/deposit_test.go | 4 +- beacon-chain/execution/engine_client.go | 6 +- .../execution/testing/mock_engine_client.go | 4 +- .../doubly-linked-tree/ffg_update_test.go | 4 +- .../doubly-linked-tree/forkchoice.go | 22 +- .../doubly-linked-tree/forkchoice_test.go | 24 +- .../forkchoice/doubly-linked-tree/node.go | 8 +- .../doubly-linked-tree/node_test.go | 6 +- .../forkchoice/doubly-linked-tree/on_tick.go | 4 +- .../doubly-linked-tree/on_tick_test.go | 4 +- .../doubly-linked-tree/proposer_boost_test.go | 44 +-- .../forkchoice/doubly-linked-tree/store.go | 12 +- .../doubly-linked-tree/store_test.go | 48 +-- .../forkchoice/doubly-linked-tree/types.go | 24 +- .../unrealized_justification.go | 6 +- .../unrealized_justification_test.go | 48 +-- beacon-chain/forkchoice/interfaces.go | 18 +- beacon-chain/forkchoice/types/types.go | 8 +- beacon-chain/monitor/process_attestation.go | 28 +- beacon-chain/monitor/process_block.go | 4 +- beacon-chain/monitor/process_block_test.go | 4 +- beacon-chain/monitor/process_exit_test.go | 10 +- beacon-chain/monitor/service.go | 34 +- beacon-chain/monitor/service_test.go | 24 +- beacon-chain/node/config.go | 10 +- beacon-chain/node/config_test.go | 6 +- beacon-chain/node/node.go | 6 +- .../operations/attestations/kv/aggregated.go | 6 +- .../attestations/kv/aggregated_test.go | 4 +- .../attestations/kv/unaggregated.go | 4 +- .../operations/attestations/mock/mock.go | 8 +- beacon-chain/operations/attestations/pool.go | 8 +- .../operations/attestations/prune_expired.go | 4 +- .../operations/blstoexec/mock/mock.go | 4 +- beacon-chain/operations/blstoexec/pool.go | 10 +- .../operations/blstoexec/pool_test.go | 62 ++-- beacon-chain/operations/slashings/service.go | 16 +- .../slashings/service_attester_test.go | 78 ++-- .../slashings/service_proposer_test.go | 54 +-- beacon-chain/operations/slashings/types.go | 6 +- .../operations/synccommittee/contribution.go | 6 +- .../operations/synccommittee/message.go | 4 +- beacon-chain/operations/synccommittee/pool.go | 6 +- .../operations/voluntaryexits/mock/mock.go | 4 +- .../operations/voluntaryexits/service.go | 8 +- .../operations/voluntaryexits/service_test.go | 4 +- beacon-chain/p2p/fork_test.go | 10 +- beacon-chain/p2p/gossip_topic_mappings.go | 4 +- .../p2p/gossip_topic_mappings_test.go | 14 +- beacon-chain/p2p/message_id.go | 4 +- beacon-chain/p2p/peers/scorers/peer_status.go | 8 +- .../p2p/peers/scorers/peer_status_test.go | 8 +- beacon-chain/p2p/peers/status.go | 26 +- beacon-chain/p2p/peers/status_test.go | 20 +- beacon-chain/p2p/rpc_topic_mappings.go | 8 +- beacon-chain/p2p/rpc_topic_mappings_test.go | 6 +- beacon-chain/p2p/types/rpc_goodbye_codes.go | 4 +- beacon-chain/p2p/types/types_test.go | 16 +- .../rpc/apimiddleware/custom_hooks.go | 6 +- beacon-chain/rpc/eth/beacon/blocks.go | 8 +- beacon-chain/rpc/eth/beacon/blocks_test.go | 36 +- beacon-chain/rpc/eth/beacon/config_test.go | 10 +- beacon-chain/rpc/eth/beacon/pool_test.go | 18 +- beacon-chain/rpc/eth/beacon/state.go | 4 +- beacon-chain/rpc/eth/beacon/state_test.go | 10 +- beacon-chain/rpc/eth/beacon/sync_committee.go | 16 +- .../rpc/eth/beacon/sync_committee_test.go | 30 +- beacon-chain/rpc/eth/beacon/validator.go | 10 +- beacon-chain/rpc/eth/beacon/validator_test.go | 70 ++-- beacon-chain/rpc/eth/debug/debug_test.go | 8 +- beacon-chain/rpc/eth/helpers/sync_test.go | 6 +- .../rpc/eth/helpers/validator_status.go | 6 +- .../rpc/eth/helpers/validator_status_test.go | 42 +-- beacon-chain/rpc/eth/node/node_test.go | 8 +- beacon-chain/rpc/eth/validator/validator.go | 30 +- .../rpc/eth/validator/validator_test.go | 200 +++++------ .../rpc/prysm/v1alpha1/beacon/assignments.go | 8 +- .../prysm/v1alpha1/beacon/assignments_test.go | 8 +- .../v1alpha1/beacon/attestations_test.go | 44 +-- .../rpc/prysm/v1alpha1/beacon/blocks_test.go | 50 +-- .../rpc/prysm/v1alpha1/beacon/committees.go | 18 +- .../rpc/prysm/v1alpha1/beacon/slashings.go | 8 +- .../prysm/v1alpha1/beacon/slashings_test.go | 18 +- .../rpc/prysm/v1alpha1/beacon/validators.go | 48 +-- .../v1alpha1/beacon/validators_stream.go | 22 +- .../v1alpha1/beacon/validators_stream_test.go | 4 +- .../prysm/v1alpha1/beacon/validators_test.go | 100 +++--- .../rpc/prysm/v1alpha1/debug/block.go | 6 +- .../rpc/prysm/v1alpha1/debug/state_test.go | 4 +- .../prysm/v1alpha1/slasher/attestations.go | 6 +- .../v1alpha1/slasher/attestations_test.go | 4 +- .../prysm/v1alpha1/validator/assignments.go | 14 +- .../v1alpha1/validator/assignments_test.go | 28 +- .../rpc/prysm/v1alpha1/validator/attester.go | 4 +- .../validator/attester_mainnet_test.go | 4 +- .../prysm/v1alpha1/validator/attester_test.go | 24 +- .../rpc/prysm/v1alpha1/validator/exit_test.go | 10 +- .../rpc/prysm/v1alpha1/validator/proposer.go | 4 +- .../v1alpha1/validator/proposer_altair.go | 4 +- .../validator/proposer_attestations.go | 6 +- .../validator/proposer_attestations_test.go | 4 +- .../v1alpha1/validator/proposer_bellatrix.go | 4 +- .../v1alpha1/validator/proposer_builder.go | 8 +- .../validator/proposer_builder_test.go | 10 +- .../validator/proposer_empty_block.go | 4 +- .../validator/proposer_empty_block_test.go | 10 +- .../v1alpha1/validator/proposer_eth1data.go | 6 +- .../validator/proposer_execution_payload.go | 6 +- .../proposer_execution_payload_test.go | 12 +- .../v1alpha1/validator/proposer_exits.go | 4 +- .../v1alpha1/validator/proposer_exits_test.go | 4 +- .../validator/proposer_slashings_test.go | 6 +- .../prysm/v1alpha1/validator/proposer_test.go | 20 +- .../rpc/prysm/v1alpha1/validator/status.go | 22 +- .../prysm/v1alpha1/validator/status_test.go | 24 +- .../v1alpha1/validator/sync_committee.go | 4 +- .../v1alpha1/validator/sync_committee_test.go | 10 +- beacon-chain/rpc/statefetcher/fetcher.go | 12 +- beacon-chain/rpc/statefetcher/fetcher_test.go | 16 +- .../rpc/testutil/mock_genesis_timefetcher.go | 6 +- .../rpc/testutil/mock_state_fetcher.go | 6 +- beacon-chain/slasher/chunks.go | 60 ++-- beacon-chain/slasher/chunks_test.go | 84 ++--- beacon-chain/slasher/detect_attestations.go | 10 +- .../slasher/detect_attestations_test.go | 78 ++-- beacon-chain/slasher/detect_blocks.go | 4 +- beacon-chain/slasher/detect_blocks_test.go | 12 +- beacon-chain/slasher/helpers.go | 6 +- beacon-chain/slasher/helpers_test.go | 4 +- .../slasher/mock/mock_slashing_checker.go | 6 +- beacon-chain/slasher/params.go | 26 +- beacon-chain/slasher/params_test.go | 24 +- beacon-chain/slasher/queue_test.go | 10 +- beacon-chain/slasher/receive.go | 12 +- beacon-chain/slasher/receive_test.go | 46 +-- beacon-chain/slasher/rpc.go | 4 +- beacon-chain/slasher/rpc_test.go | 20 +- beacon-chain/slasher/service.go | 12 +- beacon-chain/slasher/service_test.go | 4 +- beacon-chain/slasher/types/types.go | 14 +- beacon-chain/state/fieldtrie/BUILD.bazel | 2 - beacon-chain/state/fieldtrie/field_trie.go | 23 +- .../state/fieldtrie/field_trie_helpers.go | 29 +- .../state/fieldtrie/field_trie_test.go | 32 +- beacon-chain/state/fieldtrie/helpers_test.go | 53 ++- beacon-chain/state/interfaces.go | 36 +- beacon-chain/state/state-native/BUILD.bazel | 1 - .../state-native/beacon_state_mainnet.go | 18 +- .../state-native/beacon_state_minimal.go | 18 +- .../state/state-native/getters_checkpoint.go | 4 +- .../state/state-native/getters_misc.go | 4 +- .../state/state-native/getters_validator.go | 18 +- .../state/state-native/getters_withdrawal.go | 6 +- .../state-native/getters_withdrawal_test.go | 28 +- beacon-chain/state/state-native/hasher.go | 64 ++-- beacon-chain/state/state-native/proofs.go | 12 +- .../state/state-native/readonly_validator.go | 12 +- .../state-native/readonly_validator_test.go | 10 +- .../state/state-native/references_test.go | 184 +++++----- .../state/state-native/setters_attestation.go | 38 +- .../state-native/setters_attestation_test.go | 16 +- .../state/state-native/setters_block.go | 20 +- .../state/state-native/setters_checkpoint.go | 10 +- .../state/state-native/setters_eth1.go | 24 +- .../state/state-native/setters_misc.go | 40 +-- .../state-native/setters_participation.go | 58 +-- .../state-native/setters_payload_header.go | 10 +- .../state/state-native/setters_randao.go | 20 +- .../state/state-native/setters_state.go | 18 +- .../state-native/setters_sync_committee.go | 6 +- .../state/state-native/setters_validator.go | 100 +++--- .../state/state-native/setters_withdrawal.go | 10 +- .../state-native/setters_withdrawal_test.go | 14 +- .../state/state-native/state_fuzz_test.go | 10 +- beacon-chain/state/state-native/state_test.go | 8 +- beacon-chain/state/state-native/state_trie.go | 333 +++++++++--------- beacon-chain/state/state-native/types.go | 23 +- .../state/state-native/types/types.go | 20 +- .../stategen/epoch_boundary_state_cache.go | 8 +- .../epoch_boundary_state_cache_test.go | 6 +- beacon-chain/state/stategen/getter.go | 4 +- beacon-chain/state/stategen/getter_test.go | 14 +- beacon-chain/state/stategen/history.go | 8 +- beacon-chain/state/stategen/history_test.go | 54 +-- beacon-chain/state/stategen/migrate_test.go | 18 +- beacon-chain/state/stategen/mock/mock.go | 12 +- beacon-chain/state/stategen/mock/replayer.go | 22 +- beacon-chain/state/stategen/mock_test.go | 28 +- beacon-chain/state/stategen/replay.go | 10 +- beacon-chain/state/stategen/replayer.go | 16 +- beacon-chain/state/stategen/replayer_test.go | 6 +- beacon-chain/state/stategen/service.go | 14 +- .../state/stateutil/trie_helpers_test.go | 6 +- .../stateutil/unrealized_justification.go | 4 +- .../state/stateutil/validator_map_handler.go | 12 +- beacon-chain/state/testing/getters.go | 6 +- .../state/testing/getters_checkpoint.go | 4 +- beacon-chain/state/types/BUILD.bazel | 19 - beacon-chain/state/types/types.go | 172 --------- beacon-chain/state/types/types_test.go | 36 -- beacon-chain/sync/backfill/status.go | 14 +- beacon-chain/sync/backfill/status_test.go | 10 +- beacon-chain/sync/broadcast_bls_changes.go | 4 +- beacon-chain/sync/fork_watcher.go | 6 +- beacon-chain/sync/fork_watcher_test.go | 6 +- .../sync/initial-sync/blocks_fetcher.go | 12 +- .../initial-sync/blocks_fetcher_peers_test.go | 4 +- .../sync/initial-sync/blocks_fetcher_test.go | 30 +- .../sync/initial-sync/blocks_fetcher_utils.go | 20 +- .../initial-sync/blocks_fetcher_utils_test.go | 42 +-- .../sync/initial-sync/blocks_queue.go | 12 +- .../sync/initial-sync/blocks_queue_test.go | 150 ++++---- .../sync/initial-sync/blocks_queue_utils.go | 8 +- beacon-chain/sync/initial-sync/fsm.go | 22 +- beacon-chain/sync/initial-sync/fsm_test.go | 42 +-- .../sync/initial-sync/initial_sync_test.go | 40 +-- beacon-chain/sync/initial-sync/round_robin.go | 12 +- .../sync/initial-sync/round_robin_test.go | 30 +- .../sync/initial-sync/service_test.go | 12 +- .../sync/pending_attestations_queue.go | 4 +- .../sync/pending_attestations_queue_test.go | 16 +- beacon-chain/sync/pending_blocks_queue.go | 18 +- .../sync/pending_blocks_queue_test.go | 6 +- .../sync/rpc_beacon_blocks_by_range.go | 6 +- .../sync/rpc_beacon_blocks_by_range_test.go | 40 +-- .../sync/rpc_beacon_blocks_by_root_test.go | 6 +- beacon-chain/sync/rpc_goodbye.go | 6 +- beacon-chain/sync/rpc_goodbye_test.go | 6 +- beacon-chain/sync/rpc_ping.go | 12 +- beacon-chain/sync/rpc_ping_test.go | 10 +- beacon-chain/sync/rpc_send_request.go | 4 +- beacon-chain/sync/rpc_send_request_test.go | 10 +- beacon-chain/sync/rpc_status.go | 6 +- beacon-chain/sync/rpc_status_test.go | 20 +- beacon-chain/sync/subscriber.go | 8 +- .../sync/subscriber_beacon_attestation.go | 6 +- beacon-chain/sync/subscriber_test.go | 12 +- beacon-chain/sync/utils_test.go | 8 +- beacon-chain/sync/validate_aggregate_proof.go | 12 +- .../sync/validate_aggregate_proof_test.go | 12 +- .../sync/validate_attester_slashing_test.go | 4 +- .../sync/validate_beacon_attestation.go | 6 +- beacon-chain/sync/validate_beacon_blocks.go | 10 +- .../sync/validate_beacon_blocks_test.go | 6 +- .../sync/validate_proposer_slashing.go | 6 +- .../sync/validate_proposer_slashing_test.go | 4 +- .../sync/validate_sync_committee_message.go | 16 +- .../validate_sync_committee_message_test.go | 34 +- .../sync/validate_sync_contribution_proof.go | 12 +- .../validate_sync_contribution_proof_test.go | 52 +-- beacon-chain/sync/validate_voluntary_exit.go | 6 +- cmd/prysmctl/p2p/handshake.go | 4 +- cmd/prysmctl/p2p/mock_chain.go | 4 +- cmd/prysmctl/p2p/request_blocks.go | 6 +- config/params/config.go | 140 ++++---- config/params/loader.go | 4 +- config/params/network_config.go | 26 +- consensus-types/blocks/getters.go | 6 +- consensus-types/blocks/getters_test.go | 6 +- consensus-types/blocks/setters.go | 6 +- consensus-types/blocks/testing/mutator.go | 6 +- consensus-types/blocks/types.go | 6 +- consensus-types/interfaces/beacon_block.go | 10 +- consensus-types/mock/block.go | 12 +- consensus-types/primitives/committee_index.go | 2 +- .../primitives/committee_index_test.go | 2 +- consensus-types/primitives/domain.go | 2 +- consensus-types/primitives/domain_test.go | 2 +- consensus-types/primitives/epoch.go | 2 +- consensus-types/primitives/epoch_test.go | 58 +-- consensus-types/primitives/slot.go | 2 +- consensus-types/primitives/slot_test.go | 98 +++--- consensus-types/primitives/sszbytes.go | 2 +- consensus-types/primitives/sszbytes_test.go | 6 +- consensus-types/primitives/sszuint64.go | 2 +- consensus-types/primitives/sszuint64_test.go | 12 +- consensus-types/primitives/validator.go | 2 +- consensus-types/primitives/validator_test.go | 2 +- container/slice/slice.go | 18 +- container/slice/slice_test.go | 78 ++-- encoding/bytesutil/eth_types.go | 16 +- encoding/ssz/detect/configfork.go | 8 +- encoding/ssz/detect/configfork_test.go | 24 +- encoding/ssz/equality/deep_equal.go | 10 +- network/forks/fork.go | 16 +- network/forks/fork_test.go | 44 +-- network/forks/ordered.go | 6 +- network/forks/ordered_test.go | 32 +- proto/engine/v1/json_marshal_unmarshal.go | 4 +- .../engine/v1/json_marshal_unmarshal_test.go | 8 +- proto/migration/v1alpha1_to_v1_test.go | 74 ++-- proto/migration/v1alpha1_to_v2_test.go | 70 ++-- .../aggregation/testing/bitlistutils.go | 4 +- .../v1alpha1/attestation/attestation_utils.go | 6 +- .../attestation/attestation_utils_test.go | 12 +- .../v1alpha1/slashings/surround_votes_test.go | 4 +- testing/endtoend/endtoend_test.go | 8 +- testing/endtoend/evaluators/api_middleware.go | 4 +- .../beaconapi_evaluators/beacon_api.go | 40 +-- testing/endtoend/evaluators/data.go | 6 +- .../endtoend/evaluators/execution_engine.go | 6 +- testing/endtoend/evaluators/finality.go | 4 +- testing/endtoend/evaluators/fork.go | 4 +- testing/endtoend/evaluators/node.go | 4 +- testing/endtoend/evaluators/operations.go | 10 +- testing/endtoend/evaluators/slashing.go | 22 +- testing/endtoend/evaluators/validator.go | 4 +- testing/endtoend/policies/policies.go | 16 +- .../endtoend/slasher_simulator_e2e_test.go | 6 +- testing/endtoend/types/types.go | 8 +- .../simulator/attestation_generator.go | 8 +- testing/slasher/simulator/block_generator.go | 8 +- testing/slasher/simulator/simulator.go | 8 +- testing/slasher/simulator/simulator_test.go | 6 +- .../spectest/shared/altair/fork/transition.go | 4 +- .../shared/bellatrix/fork/transition.go | 4 +- .../shared/capella/fork/transition.go | 4 +- .../shared/common/forkchoice/builder.go | 12 +- .../shared/common/forkchoice/service.go | 4 +- .../phase0/shuffling/core/shuffle/shuffle.go | 10 +- .../core/shuffle/shuffle_test_format.go | 8 +- testing/spectest/utils/config_test.go | 6 +- testing/util/altair.go | 4 +- testing/util/attestation.go | 6 +- testing/util/bellatrix.go | 4 +- testing/util/block.go | 16 +- testing/util/block_test.go | 4 +- testing/util/capella_block.go | 8 +- testing/util/helpers.go | 8 +- testing/util/helpers_test.go | 4 +- time/slots/slotticker.go | 16 +- time/slots/slotticker_test.go | 6 +- time/slots/slottime.go | 52 +-- time/slots/slottime_test.go | 64 ++-- time/slots/testing/mock.go | 6 +- tools/benchmark-files-gen/main.go | 6 +- tools/blocktree/main.go | 6 +- tools/eth1voting/main.go | 4 +- tools/exploredb/main.go | 4 +- tools/extractor/main.go | 4 +- tools/forkchecker/forkchecker.go | 4 +- validator/accounts/accounts_list_test.go | 4 +- validator/accounts/testing/mock.go | 26 +- validator/client/aggregate.go | 12 +- validator/client/aggregate_test.go | 6 +- validator/client/attest.go | 14 +- validator/client/attest_protect_test.go | 10 +- validator/client/attest_test.go | 36 +- validator/client/beacon-api/activation.go | 9 +- .../client/beacon-api/attestation_data.go | 14 +- .../beacon-api/attestation_data_test.go | 8 +- .../client/beacon-api/beacon_api_helpers.go | 6 +- .../beacon-api/beacon_api_helpers_test.go | 10 +- .../beacon-api/beacon_api_validator_client.go | 4 +- .../beacon_api_validator_client_test.go | 10 +- .../beacon-api/beacon_block_proto_helpers.go | 20 +- validator/client/beacon-api/domain_data.go | 4 +- validator/client/beacon-api/doppelganger.go | 8 +- validator/client/beacon-api/duties.go | 62 ++-- validator/client/beacon-api/duties_test.go | 104 +++--- .../client/beacon-api/get_beacon_block.go | 8 +- .../get_beacon_block_altair_test.go | 4 +- .../get_beacon_block_bellatrix_test.go | 4 +- .../get_beacon_block_capella_test.go | 4 +- .../get_beacon_block_phase0_test.go | 4 +- validator/client/beacon-api/index.go | 4 +- validator/client/beacon-api/index_test.go | 4 +- validator/client/beacon-api/status.go | 12 +- validator/client/beacon-api/status_test.go | 12 +- .../beacon-api/subscribe_committee_subnets.go | 8 +- .../subscribe_committee_subnets_test.go | 64 ++-- validator/client/beacon-api/sync_committee.go | 4 +- .../client/beacon-api/sync_committee_test.go | 8 +- .../client/grpc-api/grpc_validator_client.go | 6 +- validator/client/iface/validator.go | 26 +- validator/client/iface/validator_client.go | 4 +- validator/client/log.go | 6 +- validator/client/metrics.go | 14 +- validator/client/metrics_test.go | 6 +- validator/client/propose.go | 16 +- validator/client/propose_protect_test.go | 4 +- validator/client/propose_test.go | 10 +- validator/client/registration_test.go | 10 +- validator/client/runner.go | 10 +- validator/client/runner_test.go | 38 +- validator/client/service.go | 6 +- validator/client/sync_committee.go | 14 +- validator/client/sync_committee_test.go | 50 +-- validator/client/testutil/helper.go | 6 +- validator/client/testutil/mock_validator.go | 28 +- validator/client/validator.go | 48 +-- validator/client/validator_test.go | 62 ++-- validator/client/wait_for_activation_test.go | 10 +- validator/db/iface/interface.go | 16 +- validator/db/kv/attester_protection.go | 26 +- validator/db/kv/attester_protection_test.go | 52 +-- .../db/kv/deprecated_attester_protection.go | 20 +- .../kv/deprecated_attester_protection_test.go | 10 +- .../migration_optimal_attester_protection.go | 12 +- ...ration_optimal_attester_protection_test.go | 12 +- validator/db/kv/proposer_protection.go | 24 +- validator/db/kv/proposer_protection_test.go | 42 +-- validator/db/kv/prune_attester_protection.go | 6 +- .../db/kv/prune_attester_protection_test.go | 12 +- validator/graffiti/parse_graffiti.go | 10 +- validator/graffiti/parse_graffiti_test.go | 6 +- .../remote-web3signer/v1/custom_mappers.go | 4 +- .../v1/custom_mappers_test.go | 4 +- .../export_test.go | 14 +- .../slashing-protection-history/helpers.go | 14 +- .../helpers_test.go | 6 +- .../slashing-protection-history/import.go | 10 +- .../import_test.go | 4 +- .../round_trip_test.go | 4 +- validator/testing/protection_history.go | 10 +- 555 files changed, 4696 insertions(+), 4958 deletions(-) delete mode 100644 beacon-chain/state/types/BUILD.bazel delete mode 100644 beacon-chain/state/types/types.go delete mode 100644 beacon-chain/state/types/types_test.go diff --git a/api/client/beacon/checkpoint.go b/api/client/beacon/checkpoint.go index 61c28bf746..421713966e 100644 --- a/api/client/beacon/checkpoint.go +++ b/api/client/beacon/checkpoint.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/ssz/detect" "github.com/prysmaticlabs/prysm/v3/io/file" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -54,7 +54,7 @@ func (o *OriginData) BlockBytes() []byte { return o.bb } -func fname(prefix string, vu *detect.VersionedUnmarshaler, slot types.Slot, root [32]byte) string { +func fname(prefix string, vu *detect.VersionedUnmarshaler, slot primitives.Slot, root [32]byte) string { return fmt.Sprintf("%s_%s_%s_%d-%#x.ssz", prefix, vu.Config.ConfigName, version.String(vu.Fork), slot, root) } @@ -122,7 +122,7 @@ func DownloadFinalizedData(ctx context.Context, client *Client) (*OriginData, er type WeakSubjectivityData struct { BlockRoot [32]byte StateRoot [32]byte - Epoch types.Epoch + Epoch primitives.Epoch } // CheckpointString returns the standard string representation of a Checkpoint. @@ -238,7 +238,7 @@ func computeBackwardsCompatible(ctx context.Context, client *Client) (*WeakSubje // this method downloads the head state, which can be used to find the correct chain config // and use prysm's helper methods to compute the latest weak subjectivity epoch. -func getWeakSubjectivityEpochFromHead(ctx context.Context, client *Client) (types.Epoch, error) { +func getWeakSubjectivityEpochFromHead(ctx context.Context, client *Client) (primitives.Epoch, error) { headBytes, err := client.GetState(ctx, IdHead) if err != nil { return 0, err diff --git a/api/client/beacon/checkpoint_test.go b/api/client/beacon/checkpoint_test.go index c274faf2dd..b0b9c6fd7c 100644 --- a/api/client/beacon/checkpoint_test.go +++ b/api/client/beacon/checkpoint_test.go @@ -19,7 +19,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/time/slots" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/ssz/detect" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -102,7 +102,7 @@ func TestFname(t *testing.T) { Config: params.MainnetConfig(), Fork: version.Phase0, } - slot := types.Slot(23) + slot := primitives.Slot(23) prefix := "block" var root [32]byte copy(root[:], []byte{0x23, 0x23, 0x23}) @@ -335,7 +335,7 @@ func TestGetWeakSubjectivityEpochFromHead(t *testing.T) { require.Equal(t, expectedEpoch, actualEpoch) } -func forkForEpoch(cfg *params.BeaconChainConfig, epoch types.Epoch) (*ethpb.Fork, error) { +func forkForEpoch(cfg *params.BeaconChainConfig, epoch primitives.Epoch) (*ethpb.Fork, error) { os := forks.NewOrderedSchedule(cfg) currentVersion, err := os.VersionForEpoch(epoch) if err != nil { @@ -357,7 +357,7 @@ func forkForEpoch(cfg *params.BeaconChainConfig, epoch types.Epoch) (*ethpb.Fork }, nil } -func defaultTestHeadState(t *testing.T, cfg *params.BeaconChainConfig) (state.BeaconState, types.Epoch) { +func defaultTestHeadState(t *testing.T, cfg *params.BeaconChainConfig) (state.BeaconState, primitives.Epoch) { st, err := util.NewBeaconStateAltair() require.NoError(t, err) diff --git a/api/client/beacon/client.go b/api/client/beacon/client.go index 05f54d7287..1563305c0f 100644 --- a/api/client/beacon/client.go +++ b/api/client/beacon/client.go @@ -21,7 +21,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" log "github.com/sirupsen/logrus" @@ -62,7 +62,7 @@ func IdFromRoot(r [32]byte) StateOrBlockId { // IdFromSlot encodes a Slot in the format expected by the API in places where a slot can be used to identify // a BeaconState or SignedBeaconBlock. -func IdFromSlot(s types.Slot) StateOrBlockId { +func IdFromSlot(s primitives.Slot) StateOrBlockId { return StateOrBlockId(strconv.FormatUint(uint64(s), 10)) } @@ -337,7 +337,7 @@ func (c *Client) GetWeakSubjectivity(ctx context.Context) (*WeakSubjectivityData return nil, err } return &WeakSubjectivityData{ - Epoch: types.Epoch(epoch), + Epoch: primitives.Epoch(epoch), BlockRoot: bytesutil.ToBytes32(blockRoot), StateRoot: bytesutil.ToBytes32(stateRoot), }, nil @@ -442,7 +442,7 @@ func (f *forkResponse) Fork() (*ethpb.Fork, error) { return ðpb.Fork{ CurrentVersion: cSlice, PreviousVersion: pSlice, - Epoch: types.Epoch(epoch), + Epoch: primitives.Epoch(epoch), }, nil } @@ -467,7 +467,7 @@ func (fsr *forkScheduleResponse) OrderedForkSchedule() (forks.OrderedSchedule, e version := bytesutil.ToBytes4(vSlice) ofs = append(ofs, forks.ForkScheduleEntry{ Version: version, - Epoch: types.Epoch(uint64(epoch)), + Epoch: primitives.Epoch(uint64(epoch)), }) } sort.Sort(ofs) diff --git a/api/client/builder/client.go b/api/client/builder/client.go index 88ad654fed..aed0fa2181 100644 --- a/api/client/builder/client.go +++ b/api/client/builder/client.go @@ -16,7 +16,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" "github.com/prysmaticlabs/prysm/v3/network" "github.com/prysmaticlabs/prysm/v3/network/authorization" @@ -87,7 +87,7 @@ var _ observer = &requestLogger{} // BuilderClient provides a collection of helper methods for calling Builder API endpoints. type BuilderClient interface { NodeURL() string - GetHeader(ctx context.Context, slot types.Slot, parentHash [32]byte, pubkey [48]byte) (SignedBid, error) + GetHeader(ctx context.Context, slot primitives.Slot, parentHash [32]byte, pubkey [48]byte) (SignedBid, error) RegisterValidator(ctx context.Context, svr []*ethpb.SignedValidatorRegistrationV1) error SubmitBlindedBlock(ctx context.Context, sb interfaces.SignedBeaconBlock) (interfaces.ExecutionData, error) Status(ctx context.Context) error @@ -189,9 +189,9 @@ func (c *Client) do(ctx context.Context, method string, path string, body io.Rea var execHeaderTemplate = template.Must(template.New("").Parse(getExecHeaderPath)) -func execHeaderPath(slot types.Slot, parentHash [32]byte, pubkey [48]byte) (string, error) { +func execHeaderPath(slot primitives.Slot, parentHash [32]byte, pubkey [48]byte) (string, error) { v := struct { - Slot types.Slot + Slot primitives.Slot ParentHash string Pubkey string }{ @@ -208,7 +208,7 @@ func execHeaderPath(slot types.Slot, parentHash [32]byte, pubkey [48]byte) (stri } // GetHeader is used by a proposing validator to request an execution payload header from the Builder node. -func (c *Client) GetHeader(ctx context.Context, slot types.Slot, parentHash [32]byte, pubkey [48]byte) (SignedBid, error) { +func (c *Client) GetHeader(ctx context.Context, slot primitives.Slot, parentHash [32]byte, pubkey [48]byte) (SignedBid, error) { path, err := execHeaderPath(slot, parentHash, pubkey) if err != nil { return nil, err diff --git a/api/client/builder/testing/mock.go b/api/client/builder/testing/mock.go index ea96f9bf86..3e3243bfc1 100644 --- a/api/client/builder/testing/mock.go +++ b/api/client/builder/testing/mock.go @@ -5,7 +5,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/api/client/builder" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -26,7 +26,7 @@ func (MockClient) NodeURL() string { } // GetHeader -- -func (MockClient) GetHeader(_ context.Context, _ types.Slot, _ [32]byte, _ [48]byte) (builder.SignedBid, error) { +func (MockClient) GetHeader(_ context.Context, _ primitives.Slot, _ [32]byte, _ [48]byte) (builder.SignedBid, error) { return nil, nil } diff --git a/beacon-chain/blockchain/chain_info.go b/beacon-chain/blockchain/chain_info.go index 1a560c4271..95a8f8cce1 100644 --- a/beacon-chain/blockchain/chain_info.go +++ b/beacon-chain/blockchain/chain_info.go @@ -13,7 +13,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -39,7 +39,7 @@ type HeadUpdater interface { // TimeFetcher retrieves the Ethereum consensus data that's related to time. type TimeFetcher interface { GenesisTime() time.Time - CurrentSlot() types.Slot + CurrentSlot() primitives.Slot } // GenesisFetcher retrieves the Ethereum consensus data related to its genesis. @@ -50,16 +50,16 @@ type GenesisFetcher interface { // HeadFetcher defines a common interface for methods in blockchain service which // directly retrieve head related data. type HeadFetcher interface { - HeadSlot() types.Slot + HeadSlot() primitives.Slot HeadRoot(ctx context.Context) ([]byte, error) HeadBlock(ctx context.Context) (interfaces.SignedBeaconBlock, error) HeadState(ctx context.Context) (state.BeaconState, error) - HeadValidatorsIndices(ctx context.Context, epoch types.Epoch) ([]types.ValidatorIndex, error) + HeadValidatorsIndices(ctx context.Context, epoch primitives.Epoch) ([]primitives.ValidatorIndex, error) HeadGenesisValidatorsRoot() [32]byte HeadETH1Data() *ethpb.Eth1Data - HeadPublicKeyToValidatorIndex(pubKey [fieldparams.BLSPubkeyLength]byte) (types.ValidatorIndex, bool) - HeadValidatorIndexToPublicKey(ctx context.Context, index types.ValidatorIndex) ([fieldparams.BLSPubkeyLength]byte, error) - ChainHeads() ([][32]byte, []types.Slot) + HeadPublicKeyToValidatorIndex(pubKey [fieldparams.BLSPubkeyLength]byte) (primitives.ValidatorIndex, bool) + HeadValidatorIndexToPublicKey(ctx context.Context, index primitives.ValidatorIndex) ([fieldparams.BLSPubkeyLength]byte, error) + ChainHeads() ([][32]byte, []primitives.Slot) HeadSyncCommitteeFetcher HeadDomainFetcher } @@ -118,7 +118,7 @@ func (s *Service) BestJustifiedCheckpt() *ethpb.Checkpoint { } // HeadSlot returns the slot of the head of the chain. -func (s *Service) HeadSlot() types.Slot { +func (s *Service) HeadSlot() primitives.Slot { s.headLock.RLock() defer s.headLock.RUnlock() @@ -188,12 +188,12 @@ func (s *Service) HeadState(ctx context.Context) (state.BeaconState, error) { } // HeadValidatorsIndices returns a list of active validator indices from the head view of a given epoch. -func (s *Service) HeadValidatorsIndices(ctx context.Context, epoch types.Epoch) ([]types.ValidatorIndex, error) { +func (s *Service) HeadValidatorsIndices(ctx context.Context, epoch primitives.Epoch) ([]primitives.ValidatorIndex, error) { s.headLock.RLock() defer s.headLock.RUnlock() if !s.hasHeadState() { - return []types.ValidatorIndex{}, nil + return []primitives.ValidatorIndex{}, nil } return helpers.ActiveValidatorIndices(ctx, s.headState(ctx), epoch) } @@ -265,12 +265,12 @@ func (s *Service) IsCanonical(ctx context.Context, blockRoot [32]byte) (bool, er // ChainHeads returns all possible chain heads (leaves of fork choice tree). // Heads roots and heads slots are returned. -func (s *Service) ChainHeads() ([][32]byte, []types.Slot) { +func (s *Service) ChainHeads() ([][32]byte, []primitives.Slot) { return s.cfg.ForkChoiceStore.Tips() } // HeadPublicKeyToValidatorIndex returns the validator index of the `pubkey` in current head state. -func (s *Service) HeadPublicKeyToValidatorIndex(pubKey [fieldparams.BLSPubkeyLength]byte) (types.ValidatorIndex, bool) { +func (s *Service) HeadPublicKeyToValidatorIndex(pubKey [fieldparams.BLSPubkeyLength]byte) (primitives.ValidatorIndex, bool) { s.headLock.RLock() defer s.headLock.RUnlock() if !s.hasHeadState() { @@ -280,7 +280,7 @@ func (s *Service) HeadPublicKeyToValidatorIndex(pubKey [fieldparams.BLSPubkeyLen } // HeadValidatorIndexToPublicKey returns the pubkey of the validator `index` in current head state. -func (s *Service) HeadValidatorIndexToPublicKey(_ context.Context, index types.ValidatorIndex) ([fieldparams.BLSPubkeyLength]byte, error) { +func (s *Service) HeadValidatorIndexToPublicKey(_ context.Context, index primitives.ValidatorIndex) ([fieldparams.BLSPubkeyLength]byte, error) { s.headLock.RLock() defer s.headLock.RUnlock() if !s.hasHeadState() { diff --git a/beacon-chain/blockchain/chain_info_test.go b/beacon-chain/blockchain/chain_info_test.go index 3e9ab287d4..b233de3d2c 100644 --- a/beacon-chain/blockchain/chain_info_test.go +++ b/beacon-chain/blockchain/chain_info_test.go @@ -14,7 +14,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -33,7 +33,7 @@ var _ ForkFetcher = (*Service)(nil) // insert into forkchoice func prepareForkchoiceState( _ context.Context, - slot types.Slot, + slot primitives.Slot, blockRoot [32]byte, parentRoot [32]byte, payloadHash [32]byte, @@ -74,7 +74,7 @@ func TestHeadRoot_Nil(t *testing.T) { func TestService_ForkChoiceStore(t *testing.T) { c := &Service{cfg: &config{ForkChoiceStore: doublylinkedtree.New()}} p := c.ForkChoiceStore() - require.Equal(t, types.Epoch(0), p.FinalizedCheckpoint().Epoch) + require.Equal(t, primitives.Epoch(0), p.FinalizedCheckpoint().Epoch) } func TestFinalizedCheckpt_GenesisRootOk(t *testing.T) { @@ -129,7 +129,7 @@ func TestHeadSlot_CanRetrieve(t *testing.T) { require.NoError(t, err) b.Block().SetSlot(100) c.head = &head{block: b, state: s} - assert.Equal(t, types.Slot(100), c.HeadSlot()) + assert.Equal(t, primitives.Slot(100), c.HeadSlot()) } func TestHeadRoot_CanRetrieve(t *testing.T) { @@ -340,7 +340,7 @@ func TestService_ChainHeads(t *testing.T) { roots, slots := c.ChainHeads() require.Equal(t, 3, len(roots)) - rootMap := map[[32]byte]types.Slot{{'c'}: 102, {'d'}: 103, {'e'}: 104} + rootMap := map[[32]byte]primitives.Slot{{'c'}: 102, {'d'}: 103, {'e'}: 104} for i, root := range roots { slot, ok := rootMap[root] require.Equal(t, true, ok) @@ -361,7 +361,7 @@ func TestService_HeadPublicKeyToValidatorIndex(t *testing.T) { i, e := c.HeadPublicKeyToValidatorIndex(bytesutil.ToBytes48(v.PublicKey)) require.Equal(t, true, e) - require.Equal(t, types.ValidatorIndex(0), i) + require.Equal(t, primitives.ValidatorIndex(0), i) } func TestService_HeadPublicKeyToValidatorIndexNil(t *testing.T) { @@ -370,12 +370,12 @@ func TestService_HeadPublicKeyToValidatorIndexNil(t *testing.T) { idx, e := c.HeadPublicKeyToValidatorIndex([fieldparams.BLSPubkeyLength]byte{}) require.Equal(t, false, e) - require.Equal(t, types.ValidatorIndex(0), idx) + require.Equal(t, primitives.ValidatorIndex(0), idx) c.head = &head{state: nil} i, e := c.HeadPublicKeyToValidatorIndex([fieldparams.BLSPubkeyLength]byte{}) require.Equal(t, false, e) - require.Equal(t, types.ValidatorIndex(0), i) + require.Equal(t, primitives.ValidatorIndex(0), i) } func TestService_HeadValidatorIndexToPublicKey(t *testing.T) { diff --git a/beacon-chain/blockchain/execution_engine.go b/beacon-chain/blockchain/execution_engine.go index bf35cc61dd..806be8c15e 100644 --- a/beacon-chain/blockchain/execution_engine.go +++ b/beacon-chain/blockchain/execution_engine.go @@ -16,7 +16,7 @@ import ( consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" payloadattribute "github.com/prysmaticlabs/prysm/v3/consensus-types/payload-attribute" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -250,7 +250,7 @@ func (s *Service) notifyNewPayload(ctx context.Context, postStateVersion int, // getPayloadAttributes returns the payload attributes for the given state and slot. // The attribute is required to initiate a payload build process in the context of an `engine_forkchoiceUpdated` call. -func (s *Service) getPayloadAttribute(ctx context.Context, st state.BeaconState, slot types.Slot) (bool, payloadattribute.Attributer, types.ValidatorIndex) { +func (s *Service) getPayloadAttribute(ctx context.Context, st state.BeaconState, slot primitives.Slot) (bool, payloadattribute.Attributer, primitives.ValidatorIndex) { emptyAttri := payloadattribute.EmptyWithVersion(st.Version()) // Root is `[32]byte{}` since we are retrieving proposer ID of a given slot. During insertion at assignment the root was not known. proposerID, _, ok := s.cfg.ProposerSlotIndexCache.GetProposerPayloadIDs(slot, [32]byte{} /* root */) diff --git a/beacon-chain/blockchain/execution_engine_test.go b/beacon-chain/blockchain/execution_engine_test.go index 9aed45e932..419fc2996e 100644 --- a/beacon-chain/blockchain/execution_engine_test.go +++ b/beacon-chain/blockchain/execution_engine_test.go @@ -21,7 +21,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" v1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -795,11 +795,11 @@ func Test_GetPayloadAttribute(t *testing.T) { st, _ := util.DeterministicGenesisStateBellatrix(t, 1) hasPayload, _, vId := service.getPayloadAttribute(ctx, st, 0) require.Equal(t, false, hasPayload) - require.Equal(t, types.ValidatorIndex(0), vId) + require.Equal(t, primitives.ValidatorIndex(0), vId) // Cache hit, advance state, no fee recipient - suggestedVid := types.ValidatorIndex(1) - slot := types.Slot(1) + suggestedVid := primitives.ValidatorIndex(1) + slot := primitives.Slot(1) service.cfg.ProposerSlotIndexCache.SetProposerAndPayloadIDs(slot, suggestedVid, [8]byte{}, [32]byte{}) hook := logTest.NewGlobal() hasPayload, attr, vId := service.getPayloadAttribute(ctx, st, slot) @@ -810,7 +810,7 @@ func Test_GetPayloadAttribute(t *testing.T) { // Cache hit, advance state, has fee recipient suggestedAddr := common.HexToAddress("123") - require.NoError(t, service.cfg.BeaconDB.SaveFeeRecipientsByValidatorIDs(ctx, []types.ValidatorIndex{suggestedVid}, []common.Address{suggestedAddr})) + require.NoError(t, service.cfg.BeaconDB.SaveFeeRecipientsByValidatorIDs(ctx, []primitives.ValidatorIndex{suggestedVid}, []common.Address{suggestedAddr})) service.cfg.ProposerSlotIndexCache.SetProposerAndPayloadIDs(slot, suggestedVid, [8]byte{}, [32]byte{}) hasPayload, attr, vId = service.getPayloadAttribute(ctx, st, slot) require.Equal(t, true, hasPayload) @@ -833,11 +833,11 @@ func Test_GetPayloadAttributeV2(t *testing.T) { st, _ := util.DeterministicGenesisStateCapella(t, 1) hasPayload, _, vId := service.getPayloadAttribute(ctx, st, 0) require.Equal(t, false, hasPayload) - require.Equal(t, types.ValidatorIndex(0), vId) + require.Equal(t, primitives.ValidatorIndex(0), vId) // Cache hit, advance state, no fee recipient - suggestedVid := types.ValidatorIndex(1) - slot := types.Slot(1) + suggestedVid := primitives.ValidatorIndex(1) + slot := primitives.Slot(1) service.cfg.ProposerSlotIndexCache.SetProposerAndPayloadIDs(slot, suggestedVid, [8]byte{}, [32]byte{}) hook := logTest.NewGlobal() hasPayload, attr, vId := service.getPayloadAttribute(ctx, st, slot) @@ -851,7 +851,7 @@ func Test_GetPayloadAttributeV2(t *testing.T) { // Cache hit, advance state, has fee recipient suggestedAddr := common.HexToAddress("123") - require.NoError(t, service.cfg.BeaconDB.SaveFeeRecipientsByValidatorIDs(ctx, []types.ValidatorIndex{suggestedVid}, []common.Address{suggestedAddr})) + require.NoError(t, service.cfg.BeaconDB.SaveFeeRecipientsByValidatorIDs(ctx, []primitives.ValidatorIndex{suggestedVid}, []common.Address{suggestedAddr})) service.cfg.ProposerSlotIndexCache.SetProposerAndPayloadIDs(slot, suggestedVid, [8]byte{}, [32]byte{}) hasPayload, attr, vId = service.getPayloadAttribute(ctx, st, slot) require.Equal(t, true, hasPayload) diff --git a/beacon-chain/blockchain/head.go b/beacon-chain/blockchain/head.go index 2b697c7b43..e9d6c9e48d 100644 --- a/beacon-chain/blockchain/head.go +++ b/beacon-chain/blockchain/head.go @@ -15,7 +15,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/math" ethpbv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" @@ -241,7 +241,7 @@ func (s *Service) setHeadInitialSync(root [32]byte, block interfaces.SignedBeaco // This returns the head slot. // This is a lock free version. -func (s *Service) headSlot() types.Slot { +func (s *Service) headSlot() primitives.Slot { if s.head == nil || s.head.block == nil || s.head.block.Block() == nil { return 0 } @@ -285,14 +285,14 @@ func (s *Service) headGenesisValidatorsRoot() [32]byte { // This returns the validator referenced by the provided index in // the head state. // This is a lock free version. -func (s *Service) headValidatorAtIndex(index types.ValidatorIndex) (state.ReadOnlyValidator, error) { +func (s *Service) headValidatorAtIndex(index primitives.ValidatorIndex) (state.ReadOnlyValidator, error) { return s.head.state.ValidatorAtIndexReadOnly(index) } // This returns the validator index referenced by the provided pubkey in // the head state. // This is a lock free version. -func (s *Service) headValidatorIndexAtPubkey(pubKey [fieldparams.BLSPubkeyLength]byte) (types.ValidatorIndex, bool) { +func (s *Service) headValidatorIndexAtPubkey(pubKey [fieldparams.BLSPubkeyLength]byte) (primitives.ValidatorIndex, bool) { return s.head.state.ValidatorIndexByPubkey(pubKey) } @@ -306,7 +306,7 @@ func (s *Service) hasHeadState() bool { // chain head is determined, set, and saved to disk. func (s *Service) notifyNewHeadEvent( ctx context.Context, - newHeadSlot types.Slot, + newHeadSlot primitives.Slot, newHeadState state.BeaconState, newHeadStateRoot, newHeadRoot []byte, @@ -314,7 +314,7 @@ func (s *Service) notifyNewHeadEvent( previousDutyDependentRoot := s.originBlockRoot[:] currentDutyDependentRoot := s.originBlockRoot[:] - var previousDutyEpoch types.Epoch + var previousDutyEpoch primitives.Epoch currentDutyEpoch := slots.ToEpoch(newHeadSlot) if currentDutyEpoch > 0 { previousDutyEpoch = currentDutyEpoch.Sub(1) diff --git a/beacon-chain/blockchain/head_sync_committee_info.go b/beacon-chain/blockchain/head_sync_committee_info.go index 2318899087..ea9ace948b 100644 --- a/beacon-chain/blockchain/head_sync_committee_info.go +++ b/beacon-chain/blockchain/head_sync_committee_info.go @@ -13,7 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" ) @@ -24,30 +24,30 @@ var syncCommitteeHeadStateCache = cache.NewSyncCommitteeHeadState() // HeadSyncCommitteeFetcher is the interface that wraps the head sync committee related functions. // The head sync committee functions return callers sync committee indices and public keys with respect to current head state. type HeadSyncCommitteeFetcher interface { - HeadSyncCommitteeIndices(ctx context.Context, index types.ValidatorIndex, slot types.Slot) ([]types.CommitteeIndex, error) - HeadSyncCommitteePubKeys(ctx context.Context, slot types.Slot, committeeIndex types.CommitteeIndex) ([][]byte, error) + HeadSyncCommitteeIndices(ctx context.Context, index primitives.ValidatorIndex, slot primitives.Slot) ([]primitives.CommitteeIndex, error) + HeadSyncCommitteePubKeys(ctx context.Context, slot primitives.Slot, committeeIndex primitives.CommitteeIndex) ([][]byte, error) } // HeadDomainFetcher is the interface that wraps the head sync domain related functions. // The head sync committee domain functions return callers domain data with respect to slot and head state. type HeadDomainFetcher interface { - HeadSyncCommitteeDomain(ctx context.Context, slot types.Slot) ([]byte, error) - HeadSyncSelectionProofDomain(ctx context.Context, slot types.Slot) ([]byte, error) - HeadSyncContributionProofDomain(ctx context.Context, slot types.Slot) ([]byte, error) + HeadSyncCommitteeDomain(ctx context.Context, slot primitives.Slot) ([]byte, error) + HeadSyncSelectionProofDomain(ctx context.Context, slot primitives.Slot) ([]byte, error) + HeadSyncContributionProofDomain(ctx context.Context, slot primitives.Slot) ([]byte, error) } // HeadSyncCommitteeDomain returns the head sync committee domain using current head state advanced up to `slot`. -func (s *Service) HeadSyncCommitteeDomain(ctx context.Context, slot types.Slot) ([]byte, error) { +func (s *Service) HeadSyncCommitteeDomain(ctx context.Context, slot primitives.Slot) ([]byte, error) { return s.domainWithHeadState(ctx, slot, params.BeaconConfig().DomainSyncCommittee) } // HeadSyncSelectionProofDomain returns the head sync committee domain using current head state advanced up to `slot`. -func (s *Service) HeadSyncSelectionProofDomain(ctx context.Context, slot types.Slot) ([]byte, error) { +func (s *Service) HeadSyncSelectionProofDomain(ctx context.Context, slot primitives.Slot) ([]byte, error) { return s.domainWithHeadState(ctx, slot, params.BeaconConfig().DomainSyncCommitteeSelectionProof) } // HeadSyncContributionProofDomain returns the head sync committee domain using current head state advanced up to `slot`. -func (s *Service) HeadSyncContributionProofDomain(ctx context.Context, slot types.Slot) ([]byte, error) { +func (s *Service) HeadSyncContributionProofDomain(ctx context.Context, slot primitives.Slot) ([]byte, error) { return s.domainWithHeadState(ctx, slot, params.BeaconConfig().DomainContributionAndProof) } @@ -61,7 +61,7 @@ func (s *Service) HeadSyncContributionProofDomain(ctx context.Context, slot type // [compute_start_slot_at_epoch(epoch) - 1, compute_start_slot_at_epoch(epoch) + SLOTS_PER_EPOCH - 1) // rather than for the range // [compute_start_slot_at_epoch(epoch), compute_start_slot_at_epoch(epoch) + SLOTS_PER_EPOCH) -func (s *Service) HeadSyncCommitteeIndices(ctx context.Context, index types.ValidatorIndex, slot types.Slot) ([]types.CommitteeIndex, error) { +func (s *Service) HeadSyncCommitteeIndices(ctx context.Context, index primitives.ValidatorIndex, slot primitives.Slot) ([]primitives.CommitteeIndex, error) { nextSlotEpoch := slots.ToEpoch(slot + 1) currentEpoch := slots.ToEpoch(slot) @@ -79,7 +79,7 @@ func (s *Service) HeadSyncCommitteeIndices(ctx context.Context, index types.Vali // headCurrentSyncCommitteeIndices returns the input validator `index`'s position indices in the current sync committee with respect to `slot`. // Head state advanced up to `slot` is used for calculation. -func (s *Service) headCurrentSyncCommitteeIndices(ctx context.Context, index types.ValidatorIndex, slot types.Slot) ([]types.CommitteeIndex, error) { +func (s *Service) headCurrentSyncCommitteeIndices(ctx context.Context, index primitives.ValidatorIndex, slot primitives.Slot) ([]primitives.CommitteeIndex, error) { headState, err := s.getSyncCommitteeHeadState(ctx, slot) if err != nil { return nil, err @@ -89,7 +89,7 @@ func (s *Service) headCurrentSyncCommitteeIndices(ctx context.Context, index typ // headNextSyncCommitteeIndices returns the input validator `index`'s position indices in the next sync committee with respect to `slot`. // Head state advanced up to `slot` is used for calculation. -func (s *Service) headNextSyncCommitteeIndices(ctx context.Context, index types.ValidatorIndex, slot types.Slot) ([]types.CommitteeIndex, error) { +func (s *Service) headNextSyncCommitteeIndices(ctx context.Context, index primitives.ValidatorIndex, slot primitives.Slot) ([]primitives.CommitteeIndex, error) { headState, err := s.getSyncCommitteeHeadState(ctx, slot) if err != nil { return nil, err @@ -99,7 +99,7 @@ func (s *Service) headNextSyncCommitteeIndices(ctx context.Context, index types. // HeadSyncCommitteePubKeys returns the head sync committee public keys with respect to `slot` and subcommittee index `committeeIndex`. // Head state advanced up to `slot` is used for calculation. -func (s *Service) HeadSyncCommitteePubKeys(ctx context.Context, slot types.Slot, committeeIndex types.CommitteeIndex) ([][]byte, error) { +func (s *Service) HeadSyncCommitteePubKeys(ctx context.Context, slot primitives.Slot, committeeIndex primitives.CommitteeIndex) ([][]byte, error) { headState, err := s.getSyncCommitteeHeadState(ctx, slot) if err != nil { return nil, err @@ -125,7 +125,7 @@ func (s *Service) HeadSyncCommitteePubKeys(ctx context.Context, slot types.Slot, } // returns calculated domain using input `domain` and `slot`. -func (s *Service) domainWithHeadState(ctx context.Context, slot types.Slot, domain [4]byte) ([]byte, error) { +func (s *Service) domainWithHeadState(ctx context.Context, slot primitives.Slot, domain [4]byte) ([]byte, error) { headState, err := s.getSyncCommitteeHeadState(ctx, slot) if err != nil { return nil, err @@ -135,7 +135,7 @@ func (s *Service) domainWithHeadState(ctx context.Context, slot types.Slot, doma // returns the head state that is advanced up to `slot`. It utilizes the cache `syncCommitteeHeadState` by retrieving using `slot` as key. // For the cache miss, it processes head state up to slot and fill the cache with `slot` as key. -func (s *Service) getSyncCommitteeHeadState(ctx context.Context, slot types.Slot) (state.BeaconState, error) { +func (s *Service) getSyncCommitteeHeadState(ctx context.Context, slot primitives.Slot) (state.BeaconState, error) { var headState state.BeaconState var err error mLock := async.NewMultilock(fmt.Sprintf("%s-%d", "syncHeadState", slot)) diff --git a/beacon-chain/blockchain/head_sync_committee_info_test.go b/beacon-chain/blockchain/head_sync_committee_info_test.go index 2d9d4a9339..7231222769 100644 --- a/beacon-chain/blockchain/head_sync_committee_info_test.go +++ b/beacon-chain/blockchain/head_sync_committee_info_test.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/cache" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -20,18 +20,18 @@ func TestService_HeadSyncCommitteeIndices(t *testing.T) { // Current period slot := 2*uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod)*uint64(params.BeaconConfig().SlotsPerEpoch) + 1 - a, err := c.HeadSyncCommitteeIndices(context.Background(), 0, types.Slot(slot)) + a, err := c.HeadSyncCommitteeIndices(context.Background(), 0, primitives.Slot(slot)) require.NoError(t, err) // Current period where slot-2 across EPOCHS_PER_SYNC_COMMITTEE_PERIOD slot = 3*uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod)*uint64(params.BeaconConfig().SlotsPerEpoch) - 2 - b, err := c.HeadSyncCommitteeIndices(context.Background(), 0, types.Slot(slot)) + b, err := c.HeadSyncCommitteeIndices(context.Background(), 0, primitives.Slot(slot)) require.NoError(t, err) require.DeepEqual(t, a, b) // Next period where slot-1 across EPOCHS_PER_SYNC_COMMITTEE_PERIOD slot = 3*uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod)*uint64(params.BeaconConfig().SlotsPerEpoch) - 1 - b, err = c.HeadSyncCommitteeIndices(context.Background(), 0, types.Slot(slot)) + b, err = c.HeadSyncCommitteeIndices(context.Background(), 0, primitives.Slot(slot)) require.NoError(t, err) require.DeepNotEqual(t, a, b) } @@ -43,7 +43,7 @@ func TestService_headCurrentSyncCommitteeIndices(t *testing.T) { // Process slot up to `EpochsPerSyncCommitteePeriod` so it can `ProcessSyncCommitteeUpdates`. slot := uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod)*uint64(params.BeaconConfig().SlotsPerEpoch) + 1 - indices, err := c.headCurrentSyncCommitteeIndices(context.Background(), 0, types.Slot(slot)) + indices, err := c.headCurrentSyncCommitteeIndices(context.Background(), 0, primitives.Slot(slot)) require.NoError(t, err) // NextSyncCommittee becomes CurrentSyncCommittee so it should be empty by default. @@ -57,7 +57,7 @@ func TestService_headNextSyncCommitteeIndices(t *testing.T) { // Process slot up to `EpochsPerSyncCommitteePeriod` so it can `ProcessSyncCommitteeUpdates`. slot := uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod)*uint64(params.BeaconConfig().SlotsPerEpoch) + 1 - indices, err := c.headNextSyncCommitteeIndices(context.Background(), 0, types.Slot(slot)) + indices, err := c.headNextSyncCommitteeIndices(context.Background(), 0, primitives.Slot(slot)) require.NoError(t, err) // NextSyncCommittee should be be empty after `ProcessSyncCommitteeUpdates`. Validator should get indices. @@ -71,7 +71,7 @@ func TestService_HeadSyncCommitteePubKeys(t *testing.T) { // Process slot up to 2 * `EpochsPerSyncCommitteePeriod` so it can run `ProcessSyncCommitteeUpdates` twice. slot := uint64(2*params.BeaconConfig().EpochsPerSyncCommitteePeriod)*uint64(params.BeaconConfig().SlotsPerEpoch) + 1 - pubkeys, err := c.HeadSyncCommitteePubKeys(context.Background(), types.Slot(slot), 0) + pubkeys, err := c.HeadSyncCommitteePubKeys(context.Background(), primitives.Slot(slot), 0) require.NoError(t, err) // Any subcommittee should match the subcommittee size. diff --git a/beacon-chain/blockchain/head_test.go b/beacon-chain/blockchain/head_test.go index 02b16adb9c..4bab05bd3a 100644 --- a/beacon-chain/blockchain/head_test.go +++ b/beacon-chain/blockchain/head_test.go @@ -15,7 +15,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/features" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpbv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -36,7 +36,7 @@ func TestSaveHead_Same(t *testing.T) { require.NoError(t, err) st, _ := util.DeterministicGenesisState(t, 1) require.NoError(t, service.saveHead(context.Background(), r, b, st)) - assert.Equal(t, types.Slot(0), service.headSlot(), "Head did not stay the same") + assert.Equal(t, primitives.Slot(0), service.headSlot(), "Head did not stay the same") assert.Equal(t, r, service.headRoot(), "Head did not stay the same") } @@ -79,7 +79,7 @@ func TestSaveHead_Different(t *testing.T) { require.NoError(t, service.cfg.BeaconDB.SaveState(context.Background(), headState, newRoot)) require.NoError(t, service.saveHead(context.Background(), newRoot, wsb, headState)) - assert.Equal(t, types.Slot(1), service.HeadSlot(), "Head did not change") + assert.Equal(t, primitives.Slot(1), service.HeadSlot(), "Head did not change") cachedRoot, err := service.HeadRoot(context.Background()) require.NoError(t, err) @@ -134,7 +134,7 @@ func TestSaveHead_Different_Reorg(t *testing.T) { require.NoError(t, service.cfg.BeaconDB.SaveState(context.Background(), headState, newRoot)) require.NoError(t, service.saveHead(context.Background(), newRoot, wsb, headState)) - assert.Equal(t, types.Slot(1), service.HeadSlot(), "Head did not change") + assert.Equal(t, primitives.Slot(1), service.HeadSlot(), "Head did not change") cachedRoot, err := service.HeadRoot(context.Background()) require.NoError(t, err) diff --git a/beacon-chain/blockchain/metrics.go b/beacon-chain/blockchain/metrics.go index fbe638d5a5..2e96ad9ecf 100644 --- a/beacon-chain/blockchain/metrics.go +++ b/beacon-chain/blockchain/metrics.go @@ -11,7 +11,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -216,7 +216,7 @@ var ( ) // reportSlotMetrics reports slot related metrics. -func reportSlotMetrics(stateSlot, headSlot, clockSlot types.Slot, finalizedCheckpoint *ethpb.Checkpoint) { +func reportSlotMetrics(stateSlot, headSlot, clockSlot primitives.Slot, finalizedCheckpoint *ethpb.Checkpoint) { clockTimeSlot.Set(float64(clockSlot)) beaconSlot.Set(float64(stateSlot)) beaconHeadSlot.Set(float64(headSlot)) @@ -228,7 +228,7 @@ func reportSlotMetrics(stateSlot, headSlot, clockSlot types.Slot, finalizedCheck // reportEpochMetrics reports epoch related metrics. func reportEpochMetrics(ctx context.Context, postState, headState state.BeaconState) error { - currentEpoch := types.Epoch(postState.Slot() / params.BeaconConfig().SlotsPerEpoch) + currentEpoch := primitives.Epoch(postState.Slot() / params.BeaconConfig().SlotsPerEpoch) // Validator instances pendingInstances := 0 @@ -247,7 +247,7 @@ func reportEpochMetrics(ctx context.Context, postState, headState state.BeaconSt slashingEffectiveBalance := uint64(0) for i, validator := range postState.Validators() { - bal, err := postState.BalanceAtIndex(types.ValidatorIndex(i)) + bal, err := postState.BalanceAtIndex(primitives.ValidatorIndex(i)) if err != nil { log.WithError(err).Error("Could not load validator balance") continue diff --git a/beacon-chain/blockchain/pow_block.go b/beacon-chain/blockchain/pow_block.go index f5dadeeb5c..809b117196 100644 --- a/beacon-chain/blockchain/pow_block.go +++ b/beacon-chain/blockchain/pow_block.go @@ -13,7 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/runtime/version" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -117,7 +117,7 @@ func (s *Service) getBlkParentHashAndTD(ctx context.Context, blkHash []byte) ([] // assert compute_epoch_at_slot(block.slot) >= TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH // assert block.body.execution_payload.parent_hash == TERMINAL_BLOCK_HASH // return -func canUseValidatedTerminalBlockHash(blkSlot types.Slot, payload interfaces.ExecutionData) (bool, error) { +func canUseValidatedTerminalBlockHash(blkSlot primitives.Slot, payload interfaces.ExecutionData) (bool, error) { if bytesutil.ToBytes32(params.BeaconConfig().TerminalBlockHash.Bytes()) == [32]byte{} { return false, nil } diff --git a/beacon-chain/blockchain/process_attestation_helpers.go b/beacon-chain/blockchain/process_attestation_helpers.go index 550986fe35..c8afac4b60 100644 --- a/beacon-chain/blockchain/process_attestation_helpers.go +++ b/beacon-chain/blockchain/process_attestation_helpers.go @@ -11,7 +11,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -60,9 +60,9 @@ func (s *Service) getAttPreState(ctx context.Context, c *ethpb.Checkpoint) (stat // verifyAttTargetEpoch validates attestation is from the current or previous epoch. func verifyAttTargetEpoch(_ context.Context, genesisTime, nowTime uint64, c *ethpb.Checkpoint) error { - currentSlot := types.Slot((nowTime - genesisTime) / params.BeaconConfig().SecondsPerSlot) + currentSlot := primitives.Slot((nowTime - genesisTime) / params.BeaconConfig().SecondsPerSlot) currentEpoch := slots.ToEpoch(currentSlot) - var prevEpoch types.Epoch + var prevEpoch primitives.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 849be0058d..16f0c78ca0 100644 --- a/beacon-chain/blockchain/process_attestation_test.go +++ b/beacon-chain/blockchain/process_attestation_test.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -231,7 +231,7 @@ func TestStore_UpdateCheckpointState(t *testing.T) { service, err := NewService(ctx, opts...) require.NoError(t, err) - epoch := types.Epoch(1) + epoch := primitives.Epoch(1) baseState, _ := util.DeterministicGenesisState(t, 1) checkpoint := ðpb.Checkpoint{Epoch: epoch, Root: bytesutil.PadTo([]byte("hi"), fieldparams.RootLength)} require.NoError(t, service.cfg.BeaconDB.SaveState(ctx, baseState, bytesutil.ToBytes32(checkpoint.Root))) diff --git a/beacon-chain/blockchain/process_block.go b/beacon-chain/blockchain/process_block.go index 298d2bd824..18e8f51a75 100644 --- a/beacon-chain/blockchain/process_block.go +++ b/beacon-chain/blockchain/process_block.go @@ -19,7 +19,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" @@ -563,7 +563,7 @@ func (s *Service) InsertSlashingsToForkChoiceStore(ctx context.Context, slashing for _, slashing := range slashings { indices := blocks.SlashableAttesterIndices(slashing) for _, index := range indices { - s.ForkChoicer().InsertSlashedIndex(ctx, types.ValidatorIndex(index)) + s.ForkChoicer().InsertSlashedIndex(ctx, primitives.ValidatorIndex(index)) } } } diff --git a/beacon-chain/blockchain/process_block_helpers.go b/beacon-chain/blockchain/process_block_helpers.go index 729864b98a..714524a5bd 100644 --- a/beacon-chain/blockchain/process_block_helpers.go +++ b/beacon-chain/blockchain/process_block_helpers.go @@ -11,7 +11,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" mathutil "github.com/prysmaticlabs/prysm/v3/math" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" @@ -21,7 +21,7 @@ import ( ) // CurrentSlot returns the current slot based on time. -func (s *Service) CurrentSlot() types.Slot { +func (s *Service) CurrentSlot() primitives.Slot { return slots.CurrentSlot(uint64(s.genesisTime.Unix())) } @@ -194,7 +194,7 @@ func (s *Service) updateFinalized(ctx context.Context, cp *ethpb.Checkpoint) err // else: // # root is older than queried slot, thus a skip slot. Return most recent root prior to slot // return root -func (s *Service) ancestor(ctx context.Context, root []byte, slot types.Slot) ([]byte, error) { +func (s *Service) ancestor(ctx context.Context, root []byte, slot primitives.Slot) ([]byte, error) { ctx, span := trace.StartSpan(ctx, "blockChain.ancestor") defer span.End() @@ -215,7 +215,7 @@ func (s *Service) ancestor(ctx context.Context, root []byte, slot types.Slot) ([ } // This retrieves an ancestor root using fork choice store. The look up is looping through the a flat array structure. -func (s *Service) ancestorByForkChoiceStore(ctx context.Context, r [32]byte, slot types.Slot) ([]byte, error) { +func (s *Service) ancestorByForkChoiceStore(ctx context.Context, r [32]byte, slot primitives.Slot) ([]byte, error) { ctx, span := trace.StartSpan(ctx, "blockChain.ancestorByForkChoiceStore") defer span.End() @@ -227,7 +227,7 @@ func (s *Service) ancestorByForkChoiceStore(ctx context.Context, r [32]byte, slo } // This retrieves an ancestor root using DB. The look up is recursively looking up DB. Slower than `ancestorByForkChoiceStore`. -func (s *Service) ancestorByDB(ctx context.Context, r [32]byte, slot types.Slot) ([]byte, error) { +func (s *Service) ancestorByDB(ctx context.Context, r [32]byte, slot primitives.Slot) ([]byte, error) { ctx, span := trace.StartSpan(ctx, "blockChain.ancestorByDB") defer span.End() diff --git a/beacon-chain/blockchain/process_block_test.go b/beacon-chain/blockchain/process_block_test.go index 7bd6431d04..7186b097a7 100644 --- a/beacon-chain/blockchain/process_block_test.go +++ b/beacon-chain/blockchain/process_block_test.go @@ -31,7 +31,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" @@ -160,7 +160,7 @@ func TestStore_OnBlockBatch(t *testing.T) { var blks []interfaces.SignedBeaconBlock var blkRoots [][32]byte for i := 0; i < 97; i++ { - b, err := util.GenerateFullBlock(bState, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlock(bState, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -181,7 +181,7 @@ func TestStore_OnBlockBatch(t *testing.T) { jcp := service.CurrentJustifiedCheckpt() jroot := bytesutil.ToBytes32(jcp.Root) require.Equal(t, blkRoots[63], jroot) - require.Equal(t, types.Epoch(2), service.cfg.ForkChoiceStore.JustifiedCheckpoint().Epoch) + require.Equal(t, primitives.Epoch(2), service.cfg.ForkChoiceStore.JustifiedCheckpoint().Epoch) } func TestStore_OnBlockBatch_NotifyNewPayload(t *testing.T) { @@ -204,7 +204,7 @@ func TestStore_OnBlockBatch_NotifyNewPayload(t *testing.T) { var blkRoots [][32]byte blkCount := 4 for i := 0; i <= blkCount; i++ { - b, err := util.GenerateFullBlock(bState, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlock(bState, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -235,7 +235,7 @@ func TestCachedPreState_CanGetFromStateSummary(t *testing.T) { st, keys := util.DeterministicGenesisState(t, 64) require.NoError(t, service.saveGenesisData(ctx, st)) - b, err := util.GenerateFullBlock(st, keys, util.DefaultBlockGenConfig(), types.Slot(1)) + b, err := util.GenerateFullBlock(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(1)) require.NoError(t, err) root, err := b.Block.HashTreeRoot() require.NoError(t, err) @@ -541,7 +541,7 @@ func TestCurrentSlot_HandlesOverflow(t *testing.T) { svc := Service{genesisTime: prysmTime.Now().Add(1 * time.Hour)} slot := svc.CurrentSlot() - require.Equal(t, types.Slot(0), slot, "Unexpected slot") + require.Equal(t, primitives.Slot(0), slot, "Unexpected slot") } func TestAncestorByDB_CtxErr(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) @@ -823,7 +823,7 @@ func TestOnBlock_CanFinalize_WithOnTick(t *testing.T) { require.NoError(t, fcs.UpdateFinalizedCheckpoint(&forkchoicetypes.Checkpoint{Root: service.originBlockRoot})) testState := gs.Copy() - for i := types.Slot(1); i <= 4*params.BeaconConfig().SlotsPerEpoch; i++ { + for i := primitives.Slot(1); i <= 4*params.BeaconConfig().SlotsPerEpoch; i++ { blk, err := util.GenerateFullBlock(testState, keys, util.DefaultBlockGenConfig(), i) require.NoError(t, err) r, err := blk.Block.HashTreeRoot() @@ -836,9 +836,9 @@ func TestOnBlock_CanFinalize_WithOnTick(t *testing.T) { require.NoError(t, err) } cp := service.CurrentJustifiedCheckpt() - require.Equal(t, types.Epoch(3), cp.Epoch) + require.Equal(t, primitives.Epoch(3), cp.Epoch) cp = service.FinalizedCheckpt() - require.Equal(t, types.Epoch(2), cp.Epoch) + require.Equal(t, primitives.Epoch(2), cp.Epoch) // The update should persist in DB. j, err := service.cfg.BeaconDB.JustifiedCheckpoint(ctx) @@ -872,7 +872,7 @@ func TestOnBlock_CanFinalize(t *testing.T) { require.NoError(t, service.saveGenesisData(ctx, gs)) testState := gs.Copy() - for i := types.Slot(1); i <= 4*params.BeaconConfig().SlotsPerEpoch; i++ { + for i := primitives.Slot(1); i <= 4*params.BeaconConfig().SlotsPerEpoch; i++ { blk, err := util.GenerateFullBlock(testState, keys, util.DefaultBlockGenConfig(), i) require.NoError(t, err) r, err := blk.Block.HashTreeRoot() @@ -884,9 +884,9 @@ func TestOnBlock_CanFinalize(t *testing.T) { require.NoError(t, err) } cp := service.CurrentJustifiedCheckpt() - require.Equal(t, types.Epoch(3), cp.Epoch) + require.Equal(t, primitives.Epoch(3), cp.Epoch) cp = service.FinalizedCheckpt() - require.Equal(t, types.Epoch(2), cp.Epoch) + require.Equal(t, primitives.Epoch(2), cp.Epoch) // The update should persist in DB. j, err := service.cfg.BeaconDB.JustifiedCheckpoint(ctx) @@ -974,7 +974,7 @@ func TestOnBlock_CallNewPayloadAndForkchoiceUpdated(t *testing.T) { gs, keys := util.DeterministicGenesisState(t, 32) require.NoError(t, service.saveGenesisData(ctx, gs)) testState := gs.Copy() - for i := types.Slot(1); i < params.BeaconConfig().SlotsPerEpoch; i++ { + for i := primitives.Slot(1); i < params.BeaconConfig().SlotsPerEpoch; i++ { blk, err := util.GenerateFullBlock(testState, keys, util.DefaultBlockGenConfig(), i) require.NoError(t, err) r, err := blk.Block.HashTreeRoot() @@ -1512,7 +1512,7 @@ func TestStore_NoViableHead_FCU(t *testing.T) { driftGenesisTime(service, int64(i), 0) st, err := service.HeadState(ctx) require.NoError(t, err) - b, err := util.GenerateFullBlock(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlock(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -1525,7 +1525,7 @@ func TestStore_NoViableHead_FCU(t *testing.T) { driftGenesisTime(service, int64(i), 0) st, err := service.HeadState(ctx) require.NoError(t, err) - b, err := util.GenerateFullBlockAltair(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlockAltair(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -1539,7 +1539,7 @@ func TestStore_NoViableHead_FCU(t *testing.T) { driftGenesisTime(service, int64(i), 0) st, err := service.HeadState(ctx) require.NoError(t, err) - b, err := util.GenerateFullBlockBellatrix(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlockBellatrix(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -1550,7 +1550,7 @@ func TestStore_NoViableHead_FCU(t *testing.T) { } // Check that we haven't justified the second epoch yet jc := service.ForkChoicer().JustifiedCheckpoint() - require.Equal(t, types.Epoch(0), jc.Epoch) + require.Equal(t, primitives.Epoch(0), jc.Epoch) // import a block that justifies the second epoch driftGenesisTime(service, 18, 0) @@ -1565,10 +1565,10 @@ func TestStore_NoViableHead_FCU(t *testing.T) { err = service.onBlock(ctx, wsb, firstInvalidRoot) require.NoError(t, err) jc = service.ForkChoicer().JustifiedCheckpoint() - require.Equal(t, types.Epoch(2), jc.Epoch) + require.Equal(t, primitives.Epoch(2), jc.Epoch) sjc := validHeadState.CurrentJustifiedCheckpoint() - require.Equal(t, types.Epoch(0), sjc.Epoch) + require.Equal(t, primitives.Epoch(0), sjc.Epoch) lvh := b.Block.Body.ExecutionPayload.ParentHash // check our head require.Equal(t, firstInvalidRoot, service.ForkChoicer().CachedHeadRoot()) @@ -1672,7 +1672,7 @@ func TestStore_NoViableHead_NewPayload(t *testing.T) { driftGenesisTime(service, int64(i), 0) st, err := service.HeadState(ctx) require.NoError(t, err) - b, err := util.GenerateFullBlock(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlock(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -1685,7 +1685,7 @@ func TestStore_NoViableHead_NewPayload(t *testing.T) { driftGenesisTime(service, int64(i), 0) st, err := service.HeadState(ctx) require.NoError(t, err) - b, err := util.GenerateFullBlockAltair(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlockAltair(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -1699,7 +1699,7 @@ func TestStore_NoViableHead_NewPayload(t *testing.T) { driftGenesisTime(service, int64(i), 0) st, err := service.HeadState(ctx) require.NoError(t, err) - b, err := util.GenerateFullBlockBellatrix(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlockBellatrix(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -1710,7 +1710,7 @@ func TestStore_NoViableHead_NewPayload(t *testing.T) { } // Check that we haven't justified the second epoch yet jc := service.ForkChoicer().JustifiedCheckpoint() - require.Equal(t, types.Epoch(0), jc.Epoch) + require.Equal(t, primitives.Epoch(0), jc.Epoch) // import a block that justifies the second epoch driftGenesisTime(service, 18, 0) @@ -1725,10 +1725,10 @@ func TestStore_NoViableHead_NewPayload(t *testing.T) { err = service.onBlock(ctx, wsb, firstInvalidRoot) require.NoError(t, err) jc = service.ForkChoicer().JustifiedCheckpoint() - require.Equal(t, types.Epoch(2), jc.Epoch) + require.Equal(t, primitives.Epoch(2), jc.Epoch) sjc := validHeadState.CurrentJustifiedCheckpoint() - require.Equal(t, types.Epoch(0), sjc.Epoch) + require.Equal(t, primitives.Epoch(0), sjc.Epoch) lvh := b.Block.Body.ExecutionPayload.ParentHash // check our head require.Equal(t, firstInvalidRoot, service.ForkChoicer().CachedHeadRoot()) @@ -1833,7 +1833,7 @@ func TestStore_NoViableHead_Liveness(t *testing.T) { driftGenesisTime(service, int64(i), 0) st, err := service.HeadState(ctx) require.NoError(t, err) - b, err := util.GenerateFullBlock(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlock(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -1846,7 +1846,7 @@ func TestStore_NoViableHead_Liveness(t *testing.T) { driftGenesisTime(service, int64(i), 0) st, err := service.HeadState(ctx) require.NoError(t, err) - b, err := util.GenerateFullBlockAltair(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlockAltair(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -1874,7 +1874,7 @@ func TestStore_NoViableHead_Liveness(t *testing.T) { require.NoError(t, err) lvh := b.Block.Body.ExecutionPayload.BlockHash validjc := validHeadState.CurrentJustifiedCheckpoint() - require.Equal(t, types.Epoch(0), validjc.Epoch) + require.Equal(t, primitives.Epoch(0), validjc.Epoch) // import blocks 13 through 18 to justify 12 invalidRoots := make([][32]byte, 19-13) @@ -1882,7 +1882,7 @@ func TestStore_NoViableHead_Liveness(t *testing.T) { driftGenesisTime(service, int64(i), 0) st, err := service.HeadState(ctx) require.NoError(t, err) - b, err := util.GenerateFullBlockBellatrix(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlockBellatrix(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -1893,7 +1893,7 @@ func TestStore_NoViableHead_Liveness(t *testing.T) { } // Check that we have justified the second epoch jc := service.ForkChoicer().JustifiedCheckpoint() - require.Equal(t, types.Epoch(2), jc.Epoch) + require.Equal(t, primitives.Epoch(2), jc.Epoch) invalidHeadRoot := service.ForkChoicer().CachedHeadRoot() // import block 19 to find out that the whole chain 13--18 was in fact @@ -1931,7 +1931,7 @@ func TestStore_NoViableHead_Liveness(t *testing.T) { // Check that the node's justified checkpoint does not agree with the // last valid state's justified checkpoint sjc := service.CurrentJustifiedCheckpt() - require.Equal(t, types.Epoch(2), sjc.Epoch) + require.Equal(t, primitives.Epoch(2), sjc.Epoch) // import another block based on the last valid head state mockEngine = &mockExecution.EngineClient{} @@ -1955,7 +1955,7 @@ func TestStore_NoViableHead_Liveness(t *testing.T) { for i := 21; i < 30; i++ { driftGenesisTime(service, int64(i), 0) require.NoError(t, err) - b, err := util.GenerateFullBlockBellatrix(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlockBellatrix(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -1985,7 +1985,7 @@ func TestStore_NoViableHead_Liveness(t *testing.T) { require.NoError(t, err) require.Equal(t, root, service.ForkChoicer().CachedHeadRoot()) sjc = service.CurrentJustifiedCheckpt() - require.Equal(t, types.Epoch(4), sjc.Epoch) + require.Equal(t, primitives.Epoch(4), sjc.Epoch) optimistic, err = service.IsOptimistic(ctx) require.NoError(t, err) require.Equal(t, false, optimistic) @@ -2042,7 +2042,7 @@ func TestNoViableHead_Reboot(t *testing.T) { driftGenesisTime(service, int64(i), 0) st, err := service.HeadState(ctx) require.NoError(t, err) - b, err := util.GenerateFullBlock(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlock(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -2055,7 +2055,7 @@ func TestNoViableHead_Reboot(t *testing.T) { driftGenesisTime(service, int64(i), 0) st, err := service.HeadState(ctx) require.NoError(t, err) - b, err := util.GenerateFullBlockAltair(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlockAltair(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -2083,14 +2083,14 @@ func TestNoViableHead_Reboot(t *testing.T) { require.NoError(t, err) lvh := b.Block.Body.ExecutionPayload.BlockHash validjc := validHeadState.CurrentJustifiedCheckpoint() - require.Equal(t, types.Epoch(0), validjc.Epoch) + require.Equal(t, primitives.Epoch(0), validjc.Epoch) // import blocks 13 through 18 to justify 12 for i := 13; i < 19; i++ { driftGenesisTime(service, int64(i), 0) st, err := service.HeadState(ctx) require.NoError(t, err) - b, err := util.GenerateFullBlockBellatrix(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlockBellatrix(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -2100,7 +2100,7 @@ func TestNoViableHead_Reboot(t *testing.T) { } // Check that we have justified the second epoch jc := service.ForkChoicer().JustifiedCheckpoint() - require.Equal(t, types.Epoch(2), jc.Epoch) + require.Equal(t, primitives.Epoch(2), jc.Epoch) // import block 19 to find out that the whole chain 13--18 was in fact // invalid @@ -2140,7 +2140,7 @@ func TestNoViableHead_Reboot(t *testing.T) { // Check that the node's justified checkpoint does not agree with the // last valid state's justified checkpoint sjc := service.CurrentJustifiedCheckpt() - require.Equal(t, types.Epoch(2), sjc.Epoch) + require.Equal(t, primitives.Epoch(2), sjc.Epoch) // import another block based on the last valid head state mockEngine = &mockExecution.EngineClient{} @@ -2170,7 +2170,7 @@ func TestNoViableHead_Reboot(t *testing.T) { for i := 21; i < 24; i++ { driftGenesisTime(service, int64(i), 0) require.NoError(t, err) - b, err := util.GenerateFullBlockBellatrix(st, keys, util.DefaultBlockGenConfig(), types.Slot(i)) + b, err := util.GenerateFullBlockBellatrix(st, keys, util.DefaultBlockGenConfig(), primitives.Slot(i)) require.NoError(t, err) wsb, err := consensusblocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -2209,7 +2209,7 @@ func TestNoViableHead_Reboot(t *testing.T) { require.Equal(t, root, bytesutil.ToBytes32(headRoot)) sjc = service.CurrentJustifiedCheckpt() - require.Equal(t, types.Epoch(3), sjc.Epoch) + require.Equal(t, primitives.Epoch(3), sjc.Epoch) optimistic, err = service.IsOptimistic(ctx) require.NoError(t, err) require.Equal(t, false, optimistic) diff --git a/beacon-chain/blockchain/receive_attestation_test.go b/beacon-chain/blockchain/receive_attestation_test.go index 1592990ed6..592e25471d 100644 --- a/beacon-chain/blockchain/receive_attestation_test.go +++ b/beacon-chain/blockchain/receive_attestation_test.go @@ -13,7 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/operations/attestations" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -35,7 +35,7 @@ func TestAttestationCheckPtState_FarFutureSlot(t *testing.T) { chainService := setupBeaconChain(t, beaconDB) chainService.genesisTime = time.Now() - e := types.Epoch(slots.MaxSlotBuffer/uint64(params.BeaconConfig().SlotsPerEpoch) + 1) + e := primitives.Epoch(slots.MaxSlotBuffer/uint64(params.BeaconConfig().SlotsPerEpoch) + 1) _, err := chainService.AttestationTargetState(context.Background(), ðpb.Checkpoint{Epoch: e}) require.ErrorContains(t, "exceeds max allowed value relative to the local clock", err) } @@ -186,7 +186,7 @@ func TestNotifyEngineIfChangedHead(t *testing.T) { require.LogsDoNotContain(t, hook, hookErr) vId, payloadID, has := service.cfg.ProposerSlotIndexCache.GetProposerPayloadIDs(2, [32]byte{2}) require.Equal(t, true, has) - require.Equal(t, types.ValidatorIndex(1), vId) + require.Equal(t, primitives.ValidatorIndex(1), vId) require.Equal(t, [8]byte{1}, payloadID) // Test zero headRoot returns immediately. diff --git a/beacon-chain/blockchain/receive_block.go b/beacon-chain/blockchain/receive_block.go index 5ed174f7ba..b6a023484b 100644 --- a/beacon-chain/blockchain/receive_block.go +++ b/beacon-chain/blockchain/receive_block.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/feed" statefeed "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/feed/state" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -17,7 +17,7 @@ import ( ) // This defines how many epochs since finality the run time will begin to save hot state on to the DB. -var epochsSinceFinalitySaveHotStateDB = types.Epoch(100) +var epochsSinceFinalitySaveHotStateDB = primitives.Epoch(100) // BlockReceiver interface defines the methods of chain service for receiving and processing new blocks. type BlockReceiver interface { @@ -182,7 +182,7 @@ func (s *Service) handleBlockBLSToExecChanges(blk interfaces.BeaconBlock) error func (s *Service) checkSaveHotStateDB(ctx context.Context) error { currentEpoch := slots.ToEpoch(s.CurrentSlot()) // Prevent `sinceFinality` going underflow. - var sinceFinality types.Epoch + var sinceFinality primitives.Epoch finalized := s.FinalizedCheckpt() if finalized == nil { return errNilFinalizedInStore diff --git a/beacon-chain/blockchain/receive_block_test.go b/beacon-chain/blockchain/receive_block_test.go index 9fa6cb203c..296eb23121 100644 --- a/beacon-chain/blockchain/receive_block_test.go +++ b/beacon-chain/blockchain/receive_block_test.go @@ -16,7 +16,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -29,7 +29,7 @@ func TestService_ReceiveBlock(t *testing.T) { ctx := context.Background() genesis, keys := util.DeterministicGenesisState(t, 64) - genFullBlock := func(t *testing.T, conf *util.BlockGenConfig, slot types.Slot) *ethpb.SignedBeaconBlock { + genFullBlock := func(t *testing.T, conf *util.BlockGenConfig, slot primitives.Slot) *ethpb.SignedBeaconBlock { blk, err := util.GenerateFullBlock(genesis, keys, conf, slot) assert.NoError(t, err) return blk @@ -205,7 +205,7 @@ func TestService_ReceiveBlockBatch(t *testing.T) { ctx := context.Background() genesis, keys := util.DeterministicGenesisState(t, 64) - genFullBlock := func(t *testing.T, conf *util.BlockGenConfig, slot types.Slot) *ethpb.SignedBeaconBlock { + genFullBlock := func(t *testing.T, conf *util.BlockGenConfig, slot primitives.Slot) *ethpb.SignedBeaconBlock { blk, err := util.GenerateFullBlock(genesis, keys, conf, slot) assert.NoError(t, err) return blk @@ -226,8 +226,8 @@ func TestService_ReceiveBlockBatch(t *testing.T) { block: genFullBlock(t, util.DefaultBlockGenConfig(), 2 /*slot*/), }, check: func(t *testing.T, s *Service) { - assert.Equal(t, types.Slot(2), s.head.state.Slot(), "Incorrect head state slot") - assert.Equal(t, types.Slot(2), s.head.block.Block().Slot(), "Incorrect head block slot") + assert.Equal(t, primitives.Slot(2), s.head.state.Slot(), "Incorrect head state slot") + assert.Equal(t, primitives.Slot(2), s.head.block.Block().Slot(), "Incorrect head block slot") }, }, { @@ -370,7 +370,7 @@ func TestHandleBlockBLSToExecutionChanges(t *testing.T) { }) t.Run("Post Capella some changes", func(t *testing.T) { - idx := types.ValidatorIndex(123) + idx := primitives.ValidatorIndex(123) change := ðpb.BLSToExecutionChange{ ValidatorIndex: idx, } diff --git a/beacon-chain/blockchain/service.go b/beacon-chain/blockchain/service.go index ab975a0e58..5cf175a565 100644 --- a/beacon-chain/blockchain/service.go +++ b/beacon-chain/blockchain/service.go @@ -33,7 +33,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" prysmTime "github.com/prysmaticlabs/prysm/v3/time" @@ -51,7 +51,7 @@ type Service struct { head *head headLock sync.RWMutex originBlockRoot [32]byte // genesis root, or weak subjectivity checkpoint root, depending on how the node is initialized - nextEpochBoundarySlot types.Slot + nextEpochBoundarySlot primitives.Slot boundaryRoots [][32]byte checkpointStateCache *cache.CheckpointStateCache initSyncBlocks map[[32]byte]interfaces.SignedBeaconBlock diff --git a/beacon-chain/blockchain/state_balance_cache_test.go b/beacon-chain/blockchain/state_balance_cache_test.go index c4e2a2448b..90128f4758 100644 --- a/beacon-chain/blockchain/state_balance_cache_test.go +++ b/beacon-chain/blockchain/state_balance_cache_test.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -23,7 +23,7 @@ func testStateWithValidators(v []*ethpb.Validator) testStateOpt { } } -func testStateWithSlot(slot types.Slot) testStateOpt { +func testStateWithSlot(slot primitives.Slot) testStateOpt { return func(a *ethpb.BeaconStateAltair) { a.Slot = slot } @@ -53,33 +53,33 @@ func generateTestValidators(count int, opts ...func(*ethpb.Validator)) []*ethpb. return vs } -func oddValidatorsExpired(currentSlot types.Slot) func(*ethpb.Validator) { +func oddValidatorsExpired(currentSlot primitives.Slot) func(*ethpb.Validator) { return func(v *ethpb.Validator) { pki := binary.LittleEndian.Uint64(v.PublicKey) if pki%2 == 0 { - v.ExitEpoch = types.Epoch(int(slots.ToEpoch(currentSlot)) + 1) + v.ExitEpoch = primitives.Epoch(int(slots.ToEpoch(currentSlot)) + 1) } else { - v.ExitEpoch = types.Epoch(int(slots.ToEpoch(currentSlot)) - 1) + v.ExitEpoch = primitives.Epoch(int(slots.ToEpoch(currentSlot)) - 1) } } } -func oddValidatorsQueued(currentSlot types.Slot) func(*ethpb.Validator) { +func oddValidatorsQueued(currentSlot primitives.Slot) func(*ethpb.Validator) { return func(v *ethpb.Validator) { - v.ExitEpoch = types.Epoch(int(slots.ToEpoch(currentSlot)) + 1) + v.ExitEpoch = primitives.Epoch(int(slots.ToEpoch(currentSlot)) + 1) pki := binary.LittleEndian.Uint64(v.PublicKey) if pki%2 == 0 { - v.ActivationEpoch = types.Epoch(int(slots.ToEpoch(currentSlot)) - 1) + v.ActivationEpoch = primitives.Epoch(int(slots.ToEpoch(currentSlot)) - 1) } else { - v.ActivationEpoch = types.Epoch(int(slots.ToEpoch(currentSlot)) + 1) + v.ActivationEpoch = primitives.Epoch(int(slots.ToEpoch(currentSlot)) + 1) } } } -func allValidatorsValid(currentSlot types.Slot) func(*ethpb.Validator) { +func allValidatorsValid(currentSlot primitives.Slot) func(*ethpb.Validator) { return func(v *ethpb.Validator) { - v.ActivationEpoch = types.Epoch(int(slots.ToEpoch(currentSlot)) - 1) - v.ExitEpoch = types.Epoch(int(slots.ToEpoch(currentSlot)) + 1) + v.ActivationEpoch = primitives.Epoch(int(slots.ToEpoch(currentSlot)) - 1) + v.ExitEpoch = primitives.Epoch(int(slots.ToEpoch(currentSlot)) + 1) } } @@ -91,21 +91,21 @@ func balanceIsKeyTimes2(v *ethpb.Validator) { func testHalfExpiredValidators() ([]*ethpb.Validator, []uint64) { balances := []uint64{0, 0, 4, 0, 8, 0, 12, 0, 16, 0} return generateTestValidators(10, - oddValidatorsExpired(types.Slot(99)), + oddValidatorsExpired(primitives.Slot(99)), balanceIsKeyTimes2), balances } func testHalfQueuedValidators() ([]*ethpb.Validator, []uint64) { balances := []uint64{0, 0, 4, 0, 8, 0, 12, 0, 16, 0} return generateTestValidators(10, - oddValidatorsQueued(types.Slot(99)), + oddValidatorsQueued(primitives.Slot(99)), balanceIsKeyTimes2), balances } func testAllValidValidators() ([]*ethpb.Validator, []uint64) { balances := []uint64{0, 2, 4, 6, 8, 10, 12, 14, 16, 18} return generateTestValidators(10, - allValidatorsValid(types.Slot(99)), + allValidatorsValid(primitives.Slot(99)), balanceIsKeyTimes2), balances } diff --git a/beacon-chain/blockchain/testing/mock.go b/beacon-chain/blockchain/testing/mock.go index 13d2746b25..f9a6e7dc85 100644 --- a/beacon-chain/blockchain/testing/mock.go +++ b/beacon-chain/blockchain/testing/mock.go @@ -22,7 +22,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/sirupsen/logrus" @@ -39,7 +39,7 @@ type ChainService struct { FinalizedCheckPoint *ethpb.Checkpoint CurrentJustifiedCheckPoint *ethpb.Checkpoint PreviousJustifiedCheckPoint *ethpb.Checkpoint - Slot *types.Slot // Pointer because 0 is a useful value, so checking against it can be incorrect. + Slot *primitives.Slot // Pointer because 0 is a useful value, so checking against it can be incorrect. Balance *precompute.Balance CanonicalRoots map[[32]byte]bool Fork *ethpb.Fork @@ -51,7 +51,7 @@ type ChainService struct { VerifyBlkDescendantErr error stateNotifier statefeed.Notifier BlocksReceived []interfaces.SignedBeaconBlock - SyncCommitteeIndices []types.CommitteeIndex + SyncCommitteeIndices []primitives.CommitteeIndex blockNotifier blockfeed.Notifier opNotifier opfeed.Notifier Root []byte @@ -259,7 +259,7 @@ func (s *ChainService) ReceiveBlock(ctx context.Context, block interfaces.Signed } // HeadSlot mocks HeadSlot method in chain service. -func (s *ChainService) HeadSlot() types.Slot { +func (s *ChainService) HeadSlot() primitives.Slot { if s.State == nil { return 0 } @@ -315,9 +315,9 @@ func (s *ChainService) AttestationTargetState(_ context.Context, _ *ethpb.Checkp } // HeadValidatorsIndices mocks the same method in the chain service. -func (s *ChainService) HeadValidatorsIndices(ctx context.Context, epoch types.Epoch) ([]types.ValidatorIndex, error) { +func (s *ChainService) HeadValidatorsIndices(ctx context.Context, epoch primitives.Epoch) ([]primitives.ValidatorIndex, error) { if s.State == nil { - return []types.ValidatorIndex{}, nil + return []primitives.ValidatorIndex{}, nil } return helpers.ActiveValidatorIndices(ctx, s.State, epoch) } @@ -338,11 +338,11 @@ func (s *ChainService) GenesisValidatorsRoot() [32]byte { } // CurrentSlot mocks the same method in the chain service. -func (s *ChainService) CurrentSlot() types.Slot { +func (s *ChainService) CurrentSlot() primitives.Slot { if s.Slot != nil { return *s.Slot } - return types.Slot(uint64(time.Now().Unix()-s.Genesis.Unix()) / params.BeaconConfig().SecondsPerSlot) + return primitives.Slot(uint64(time.Now().Unix()-s.Genesis.Unix()) / params.BeaconConfig().SecondsPerSlot) } // Participation mocks the same method in the chain service. @@ -406,46 +406,46 @@ func (s *ChainService) VerifyFinalizedConsistency(_ context.Context, r []byte) e } // ChainHeads mocks ChainHeads and always return nil. -func (_ *ChainService) ChainHeads() ([][32]byte, []types.Slot) { +func (_ *ChainService) ChainHeads() ([][32]byte, []primitives.Slot) { return [][32]byte{ bytesutil.ToBytes32(bytesutil.PadTo([]byte("foo"), 32)), bytesutil.ToBytes32(bytesutil.PadTo([]byte("bar"), 32)), }, - []types.Slot{0, 1} + []primitives.Slot{0, 1} } // HeadPublicKeyToValidatorIndex mocks HeadPublicKeyToValidatorIndex and always return 0 and true. -func (_ *ChainService) HeadPublicKeyToValidatorIndex(_ [fieldparams.BLSPubkeyLength]byte) (types.ValidatorIndex, bool) { +func (_ *ChainService) HeadPublicKeyToValidatorIndex(_ [fieldparams.BLSPubkeyLength]byte) (primitives.ValidatorIndex, bool) { return 0, true } // HeadValidatorIndexToPublicKey mocks HeadValidatorIndexToPublicKey and always return empty and nil. -func (s *ChainService) HeadValidatorIndexToPublicKey(_ context.Context, _ types.ValidatorIndex) ([fieldparams.BLSPubkeyLength]byte, error) { +func (s *ChainService) HeadValidatorIndexToPublicKey(_ context.Context, _ primitives.ValidatorIndex) ([fieldparams.BLSPubkeyLength]byte, error) { return s.PublicKey, nil } // HeadSyncCommitteeIndices mocks HeadSyncCommitteeIndices and always return `HeadNextSyncCommitteeIndices`. -func (s *ChainService) HeadSyncCommitteeIndices(_ context.Context, _ types.ValidatorIndex, _ types.Slot) ([]types.CommitteeIndex, error) { +func (s *ChainService) HeadSyncCommitteeIndices(_ context.Context, _ primitives.ValidatorIndex, _ primitives.Slot) ([]primitives.CommitteeIndex, error) { return s.SyncCommitteeIndices, nil } // HeadSyncCommitteePubKeys mocks HeadSyncCommitteePubKeys and always return empty nil. -func (s *ChainService) HeadSyncCommitteePubKeys(_ context.Context, _ types.Slot, _ types.CommitteeIndex) ([][]byte, error) { +func (s *ChainService) HeadSyncCommitteePubKeys(_ context.Context, _ primitives.Slot, _ primitives.CommitteeIndex) ([][]byte, error) { return s.SyncCommitteePubkeys, nil } // HeadSyncCommitteeDomain mocks HeadSyncCommitteeDomain and always return empty nil. -func (s *ChainService) HeadSyncCommitteeDomain(_ context.Context, _ types.Slot) ([]byte, error) { +func (s *ChainService) HeadSyncCommitteeDomain(_ context.Context, _ primitives.Slot) ([]byte, error) { return s.SyncCommitteeDomain, nil } // HeadSyncSelectionProofDomain mocks HeadSyncSelectionProofDomain and always return empty nil. -func (s *ChainService) HeadSyncSelectionProofDomain(_ context.Context, _ types.Slot) ([]byte, error) { +func (s *ChainService) HeadSyncSelectionProofDomain(_ context.Context, _ primitives.Slot) ([]byte, error) { return s.SyncSelectionProofDomain, nil } // HeadSyncContributionProofDomain mocks HeadSyncContributionProofDomain and always return empty nil. -func (s *ChainService) HeadSyncContributionProofDomain(_ context.Context, _ types.Slot) ([]byte, error) { +func (s *ChainService) HeadSyncContributionProofDomain(_ context.Context, _ primitives.Slot) ([]byte, error) { return s.SyncContributionProofDomain, nil } diff --git a/beacon-chain/blockchain/weak_subjectivity_checks.go b/beacon-chain/blockchain/weak_subjectivity_checks.go index d964c7ae35..c812a091e5 100644 --- a/beacon-chain/blockchain/weak_subjectivity_checks.go +++ b/beacon-chain/blockchain/weak_subjectivity_checks.go @@ -7,7 +7,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/filters" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -22,8 +22,8 @@ type WeakSubjectivityVerifier struct { enabled bool verified bool root [32]byte - epoch types.Epoch - slot types.Slot + epoch primitives.Epoch + slot primitives.Slot db weakSubjectivityDB } @@ -51,7 +51,7 @@ func NewWeakSubjectivityVerifier(wsc *ethpb.Checkpoint, db weakSubjectivityDB) ( // VerifyWeakSubjectivity verifies the weak subjectivity root in the service struct. // Reference design: https://github.com/ethereum/consensus-specs/blob/master/specs/phase0/weak-subjectivity.md#weak-subjectivity-sync-procedure -func (v *WeakSubjectivityVerifier) VerifyWeakSubjectivity(ctx context.Context, finalizedEpoch types.Epoch) error { +func (v *WeakSubjectivityVerifier) VerifyWeakSubjectivity(ctx context.Context, finalizedEpoch primitives.Epoch) error { if v.verified || !v.enabled { return nil } diff --git a/beacon-chain/blockchain/weak_subjectivity_checks_test.go b/beacon-chain/blockchain/weak_subjectivity_checks_test.go index 52771002f7..e143b55695 100644 --- a/beacon-chain/blockchain/weak_subjectivity_checks_test.go +++ b/beacon-chain/blockchain/weak_subjectivity_checks_test.go @@ -9,7 +9,7 @@ import ( doublylinkedtree "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/doubly-linked-tree" forkchoicetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/types" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -32,7 +32,7 @@ func TestService_VerifyWeakSubjectivityRoot(t *testing.T) { disabled bool wantErr error checkpt *ethpb.Checkpoint - finalizedEpoch types.Epoch + finalizedEpoch primitives.Epoch name string }{ { diff --git a/beacon-chain/builder/service.go b/beacon-chain/builder/service.go index 2afbc02510..005ff6a505 100644 --- a/beacon-chain/builder/service.go +++ b/beacon-chain/builder/service.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain" "github.com/prysmaticlabs/prysm/v3/beacon-chain/db" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" log "github.com/sirupsen/logrus" @@ -23,7 +23,7 @@ var ErrNoBuilder = errors.New("builder endpoint not configured") // BlockBuilder defines the interface for interacting with the block builder type BlockBuilder interface { SubmitBlindedBlock(ctx context.Context, block interfaces.SignedBeaconBlock) (interfaces.ExecutionData, error) - GetHeader(ctx context.Context, slot types.Slot, parentHash [32]byte, pubKey [48]byte) (builder.SignedBid, error) + GetHeader(ctx context.Context, slot primitives.Slot, parentHash [32]byte, pubKey [48]byte) (builder.SignedBid, error) RegisterValidator(ctx context.Context, reg []*ethpb.SignedValidatorRegistrationV1) error Configured() bool } @@ -94,7 +94,7 @@ func (s *Service) SubmitBlindedBlock(ctx context.Context, b interfaces.SignedBea } // GetHeader retrieves the header for a given slot and parent hash from the builder relay network. -func (s *Service) GetHeader(ctx context.Context, slot types.Slot, parentHash [32]byte, pubKey [48]byte) (builder.SignedBid, error) { +func (s *Service) GetHeader(ctx context.Context, slot primitives.Slot, parentHash [32]byte, pubKey [48]byte) (builder.SignedBid, error) { ctx, span := trace.StartSpan(ctx, "builder.GetHeader") defer span.End() start := time.Now() @@ -125,7 +125,7 @@ func (s *Service) RegisterValidator(ctx context.Context, reg []*ethpb.SignedVali registerValidatorLatency.Observe(float64(time.Since(start).Milliseconds())) }() - idxs := make([]types.ValidatorIndex, 0) + idxs := make([]primitives.ValidatorIndex, 0) msgs := make([]*ethpb.ValidatorRegistrationV1, 0) valid := make([]*ethpb.SignedValidatorRegistrationV1, 0) for i := 0; i < len(reg); i++ { diff --git a/beacon-chain/builder/testing/mock.go b/beacon-chain/builder/testing/mock.go index 36a8f1feb2..10302243d9 100644 --- a/beacon-chain/builder/testing/mock.go +++ b/beacon-chain/builder/testing/mock.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/api/client/builder" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" v1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -37,7 +37,7 @@ func (s *MockBuilderService) SubmitBlindedBlock(_ context.Context, _ interfaces. } // GetHeader for mocking. -func (s *MockBuilderService) GetHeader(context.Context, types.Slot, [32]byte, [48]byte) (builder.SignedBid, error) { +func (s *MockBuilderService) GetHeader(context.Context, primitives.Slot, [32]byte, [48]byte) (builder.SignedBid, error) { w, err := builder.WrappedSignedBuilderBid(s.Bid) if err != nil { return nil, errors.Wrap(err, "could not wrap bid") diff --git a/beacon-chain/cache/active_balance.go b/beacon-chain/cache/active_balance.go index 6ffbfe7167..88a74a5bb0 100644 --- a/beacon-chain/cache/active_balance.go +++ b/beacon-chain/cache/active_balance.go @@ -13,7 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" lruwrpr "github.com/prysmaticlabs/prysm/v3/cache/lru" "github.com/prysmaticlabs/prysm/v3/config/params" - ethTypes "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) const ( @@ -90,7 +90,7 @@ func balanceCacheKey(st state.ReadOnlyBeaconState) (string, error) { // impossible condition due to early division return "", errors.Errorf("start slot calculation overflows: %v", err) } - prevSlot := ethTypes.Slot(0) + prevSlot := primitives.Slot(0) if epochStartSlot > 1 { prevSlot = epochStartSlot - 1 } diff --git a/beacon-chain/cache/active_balance_test.go b/beacon-chain/cache/active_balance_test.go index 83ec176aa4..859271ce0a 100644 --- a/beacon-chain/cache/active_balance_test.go +++ b/beacon-chain/cache/active_balance_test.go @@ -9,7 +9,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -70,7 +70,7 @@ func TestBalanceCache_BalanceKey(t *testing.T) { } st, err := state_native.InitializeFromProtoPhase0(raw) require.NoError(t, err) - require.NoError(t, st.SetSlot(types.Slot(math.MaxUint64))) + require.NoError(t, st.SetSlot(primitives.Slot(math.MaxUint64))) _, err = balanceCacheKey(st) require.NoError(t, err) diff --git a/beacon-chain/cache/checkpoint_state_test.go b/beacon-chain/cache/checkpoint_state_test.go index 3245dd5229..85efadf3ba 100644 --- a/beacon-chain/cache/checkpoint_state_test.go +++ b/beacon-chain/cache/checkpoint_state_test.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -65,8 +65,8 @@ func TestCheckpointStateCache_MaxSize(t *testing.T) { require.NoError(t, err) for i := uint64(0); i < uint64(maxCheckpointStateSize+100); i++ { - require.NoError(t, st.SetSlot(types.Slot(i))) - require.NoError(t, c.AddCheckpointState(ðpb.Checkpoint{Epoch: types.Epoch(i), Root: make([]byte, 32)}, st)) + require.NoError(t, st.SetSlot(primitives.Slot(i))) + require.NoError(t, c.AddCheckpointState(ðpb.Checkpoint{Epoch: primitives.Epoch(i), Root: make([]byte, 32)}, st)) } assert.Equal(t, maxCheckpointStateSize, len(c.cache.Keys())) diff --git a/beacon-chain/cache/committee.go b/beacon-chain/cache/committee.go index f98c305b9c..3528e756f9 100644 --- a/beacon-chain/cache/committee.go +++ b/beacon-chain/cache/committee.go @@ -14,7 +14,7 @@ import ( "github.com/prometheus/client_golang/prometheus/promauto" lruwrpr "github.com/prysmaticlabs/prysm/v3/cache/lru" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" mathutil "github.com/prysmaticlabs/prysm/v3/math" ) @@ -64,7 +64,7 @@ func NewCommitteesCache() *CommitteeCache { // Committee fetches the shuffled indices by slot and committee index. Every list of indices // represent one committee. Returns true if the list exists with slot and committee index. Otherwise returns false, nil. -func (c *CommitteeCache) Committee(ctx context.Context, slot types.Slot, seed [32]byte, index types.CommitteeIndex) ([]types.ValidatorIndex, error) { +func (c *CommitteeCache) Committee(ctx context.Context, slot primitives.Slot, seed [32]byte, index primitives.CommitteeIndex) ([]primitives.ValidatorIndex, error) { if err := c.checkInProgress(ctx, seed); err != nil { return nil, err } @@ -117,7 +117,7 @@ func (c *CommitteeCache) AddCommitteeShuffledList(ctx context.Context, committee } // ActiveIndices returns the active indices of a given seed stored in cache. -func (c *CommitteeCache) ActiveIndices(ctx context.Context, seed [32]byte) ([]types.ValidatorIndex, error) { +func (c *CommitteeCache) ActiveIndices(ctx context.Context, seed [32]byte) ([]primitives.ValidatorIndex, error) { if err := c.checkInProgress(ctx, seed); err != nil { return nil, err } diff --git a/beacon-chain/cache/committee_disabled.go b/beacon-chain/cache/committee_disabled.go index caffe29769..b44f66d409 100644 --- a/beacon-chain/cache/committee_disabled.go +++ b/beacon-chain/cache/committee_disabled.go @@ -6,7 +6,7 @@ package cache import ( "context" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // FakeCommitteeCache is a struct with 1 queue for looking up shuffled indices list by seed. @@ -20,7 +20,7 @@ func NewCommitteesCache() *FakeCommitteeCache { // Committee fetches the shuffled indices by slot and committee index. Every list of indices // represent one committee. Returns true if the list exists with slot and committee index. Otherwise returns false, nil. -func (c *FakeCommitteeCache) Committee(ctx context.Context, slot types.Slot, seed [32]byte, index types.CommitteeIndex) ([]types.ValidatorIndex, error) { +func (c *FakeCommitteeCache) Committee(ctx context.Context, slot primitives.Slot, seed [32]byte, index primitives.CommitteeIndex) ([]primitives.ValidatorIndex, error) { return nil, nil } @@ -31,12 +31,12 @@ func (c *FakeCommitteeCache) AddCommitteeShuffledList(ctx context.Context, commi } // AddProposerIndicesList updates the committee shuffled list with proposer indices. -func (c *FakeCommitteeCache) AddProposerIndicesList(seed [32]byte, indices []types.ValidatorIndex) error { +func (c *FakeCommitteeCache) AddProposerIndicesList(seed [32]byte, indices []primitives.ValidatorIndex) error { return nil } // ActiveIndices returns the active indices of a given seed stored in cache. -func (c *FakeCommitteeCache) ActiveIndices(ctx context.Context, seed [32]byte) ([]types.ValidatorIndex, error) { +func (c *FakeCommitteeCache) ActiveIndices(ctx context.Context, seed [32]byte) ([]primitives.ValidatorIndex, error) { return nil, nil } @@ -51,7 +51,7 @@ func (c *FakeCommitteeCache) ActiveBalance(seed [32]byte) (uint64, error) { } // ProposerIndices returns the proposer indices of a given seed. -func (c *FakeCommitteeCache) ProposerIndices(seed [32]byte) ([]types.ValidatorIndex, error) { +func (c *FakeCommitteeCache) ProposerIndices(seed [32]byte) ([]primitives.ValidatorIndex, error) { return nil, nil } diff --git a/beacon-chain/cache/committee_test.go b/beacon-chain/cache/committee_test.go index d347caab1f..f610332c8b 100644 --- a/beacon-chain/cache/committee_test.go +++ b/beacon-chain/cache/committee_test.go @@ -10,7 +10,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -20,7 +20,7 @@ func TestCommitteeKeyFn_OK(t *testing.T) { item := &Committees{ CommitteeCount: 1, Seed: [32]byte{'A'}, - ShuffledIndices: []types.ValidatorIndex{1, 2, 3, 4, 5}, + ShuffledIndices: []primitives.ValidatorIndex{1, 2, 3, 4, 5}, } k, err := committeeKeyFn(item) @@ -37,13 +37,13 @@ func TestCommitteeCache_CommitteesByEpoch(t *testing.T) { cache := NewCommitteesCache() item := &Committees{ - ShuffledIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}, + ShuffledIndices: []primitives.ValidatorIndex{1, 2, 3, 4, 5, 6}, Seed: [32]byte{'A'}, CommitteeCount: 3, } slot := params.BeaconConfig().SlotsPerEpoch - committeeIndex := types.CommitteeIndex(1) + committeeIndex := primitives.CommitteeIndex(1) indices, err := cache.Committee(context.Background(), slot, item.Seed, committeeIndex) require.NoError(t, err) if indices != nil { @@ -51,7 +51,7 @@ func TestCommitteeCache_CommitteesByEpoch(t *testing.T) { } require.NoError(t, cache.AddCommitteeShuffledList(context.Background(), item)) - wantedIndex := types.CommitteeIndex(0) + wantedIndex := primitives.CommitteeIndex(0) indices, err = cache.Committee(context.Background(), slot, item.Seed, wantedIndex) require.NoError(t, err) @@ -62,7 +62,7 @@ func TestCommitteeCache_CommitteesByEpoch(t *testing.T) { func TestCommitteeCache_ActiveIndices(t *testing.T) { cache := NewCommitteesCache() - item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}} + item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []primitives.ValidatorIndex{1, 2, 3, 4, 5, 6}} indices, err := cache.ActiveIndices(context.Background(), item.Seed) require.NoError(t, err) if indices != nil { @@ -79,7 +79,7 @@ func TestCommitteeCache_ActiveIndices(t *testing.T) { func TestCommitteeCache_ActiveCount(t *testing.T) { cache := NewCommitteesCache() - item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}} + item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []primitives.ValidatorIndex{1, 2, 3, 4, 5, 6}} count, err := cache.ActiveIndicesCount(context.Background(), item.Seed) require.NoError(t, err) assert.Equal(t, 0, count, "Expected active count not to exist in empty cache") @@ -123,8 +123,8 @@ func TestCommitteeCacheOutOfRange(t *testing.T) { comms := &Committees{ CommitteeCount: 1, Seed: seed, - ShuffledIndices: []types.ValidatorIndex{0}, - SortedIndices: []types.ValidatorIndex{}, + ShuffledIndices: []primitives.ValidatorIndex{0}, + SortedIndices: []primitives.ValidatorIndex{}, } key, err := committeeKeyFn(comms) assert.NoError(t, err) @@ -137,7 +137,7 @@ func TestCommitteeCacheOutOfRange(t *testing.T) { func TestCommitteeCache_DoesNothingWhenCancelledContext(t *testing.T) { cache := NewCommitteesCache() - item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}} + item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []primitives.ValidatorIndex{1, 2, 3, 4, 5, 6}} count, err := cache.ActiveIndicesCount(context.Background(), item.Seed) require.NoError(t, err) assert.Equal(t, 0, count, "Expected active count not to exist in empty cache") diff --git a/beacon-chain/cache/committees.go b/beacon-chain/cache/committees.go index 47ca8a9724..a50fd794a3 100644 --- a/beacon-chain/cache/committees.go +++ b/beacon-chain/cache/committees.go @@ -3,7 +3,7 @@ package cache import ( "errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // ErrNotCommittee will be returned when a cache object is not a pointer to @@ -14,6 +14,6 @@ var ErrNotCommittee = errors.New("object is not a committee struct") type Committees struct { CommitteeCount uint64 Seed [32]byte - ShuffledIndices []types.ValidatorIndex - SortedIndices []types.ValidatorIndex + ShuffledIndices []primitives.ValidatorIndex + SortedIndices []primitives.ValidatorIndex } diff --git a/beacon-chain/cache/payload_id.go b/beacon-chain/cache/payload_id.go index 44fe2a9c53..f212fe8d77 100644 --- a/beacon-chain/cache/payload_id.go +++ b/beacon-chain/cache/payload_id.go @@ -4,7 +4,7 @@ import ( "bytes" "sync" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ) @@ -27,7 +27,7 @@ func NewProposerPayloadIDsCache() *ProposerPayloadIDsCache { } // GetProposerPayloadIDs returns the proposer and payload IDs for the given slot. -func (f *ProposerPayloadIDsCache) GetProposerPayloadIDs(slot types.Slot, r [32]byte) (types.ValidatorIndex, [8]byte, bool) { +func (f *ProposerPayloadIDsCache) GetProposerPayloadIDs(slot primitives.Slot, r [32]byte) (primitives.ValidatorIndex, [8]byte, bool) { f.RLock() defer f.RUnlock() ids, ok := f.slotToProposerAndPayloadIDs[idKey(slot, r)] @@ -40,11 +40,11 @@ func (f *ProposerPayloadIDsCache) GetProposerPayloadIDs(slot types.Slot, r [32]b var pId [pIdLength]byte copy(pId[:], b) - return types.ValidatorIndex(bytesutil.BytesToUint64BigEndian(vId)), pId, true + return primitives.ValidatorIndex(bytesutil.BytesToUint64BigEndian(vId)), pId, true } // SetProposerAndPayloadIDs sets the proposer and payload IDs for the given slot. -func (f *ProposerPayloadIDsCache) SetProposerAndPayloadIDs(slot types.Slot, vId types.ValidatorIndex, pId [8]byte, r [32]byte) { +func (f *ProposerPayloadIDsCache) SetProposerAndPayloadIDs(slot primitives.Slot, vId primitives.ValidatorIndex, pId [8]byte, r [32]byte) { f.Lock() defer f.Unlock() var vIdBytes [vIdLength]byte @@ -64,19 +64,19 @@ func (f *ProposerPayloadIDsCache) SetProposerAndPayloadIDs(slot types.Slot, vId } // PrunePayloadIDs removes the payload id entries that's current than input slot. -func (f *ProposerPayloadIDsCache) PrunePayloadIDs(slot types.Slot) { +func (f *ProposerPayloadIDsCache) PrunePayloadIDs(slot primitives.Slot) { f.Lock() defer f.Unlock() for k := range f.slotToProposerAndPayloadIDs { - s := types.Slot(bytesutil.BytesToUint64BigEndian(k[:8])) + s := primitives.Slot(bytesutil.BytesToUint64BigEndian(k[:8])) if slot > s { delete(f.slotToProposerAndPayloadIDs, k) } } } -func idKey(slot types.Slot, r [32]byte) [40]byte { +func idKey(slot primitives.Slot, r [32]byte) [40]byte { var k [40]byte copy(k[:], append(bytesutil.Uint64ToBytesBigEndian(uint64(slot)), r[:]...)) return k diff --git a/beacon-chain/cache/payload_id_test.go b/beacon-chain/cache/payload_id_test.go index 4da4dc9edf..07b48985ed 100644 --- a/beacon-chain/cache/payload_id_test.go +++ b/beacon-chain/cache/payload_id_test.go @@ -3,7 +3,7 @@ package cache import ( "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -12,11 +12,11 @@ func TestValidatorPayloadIDsCache_GetAndSaveValidatorPayloadIDs(t *testing.T) { var r [32]byte i, p, ok := cache.GetProposerPayloadIDs(0, r) require.Equal(t, false, ok) - require.Equal(t, types.ValidatorIndex(0), i) + require.Equal(t, primitives.ValidatorIndex(0), i) require.Equal(t, [pIdLength]byte{}, p) - slot := types.Slot(1234) - vid := types.ValidatorIndex(34234324) + slot := primitives.Slot(1234) + vid := primitives.ValidatorIndex(34234324) pid := [8]byte{1, 2, 3, 3, 7, 8, 7, 8} r = [32]byte{1, 2, 3} cache.SetProposerAndPayloadIDs(slot, vid, pid, r) @@ -25,8 +25,8 @@ func TestValidatorPayloadIDsCache_GetAndSaveValidatorPayloadIDs(t *testing.T) { require.Equal(t, vid, i) require.Equal(t, pid, p) - slot = types.Slot(9456456) - vid = types.ValidatorIndex(6786745) + slot = primitives.Slot(9456456) + vid = primitives.ValidatorIndex(6786745) r = [32]byte{4, 5, 6} cache.SetProposerAndPayloadIDs(slot, vid, [pIdLength]byte{}, r) i, p, ok = cache.GetProposerPayloadIDs(slot, r) @@ -35,8 +35,8 @@ func TestValidatorPayloadIDsCache_GetAndSaveValidatorPayloadIDs(t *testing.T) { require.Equal(t, [pIdLength]byte{}, p) // reset cache without pid - slot = types.Slot(9456456) - vid = types.ValidatorIndex(11111) + slot = primitives.Slot(9456456) + vid = primitives.ValidatorIndex(11111) r = [32]byte{7, 8, 9} pid = [8]byte{3, 2, 3, 33, 72, 8, 7, 8} cache.SetProposerAndPayloadIDs(slot, vid, pid, r) @@ -49,12 +49,12 @@ func TestValidatorPayloadIDsCache_GetAndSaveValidatorPayloadIDs(t *testing.T) { r = [32]byte{1, 2, 3} i, p, ok = cache.GetProposerPayloadIDs(slot, r) require.Equal(t, false, ok) - require.Equal(t, types.ValidatorIndex(0), i) + require.Equal(t, primitives.ValidatorIndex(0), i) require.Equal(t, [pIdLength]byte{}, p) // existing pid - no change in cache - slot = types.Slot(9456456) - vid = types.ValidatorIndex(11111) + slot = primitives.Slot(9456456) + vid = primitives.ValidatorIndex(11111) r = [32]byte{7, 8, 9} newPid := [8]byte{1, 2, 3, 33, 72, 8, 7, 1} cache.SetProposerAndPayloadIDs(slot, vid, newPid, r) @@ -67,6 +67,6 @@ func TestValidatorPayloadIDsCache_GetAndSaveValidatorPayloadIDs(t *testing.T) { cache.PrunePayloadIDs(slot + 1) i, p, ok = cache.GetProposerPayloadIDs(slot, r) require.Equal(t, false, ok) - require.Equal(t, types.ValidatorIndex(0), i) + require.Equal(t, primitives.ValidatorIndex(0), i) require.Equal(t, [pIdLength]byte{}, p) } diff --git a/beacon-chain/cache/proposer_indices.go b/beacon-chain/cache/proposer_indices.go index 0a14ade410..0352d3835d 100644 --- a/beacon-chain/cache/proposer_indices.go +++ b/beacon-chain/cache/proposer_indices.go @@ -7,7 +7,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "k8s.io/client-go/tools/cache" ) @@ -76,7 +76,7 @@ func (c *ProposerIndicesCache) HasProposerIndices(r [32]byte) (bool, error) { } // ProposerIndices returns the proposer indices of a block root seed. -func (c *ProposerIndicesCache) ProposerIndices(r [32]byte) ([]types.ValidatorIndex, error) { +func (c *ProposerIndicesCache) ProposerIndices(r [32]byte) ([]primitives.ValidatorIndex, error) { c.lock.RLock() defer c.lock.RUnlock() obj, exists, err := c.proposerIndicesCache.GetByKey(key(r)) diff --git a/beacon-chain/cache/proposer_indices_disabled.go b/beacon-chain/cache/proposer_indices_disabled.go index 9925490c12..e80ef4e030 100644 --- a/beacon-chain/cache/proposer_indices_disabled.go +++ b/beacon-chain/cache/proposer_indices_disabled.go @@ -3,7 +3,7 @@ // This file is used in fuzzer builds to bypass proposer indices caches. package cache -import types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" +import "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" // FakeProposerIndicesCache is a struct with 1 queue for looking up proposer indices by root. type FakeProposerIndicesCache struct { @@ -21,7 +21,7 @@ func (c *FakeProposerIndicesCache) AddProposerIndices(p *ProposerIndices) error } // ProposerIndices returns the proposer indices of a block root seed. -func (c *FakeProposerIndicesCache) ProposerIndices(r [32]byte) ([]types.ValidatorIndex, error) { +func (c *FakeProposerIndicesCache) ProposerIndices(r [32]byte) ([]primitives.ValidatorIndex, error) { return nil, nil } diff --git a/beacon-chain/cache/proposer_indices_test.go b/beacon-chain/cache/proposer_indices_test.go index 966bd0e18a..e4b642685d 100644 --- a/beacon-chain/cache/proposer_indices_test.go +++ b/beacon-chain/cache/proposer_indices_test.go @@ -6,7 +6,7 @@ import ( "strconv" "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -15,7 +15,7 @@ import ( func TestProposerKeyFn_OK(t *testing.T) { item := &ProposerIndices{ BlockRoot: [32]byte{'A'}, - ProposerIndices: []types.ValidatorIndex{1, 2, 3, 4, 5}, + ProposerIndices: []primitives.ValidatorIndex{1, 2, 3, 4, 5}, } k, err := proposerIndicesKeyFn(item) @@ -51,7 +51,7 @@ func TestProposerCache_AddProposerIndicesList(t *testing.T) { require.NoError(t, err) assert.Equal(t, true, has) - item := &ProposerIndices{BlockRoot: [32]byte{'B'}, ProposerIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}} + item := &ProposerIndices{BlockRoot: [32]byte{'B'}, ProposerIndices: []primitives.ValidatorIndex{1, 2, 3, 4, 5, 6}} require.NoError(t, cache.AddProposerIndices(item)) received, err = cache.ProposerIndices(item.BlockRoot) diff --git a/beacon-chain/cache/proposer_indices_type.go b/beacon-chain/cache/proposer_indices_type.go index 42e97fce35..06f1c4d761 100644 --- a/beacon-chain/cache/proposer_indices_type.go +++ b/beacon-chain/cache/proposer_indices_type.go @@ -3,7 +3,7 @@ package cache import ( "errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // ErrNotProposerIndices will be returned when a cache object is not a pointer to @@ -13,5 +13,5 @@ var ErrNotProposerIndices = errors.New("object is not a proposer indices struct" // ProposerIndices defines the cached struct for proposer indices. type ProposerIndices struct { BlockRoot [32]byte - ProposerIndices []types.ValidatorIndex + ProposerIndices []primitives.ValidatorIndex } diff --git a/beacon-chain/cache/subnet_ids.go b/beacon-chain/cache/subnet_ids.go index 2a9b47c043..0963339f00 100644 --- a/beacon-chain/cache/subnet_ids.go +++ b/beacon-chain/cache/subnet_ids.go @@ -8,7 +8,7 @@ import ( "github.com/patrickmn/go-cache" lruwrpr "github.com/prysmaticlabs/prysm/v3/cache/lru" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" ) @@ -37,7 +37,7 @@ func newSubnetIDs() *subnetIDs { } // AddAttesterSubnetID adds the subnet index for subscribing subnet for the attester of a given slot. -func (s *subnetIDs) AddAttesterSubnetID(slot types.Slot, subnetID uint64) { +func (s *subnetIDs) AddAttesterSubnetID(slot primitives.Slot, subnetID uint64) { s.attesterLock.Lock() defer s.attesterLock.Unlock() @@ -50,7 +50,7 @@ func (s *subnetIDs) AddAttesterSubnetID(slot types.Slot, subnetID uint64) { } // GetAttesterSubnetIDs gets the subnet IDs for subscribed subnets for attesters of the slot. -func (s *subnetIDs) GetAttesterSubnetIDs(slot types.Slot) []uint64 { +func (s *subnetIDs) GetAttesterSubnetIDs(slot primitives.Slot) []uint64 { s.attesterLock.RLock() defer s.attesterLock.RUnlock() @@ -65,7 +65,7 @@ func (s *subnetIDs) GetAttesterSubnetIDs(slot types.Slot) []uint64 { } // AddAggregatorSubnetID adds the subnet ID for subscribing subnet for the aggregator of a given slot. -func (s *subnetIDs) AddAggregatorSubnetID(slot types.Slot, subnetID uint64) { +func (s *subnetIDs) AddAggregatorSubnetID(slot primitives.Slot, subnetID uint64) { s.aggregatorLock.Lock() defer s.aggregatorLock.Unlock() @@ -78,7 +78,7 @@ func (s *subnetIDs) AddAggregatorSubnetID(slot types.Slot, subnetID uint64) { } // GetAggregatorSubnetIDs gets the subnet IDs for subscribing subnet for aggregator of the slot. -func (s *subnetIDs) GetAggregatorSubnetIDs(slot types.Slot) []uint64 { +func (s *subnetIDs) GetAggregatorSubnetIDs(slot primitives.Slot) []uint64 { s.aggregatorLock.RLock() defer s.aggregatorLock.RUnlock() diff --git a/beacon-chain/cache/subnet_ids_test.go b/beacon-chain/cache/subnet_ids_test.go index a2e0fac802..78c9b743e0 100644 --- a/beacon-chain/cache/subnet_ids_test.go +++ b/beacon-chain/cache/subnet_ids_test.go @@ -4,14 +4,14 @@ import ( "testing" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" ) func TestSubnetIDsCache_RoundTrip(t *testing.T) { c := newSubnetIDs() - slot := types.Slot(100) + slot := primitives.Slot(100) committeeIDs := c.GetAggregatorSubnetIDs(slot) assert.Equal(t, 0, len(committeeIDs), "Empty cache returned an object") diff --git a/beacon-chain/cache/sync_committee.go b/beacon-chain/cache/sync_committee.go index 091643f67f..3a3ac565f7 100644 --- a/beacon-chain/cache/sync_committee.go +++ b/beacon-chain/cache/sync_committee.go @@ -8,7 +8,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "k8s.io/client-go/tools/cache" ) @@ -40,13 +40,13 @@ type SyncCommitteeCache struct { // are cached where key is the validator index and the value is the `positionInCommittee` struct. type syncCommitteeIndexPosition struct { currentSyncCommitteeRoot [32]byte - vIndexToPositionMap map[types.ValidatorIndex]*positionInCommittee + vIndexToPositionMap map[primitives.ValidatorIndex]*positionInCommittee } // Index position of individual validator of current period and next period sync committee. type positionInCommittee struct { - currentPeriod []types.CommitteeIndex - nextPeriod []types.CommitteeIndex + currentPeriod []primitives.CommitteeIndex + nextPeriod []primitives.CommitteeIndex } // NewSyncCommittee initializes and returns a new SyncCommitteeCache. @@ -60,7 +60,7 @@ func NewSyncCommittee() *SyncCommitteeCache { // sync committee. If the input validator index has no assignment, an empty list will be returned. // If the input root does not exist in cache, `ErrNonExistingSyncCommitteeKey` is returned. // Manual checking of state for index position in state is recommended when `ErrNonExistingSyncCommitteeKey` is returned. -func (s *SyncCommitteeCache) CurrentPeriodIndexPosition(root [32]byte, valIdx types.ValidatorIndex) ([]types.CommitteeIndex, error) { +func (s *SyncCommitteeCache) CurrentPeriodIndexPosition(root [32]byte, valIdx primitives.ValidatorIndex) ([]primitives.CommitteeIndex, error) { s.lock.RLock() defer s.lock.RUnlock() @@ -69,7 +69,7 @@ func (s *SyncCommitteeCache) CurrentPeriodIndexPosition(root [32]byte, valIdx ty return nil, err } if pos == nil { - return []types.CommitteeIndex{}, nil + return []primitives.CommitteeIndex{}, nil } return pos.currentPeriod, nil @@ -79,7 +79,7 @@ func (s *SyncCommitteeCache) CurrentPeriodIndexPosition(root [32]byte, valIdx ty // If the input validator index has no assignment, an empty list will be returned. // If the input root does not exist in cache, `ErrNonExistingSyncCommitteeKey` is returned. // Manual checking of state for index position in state is recommended when `ErrNonExistingSyncCommitteeKey` is returned. -func (s *SyncCommitteeCache) NextPeriodIndexPosition(root [32]byte, valIdx types.ValidatorIndex) ([]types.CommitteeIndex, error) { +func (s *SyncCommitteeCache) NextPeriodIndexPosition(root [32]byte, valIdx primitives.ValidatorIndex) ([]primitives.CommitteeIndex, error) { s.lock.RLock() defer s.lock.RUnlock() @@ -88,7 +88,7 @@ func (s *SyncCommitteeCache) NextPeriodIndexPosition(root [32]byte, valIdx types return nil, err } if pos == nil { - return []types.CommitteeIndex{}, nil + return []primitives.CommitteeIndex{}, nil } return pos.nextPeriod, nil } @@ -96,7 +96,7 @@ func (s *SyncCommitteeCache) NextPeriodIndexPosition(root [32]byte, valIdx types // Helper function for `CurrentPeriodIndexPosition` and `NextPeriodIndexPosition` to return a mapping // of validator index to its index(s) position in the sync committee. func (s *SyncCommitteeCache) idxPositionInCommittee( - root [32]byte, valIdx types.ValidatorIndex, + root [32]byte, valIdx primitives.ValidatorIndex, ) (*positionInCommittee, error) { obj, exists, err := s.cache.GetByKey(key(root)) if err != nil { @@ -127,7 +127,7 @@ func (s *SyncCommitteeCache) UpdatePositionsInCommittee(syncCommitteeBoundaryRoo if err != nil { return err } - positionsMap := make(map[types.ValidatorIndex]*positionInCommittee) + positionsMap := make(map[primitives.ValidatorIndex]*positionInCommittee) for i, pubkey := range csc.Pubkeys { p := bytesutil.ToBytes48(pubkey) validatorIndex, ok := st.ValidatorIndexByPubkey(p) @@ -135,10 +135,10 @@ func (s *SyncCommitteeCache) UpdatePositionsInCommittee(syncCommitteeBoundaryRoo continue } if _, ok := positionsMap[validatorIndex]; !ok { - m := &positionInCommittee{currentPeriod: []types.CommitteeIndex{types.CommitteeIndex(i)}, nextPeriod: []types.CommitteeIndex{}} + m := &positionInCommittee{currentPeriod: []primitives.CommitteeIndex{primitives.CommitteeIndex(i)}, nextPeriod: []primitives.CommitteeIndex{}} positionsMap[validatorIndex] = m } else { - positionsMap[validatorIndex].currentPeriod = append(positionsMap[validatorIndex].currentPeriod, types.CommitteeIndex(i)) + positionsMap[validatorIndex].currentPeriod = append(positionsMap[validatorIndex].currentPeriod, primitives.CommitteeIndex(i)) } } @@ -153,10 +153,10 @@ func (s *SyncCommitteeCache) UpdatePositionsInCommittee(syncCommitteeBoundaryRoo continue } if _, ok := positionsMap[validatorIndex]; !ok { - m := &positionInCommittee{nextPeriod: []types.CommitteeIndex{types.CommitteeIndex(i)}, currentPeriod: []types.CommitteeIndex{}} + m := &positionInCommittee{nextPeriod: []primitives.CommitteeIndex{primitives.CommitteeIndex(i)}, currentPeriod: []primitives.CommitteeIndex{}} positionsMap[validatorIndex] = m } else { - positionsMap[validatorIndex].nextPeriod = append(positionsMap[validatorIndex].nextPeriod, types.CommitteeIndex(i)) + positionsMap[validatorIndex].nextPeriod = append(positionsMap[validatorIndex].nextPeriod, primitives.CommitteeIndex(i)) } } diff --git a/beacon-chain/cache/sync_committee_disabled.go b/beacon-chain/cache/sync_committee_disabled.go index 5766783ae3..4640cdeae9 100644 --- a/beacon-chain/cache/sync_committee_disabled.go +++ b/beacon-chain/cache/sync_committee_disabled.go @@ -4,7 +4,7 @@ package cache import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // FakeSyncCommitteeCache is a fake `SyncCommitteeCache` to satisfy fuzzing. @@ -17,12 +17,12 @@ func NewSyncCommittee() *FakeSyncCommitteeCache { } // CurrentEpochIndexPosition -- fake. -func (s *FakeSyncCommitteeCache) CurrentPeriodIndexPosition(root [32]byte, valIdx types.ValidatorIndex) ([]types.CommitteeIndex, error) { +func (s *FakeSyncCommitteeCache) CurrentPeriodIndexPosition(root [32]byte, valIdx primitives.ValidatorIndex) ([]primitives.CommitteeIndex, error) { return nil, nil } // NextEpochIndexPosition -- fake. -func (s *FakeSyncCommitteeCache) NextPeriodIndexPosition(root [32]byte, valIdx types.ValidatorIndex) ([]types.CommitteeIndex, error) { +func (s *FakeSyncCommitteeCache) NextPeriodIndexPosition(root [32]byte, valIdx primitives.ValidatorIndex) ([]primitives.CommitteeIndex, error) { return nil, nil } diff --git a/beacon-chain/cache/sync_committee_head_state.go b/beacon-chain/cache/sync_committee_head_state.go index 1bb0047d59..f4df6c742d 100644 --- a/beacon-chain/cache/sync_committee_head_state.go +++ b/beacon-chain/cache/sync_committee_head_state.go @@ -6,7 +6,7 @@ import ( lru "github.com/hashicorp/golang-lru" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" lruwrpr "github.com/prysmaticlabs/prysm/v3/cache/lru" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/runtime/version" ) @@ -23,7 +23,7 @@ func NewSyncCommitteeHeadState() *SyncCommitteeHeadStateCache { } // Put `slot` as key and `state` as value onto the cache. -func (c *SyncCommitteeHeadStateCache) Put(slot types.Slot, st state.BeaconState) error { +func (c *SyncCommitteeHeadStateCache) Put(slot primitives.Slot, st state.BeaconState) error { c.lock.Lock() defer c.lock.Unlock() // Make sure that the provided state is non nil @@ -41,7 +41,7 @@ func (c *SyncCommitteeHeadStateCache) Put(slot types.Slot, st state.BeaconState) } // Get `state` using `slot` as key. Return nil if nothing is found. -func (c *SyncCommitteeHeadStateCache) Get(slot types.Slot) (state.BeaconState, error) { +func (c *SyncCommitteeHeadStateCache) Get(slot primitives.Slot) (state.BeaconState, error) { c.lock.RLock() defer c.lock.RUnlock() val, exists := c.cache.Get(slot) diff --git a/beacon-chain/cache/sync_committee_head_state_test.go b/beacon-chain/cache/sync_committee_head_state_test.go index 9fe2c4ffc7..a2c7227ca8 100644 --- a/beacon-chain/cache/sync_committee_head_state_test.go +++ b/beacon-chain/cache/sync_committee_head_state_test.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -41,12 +41,12 @@ func TestSyncCommitteeHeadState(t *testing.T) { }) require.NoError(t, err) type put struct { - slot types.Slot + slot primitives.Slot state state.BeaconState } tests := []struct { name string - key types.Slot + key primitives.Slot put *put want state.BeaconState wantErr bool @@ -54,9 +54,9 @@ func TestSyncCommitteeHeadState(t *testing.T) { }{ { name: "putting error in", - key: types.Slot(1), + key: primitives.Slot(1), put: &put{ - slot: types.Slot(1), + slot: primitives.Slot(1), state: nil, }, wantPutErr: true, @@ -64,9 +64,9 @@ func TestSyncCommitteeHeadState(t *testing.T) { }, { name: "putting invalid state in", - key: types.Slot(1), + key: primitives.Slot(1), put: &put{ - slot: types.Slot(1), + slot: primitives.Slot(1), state: phase0State, }, wantPutErr: true, @@ -74,50 +74,50 @@ func TestSyncCommitteeHeadState(t *testing.T) { }, { name: "not found when empty cache", - key: types.Slot(1), + key: primitives.Slot(1), wantErr: true, }, { name: "not found when non-existent key in non-empty cache", - key: types.Slot(2), + key: primitives.Slot(2), put: &put{ - slot: types.Slot(1), + slot: primitives.Slot(1), state: beaconState, }, wantErr: true, }, { name: "found with key", - key: types.Slot(1), + key: primitives.Slot(1), put: &put{ - slot: types.Slot(1), + slot: primitives.Slot(1), state: beaconState, }, want: beaconState, }, { name: "not found when non-existent key in non-empty cache (bellatrix state)", - key: types.Slot(2), + key: primitives.Slot(2), put: &put{ - slot: types.Slot(1), + slot: primitives.Slot(1), state: bellatrixState, }, wantErr: true, }, { name: "found with key (bellatrix state)", - key: types.Slot(100), + key: primitives.Slot(100), put: &put{ - slot: types.Slot(100), + slot: primitives.Slot(100), state: bellatrixState, }, want: bellatrixState, }, { name: "found with key (capella state)", - key: types.Slot(200), + key: primitives.Slot(200), put: &put{ - slot: types.Slot(200), + slot: primitives.Slot(200), state: capellaState, }, want: capellaState, diff --git a/beacon-chain/cache/sync_committee_test.go b/beacon-chain/cache/sync_committee_test.go index 164c5d8bd7..e4311b4f45 100644 --- a/beacon-chain/cache/sync_committee_test.go +++ b/beacon-chain/cache/sync_committee_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/beacon-chain/cache" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -21,8 +21,8 @@ func TestSyncCommitteeCache_CanUpdateAndRetrieve(t *testing.T) { name string currentSyncCommittee *ethpb.SyncCommittee nextSyncCommittee *ethpb.SyncCommittee - currentSyncMap map[types.ValidatorIndex][]types.CommitteeIndex - nextSyncMap map[types.ValidatorIndex][]types.CommitteeIndex + currentSyncMap map[primitives.ValidatorIndex][]primitives.CommitteeIndex + nextSyncMap map[primitives.ValidatorIndex][]primitives.CommitteeIndex }{ { name: "only current epoch", @@ -30,12 +30,12 @@ func TestSyncCommitteeCache_CanUpdateAndRetrieve(t *testing.T) { pubKeys[1], pubKeys[2], pubKeys[3], pubKeys[2], pubKeys[2], }), nextSyncCommittee: util.ConvertToCommittee([][]byte{}), - currentSyncMap: map[types.ValidatorIndex][]types.CommitteeIndex{ + currentSyncMap: map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 1: {0}, 2: {1, 3, 4}, 3: {2}, }, - nextSyncMap: map[types.ValidatorIndex][]types.CommitteeIndex{ + nextSyncMap: map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 1: {}, 2: {}, 3: {}, @@ -47,12 +47,12 @@ func TestSyncCommitteeCache_CanUpdateAndRetrieve(t *testing.T) { nextSyncCommittee: util.ConvertToCommittee([][]byte{ pubKeys[1], pubKeys[2], pubKeys[3], pubKeys[2], pubKeys[2], }), - currentSyncMap: map[types.ValidatorIndex][]types.CommitteeIndex{ + currentSyncMap: map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 1: {}, 2: {}, 3: {}, }, - nextSyncMap: map[types.ValidatorIndex][]types.CommitteeIndex{ + nextSyncMap: map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 1: {0}, 2: {1, 3, 4}, 3: {2}, @@ -74,12 +74,12 @@ func TestSyncCommitteeCache_CanUpdateAndRetrieve(t *testing.T) { pubKeys[4], pubKeys[7], }), - currentSyncMap: map[types.ValidatorIndex][]types.CommitteeIndex{ + currentSyncMap: map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 1: {0}, 2: {1, 3, 4}, 3: {2}, }, - nextSyncMap: map[types.ValidatorIndex][]types.CommitteeIndex{ + nextSyncMap: map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 7: {0, 4}, 6: {1}, 5: {2}, @@ -102,12 +102,12 @@ func TestSyncCommitteeCache_CanUpdateAndRetrieve(t *testing.T) { pubKeys[2], pubKeys[1], }), - currentSyncMap: map[types.ValidatorIndex][]types.CommitteeIndex{ + currentSyncMap: map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 1: {0}, 2: {1, 3, 4}, 3: {2}, }, - nextSyncMap: map[types.ValidatorIndex][]types.CommitteeIndex{ + nextSyncMap: map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 1: {1, 4}, 2: {0, 3}, 3: {2}, @@ -127,10 +127,10 @@ func TestSyncCommitteeCache_CanUpdateAndRetrieve(t *testing.T) { pubKeys[100], pubKeys[100], }), - currentSyncMap: map[types.ValidatorIndex][]types.CommitteeIndex{ + currentSyncMap: map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 100: {0, 1, 2, 3}, }, - nextSyncMap: map[types.ValidatorIndex][]types.CommitteeIndex{ + nextSyncMap: map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 100: {0, 1, 2, 3}, }, }, @@ -148,10 +148,10 @@ func TestSyncCommitteeCache_CanUpdateAndRetrieve(t *testing.T) { pubKeys[100], pubKeys[100], }), - currentSyncMap: map[types.ValidatorIndex][]types.CommitteeIndex{ + currentSyncMap: map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 1: {}, }, - nextSyncMap: map[types.ValidatorIndex][]types.CommitteeIndex{ + nextSyncMap: map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 1: {}, }, }, diff --git a/beacon-chain/cache/sync_subnet_ids.go b/beacon-chain/cache/sync_subnet_ids.go index dab44981ef..ea56e2f79f 100644 --- a/beacon-chain/cache/sync_subnet_ids.go +++ b/beacon-chain/cache/sync_subnet_ids.go @@ -6,7 +6,7 @@ import ( "github.com/patrickmn/go-cache" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" "github.com/prysmaticlabs/prysm/v3/crypto/rand" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -29,7 +29,7 @@ func newSyncSubnetIDs() *syncSubnetIDs { } // GetSyncCommitteeSubnets retrieves the sync committee subnet and expiration time of that validator's subscription. -func (s *syncSubnetIDs) GetSyncCommitteeSubnets(pubkey []byte, epoch types.Epoch) ([]uint64, types.Epoch, bool, time.Time) { +func (s *syncSubnetIDs) GetSyncCommitteeSubnets(pubkey []byte, epoch primitives.Epoch) ([]uint64, primitives.Epoch, bool, time.Time) { s.sCommiteeLock.RLock() defer s.sCommiteeLock.RUnlock() @@ -50,13 +50,13 @@ func (s *syncSubnetIDs) GetSyncCommitteeSubnets(pubkey []byte, epoch types.Epoch // Index 0 was used to store validator's join epoch. We do not // return it to the caller. // Index 1 and beyond were used to store subnets. - return idxs[1:], types.Epoch(idxs[0]), ok, duration + return idxs[1:], primitives.Epoch(idxs[0]), ok, duration } // GetAllSubnets retrieves all the non-expired subscribed subnets of all the validators // in the cache. This method also takes the epoch as an argument to only retrieve // assignments for epochs that have happened. -func (s *syncSubnetIDs) GetAllSubnets(currEpoch types.Epoch) []uint64 { +func (s *syncSubnetIDs) GetAllSubnets(currEpoch primitives.Epoch) []uint64 { s.sCommiteeLock.RLock() defer s.sCommiteeLock.RUnlock() @@ -79,7 +79,7 @@ func (s *syncSubnetIDs) GetAllSubnets(currEpoch types.Epoch) []uint64 { // Check if the subnet is valid in the current epoch. If our // join epoch is still in the future we skip retrieving the // relevant committee index. - if types.Epoch(idxs[0]) > currEpoch { + if primitives.Epoch(idxs[0]) > currEpoch { continue } // Ignore the first index as that represents the @@ -92,7 +92,7 @@ func (s *syncSubnetIDs) GetAllSubnets(currEpoch types.Epoch) []uint64 { // AddSyncCommitteeSubnets adds the relevant committee for that particular validator along with its // expiration period. An Epoch argument here denotes the epoch from which the sync committee subnets // will be active. -func (s *syncSubnetIDs) AddSyncCommitteeSubnets(pubkey []byte, epoch types.Epoch, comIndex []uint64, duration time.Duration) { +func (s *syncSubnetIDs) AddSyncCommitteeSubnets(pubkey []byte, epoch primitives.Epoch, comIndex []uint64, duration time.Duration) { s.sCommiteeLock.Lock() defer s.sCommiteeLock.Unlock() subComCount := params.BeaconConfig().SyncCommitteeSubnetCount @@ -125,7 +125,7 @@ func (s *syncSubnetIDs) EmptyAllCaches() { // build a key composed of both the pubkey and epoch here. The epoch // here would be the 1st epoch of the sync committee period. -func keyBuilder(pubkey []byte, epoch types.Epoch) string { +func keyBuilder(pubkey []byte, epoch primitives.Epoch) string { epochBytes := bytesutil.Bytes8(uint64(epoch)) return string(append(pubkey, epochBytes...)) } diff --git a/beacon-chain/core/altair/attestation.go b/beacon-chain/core/altair/attestation.go index b53c393a02..aa8b9f40c2 100644 --- a/beacon-chain/core/altair/attestation.go +++ b/beacon-chain/core/altair/attestation.go @@ -13,7 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/attestation" "go.opencensus.io/trace" @@ -103,7 +103,7 @@ func ProcessAttestationNoVerifySignature( func SetParticipationAndRewardProposer( ctx context.Context, beaconState state.BeaconState, - targetEpoch types.Epoch, + targetEpoch primitives.Epoch, indices []uint64, participatedFlags map[uint8]bool, totalBalance uint64) (state.BeaconState, error) { var proposerRewardNumerator uint64 @@ -175,7 +175,7 @@ func EpochParticipation(beaconState state.BeaconState, indices []uint64, epochPa if index >= uint64(len(epochParticipation)) { return 0, nil, fmt.Errorf("index %d exceeds participation length %d", index, len(epochParticipation)) } - br, err := BaseRewardWithTotalBalance(beaconState, types.ValidatorIndex(index), totalBalance) + br, err := BaseRewardWithTotalBalance(beaconState, primitives.ValidatorIndex(index), totalBalance) if err != nil { return 0, nil, err } @@ -267,7 +267,7 @@ func RewardProposer(ctx context.Context, beaconState state.BeaconState, proposer // participation_flag_indices.append(TIMELY_HEAD_FLAG_INDEX) // // return participation_flag_indices -func AttestationParticipationFlagIndices(beaconState state.BeaconState, data *ethpb.AttestationData, delay types.Slot) (map[uint8]bool, error) { +func AttestationParticipationFlagIndices(beaconState state.BeaconState, data *ethpb.AttestationData, delay primitives.Slot) (map[uint8]bool, error) { currEpoch := time.CurrentEpoch(beaconState) var justifiedCheckpt *ethpb.Checkpoint if data.Target.Epoch == currEpoch { diff --git a/beacon-chain/core/altair/attestation_test.go b/beacon-chain/core/altair/attestation_test.go index ecf229fb7d..87d1a17b42 100644 --- a/beacon-chain/core/altair/attestation_test.go +++ b/beacon-chain/core/altair/attestation_test.go @@ -16,7 +16,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/math" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -443,7 +443,7 @@ func TestSetParticipationAndRewardProposer(t *testing.T) { indices []uint64 epochParticipation []byte participatedFlags map[uint8]bool - epoch types.Epoch + epoch primitives.Epoch wantedBalance uint64 wantedParticipation []byte }{ @@ -634,7 +634,7 @@ func TestAttestationParticipationFlagIndices(t *testing.T) { name string inputState state.BeaconState inputData *ethpb.AttestationData - inputDelay types.Slot + inputDelay primitives.Slot participationIndices map[uint8]bool }{ { @@ -658,7 +658,7 @@ func TestAttestationParticipationFlagIndices(t *testing.T) { Source: ðpb.Checkpoint{Root: params.BeaconConfig().ZeroHash[:]}, Target: ðpb.Checkpoint{}, }, - inputDelay: types.Slot(math.IntegerSquareRoot(uint64(cfg.SlotsPerEpoch)) - 1), + inputDelay: primitives.Slot(math.IntegerSquareRoot(uint64(cfg.SlotsPerEpoch)) - 1), participationIndices: map[uint8]bool{ sourceFlagIndex: true, }, @@ -672,7 +672,7 @@ func TestAttestationParticipationFlagIndices(t *testing.T) { Source: ðpb.Checkpoint{Root: params.BeaconConfig().ZeroHash[:]}, Target: ðpb.Checkpoint{Root: params.BeaconConfig().ZeroHash[:]}, }, - inputDelay: types.Slot(math.IntegerSquareRoot(uint64(cfg.SlotsPerEpoch)) - 1), + inputDelay: primitives.Slot(math.IntegerSquareRoot(uint64(cfg.SlotsPerEpoch)) - 1), participationIndices: map[uint8]bool{ sourceFlagIndex: true, targetFlagIndex: true, diff --git a/beacon-chain/core/altair/block_test.go b/beacon-chain/core/altair/block_test.go index 40b741b638..aa29929333 100644 --- a/beacon-chain/core/altair/block_test.go +++ b/beacon-chain/core/altair/block_test.go @@ -13,7 +13,7 @@ import ( p2pType "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/types" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -57,12 +57,12 @@ func TestProcessSyncCommittee_PerfectParticipation(t *testing.T) { require.NoError(t, err) // Use a non-sync committee index to compare profitability. - syncCommittee := make(map[types.ValidatorIndex]bool) + syncCommittee := make(map[primitives.ValidatorIndex]bool) for _, index := range indices { syncCommittee[index] = true } - nonSyncIndex := types.ValidatorIndex(params.BeaconConfig().MaxValidatorsPerCommittee + 1) - for i := types.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxValidatorsPerCommittee; i++ { + nonSyncIndex := primitives.ValidatorIndex(params.BeaconConfig().MaxValidatorsPerCommittee + 1) + for i := primitives.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxValidatorsPerCommittee; i++ { if !syncCommittee[i] { nonSyncIndex = i break diff --git a/beacon-chain/core/altair/epoch_precompute_test.go b/beacon-chain/core/altair/epoch_precompute_test.go index fd72cbec64..a11f17afb9 100644 --- a/beacon-chain/core/altair/epoch_precompute_test.go +++ b/beacon-chain/core/altair/epoch_precompute_test.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -330,7 +330,7 @@ func TestProcessInactivityScores_CanProcessInactivityLeak(t *testing.T) { require.NoError(t, err) defaultScore := uint64(5) require.NoError(t, s.SetInactivityScores([]uint64{defaultScore, defaultScore, defaultScore, defaultScore})) - require.NoError(t, s.SetSlot(params.BeaconConfig().SlotsPerEpoch*types.Slot(params.BeaconConfig().MinEpochsToInactivityPenalty+2))) + require.NoError(t, s.SetSlot(params.BeaconConfig().SlotsPerEpoch*primitives.Slot(params.BeaconConfig().MinEpochsToInactivityPenalty+2))) validators, balance, err := InitializePrecomputeValidators(context.Background(), s) require.NoError(t, err) validators, _, err = ProcessEpochParticipation(context.Background(), s, balance, validators) diff --git a/beacon-chain/core/altair/epoch_spec_test.go b/beacon-chain/core/altair/epoch_spec_test.go index dbf93168cb..90217e4cb4 100644 --- a/beacon-chain/core/altair/epoch_spec_test.go +++ b/beacon-chain/core/altair/epoch_spec_test.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -47,7 +47,7 @@ func TestProcessSyncCommitteeUpdates_CanRotate(t *testing.T) { require.DeepEqual(t, current, c) require.DeepEqual(t, next, n) - require.NoError(t, s.SetSlot(types.Slot(params.BeaconConfig().EpochsPerSyncCommitteePeriod)*params.BeaconConfig().SlotsPerEpoch-1)) + require.NoError(t, s.SetSlot(primitives.Slot(params.BeaconConfig().EpochsPerSyncCommitteePeriod)*params.BeaconConfig().SlotsPerEpoch-1)) postState, err = altair.ProcessSyncCommitteeUpdates(context.Background(), s) require.NoError(t, err) c, err = postState.CurrentSyncCommittee() @@ -59,7 +59,7 @@ func TestProcessSyncCommitteeUpdates_CanRotate(t *testing.T) { require.DeepEqual(t, next, c) // Test boundary condition. - slot := params.BeaconConfig().SlotsPerEpoch * types.Slot(time.CurrentEpoch(s)+params.BeaconConfig().EpochsPerSyncCommitteePeriod) + slot := params.BeaconConfig().SlotsPerEpoch * primitives.Slot(time.CurrentEpoch(s)+params.BeaconConfig().EpochsPerSyncCommitteePeriod) require.NoError(t, s.SetSlot(slot)) boundaryCommittee, err := altair.NextSyncCommittee(context.Background(), s) require.NoError(t, err) diff --git a/beacon-chain/core/altair/reward.go b/beacon-chain/core/altair/reward.go index d9f20363ad..a00537608f 100644 --- a/beacon-chain/core/altair/reward.go +++ b/beacon-chain/core/altair/reward.go @@ -5,7 +5,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/math" ) @@ -24,7 +24,7 @@ import ( // """ // increments = state.validators[index].effective_balance // EFFECTIVE_BALANCE_INCREMENT // return Gwei(increments * get_base_reward_per_increment(state)) -func BaseReward(s state.ReadOnlyBeaconState, index types.ValidatorIndex) (uint64, error) { +func BaseReward(s state.ReadOnlyBeaconState, index primitives.ValidatorIndex) (uint64, error) { totalBalance, err := helpers.TotalActiveBalance(s) if err != nil { return 0, errors.Wrap(err, "could not calculate active balance") @@ -33,7 +33,7 @@ func BaseReward(s state.ReadOnlyBeaconState, index types.ValidatorIndex) (uint64 } // BaseRewardWithTotalBalance calculates the base reward with the provided total balance. -func BaseRewardWithTotalBalance(s state.ReadOnlyBeaconState, index types.ValidatorIndex, totalBalance uint64) (uint64, error) { +func BaseRewardWithTotalBalance(s state.ReadOnlyBeaconState, index primitives.ValidatorIndex, totalBalance uint64) (uint64, error) { val, err := s.ValidatorAtIndexReadOnly(index) if err != nil { return 0, err diff --git a/beacon-chain/core/altair/reward_test.go b/beacon-chain/core/altair/reward_test.go index aba56c6df3..b835b27a2a 100644 --- a/beacon-chain/core/altair/reward_test.go +++ b/beacon-chain/core/altair/reward_test.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" ) @@ -21,7 +21,7 @@ func Test_BaseReward(t *testing.T) { } tests := []struct { name string - valIdx types.ValidatorIndex + valIdx primitives.ValidatorIndex st state.ReadOnlyBeaconState want uint64 errString string @@ -72,7 +72,7 @@ func Test_BaseRewardWithTotalBalance(t *testing.T) { s, _ := util.DeterministicGenesisStateAltair(t, 1) tests := []struct { name string - valIdx types.ValidatorIndex + valIdx primitives.ValidatorIndex activeBalance uint64 want uint64 errString string diff --git a/beacon-chain/core/altair/sync_committee.go b/beacon-chain/core/altair/sync_committee.go index 3a3cfddba3..70c0b05c52 100644 --- a/beacon-chain/core/altair/sync_committee.go +++ b/beacon-chain/core/altair/sync_committee.go @@ -11,7 +11,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -100,7 +100,7 @@ func NextSyncCommittee(ctx context.Context, s state.BeaconState) (*ethpb.SyncCom // sync_committee_indices.append(candidate_index) // i += 1 // return sync_committee_indices -func NextSyncCommitteeIndices(ctx context.Context, s state.BeaconState) ([]types.ValidatorIndex, error) { +func NextSyncCommitteeIndices(ctx context.Context, s state.BeaconState) ([]primitives.ValidatorIndex, error) { epoch := coreTime.NextEpoch(s) indices, err := helpers.ActiveValidatorIndices(ctx, s, epoch) if err != nil { @@ -113,10 +113,10 @@ func NextSyncCommitteeIndices(ctx context.Context, s state.BeaconState) ([]types count := uint64(len(indices)) cfg := params.BeaconConfig() syncCommitteeSize := cfg.SyncCommitteeSize - cIndices := make([]types.ValidatorIndex, 0, syncCommitteeSize) + cIndices := make([]primitives.ValidatorIndex, 0, syncCommitteeSize) hashFunc := hash.CustomSHA256Hasher() - for i := types.ValidatorIndex(0); uint64(len(cIndices)) < params.BeaconConfig().SyncCommitteeSize; i++ { + for i := primitives.ValidatorIndex(0); uint64(len(cIndices)) < params.BeaconConfig().SyncCommitteeSize; i++ { if ctx.Err() != nil { return nil, ctx.Err() } @@ -159,7 +159,7 @@ func NextSyncCommitteeIndices(ctx context.Context, s state.BeaconState) ([]types // sync_subcommittee_size = SYNC_COMMITTEE_SIZE // SYNC_COMMITTEE_SUBNET_COUNT // i = subcommittee_index * sync_subcommittee_size // return sync_committee.pubkeys[i:i + sync_subcommittee_size] -func SyncSubCommitteePubkeys(syncCommittee *ethpb.SyncCommittee, subComIdx types.CommitteeIndex) ([][]byte, error) { +func SyncSubCommitteePubkeys(syncCommittee *ethpb.SyncCommittee, subComIdx primitives.CommitteeIndex) ([][]byte, error) { cfg := params.BeaconConfig() subCommSize := cfg.SyncCommitteeSize / cfg.SyncCommitteeSubnetCount i := uint64(subComIdx) * subCommSize @@ -190,7 +190,7 @@ func IsSyncCommitteeAggregator(sig []byte) (bool, error) { } // ValidateSyncMessageTime validates sync message to ensure that the provided slot is valid. -func ValidateSyncMessageTime(slot types.Slot, genesisTime time.Time, clockDisparity time.Duration) error { +func ValidateSyncMessageTime(slot primitives.Slot, genesisTime time.Time, clockDisparity time.Duration) error { if err := slots.ValidateClock(slot, uint64(genesisTime.Unix())); err != nil { return err } diff --git a/beacon-chain/core/altair/sync_committee_test.go b/beacon-chain/core/altair/sync_committee_test.go index 47371ea1ca..ef2142a1ba 100644 --- a/beacon-chain/core/altair/sync_committee_test.go +++ b/beacon-chain/core/altair/sync_committee_test.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -37,7 +37,7 @@ func TestSyncCommitteeIndices_CanGet(t *testing.T) { type args struct { state state.BeaconState - epoch types.Epoch + epoch primitives.Epoch } tests := []struct { name string @@ -109,11 +109,11 @@ func TestSyncCommitteeIndices_DifferentPeriods(t *testing.T) { got2, err := altair.NextSyncCommitteeIndices(context.Background(), st) require.NoError(t, err) require.DeepNotEqual(t, got1, got2) - require.NoError(t, st.SetSlot(params.BeaconConfig().SlotsPerEpoch*types.Slot(params.BeaconConfig().EpochsPerSyncCommitteePeriod))) + require.NoError(t, st.SetSlot(params.BeaconConfig().SlotsPerEpoch*primitives.Slot(params.BeaconConfig().EpochsPerSyncCommitteePeriod))) got2, err = altair.NextSyncCommitteeIndices(context.Background(), st) require.NoError(t, err) require.DeepNotEqual(t, got1, got2) - require.NoError(t, st.SetSlot(params.BeaconConfig().SlotsPerEpoch*types.Slot(2*params.BeaconConfig().EpochsPerSyncCommitteePeriod))) + require.NoError(t, st.SetSlot(params.BeaconConfig().SlotsPerEpoch*primitives.Slot(2*params.BeaconConfig().EpochsPerSyncCommitteePeriod))) got2, err = altair.NextSyncCommitteeIndices(context.Background(), st) require.NoError(t, err) require.DeepNotEqual(t, got1, got2) @@ -141,7 +141,7 @@ func TestSyncCommittee_CanGet(t *testing.T) { type args struct { state state.BeaconState - epoch types.Epoch + epoch primitives.Epoch } tests := []struct { name string @@ -178,7 +178,7 @@ func TestSyncCommittee_CanGet(t *testing.T) { t.Run(tt.name, func(t *testing.T) { helpers.ClearCache() if !tt.wantErr { - require.NoError(t, tt.args.state.SetSlot(types.Slot(tt.args.epoch)*params.BeaconConfig().SlotsPerEpoch)) + require.NoError(t, tt.args.state.SetSlot(primitives.Slot(tt.args.epoch)*params.BeaconConfig().SlotsPerEpoch)) } got, err := altair.NextSyncCommittee(context.Background(), tt.args.state) if tt.wantErr { @@ -272,7 +272,7 @@ func Test_ValidateSyncMessageTime(t *testing.T) { } type args struct { - syncMessageSlot types.Slot + syncMessageSlot primitives.Slot genesisTime time.Time } tests := []struct { diff --git a/beacon-chain/core/altair/upgrade_test.go b/beacon-chain/core/altair/upgrade_test.go index b0aa22b0c5..042553e913 100644 --- a/beacon-chain/core/altair/upgrade_test.go +++ b/beacon-chain/core/altair/upgrade_test.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/attestation" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -37,7 +37,7 @@ func TestTranslateParticipation(t *testing.T) { for i := 0; i < 3; i++ { pendingAtts = append(pendingAtts, ðpb.PendingAttestation{ Data: ðpb.AttestationData{ - CommitteeIndex: types.CommitteeIndex(i), + CommitteeIndex: primitives.CommitteeIndex(i), BeaconBlockRoot: r, Source: ðpb.Checkpoint{Epoch: 0, Root: make([]byte, 32)}, Target: ðpb.Checkpoint{Epoch: 0, Root: make([]byte, 32)}, diff --git a/beacon-chain/core/blocks/attestation.go b/beacon-chain/core/blocks/attestation.go index 65a613efa1..2f0a43d856 100644 --- a/beacon-chain/core/blocks/attestation.go +++ b/beacon-chain/core/blocks/attestation.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/attestation" @@ -218,7 +218,7 @@ func VerifyIndexedAttestation(ctx context.Context, beaconState state.ReadOnlyBea indices := indexedAtt.AttestingIndices var pubkeys []bls.PublicKey for i := 0; i < len(indices); i++ { - pubkeyAtIdx := beaconState.PubkeyAtIndex(types.ValidatorIndex(indices[i])) + pubkeyAtIdx := beaconState.PubkeyAtIndex(primitives.ValidatorIndex(indices[i])) pk, err := bls.PublicKeyFromBytes(pubkeyAtIdx[:]) if err != nil { return errors.Wrap(err, "could not deserialize validator public key") diff --git a/beacon-chain/core/blocks/attestation_test.go b/beacon-chain/core/blocks/attestation_test.go index 75bdb843fb..dee6e3d868 100644 --- a/beacon-chain/core/blocks/attestation_test.go +++ b/beacon-chain/core/blocks/attestation_test.go @@ -11,7 +11,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -331,7 +331,7 @@ func TestValidateIndexedAttestation_AboveMaxLength(t *testing.T) { indexedAtt1.AttestingIndices[i] = i indexedAtt1.Data = ðpb.AttestationData{ Target: ðpb.Checkpoint{ - Epoch: types.Epoch(i), + Epoch: primitives.Epoch(i), }, } } diff --git a/beacon-chain/core/blocks/attester_slashing.go b/beacon-chain/core/blocks/attester_slashing.go index d6bb93da9b..1547ebb751 100644 --- a/beacon-chain/core/blocks/attester_slashing.go +++ b/beacon-chain/core/blocks/attester_slashing.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/attestation" @@ -72,7 +72,7 @@ func ProcessAttesterSlashing( var slashedAny bool var val state.ReadOnlyValidator for _, validatorIndex := range slashableIndices { - val, err = beaconState.ValidatorAtIndexReadOnly(types.ValidatorIndex(validatorIndex)) + val, err = beaconState.ValidatorAtIndexReadOnly(primitives.ValidatorIndex(validatorIndex)) if err != nil { return nil, err } @@ -89,7 +89,7 @@ func ProcessAttesterSlashing( default: return nil, errors.New("unknown state version") } - beaconState, err = slashFunc(ctx, beaconState, types.ValidatorIndex(validatorIndex), slashingQuotient, cfg.ProposerRewardQuotient) + beaconState, err = slashFunc(ctx, beaconState, primitives.ValidatorIndex(validatorIndex), slashingQuotient, cfg.ProposerRewardQuotient) if err != nil { return nil, errors.Wrapf(err, "could not slash validator index %d", validatorIndex) diff --git a/beacon-chain/core/blocks/attester_slashing_test.go b/beacon-chain/core/blocks/attester_slashing_test.go index ccfd46755e..e617268eb4 100644 --- a/beacon-chain/core/blocks/attester_slashing_test.go +++ b/beacon-chain/core/blocks/attester_slashing_test.go @@ -9,7 +9,7 @@ import ( v "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/validators" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -44,7 +44,7 @@ func TestProcessAttesterSlashings_DataNotSlashable(t *testing.T) { })}} var registry []*ethpb.Validator - currentSlot := types.Slot(0) + currentSlot := primitives.Slot(0) beaconState, err := state_native.InitializeFromProtoPhase0(ðpb.BeaconState{ Validators: registry, @@ -63,7 +63,7 @@ func TestProcessAttesterSlashings_DataNotSlashable(t *testing.T) { func TestProcessAttesterSlashings_IndexedAttestationFailedToVerify(t *testing.T) { var registry []*ethpb.Validator - currentSlot := types.Slot(0) + currentSlot := primitives.Slot(0) beaconState, err := state_native.InitializeFromProtoPhase0(ðpb.BeaconState{ Validators: registry, @@ -99,7 +99,7 @@ func TestProcessAttesterSlashings_IndexedAttestationFailedToVerify(t *testing.T) func TestProcessAttesterSlashings_AppliesCorrectStatus(t *testing.T) { beaconState, privKeys := util.DeterministicGenesisState(t, 100) for _, vv := range beaconState.Validators() { - vv.WithdrawableEpoch = types.Epoch(params.BeaconConfig().SlotsPerEpoch) + vv.WithdrawableEpoch = primitives.Epoch(params.BeaconConfig().SlotsPerEpoch) } att1 := util.HydrateIndexedAttestation(ðpb.IndexedAttestation{ @@ -168,7 +168,7 @@ func TestProcessAttesterSlashings_AppliesCorrectStatus(t *testing.T) { func TestProcessAttesterSlashings_AppliesCorrectStatusAltair(t *testing.T) { beaconState, privKeys := util.DeterministicGenesisStateAltair(t, 100) for _, vv := range beaconState.Validators() { - vv.WithdrawableEpoch = types.Epoch(params.BeaconConfig().SlotsPerEpoch) + vv.WithdrawableEpoch = primitives.Epoch(params.BeaconConfig().SlotsPerEpoch) } att1 := util.HydrateIndexedAttestation(ðpb.IndexedAttestation{ @@ -237,7 +237,7 @@ func TestProcessAttesterSlashings_AppliesCorrectStatusAltair(t *testing.T) { func TestProcessAttesterSlashings_AppliesCorrectStatusBellatrix(t *testing.T) { beaconState, privKeys := util.DeterministicGenesisStateBellatrix(t, 100) for _, vv := range beaconState.Validators() { - vv.WithdrawableEpoch = types.Epoch(params.BeaconConfig().SlotsPerEpoch) + vv.WithdrawableEpoch = primitives.Epoch(params.BeaconConfig().SlotsPerEpoch) } att1 := util.HydrateIndexedAttestation(ðpb.IndexedAttestation{ @@ -306,7 +306,7 @@ func TestProcessAttesterSlashings_AppliesCorrectStatusBellatrix(t *testing.T) { func TestProcessAttesterSlashings_AppliesCorrectStatusCapella(t *testing.T) { beaconState, privKeys := util.DeterministicGenesisStateCapella(t, 100) for _, vv := range beaconState.Validators() { - vv.WithdrawableEpoch = types.Epoch(params.BeaconConfig().SlotsPerEpoch) + vv.WithdrawableEpoch = primitives.Epoch(params.BeaconConfig().SlotsPerEpoch) } att1 := util.HydrateIndexedAttestation(ðpb.IndexedAttestation{ diff --git a/beacon-chain/core/blocks/block_operations_fuzz_test.go b/beacon-chain/core/blocks/block_operations_fuzz_test.go index 3d78eb3c35..f8eafbe472 100644 --- a/beacon-chain/core/blocks/block_operations_fuzz_test.go +++ b/beacon-chain/core/blocks/block_operations_fuzz_test.go @@ -10,7 +10,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -418,7 +418,7 @@ func TestFuzzVerifyExit_10000(_ *testing.T) { ve := ðpb.SignedVoluntaryExit{} rawVal := ðpb.Validator{} fork := ðpb.Fork{} - var slot types.Slot + var slot primitives.Slot for i := 0; i < 10000; i++ { fuzzer.Fuzz(ve) diff --git a/beacon-chain/core/blocks/block_regression_test.go b/beacon-chain/core/blocks/block_regression_test.go index f3507725e6..1e71afd8aa 100644 --- a/beacon-chain/core/blocks/block_regression_test.go +++ b/beacon-chain/core/blocks/block_regression_test.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" v "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/validators" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -20,7 +20,7 @@ func TestProcessAttesterSlashings_RegressionSlashableIndices(t *testing.T) { beaconState, privKeys := util.DeterministicGenesisState(t, 5500) for _, vv := range beaconState.Validators() { - vv.WithdrawableEpoch = types.Epoch(params.BeaconConfig().SlotsPerEpoch) + vv.WithdrawableEpoch = primitives.Epoch(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 2c5bdc8dff..e56fc489e3 100644 --- a/beacon-chain/core/blocks/deposit_test.go +++ b/beacon-chain/core/blocks/deposit_test.go @@ -9,7 +9,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/trie" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -322,11 +322,11 @@ func TestPreGenesisDeposits_SkipInvalidDeposit(t *testing.T) { require.Equal(t, false, ok, "bad pubkey should not exist in state") for i := 1; i < newState.NumValidators(); i++ { - val, err := newState.ValidatorAtIndex(types.ValidatorIndex(i)) + val, err := newState.ValidatorAtIndex(primitives.ValidatorIndex(i)) require.NoError(t, err) require.Equal(t, params.BeaconConfig().MaxEffectiveBalance, val.EffectiveBalance, "unequal effective balance") - require.Equal(t, types.Epoch(0), val.ActivationEpoch) - require.Equal(t, types.Epoch(0), val.ActivationEligibilityEpoch) + require.Equal(t, primitives.Epoch(0), val.ActivationEpoch) + require.Equal(t, primitives.Epoch(0), val.ActivationEligibilityEpoch) } if newState.Eth1DepositIndex() != 100 { t.Errorf( diff --git a/beacon-chain/core/blocks/eth1_data_test.go b/beacon-chain/core/blocks/eth1_data_test.go index 3d5fdf5b9f..8680959499 100644 --- a/beacon-chain/core/blocks/eth1_data_test.go +++ b/beacon-chain/core/blocks/eth1_data_test.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/blocks" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -34,7 +34,7 @@ func TestEth1DataHasEnoughSupport(t *testing.T) { stateVotes []*ethpb.Eth1Data data *ethpb.Eth1Data hasSupport bool - votingPeriodLength types.Epoch + votingPeriodLength primitives.Epoch }{ { stateVotes: FakeDeposits(uint64(params.BeaconConfig().SlotsPerEpoch.Mul(4))), diff --git a/beacon-chain/core/blocks/exit.go b/beacon-chain/core/blocks/exit.go index f5a5dd0fc1..4ca5ca62e3 100644 --- a/beacon-chain/core/blocks/exit.go +++ b/beacon-chain/core/blocks/exit.go @@ -10,7 +10,7 @@ import ( v "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/validators" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" ) @@ -92,7 +92,7 @@ func ProcessVoluntaryExits( // initiate_validator_exit(state, voluntary_exit.validator_index) func VerifyExitAndSignature( validator state.ReadOnlyValidator, - currentSlot types.Slot, + currentSlot primitives.Slot, fork *ethpb.Fork, signed *ethpb.SignedVoluntaryExit, genesisRoot []byte, @@ -137,7 +137,7 @@ func VerifyExitAndSignature( // assert bls.Verify(validator.pubkey, signing_root, signed_voluntary_exit.signature) // # Initiate exit // initiate_validator_exit(state, voluntary_exit.validator_index) -func verifyExitConditions(validator state.ReadOnlyValidator, currentSlot types.Slot, exit *ethpb.VoluntaryExit) error { +func verifyExitConditions(validator state.ReadOnlyValidator, currentSlot primitives.Slot, exit *ethpb.VoluntaryExit) error { currentEpoch := slots.ToEpoch(currentSlot) // Verify the validator is active. if !helpers.IsActiveValidatorUsingTrie(validator, currentEpoch) { diff --git a/beacon-chain/core/blocks/exit_test.go b/beacon-chain/core/blocks/exit_test.go index 082bb6a601..d597e60c88 100644 --- a/beacon-chain/core/blocks/exit_test.go +++ b/beacon-chain/core/blocks/exit_test.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -126,15 +126,15 @@ func TestProcessVoluntaryExits_AppliesCorrectStatus(t *testing.T) { newState, err := blocks.ProcessVoluntaryExits(context.Background(), state, b.Block.Body.VoluntaryExits) require.NoError(t, err, "Could not process exits") newRegistry := newState.Validators() - if newRegistry[0].ExitEpoch != helpers.ActivationExitEpoch(types.Epoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch)) { + if newRegistry[0].ExitEpoch != helpers.ActivationExitEpoch(primitives.Epoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch)) { t.Errorf("Expected validator exit epoch to be %d, got %d", - helpers.ActivationExitEpoch(types.Epoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch)), newRegistry[0].ExitEpoch) + helpers.ActivationExitEpoch(primitives.Epoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch)), newRegistry[0].ExitEpoch) } } func TestVerifyExitAndSignature(t *testing.T) { type args struct { - currentSlot types.Slot + currentSlot primitives.Slot } tests := []struct { diff --git a/beacon-chain/core/blocks/header.go b/beacon-chain/core/blocks/header.go index 5c9aee8bea..f8c05c1ec2 100644 --- a/beacon-chain/core/blocks/header.go +++ b/beacon-chain/core/blocks/header.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -98,7 +98,7 @@ func ProcessBlockHeader( func ProcessBlockHeaderNoVerify( ctx context.Context, beaconState state.BeaconState, - slot types.Slot, proposerIndex types.ValidatorIndex, + slot primitives.Slot, proposerIndex primitives.ValidatorIndex, parentRoot, bodyRoot []byte, ) (state.BeaconState, error) { if beaconState.Slot() != slot { diff --git a/beacon-chain/core/blocks/proposer_slashing.go b/beacon-chain/core/blocks/proposer_slashing.go index 0d5fd8e271..aee872fdca 100644 --- a/beacon-chain/core/blocks/proposer_slashing.go +++ b/beacon-chain/core/blocks/proposer_slashing.go @@ -10,14 +10,14 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" "github.com/prysmaticlabs/prysm/v3/time/slots" "google.golang.org/protobuf/proto" ) -type slashValidatorFunc func(ctx context.Context, st state.BeaconState, vid types.ValidatorIndex, penaltyQuotient, proposerRewardQuotient uint64) (state.BeaconState, error) +type slashValidatorFunc func(ctx context.Context, st state.BeaconState, vid primitives.ValidatorIndex, penaltyQuotient, proposerRewardQuotient uint64) (state.BeaconState, error) // ProcessProposerSlashings is one of the operations performed // on each processed beacon block to slash proposers based on diff --git a/beacon-chain/core/blocks/proposer_slashing_test.go b/beacon-chain/core/blocks/proposer_slashing_test.go index a5aa3abfe4..fd5d649f24 100644 --- a/beacon-chain/core/blocks/proposer_slashing_test.go +++ b/beacon-chain/core/blocks/proposer_slashing_test.go @@ -12,7 +12,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -25,7 +25,7 @@ import ( func TestProcessProposerSlashings_UnmatchedHeaderSlots(t *testing.T) { beaconState, _ := util.DeterministicGenesisState(t, 20) - currentSlot := types.Slot(0) + currentSlot := primitives.Slot(0) slashings := []*ethpb.ProposerSlashing{ { Header_1: ðpb.SignedBeaconBlockHeader{ @@ -58,7 +58,7 @@ func TestProcessProposerSlashings_UnmatchedHeaderSlots(t *testing.T) { func TestProcessProposerSlashings_SameHeaders(t *testing.T) { beaconState, _ := util.DeterministicGenesisState(t, 2) - currentSlot := types.Slot(0) + currentSlot := primitives.Slot(0) slashings := []*ethpb.ProposerSlashing{ { Header_1: ðpb.SignedBeaconBlockHeader{ @@ -97,7 +97,7 @@ func TestProcessProposerSlashings_ValidatorNotSlashable(t *testing.T) { WithdrawableEpoch: 0, }, } - currentSlot := types.Slot(0) + currentSlot := primitives.Slot(0) slashings := []*ethpb.ProposerSlashing{ { Header_1: ðpb.SignedBeaconBlockHeader{ @@ -142,7 +142,7 @@ func TestProcessProposerSlashings_AppliesCorrectStatus(t *testing.T) { // We test the case when data is correct and verify the validator // registry has been updated. beaconState, privKeys := util.DeterministicGenesisState(t, 100) - proposerIdx := types.ValidatorIndex(1) + proposerIdx := primitives.ValidatorIndex(1) header1 := ðpb.SignedBeaconBlockHeader{ Header: util.HydrateBeaconHeader(ðpb.BeaconBlockHeader{ @@ -190,7 +190,7 @@ func TestProcessProposerSlashings_AppliesCorrectStatusAltair(t *testing.T) { // We test the case when data is correct and verify the validator // registry has been updated. beaconState, privKeys := util.DeterministicGenesisStateAltair(t, 100) - proposerIdx := types.ValidatorIndex(1) + proposerIdx := primitives.ValidatorIndex(1) header1 := ðpb.SignedBeaconBlockHeader{ Header: util.HydrateBeaconHeader(ðpb.BeaconBlockHeader{ @@ -238,7 +238,7 @@ func TestProcessProposerSlashings_AppliesCorrectStatusBellatrix(t *testing.T) { // We test the case when data is correct and verify the validator // registry has been updated. beaconState, privKeys := util.DeterministicGenesisStateBellatrix(t, 100) - proposerIdx := types.ValidatorIndex(1) + proposerIdx := primitives.ValidatorIndex(1) header1 := ðpb.SignedBeaconBlockHeader{ Header: util.HydrateBeaconHeader(ðpb.BeaconBlockHeader{ @@ -286,7 +286,7 @@ func TestProcessProposerSlashings_AppliesCorrectStatusCapella(t *testing.T) { // We test the case when data is correct and verify the validator // registry has been updated. beaconState, privKeys := util.DeterministicGenesisStateCapella(t, 100) - proposerIdx := types.ValidatorIndex(1) + proposerIdx := primitives.ValidatorIndex(1) header1 := ðpb.SignedBeaconBlockHeader{ Header: util.HydrateBeaconHeader(ðpb.BeaconBlockHeader{ @@ -337,7 +337,7 @@ func TestVerifyProposerSlashing(t *testing.T) { } beaconState, sks := util.DeterministicGenesisState(t, 2) - currentSlot := types.Slot(0) + currentSlot := primitives.Slot(0) require.NoError(t, beaconState.SetSlot(currentSlot)) rand1, err := bls.RandKey() require.NoError(t, err) diff --git a/beacon-chain/core/blocks/randao_test.go b/beacon-chain/core/blocks/randao_test.go index 142604c118..966747c050 100644 --- a/beacon-chain/core/blocks/randao_test.go +++ b/beacon-chain/core/blocks/randao_test.go @@ -11,7 +11,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -23,7 +23,7 @@ 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(context.Background(), beaconState) require.NoError(t, err) - epoch := types.Epoch(0) + epoch := primitives.Epoch(0) buf := make([]byte, 32) binary.LittleEndian.PutUint64(buf, uint64(epoch)) domain, err := signing.Domain(beaconState.Fork(), epoch, params.BeaconConfig().DomainRandao, beaconState.GenesisValidatorsRoot()) diff --git a/beacon-chain/core/blocks/signature.go b/beacon-chain/core/blocks/signature.go index d3d7ae0a61..ccf54b5352 100644 --- a/beacon-chain/core/blocks/signature.go +++ b/beacon-chain/core/blocks/signature.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/network/forks" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -65,7 +65,7 @@ func verifySignature(signedData, pub, signature, domain []byte) error { // VerifyBlockSignature verifies the proposer signature of a beacon block. func VerifyBlockSignature(beaconState state.ReadOnlyBeaconState, - proposerIndex types.ValidatorIndex, + proposerIndex primitives.ValidatorIndex, sig []byte, rootFunc func() ([32]byte, error)) error { currentEpoch := slots.ToEpoch(beaconState.Slot()) @@ -120,7 +120,7 @@ func VerifyBlockSignatureUsingCurrentFork(beaconState state.ReadOnlyBeaconState, // BlockSignatureBatch retrieves the block signature batch from the provided block and its corresponding state. func BlockSignatureBatch(beaconState state.ReadOnlyBeaconState, - proposerIndex types.ValidatorIndex, + proposerIndex primitives.ValidatorIndex, sig []byte, rootFunc func() ([32]byte, error)) (*bls.SignatureBatch, error) { currentEpoch := slots.ToEpoch(beaconState.Slot()) @@ -204,7 +204,7 @@ func createAttestationSignatureBatch( indices := ia.AttestingIndices pubkeys := make([][]byte, len(indices)) for i := 0; i < len(indices); i++ { - pubkeyAtIdx := beaconState.PubkeyAtIndex(types.ValidatorIndex(indices[i])) + pubkeyAtIdx := beaconState.PubkeyAtIndex(primitives.ValidatorIndex(indices[i])) pubkeys[i] = pubkeyAtIdx[:] } aggP, err := bls.AggregatePublicKeys(pubkeys) diff --git a/beacon-chain/core/blocks/withdrawals.go b/beacon-chain/core/blocks/withdrawals.go index d00076d058..02a565dcb7 100644 --- a/beacon-chain/core/blocks/withdrawals.go +++ b/beacon-chain/core/blocks/withdrawals.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/ssz" @@ -141,17 +141,17 @@ func ProcessWithdrawals(st state.BeaconState, withdrawals []*enginev1.Withdrawal return nil, errors.Wrap(err, "could not set next withdrawal index") } } - var nextValidatorIndex types.ValidatorIndex + var nextValidatorIndex primitives.ValidatorIndex if uint64(len(withdrawals)) < params.BeaconConfig().MaxWithdrawalsPerPayload { nextValidatorIndex, err = st.NextWithdrawalValidatorIndex() if err != nil { return nil, errors.Wrap(err, "could not get next withdrawal validator index") } - nextValidatorIndex += types.ValidatorIndex(params.BeaconConfig().MaxValidatorsPerWithdrawalsSweep) - nextValidatorIndex = nextValidatorIndex % types.ValidatorIndex(st.NumValidators()) + nextValidatorIndex += primitives.ValidatorIndex(params.BeaconConfig().MaxValidatorsPerWithdrawalsSweep) + nextValidatorIndex = nextValidatorIndex % primitives.ValidatorIndex(st.NumValidators()) } else { nextValidatorIndex = withdrawals[len(withdrawals)-1].ValidatorIndex + 1 - if nextValidatorIndex == types.ValidatorIndex(st.NumValidators()) { + if nextValidatorIndex == primitives.ValidatorIndex(st.NumValidators()) { nextValidatorIndex = 0 } } diff --git a/beacon-chain/core/blocks/withdrawals_test.go b/beacon-chain/core/blocks/withdrawals_test.go index 0d7e291308..7428fa7608 100644 --- a/beacon-chain/core/blocks/withdrawals_test.go +++ b/beacon-chain/core/blocks/withdrawals_test.go @@ -11,7 +11,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/bls/common" "github.com/prysmaticlabs/prysm/v3/crypto/hash" @@ -239,9 +239,9 @@ func TestProcessBLSToExecutionChange(t *testing.T) { func TestProcessWithdrawals(t *testing.T) { const ( - currentEpoch = types.Epoch(10) - epochInFuture = types.Epoch(12) - epochInPast = types.Epoch(8) + currentEpoch = primitives.Epoch(10) + epochInFuture = primitives.Epoch(12) + epochInPast = primitives.Epoch(8) numValidators = 128 notWithdrawableIndex = 127 notPartiallyWithdrawable = 126 @@ -251,14 +251,14 @@ func TestProcessWithdrawals(t *testing.T) { type args struct { Name string - NextWithdrawalValidatorIndex types.ValidatorIndex + NextWithdrawalValidatorIndex primitives.ValidatorIndex NextWithdrawalIndex uint64 - FullWithdrawalIndices []types.ValidatorIndex - PartialWithdrawalIndices []types.ValidatorIndex + FullWithdrawalIndices []primitives.ValidatorIndex + PartialWithdrawalIndices []primitives.ValidatorIndex Withdrawals []*enginev1.Withdrawal } type control struct { - NextWithdrawalValidatorIndex types.ValidatorIndex + NextWithdrawalValidatorIndex primitives.ValidatorIndex NextWithdrawalIndex uint64 ExpectedError bool Balances map[uint64]uint64 @@ -267,15 +267,15 @@ func TestProcessWithdrawals(t *testing.T) { Args args Control control } - executionAddress := func(i types.ValidatorIndex) []byte { + executionAddress := func(i primitives.ValidatorIndex) []byte { wc := make([]byte, 20) wc[19] = byte(i) return wc } - withdrawalAmount := func(i types.ValidatorIndex) uint64 { + withdrawalAmount := func(i primitives.ValidatorIndex) uint64 { return maxEffectiveBalance + uint64(i)*100000 } - fullWithdrawal := func(i types.ValidatorIndex, idx uint64) *enginev1.Withdrawal { + fullWithdrawal := func(i primitives.ValidatorIndex, idx uint64) *enginev1.Withdrawal { return &enginev1.Withdrawal{ Index: idx, ValidatorIndex: i, @@ -283,7 +283,7 @@ func TestProcessWithdrawals(t *testing.T) { Amount: withdrawalAmount(i), } } - partialWithdrawal := func(i types.ValidatorIndex, idx uint64) *enginev1.Withdrawal { + partialWithdrawal := func(i primitives.ValidatorIndex, idx uint64) *enginev1.Withdrawal { return &enginev1.Withdrawal{ Index: idx, ValidatorIndex: i, @@ -308,7 +308,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "success one full withdrawal", NextWithdrawalIndex: 3, NextWithdrawalValidatorIndex: 5, - FullWithdrawalIndices: []types.ValidatorIndex{70}, + FullWithdrawalIndices: []primitives.ValidatorIndex{70}, Withdrawals: []*enginev1.Withdrawal{ fullWithdrawal(70, 3), }, @@ -324,7 +324,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "success one partial withdrawal", NextWithdrawalIndex: 21, NextWithdrawalValidatorIndex: 120, - PartialWithdrawalIndices: []types.ValidatorIndex{7}, + PartialWithdrawalIndices: []primitives.ValidatorIndex{7}, Withdrawals: []*enginev1.Withdrawal{ partialWithdrawal(7, 21), }, @@ -340,7 +340,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "success many full withdrawals", NextWithdrawalIndex: 22, NextWithdrawalValidatorIndex: 4, - FullWithdrawalIndices: []types.ValidatorIndex{7, 19, 28, 1}, + FullWithdrawalIndices: []primitives.ValidatorIndex{7, 19, 28, 1}, Withdrawals: []*enginev1.Withdrawal{ fullWithdrawal(7, 22), fullWithdrawal(19, 23), fullWithdrawal(28, 24), }, @@ -356,7 +356,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "Less than max sweep at end", NextWithdrawalIndex: 22, NextWithdrawalValidatorIndex: 4, - FullWithdrawalIndices: []types.ValidatorIndex{80, 81, 82, 83}, + FullWithdrawalIndices: []primitives.ValidatorIndex{80, 81, 82, 83}, Withdrawals: []*enginev1.Withdrawal{ fullWithdrawal(80, 22), fullWithdrawal(81, 23), fullWithdrawal(82, 24), fullWithdrawal(83, 25), @@ -373,7 +373,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "Less than max sweep and beginning", NextWithdrawalIndex: 22, NextWithdrawalValidatorIndex: 4, - FullWithdrawalIndices: []types.ValidatorIndex{4, 5, 6}, + FullWithdrawalIndices: []primitives.ValidatorIndex{4, 5, 6}, Withdrawals: []*enginev1.Withdrawal{ fullWithdrawal(4, 22), fullWithdrawal(5, 23), fullWithdrawal(6, 24), }, @@ -389,7 +389,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "success many partial withdrawals", NextWithdrawalIndex: 22, NextWithdrawalValidatorIndex: 4, - PartialWithdrawalIndices: []types.ValidatorIndex{7, 19, 28}, + PartialWithdrawalIndices: []primitives.ValidatorIndex{7, 19, 28}, Withdrawals: []*enginev1.Withdrawal{ partialWithdrawal(7, 22), partialWithdrawal(19, 23), partialWithdrawal(28, 24), }, @@ -409,8 +409,8 @@ func TestProcessWithdrawals(t *testing.T) { Name: "success many withdrawals", NextWithdrawalIndex: 22, NextWithdrawalValidatorIndex: 88, - FullWithdrawalIndices: []types.ValidatorIndex{7, 19, 28}, - PartialWithdrawalIndices: []types.ValidatorIndex{2, 1, 89, 15}, + FullWithdrawalIndices: []primitives.ValidatorIndex{7, 19, 28}, + PartialWithdrawalIndices: []primitives.ValidatorIndex{2, 1, 89, 15}, Withdrawals: []*enginev1.Withdrawal{ partialWithdrawal(89, 22), partialWithdrawal(1, 23), partialWithdrawal(2, 24), fullWithdrawal(7, 25), partialWithdrawal(15, 26), fullWithdrawal(19, 27), @@ -432,7 +432,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "success more than max fully withdrawals", NextWithdrawalIndex: 22, NextWithdrawalValidatorIndex: 0, - FullWithdrawalIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6, 7, 8, 9, 21, 22, 23, 24, 25, 26, 27, 29, 35, 89}, + FullWithdrawalIndices: []primitives.ValidatorIndex{1, 2, 3, 4, 5, 6, 7, 8, 9, 21, 22, 23, 24, 25, 26, 27, 29, 35, 89}, Withdrawals: []*enginev1.Withdrawal{ fullWithdrawal(1, 22), fullWithdrawal(2, 23), fullWithdrawal(3, 24), fullWithdrawal(4, 25), fullWithdrawal(5, 26), fullWithdrawal(6, 27), @@ -456,7 +456,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "success more than max partially withdrawals", NextWithdrawalIndex: 22, NextWithdrawalValidatorIndex: 0, - PartialWithdrawalIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6, 7, 8, 9, 21, 22, 23, 24, 25, 26, 27, 29, 35, 89}, + PartialWithdrawalIndices: []primitives.ValidatorIndex{1, 2, 3, 4, 5, 6, 7, 8, 9, 21, 22, 23, 24, 25, 26, 27, 29, 35, 89}, Withdrawals: []*enginev1.Withdrawal{ partialWithdrawal(1, 22), partialWithdrawal(2, 23), partialWithdrawal(3, 24), partialWithdrawal(4, 25), partialWithdrawal(5, 26), partialWithdrawal(6, 27), @@ -494,7 +494,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "failure wrong number of partial withdrawal", NextWithdrawalIndex: 21, NextWithdrawalValidatorIndex: 37, - PartialWithdrawalIndices: []types.ValidatorIndex{7}, + PartialWithdrawalIndices: []primitives.ValidatorIndex{7}, Withdrawals: []*enginev1.Withdrawal{ partialWithdrawal(7, 21), partialWithdrawal(9, 22), }, @@ -508,7 +508,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "failure invalid withdrawal index", NextWithdrawalIndex: 22, NextWithdrawalValidatorIndex: 4, - FullWithdrawalIndices: []types.ValidatorIndex{7, 19, 28, 1}, + FullWithdrawalIndices: []primitives.ValidatorIndex{7, 19, 28, 1}, Withdrawals: []*enginev1.Withdrawal{ fullWithdrawal(7, 22), fullWithdrawal(19, 23), fullWithdrawal(28, 25), fullWithdrawal(1, 25), @@ -523,7 +523,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "failure invalid validator index", NextWithdrawalIndex: 22, NextWithdrawalValidatorIndex: 4, - FullWithdrawalIndices: []types.ValidatorIndex{7, 19, 28, 1}, + FullWithdrawalIndices: []primitives.ValidatorIndex{7, 19, 28, 1}, Withdrawals: []*enginev1.Withdrawal{ fullWithdrawal(7, 22), fullWithdrawal(19, 23), fullWithdrawal(27, 24), fullWithdrawal(1, 25), @@ -538,7 +538,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "failure invalid withdrawal amount", NextWithdrawalIndex: 22, NextWithdrawalValidatorIndex: 4, - FullWithdrawalIndices: []types.ValidatorIndex{7, 19, 28, 1}, + FullWithdrawalIndices: []primitives.ValidatorIndex{7, 19, 28, 1}, Withdrawals: []*enginev1.Withdrawal{ fullWithdrawal(7, 22), fullWithdrawal(19, 23), partialWithdrawal(28, 24), fullWithdrawal(1, 25), @@ -553,7 +553,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "failure validator not fully withdrawable", NextWithdrawalIndex: 22, NextWithdrawalValidatorIndex: 4, - FullWithdrawalIndices: []types.ValidatorIndex{notWithdrawableIndex}, + FullWithdrawalIndices: []primitives.ValidatorIndex{notWithdrawableIndex}, Withdrawals: []*enginev1.Withdrawal{ fullWithdrawal(notWithdrawableIndex, 22), }, @@ -567,7 +567,7 @@ func TestProcessWithdrawals(t *testing.T) { Name: "failure validator not partially withdrawable", NextWithdrawalIndex: 22, NextWithdrawalValidatorIndex: 4, - PartialWithdrawalIndices: []types.ValidatorIndex{notPartiallyWithdrawable}, + PartialWithdrawalIndices: []primitives.ValidatorIndex{notPartiallyWithdrawable}, Withdrawals: []*enginev1.Withdrawal{ fullWithdrawal(notPartiallyWithdrawable, 22), }, @@ -627,10 +627,10 @@ func TestProcessWithdrawals(t *testing.T) { test.Args.Withdrawals = make([]*enginev1.Withdrawal, 0) } if test.Args.FullWithdrawalIndices == nil { - test.Args.FullWithdrawalIndices = make([]types.ValidatorIndex, 0) + test.Args.FullWithdrawalIndices = make([]primitives.ValidatorIndex, 0) } if test.Args.PartialWithdrawalIndices == nil { - test.Args.PartialWithdrawalIndices = make([]types.ValidatorIndex, 0) + test.Args.PartialWithdrawalIndices = make([]primitives.ValidatorIndex, 0) } slot, err := slots.EpochStart(currentEpoch) require.NoError(t, err) @@ -680,7 +680,7 @@ func TestProcessBLSToExecutionChanges(t *testing.T) { message := ðpb.BLSToExecutionChange{ ToExecutionAddress: executionAddress, - ValidatorIndex: types.ValidatorIndex(i), + ValidatorIndex: primitives.ValidatorIndex(i), FromBlsPubkey: pubkey, } @@ -754,7 +754,7 @@ func TestBLSChangesSignatureBatch(t *testing.T) { message := ðpb.BLSToExecutionChange{ ToExecutionAddress: executionAddress, - ValidatorIndex: types.ValidatorIndex(i), + ValidatorIndex: primitives.ValidatorIndex(i), FromBlsPubkey: pubkey, } @@ -819,7 +819,7 @@ func TestBLSChangesSignatureBatchWrongFork(t *testing.T) { message := ðpb.BLSToExecutionChange{ ToExecutionAddress: executionAddress, - ValidatorIndex: types.ValidatorIndex(i), + ValidatorIndex: primitives.ValidatorIndex(i), FromBlsPubkey: pubkey, } @@ -893,7 +893,7 @@ func TestBLSChangesSignatureBatchFromBellatrix(t *testing.T) { message := ðpb.BLSToExecutionChange{ ToExecutionAddress: executionAddress, - ValidatorIndex: types.ValidatorIndex(i), + ValidatorIndex: primitives.ValidatorIndex(i), FromBlsPubkey: pubkey, } diff --git a/beacon-chain/core/capella/upgrade_test.go b/beacon-chain/core/capella/upgrade_test.go index 4787d73889..a7023882b4 100644 --- a/beacon-chain/core/capella/upgrade_test.go +++ b/beacon-chain/core/capella/upgrade_test.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/capella" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -96,7 +96,7 @@ func TestUpgradeToCapella(t *testing.T) { lwvi, err := mSt.NextWithdrawalValidatorIndex() require.NoError(t, err) - require.Equal(t, types.ValidatorIndex(0), lwvi) + require.Equal(t, primitives.ValidatorIndex(0), lwvi) summaries, err := mSt.HistoricalSummaries() require.NoError(t, err) diff --git a/beacon-chain/core/epoch/epoch_processing.go b/beacon-chain/core/epoch/epoch_processing.go index 5bfc5f5680..04ded55978 100644 --- a/beacon-chain/core/epoch/epoch_processing.go +++ b/beacon-chain/core/epoch/epoch_processing.go @@ -17,7 +17,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/math" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/attestation" @@ -27,7 +27,7 @@ import ( // sortableIndices implements the Sort interface to sort newly activated validator indices // by activation epoch and by index number. type sortableIndices struct { - indices []types.ValidatorIndex + indices []primitives.ValidatorIndex validators []*ethpb.Validator } @@ -101,7 +101,7 @@ func ProcessRegistryUpdates(ctx context.Context, state state.BeaconState) (state // Process the validators for activation eligibility. if helpers.IsEligibleForActivationQueue(validator) { validator.ActivationEligibilityEpoch = activationEligibilityEpoch - if err := state.UpdateValidatorAtIndex(types.ValidatorIndex(idx), validator); err != nil { + if err := state.UpdateValidatorAtIndex(primitives.ValidatorIndex(idx), validator); err != nil { return nil, err } } @@ -110,7 +110,7 @@ func ProcessRegistryUpdates(ctx context.Context, state state.BeaconState) (state isActive := helpers.IsActiveValidator(validator, currentEpoch) belowEjectionBalance := validator.EffectiveBalance <= ejectionBal if isActive && belowEjectionBalance { - state, err = validators.InitiateValidatorExit(ctx, state, types.ValidatorIndex(idx)) + state, err = validators.InitiateValidatorExit(ctx, state, primitives.ValidatorIndex(idx)) if err != nil { return nil, errors.Wrapf(err, "could not initiate exit for validator %d", idx) } @@ -118,10 +118,10 @@ func ProcessRegistryUpdates(ctx context.Context, state state.BeaconState) (state } // Queue validators eligible for activation and not yet dequeued for activation. - var activationQ []types.ValidatorIndex + var activationQ []primitives.ValidatorIndex for idx, validator := range vals { if helpers.IsEligibleForActivation(state, validator) { - activationQ = append(activationQ, types.ValidatorIndex(idx)) + activationQ = append(activationQ, primitives.ValidatorIndex(idx)) } } @@ -199,7 +199,7 @@ func ProcessSlashings(state state.BeaconState, slashingMultiplier uint64) (state if val.Slashed && correctEpoch { penaltyNumerator := val.EffectiveBalance / increment * minSlashing penalty := penaltyNumerator / totalBalance * increment - if err := helpers.DecreaseBalance(state, types.ValidatorIndex(idx), penalty); err != nil { + if err := helpers.DecreaseBalance(state, primitives.ValidatorIndex(idx), penalty); err != nil { return false, val, err } return true, val, nil @@ -460,8 +460,8 @@ func ProcessFinalUpdates(state state.BeaconState) (state.BeaconState, error) { // for a in attestations: // output = output.union(get_attesting_indices(state, a.data, a.aggregation_bits)) // return set(filter(lambda index: not state.validators[index].slashed, output)) -func UnslashedAttestingIndices(ctx context.Context, state state.ReadOnlyBeaconState, atts []*ethpb.PendingAttestation) ([]types.ValidatorIndex, error) { - var setIndices []types.ValidatorIndex +func UnslashedAttestingIndices(ctx context.Context, state state.ReadOnlyBeaconState, atts []*ethpb.PendingAttestation) ([]primitives.ValidatorIndex, error) { + var setIndices []primitives.ValidatorIndex seen := make(map[uint64]bool) for _, att := range atts { @@ -476,7 +476,7 @@ func UnslashedAttestingIndices(ctx context.Context, state state.ReadOnlyBeaconSt // Create a set for attesting indices for _, index := range attestingIndices { if !seen[index] { - setIndices = append(setIndices, types.ValidatorIndex(index)) + setIndices = append(setIndices, primitives.ValidatorIndex(index)) } seen[index] = true } diff --git a/beacon-chain/core/epoch/epoch_processing_test.go b/beacon-chain/core/epoch/epoch_processing_test.go index 0aa5109a46..1fea78d019 100644 --- a/beacon-chain/core/epoch/epoch_processing_test.go +++ b/beacon-chain/core/epoch/epoch_processing_test.go @@ -16,7 +16,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -116,7 +116,7 @@ func TestAttestingBalance_CorrectBalance(t *testing.T) { Data: ðpb.AttestationData{ Target: ðpb.Checkpoint{Root: make([]byte, fieldparams.RootLength)}, Source: ðpb.Checkpoint{Root: make([]byte, fieldparams.RootLength)}, - Slot: types.Slot(i), + Slot: primitives.Slot(i), }, AggregationBits: bitfield.Bitlist{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01}, @@ -383,7 +383,7 @@ func TestProcessRegistryUpdates_ValidatorsEjected(t *testing.T) { } func TestProcessRegistryUpdates_CanExits(t *testing.T) { - e := types.Epoch(5) + e := primitives.Epoch(5) exitEpoch := helpers.ActivationExitEpoch(e) minWithdrawalDelay := params.BeaconConfig().MinValidatorWithdrawabilityDelay base := ðpb.BeaconState{ @@ -407,7 +407,7 @@ func TestProcessRegistryUpdates_CanExits(t *testing.T) { } } -func buildState(t testing.TB, slot types.Slot, validatorCount uint64) state.BeaconState { +func buildState(t testing.TB, slot primitives.Slot, validatorCount uint64) state.BeaconState { validators := make([]*ethpb.Validator, validatorCount) for i := 0; i < len(validators); i++ { validators[i] = ðpb.Validator{ diff --git a/beacon-chain/core/epoch/precompute/attestation.go b/beacon-chain/core/epoch/precompute/attestation.go index 11f54a2089..235c726079 100644 --- a/beacon-chain/core/epoch/precompute/attestation.go +++ b/beacon-chain/core/epoch/precompute/attestation.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/attestation" @@ -117,7 +117,7 @@ func AttestedPrevEpoch(s state.ReadOnlyBeaconState, a *ethpb.PendingAttestation) } // SameTarget returns true if attestation `a` attested to the same target block in state. -func SameTarget(state state.ReadOnlyBeaconState, a *ethpb.PendingAttestation, e types.Epoch) (bool, error) { +func SameTarget(state state.ReadOnlyBeaconState, a *ethpb.PendingAttestation, e primitives.Epoch) (bool, error) { r, err := helpers.BlockRoot(state, e) if err != nil { return false, err @@ -141,7 +141,7 @@ func SameHead(state state.ReadOnlyBeaconState, a *ethpb.PendingAttestation) (boo } // UpdateValidator updates pre computed validator store. -func UpdateValidator(vp []*Validator, record *Validator, indices []uint64, a *ethpb.PendingAttestation, aSlot types.Slot) []*Validator { +func UpdateValidator(vp []*Validator, record *Validator, indices []uint64, a *ethpb.PendingAttestation, aSlot primitives.Slot) []*Validator { inclusionSlot := aSlot + a.InclusionDelay for _, i := range indices { diff --git a/beacon-chain/core/epoch/precompute/justification_finalization_test.go b/beacon-chain/core/epoch/precompute/justification_finalization_test.go index a4a6aabde5..d052c9b09b 100644 --- a/beacon-chain/core/epoch/precompute/justification_finalization_test.go +++ b/beacon-chain/core/epoch/precompute/justification_finalization_test.go @@ -10,7 +10,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -47,10 +47,10 @@ func TestProcessJustificationAndFinalizationPreCompute_ConsecutiveEpochs(t *test require.NoError(t, err) rt := [32]byte{byte(64)} assert.DeepEqual(t, rt[:], newState.CurrentJustifiedCheckpoint().Root, "Unexpected justified root") - 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.Equal(t, primitives.Epoch(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch") + assert.Equal(t, primitives.Epoch(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch") assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], newState.FinalizedCheckpoint().Root, "Unexpected finalized root") - assert.Equal(t, types.Epoch(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch") + assert.Equal(t, primitives.Epoch(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch") } func TestProcessJustificationAndFinalizationPreCompute_JustifyCurrentEpoch(t *testing.T) { @@ -84,10 +84,10 @@ func TestProcessJustificationAndFinalizationPreCompute_JustifyCurrentEpoch(t *te require.NoError(t, err) rt := [32]byte{byte(64)} assert.DeepEqual(t, rt[:], newState.CurrentJustifiedCheckpoint().Root, "Unexpected current justified root") - 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.Equal(t, primitives.Epoch(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch") + assert.Equal(t, primitives.Epoch(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch") assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], newState.FinalizedCheckpoint().Root) - assert.Equal(t, types.Epoch(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch") + assert.Equal(t, primitives.Epoch(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch") } func TestProcessJustificationAndFinalizationPreCompute_JustifyPrevEpoch(t *testing.T) { @@ -120,10 +120,10 @@ func TestProcessJustificationAndFinalizationPreCompute_JustifyPrevEpoch(t *testi require.NoError(t, err) rt := [32]byte{byte(64)} assert.DeepEqual(t, rt[:], newState.CurrentJustifiedCheckpoint().Root, "Unexpected current justified root") - 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.Equal(t, primitives.Epoch(0), newState.PreviousJustifiedCheckpoint().Epoch, "Unexpected previous justified epoch") + assert.Equal(t, primitives.Epoch(2), newState.CurrentJustifiedCheckpoint().Epoch, "Unexpected justified epoch") assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], newState.FinalizedCheckpoint().Root) - assert.Equal(t, types.Epoch(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch") + assert.Equal(t, primitives.Epoch(0), newState.FinalizedCheckpointEpoch(), "Unexpected finalized epoch") } func TestUnrealizedCheckpoints(t *testing.T) { @@ -138,16 +138,16 @@ func TestUnrealizedCheckpoints(t *testing.T) { } pjr := [32]byte{'p'} cjr := [32]byte{'c'} - je := types.Epoch(3) - fe := types.Epoch(2) + je := primitives.Epoch(3) + fe := primitives.Epoch(2) pjcp := ðpb.Checkpoint{Root: pjr[:], Epoch: fe} cjcp := ðpb.Checkpoint{Root: cjr[:], Epoch: je} fcp := ðpb.Checkpoint{Root: pjr[:], Epoch: fe} tests := []struct { name string - slot types.Slot + slot primitives.Slot prevVals, currVals int - expectedJustified, expectedFinalized types.Epoch // The expected unrealized checkpoint epochs + expectedJustified, expectedFinalized primitives.Epoch // The expected unrealized checkpoint epochs }{ { "Not enough votes, keep previous justification", @@ -264,5 +264,5 @@ func Test_ComputeCheckpoints_CantUpdateToLower(t *testing.T) { jb.SetBitAt(1, true) cp, _, err := precompute.ComputeCheckpoints(st, jb) require.NoError(t, err) - require.Equal(t, types.Epoch(2), cp.Epoch) + require.Equal(t, primitives.Epoch(2), cp.Epoch) } diff --git a/beacon-chain/core/epoch/precompute/reward_penalty.go b/beacon-chain/core/epoch/precompute/reward_penalty.go index af30857791..68d7a3b5d0 100644 --- a/beacon-chain/core/epoch/precompute/reward_penalty.go +++ b/beacon-chain/core/epoch/precompute/reward_penalty.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/math" ) @@ -79,7 +79,7 @@ func AttestationsDelta(state state.ReadOnlyBeaconState, pBal *Balance, vp []*Val return rewards, penalties, nil } -func attestationDelta(pBal *Balance, sqrtActiveCurrentEpoch uint64, v *Validator, prevEpoch, finalizedEpoch types.Epoch) (uint64, uint64) { +func attestationDelta(pBal *Balance, sqrtActiveCurrentEpoch uint64, v *Validator, prevEpoch, finalizedEpoch primitives.Epoch) (uint64, uint64) { if !EligibleForRewards(v) || pBal.ActiveCurrentEpoch == 0 { return 0, 0 } diff --git a/beacon-chain/core/epoch/precompute/reward_penalty_test.go b/beacon-chain/core/epoch/precompute/reward_penalty_test.go index e748d3d450..ae50879c80 100644 --- a/beacon-chain/core/epoch/precompute/reward_penalty_test.go +++ b/beacon-chain/core/epoch/precompute/reward_penalty_test.go @@ -13,7 +13,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/math" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -83,7 +83,7 @@ func TestAttestationDeltaPrecompute(t *testing.T) { base.PreviousEpochAttestations = atts beaconState, err := state_native.InitializeFromProtoPhase0(base) require.NoError(t, err) - slashedAttestedIndices := []types.ValidatorIndex{1413} + slashedAttestedIndices := []primitives.ValidatorIndex{1413} for _, i := range slashedAttestedIndices { vs := beaconState.Validators() vs[i].Slashed = true @@ -106,7 +106,7 @@ func TestAttestationDeltaPrecompute(t *testing.T) { totalBalance, err := helpers.TotalActiveBalance(beaconState) require.NoError(t, err) - attestedIndices := []types.ValidatorIndex{55, 1339, 1746, 1811, 1569} + attestedIndices := []primitives.ValidatorIndex{55, 1339, 1746, 1811, 1569} for _, i := range attestedIndices { base, err := baseReward(beaconState, i) require.NoError(t, err, "Could not get base reward") @@ -131,7 +131,7 @@ func TestAttestationDeltaPrecompute(t *testing.T) { assert.Equal(t, 3*base, penalties[i], "Unexpected slashed indices penalty balance") } - nonAttestedIndices := []types.ValidatorIndex{434, 677, 872, 791} + nonAttestedIndices := []primitives.ValidatorIndex{434, 677, 872, 791} for _, i := range nonAttestedIndices { base, err := baseReward(beaconState, i) assert.NoError(t, err, "Could not get base reward") @@ -233,7 +233,7 @@ func TestProcessRewardsAndPenaltiesPrecompute_SlashedInactivePenalty(t *testing. require.NoError(t, err) require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch*10)) - slashedAttestedIndices := []types.ValidatorIndex{14, 37, 68, 77, 139} + slashedAttestedIndices := []primitives.ValidatorIndex{14, 37, 68, 77, 139} for _, i := range slashedAttestedIndices { vs := beaconState.Validators() vs[i].Slashed = true @@ -260,7 +260,7 @@ func TestProcessRewardsAndPenaltiesPrecompute_SlashedInactivePenalty(t *testing. } } -func buildState(slot types.Slot, validatorCount uint64) *ethpb.BeaconState { +func buildState(slot primitives.Slot, validatorCount uint64) *ethpb.BeaconState { validators := make([]*ethpb.Validator, validatorCount) for i := 0; i < len(validators); i++ { validators[i] = ðpb.Validator{ @@ -306,7 +306,7 @@ func TestProposerDeltaPrecompute_HappyCase(t *testing.T) { beaconState, err := state_native.InitializeFromProtoPhase0(base) require.NoError(t, err) - proposerIndex := types.ValidatorIndex(1) + proposerIndex := primitives.ValidatorIndex(1) b := &Balance{ActiveCurrentEpoch: 1000} v := []*Validator{ {IsPrevEpochAttester: true, CurrentEpochEffectiveBalance: 32, ProposerIndex: proposerIndex}, @@ -328,7 +328,7 @@ func TestProposerDeltaPrecompute_ValidatorIndexOutOfRange(t *testing.T) { beaconState, err := state_native.InitializeFromProtoPhase0(base) require.NoError(t, err) - proposerIndex := types.ValidatorIndex(validatorCount) + proposerIndex := primitives.ValidatorIndex(validatorCount) b := &Balance{ActiveCurrentEpoch: 1000} v := []*Validator{ {IsPrevEpochAttester: true, CurrentEpochEffectiveBalance: 32, ProposerIndex: proposerIndex}, @@ -344,7 +344,7 @@ func TestProposerDeltaPrecompute_SlashedCase(t *testing.T) { beaconState, err := state_native.InitializeFromProtoPhase0(base) require.NoError(t, err) - proposerIndex := types.ValidatorIndex(1) + proposerIndex := primitives.ValidatorIndex(1) b := &Balance{ActiveCurrentEpoch: 1000} v := []*Validator{ {IsPrevEpochAttester: true, CurrentEpochEffectiveBalance: 32, ProposerIndex: proposerIndex, IsSlashed: true}, @@ -363,7 +363,7 @@ func TestProposerDeltaPrecompute_SlashedCase(t *testing.T) { // total_balance = get_total_active_balance(state) // effective_balance = state.validators[index].effective_balance // return Gwei(effective_balance * BASE_REWARD_FACTOR // integer_squareroot(total_balance) // BASE_REWARDS_PER_EPOCH) -func baseReward(state state.ReadOnlyBeaconState, index types.ValidatorIndex) (uint64, error) { +func baseReward(state state.ReadOnlyBeaconState, index primitives.ValidatorIndex) (uint64, error) { totalBalance, err := helpers.TotalActiveBalance(state) if err != nil { return 0, errors.Wrap(err, "could not calculate active balance") diff --git a/beacon-chain/core/epoch/precompute/slashing.go b/beacon-chain/core/epoch/precompute/slashing.go index 28fb1f859e..de30e3c7c2 100644 --- a/beacon-chain/core/epoch/precompute/slashing.go +++ b/beacon-chain/core/epoch/precompute/slashing.go @@ -5,7 +5,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/math" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -49,7 +49,7 @@ func ProcessSlashingsPrecompute(s state.BeaconState, pBal *Balance) error { if val.Slashed && correctEpoch { penaltyNumerator := val.EffectiveBalance / increment * minSlashing penalty := penaltyNumerator / pBal.ActiveCurrentEpoch * increment - if err := helpers.DecreaseBalance(s, types.ValidatorIndex(idx), penalty); err != nil { + if err := helpers.DecreaseBalance(s, primitives.ValidatorIndex(idx), penalty); err != nil { return false, val, err } return true, val, nil diff --git a/beacon-chain/core/epoch/precompute/type.go b/beacon-chain/core/epoch/precompute/type.go index d76025cd11..4d7e2c1043 100644 --- a/beacon-chain/core/epoch/precompute/type.go +++ b/beacon-chain/core/epoch/precompute/type.go @@ -1,6 +1,6 @@ package precompute -import types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" +import "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" // Validator stores the pre computation of individual validator's attesting records these records // consist of attestation votes, block inclusion record. Pre computing and storing such record @@ -30,11 +30,11 @@ type Validator struct { // CurrentEpochEffectiveBalance is how much effective balance this validator has current epoch. CurrentEpochEffectiveBalance uint64 // InclusionSlot is the slot of when the attestation gets included in the chain. - InclusionSlot types.Slot + InclusionSlot primitives.Slot // InclusionDistance is the distance between the assigned slot and this validator's attestation was included in block. - InclusionDistance types.Slot + InclusionDistance primitives.Slot // ProposerIndex is the index of proposer at slot where this validator's attestation was included. - ProposerIndex types.ValidatorIndex + ProposerIndex primitives.ValidatorIndex // BeforeEpochTransitionBalance is the validator balance prior to epoch transition. BeforeEpochTransitionBalance uint64 // AfterEpochTransitionBalance is the validator balance after epoch transition. diff --git a/beacon-chain/core/feed/state/events.go b/beacon-chain/core/feed/state/events.go index 6055cf4ccd..e372447ef3 100644 --- a/beacon-chain/core/feed/state/events.go +++ b/beacon-chain/core/feed/state/events.go @@ -7,7 +7,7 @@ import ( "time" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) const ( @@ -31,7 +31,7 @@ const ( // BlockProcessedData is the data sent with BlockProcessed events. type BlockProcessedData struct { // Slot is the slot of the processed block. - Slot types.Slot + Slot primitives.Slot // BlockRoot of the processed block. BlockRoot [32]byte // SignedBlock is the physical processed block. diff --git a/beacon-chain/core/helpers/attestation.go b/beacon-chain/core/helpers/attestation.go index 325bf16d40..7540c80ea3 100644 --- a/beacon-chain/core/helpers/attestation.go +++ b/beacon-chain/core/helpers/attestation.go @@ -7,7 +7,7 @@ import ( "time" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/hash" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -124,7 +124,7 @@ func ComputeSubnetForAttestation(activeValCount uint64, att *ethpb.Attestation) // committees_since_epoch_start = committees_per_slot * slots_since_epoch_start // // return uint64((committees_since_epoch_start + committee_index) % ATTESTATION_SUBNET_COUNT) -func ComputeSubnetFromCommitteeAndSlot(activeValCount uint64, comIdx types.CommitteeIndex, attSlot types.Slot) uint64 { +func ComputeSubnetFromCommitteeAndSlot(activeValCount uint64, comIdx primitives.CommitteeIndex, attSlot primitives.Slot) uint64 { slotSinceStart := slots.SinceEpochStarts(attSlot) comCount := SlotCommitteeCount(activeValCount) commsSinceStart := uint64(slotSinceStart.Mul(comCount)) @@ -147,7 +147,7 @@ func ComputeSubnetFromCommitteeAndSlot(activeValCount uint64, comIdx types.Commi // valid_attestation_slot = 101 // // In the attestation must be within the range of 95 to 102 in the example above. -func ValidateAttestationTime(attSlot types.Slot, genesisTime time.Time, clockDisparity time.Duration) error { +func ValidateAttestationTime(attSlot primitives.Slot, genesisTime time.Time, clockDisparity time.Duration) error { if err := slots.ValidateClock(attSlot, uint64(genesisTime.Unix())); err != nil { return err } @@ -165,7 +165,7 @@ func ValidateAttestationTime(attSlot types.Slot, genesisTime time.Time, clockDis // An attestation cannot be older than the current slot - attestation propagation slot range // with a minor tolerance for peer clock disparity. - lowerBoundsSlot := types.Slot(0) + lowerBoundsSlot := primitives.Slot(0) if currentSlot > params.BeaconNetworkConfig().AttestationPropagationSlotRange { lowerBoundsSlot = currentSlot - params.BeaconNetworkConfig().AttestationPropagationSlotRange } @@ -198,10 +198,10 @@ func ValidateAttestationTime(attSlot types.Slot, genesisTime time.Time, clockDis func VerifyCheckpointEpoch(c *ethpb.Checkpoint, genesis time.Time) bool { now := uint64(prysmTime.Now().Unix()) genesisTime := uint64(genesis.Unix()) - currentSlot := types.Slot((now - genesisTime) / params.BeaconConfig().SecondsPerSlot) + currentSlot := primitives.Slot((now - genesisTime) / params.BeaconConfig().SecondsPerSlot) currentEpoch := slots.ToEpoch(currentSlot) - var prevEpoch types.Epoch + var prevEpoch primitives.Epoch if currentEpoch > 1 { prevEpoch = currentEpoch - 1 } diff --git a/beacon-chain/core/helpers/attestation_test.go b/beacon-chain/core/helpers/attestation_test.go index 200507736c..6dfa899386 100644 --- a/beacon-chain/core/helpers/attestation_test.go +++ b/beacon-chain/core/helpers/attestation_test.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -130,7 +130,7 @@ func Test_ValidateAttestationTime(t *testing.T) { } type args struct { - attSlot types.Slot + attSlot primitives.Slot genesisTime time.Time } tests := []struct { diff --git a/beacon-chain/core/helpers/beacon_committee.go b/beacon-chain/core/helpers/beacon_committee.go index ec700c68e1..771c6d4c3b 100644 --- a/beacon-chain/core/helpers/beacon_committee.go +++ b/beacon-chain/core/helpers/beacon_committee.go @@ -14,7 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -75,7 +75,7 @@ func SlotCommitteeCount(activeValidatorCount uint64) uint64 { // index=(slot % SLOTS_PER_EPOCH) * committees_per_slot + index, // count=committees_per_slot * SLOTS_PER_EPOCH, // ) -func BeaconCommitteeFromState(ctx context.Context, state state.ReadOnlyBeaconState, slot types.Slot, committeeIndex types.CommitteeIndex) ([]types.ValidatorIndex, error) { +func BeaconCommitteeFromState(ctx context.Context, state state.ReadOnlyBeaconState, slot primitives.Slot, committeeIndex primitives.CommitteeIndex) ([]primitives.ValidatorIndex, error) { epoch := slots.ToEpoch(slot) seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester) if err != nil { @@ -118,11 +118,11 @@ func BeaconCommitteeFromState(ctx context.Context, state state.ReadOnlyBeaconSta // ) func BeaconCommittee( ctx context.Context, - validatorIndices []types.ValidatorIndex, + validatorIndices []primitives.ValidatorIndex, seed [32]byte, - slot types.Slot, - committeeIndex types.CommitteeIndex, -) ([]types.ValidatorIndex, error) { + slot primitives.Slot, + committeeIndex primitives.CommitteeIndex, +) ([]primitives.ValidatorIndex, error) { committee, err := committeeCache.Committee(ctx, slot, seed, committeeIndex) if err != nil { return nil, errors.Wrap(err, "could not interface with committee cache") @@ -144,9 +144,9 @@ func BeaconCommittee( // CommitteeAssignmentContainer represents a committee list, committee index, and to be attested slot for a given epoch. type CommitteeAssignmentContainer struct { - Committee []types.ValidatorIndex - AttesterSlot types.Slot - CommitteeIndex types.CommitteeIndex + Committee []primitives.ValidatorIndex + AttesterSlot primitives.Slot + CommitteeIndex primitives.CommitteeIndex } // CommitteeAssignments is a map of validator indices pointing to the appropriate committee @@ -159,8 +159,8 @@ type CommitteeAssignmentContainer struct { func CommitteeAssignments( ctx context.Context, state state.BeaconState, - epoch types.Epoch, -) (map[types.ValidatorIndex]*CommitteeAssignmentContainer, map[types.ValidatorIndex][]types.Slot, error) { + epoch primitives.Epoch, +) (map[primitives.ValidatorIndex]*CommitteeAssignmentContainer, map[primitives.ValidatorIndex][]primitives.Slot, error) { nextEpoch := time.NextEpoch(state) if epoch > nextEpoch { return nil, nil, fmt.Errorf( @@ -177,7 +177,7 @@ func CommitteeAssignments( if err != nil { return nil, nil, err } - minValidStartSlot := types.Slot(0) + minValidStartSlot := primitives.Slot(0) if state.Slot() >= params.BeaconConfig().SlotsPerHistoricalRoot { minValidStartSlot = state.Slot() - params.BeaconConfig().SlotsPerHistoricalRoot } @@ -185,7 +185,7 @@ func CommitteeAssignments( return nil, nil, fmt.Errorf("start slot %d is smaller than the minimum valid start slot %d", startSlot, minValidStartSlot) } - proposerIndexToSlots := make(map[types.ValidatorIndex][]types.Slot, params.BeaconConfig().SlotsPerEpoch) + proposerIndexToSlots := make(map[primitives.ValidatorIndex][]primitives.Slot, params.BeaconConfig().SlotsPerEpoch) for slot := startSlot; slot < startSlot+params.BeaconConfig().SlotsPerEpoch; slot++ { // Skip proposer assignment for genesis slot. if slot == 0 { @@ -217,21 +217,21 @@ func CommitteeAssignments( // Each slot in an epoch has a different set of committees. This value is derived from the // active validator set, which does not change. numCommitteesPerSlot := SlotCommitteeCount(uint64(len(activeValidatorIndices))) - validatorIndexToCommittee := make(map[types.ValidatorIndex]*CommitteeAssignmentContainer, len(activeValidatorIndices)) + validatorIndexToCommittee := make(map[primitives.ValidatorIndex]*CommitteeAssignmentContainer, len(activeValidatorIndices)) // Compute all committees for all slots. - for i := types.Slot(0); i < params.BeaconConfig().SlotsPerEpoch; i++ { + for i := primitives.Slot(0); i < params.BeaconConfig().SlotsPerEpoch; i++ { // Compute committees. for j := uint64(0); j < numCommitteesPerSlot; j++ { slot := startSlot + i - committee, err := BeaconCommitteeFromState(ctx, state, slot, types.CommitteeIndex(j) /*committee index*/) + committee, err := BeaconCommitteeFromState(ctx, state, slot, primitives.CommitteeIndex(j) /*committee index*/) if err != nil { return nil, nil, err } cac := &CommitteeAssignmentContainer{ Committee: committee, - CommitteeIndex: types.CommitteeIndex(j), + CommitteeIndex: primitives.CommitteeIndex(j), AttesterSlot: slot, } for _, vIndex := range committee { @@ -274,16 +274,16 @@ func VerifyAttestationBitfieldLengths(ctx context.Context, state state.ReadOnlyB // 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(s state.ReadOnlyBeaconState, epoch types.Epoch) ([]types.ValidatorIndex, error) { +func ShuffledIndices(s state.ReadOnlyBeaconState, epoch primitives.Epoch) ([]primitives.ValidatorIndex, error) { seed, err := Seed(s, epoch, params.BeaconConfig().DomainBeaconAttester) if err != nil { return nil, errors.Wrapf(err, "could not get seed for epoch %d", epoch) } - indices := make([]types.ValidatorIndex, 0, s.NumValidators()) + indices := make([]primitives.ValidatorIndex, 0, s.NumValidators()) if err := s.ReadFromEveryValidator(func(idx int, val state.ReadOnlyValidator) error { if IsActiveValidatorUsingTrie(val, epoch) { - indices = append(indices, types.ValidatorIndex(idx)) + indices = append(indices, primitives.ValidatorIndex(idx)) } return nil }); err != nil { @@ -296,8 +296,8 @@ func ShuffledIndices(s state.ReadOnlyBeaconState, epoch types.Epoch) ([]types.Va // 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(ctx context.Context, state state.ReadOnlyBeaconState, epoch types.Epoch) error { - for _, e := range []types.Epoch{epoch, epoch + 1} { +func UpdateCommitteeCache(ctx context.Context, state state.ReadOnlyBeaconState, epoch primitives.Epoch) error { + for _, e := range []primitives.Epoch{epoch, epoch + 1} { seed, err := Seed(state, e, params.BeaconConfig().DomainBeaconAttester) if err != nil { return err @@ -316,7 +316,7 @@ func UpdateCommitteeCache(ctx context.Context, state state.ReadOnlyBeaconState, // Store the sorted indices as well as shuffled indices. In current spec, // sorted indices is required to retrieve proposer index. This is also // used for failing verify signature fallback. - sortedIndices := make([]types.ValidatorIndex, len(shuffledIndices)) + sortedIndices := make([]primitives.ValidatorIndex, len(shuffledIndices)) copy(sortedIndices, shuffledIndices) sort.Slice(sortedIndices, func(i, j int) bool { return sortedIndices[i] < sortedIndices[j] @@ -404,10 +404,10 @@ func ClearCache() { // end = (len(indices) * uint64(index + 1)) // count // return [indices[compute_shuffled_index(uint64(i), uint64(len(indices)), seed)] for i in range(start, end)] func computeCommittee( - indices []types.ValidatorIndex, + indices []primitives.ValidatorIndex, seed [32]byte, index, count uint64, -) ([]types.ValidatorIndex, error) { +) ([]primitives.ValidatorIndex, error) { validatorCount := uint64(len(indices)) start := slice.SplitOffset(validatorCount, count, index) end := slice.SplitOffset(validatorCount, count, index+1) @@ -417,7 +417,7 @@ func computeCommittee( } // Save the shuffled indices in cache, this is only needed once per epoch or once per new committee index. - shuffledIndices := make([]types.ValidatorIndex, len(indices)) + shuffledIndices := make([]primitives.ValidatorIndex, len(indices)) copy(shuffledIndices, indices) // UnshuffleList is used here as it is an optimized implementation created // for fast computation of committees. @@ -432,9 +432,9 @@ func computeCommittee( // This computes proposer indices of the current epoch and returns a list of proposer indices, // the index of the list represents the slot number. -func precomputeProposerIndices(state state.ReadOnlyBeaconState, activeIndices []types.ValidatorIndex) ([]types.ValidatorIndex, error) { +func precomputeProposerIndices(state state.ReadOnlyBeaconState, activeIndices []primitives.ValidatorIndex) ([]primitives.ValidatorIndex, error) { hashFunc := hash.CustomSHA256Hasher() - proposerIndices := make([]types.ValidatorIndex, params.BeaconConfig().SlotsPerEpoch) + proposerIndices := make([]primitives.ValidatorIndex, params.BeaconConfig().SlotsPerEpoch) e := time.CurrentEpoch(state) seed, err := Seed(state, e, params.BeaconConfig().DomainBeaconProposer) diff --git a/beacon-chain/core/helpers/beacon_committee_test.go b/beacon-chain/core/helpers/beacon_committee_test.go index fbde681d23..5c047abc1e 100644 --- a/beacon-chain/core/helpers/beacon_committee_test.go +++ b/beacon-chain/core/helpers/beacon_committee_test.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -71,7 +71,7 @@ func TestComputeCommittee_WithoutCache(t *testing.T) { } func TestComputeCommittee_RegressionTest(t *testing.T) { - indices := []types.ValidatorIndex{1, 3, 8, 16, 18, 19, 20, 23, 30, 35, 43, 46, 47, 54, 56, 58, 69, 70, 71, 83, 84, 85, 91, 96, 100, 103, 105, 106, 112, 121, 127, 128, 129, 140, 142, 144, 146, 147, 149, 152, 153, 154, 157, 160, 173, 175, 180, 182, 188, 189, 191, 194, 201, 204, 217, 221, 226, 228, 230, 231, 239, 241, 249, 250, 255} + indices := []primitives.ValidatorIndex{1, 3, 8, 16, 18, 19, 20, 23, 30, 35, 43, 46, 47, 54, 56, 58, 69, 70, 71, 83, 84, 85, 91, 96, 100, 103, 105, 106, 112, 121, 127, 128, 129, 140, 142, 144, 146, 147, 149, 152, 153, 154, 157, 160, 173, 175, 180, 182, 188, 189, 191, 194, 201, 204, 217, 221, 226, 228, 230, 231, 239, 241, 249, 250, 255} seed := [32]byte{68, 110, 161, 250, 98, 230, 161, 172, 227, 226, 99, 11, 138, 124, 201, 134, 38, 197, 0, 120, 6, 165, 122, 34, 19, 216, 43, 226, 210, 114, 165, 183} index := uint64(215) count := uint64(32) @@ -91,7 +91,7 @@ func TestVerifyBitfieldLength_OK(t *testing.T) { func TestCommitteeAssignments_CannotRetrieveFutureEpoch(t *testing.T) { ClearCache() - epoch := types.Epoch(1) + epoch := primitives.Epoch(1) state, err := state_native.InitializeFromProtoPhase0(ðpb.BeaconState{ Slot: 0, // Epoch 0. }) @@ -103,7 +103,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 types.Epoch + var activationEpoch primitives.Epoch if i >= len(validators)/2 { activationEpoch = 3 } @@ -133,7 +133,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 types.Epoch + var activationEpoch primitives.Epoch if i >= len(validators)/2 { activationEpoch = 3 } @@ -151,24 +151,24 @@ func TestCommitteeAssignments_CanRetrieve(t *testing.T) { require.NoError(t, err) tests := []struct { - index types.ValidatorIndex - slot types.Slot - committee []types.ValidatorIndex - committeeIndex types.CommitteeIndex + index primitives.ValidatorIndex + slot primitives.Slot + committee []primitives.ValidatorIndex + committeeIndex primitives.CommitteeIndex isProposer bool - proposerSlot types.Slot + proposerSlot primitives.Slot }{ { index: 0, slot: 78, - committee: []types.ValidatorIndex{0, 38}, + committee: []primitives.ValidatorIndex{0, 38}, committeeIndex: 0, isProposer: false, }, { index: 1, slot: 71, - committee: []types.ValidatorIndex{1, 4}, + committee: []primitives.ValidatorIndex{1, 4}, committeeIndex: 0, isProposer: true, proposerSlot: 79, @@ -176,13 +176,13 @@ func TestCommitteeAssignments_CanRetrieve(t *testing.T) { { index: 11, slot: 90, - committee: []types.ValidatorIndex{31, 11}, + committee: []primitives.ValidatorIndex{31, 11}, committeeIndex: 0, isProposer: false, }, { index: 2, slot: 127, // 3rd epoch has more active validators - committee: []types.ValidatorIndex{89, 2, 81, 5}, + committee: []primitives.ValidatorIndex{89, 2, 81, 5}, committeeIndex: 0, isProposer: false, }, @@ -210,7 +210,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 types.Epoch + var activationEpoch primitives.Epoch if i >= len(validators)/2 { activationEpoch = 3 } @@ -270,11 +270,11 @@ func TestCommitteeAssignments_EverySlotHasMin1Proposer(t *testing.T) { }) require.NoError(t, err) ClearCache() - epoch := types.Epoch(1) + epoch := primitives.Epoch(1) _, proposerIndexToSlots, err := CommitteeAssignments(context.Background(), state, epoch) require.NoError(t, err, "Failed to determine CommitteeAssignments") - slotsWithProposers := make(map[types.Slot]bool) + slotsWithProposers := make(map[primitives.Slot]bool) for _, proposerSlots := range proposerIndexToSlots { for _, slot := range proposerSlots { slotsWithProposers[slot] = true @@ -308,7 +308,7 @@ func TestVerifyAttestationBitfieldLengths_OK(t *testing.T) { tests := []struct { attestation *ethpb.Attestation - stateSlot types.Slot + stateSlot primitives.Slot verificationFailure bool }{ { @@ -392,8 +392,8 @@ func TestUpdateCommitteeCache_CanUpdate(t *testing.T) { ClearCache() validatorCount := params.BeaconConfig().MinGenesisActiveValidatorCount validators := make([]*ethpb.Validator, validatorCount) - indices := make([]types.ValidatorIndex, validatorCount) - for i := types.ValidatorIndex(0); uint64(i) < validatorCount; i++ { + indices := make([]primitives.ValidatorIndex, validatorCount) + for i := primitives.ValidatorIndex(0); uint64(i) < validatorCount; i++ { validators[i] = ðpb.Validator{ ExitEpoch: params.BeaconConfig().FarFutureEpoch, EffectiveBalance: 1, @@ -407,8 +407,8 @@ func TestUpdateCommitteeCache_CanUpdate(t *testing.T) { require.NoError(t, err) require.NoError(t, UpdateCommitteeCache(context.Background(), state, time.CurrentEpoch(state))) - epoch := types.Epoch(1) - idx := types.CommitteeIndex(1) + epoch := primitives.Epoch(1) + idx := primitives.CommitteeIndex(1) seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester) require.NoError(t, err) @@ -636,7 +636,7 @@ func TestPrecomputeProposerIndices_Ok(t *testing.T) { proposerIndices, err := precomputeProposerIndices(state, indices) require.NoError(t, err) - var wantedProposerIndices []types.ValidatorIndex + var wantedProposerIndices []primitives.ValidatorIndex seed, err := Seed(state, 0, params.BeaconConfig().DomainBeaconProposer) require.NoError(t, err) for i := uint64(0); i < uint64(params.BeaconConfig().SlotsPerEpoch); i++ { diff --git a/beacon-chain/core/helpers/block.go b/beacon-chain/core/helpers/block.go index 3c2531a876..2cb88306cc 100644 --- a/beacon-chain/core/helpers/block.go +++ b/beacon-chain/core/helpers/block.go @@ -6,7 +6,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/time/slots" ) @@ -21,7 +21,7 @@ import ( // """ // assert slot < state.slot <= slot + SLOTS_PER_HISTORICAL_ROOT // return state.block_roots[slot % SLOTS_PER_HISTORICAL_ROOT] -func BlockRootAtSlot(state state.ReadOnlyBeaconState, slot types.Slot) ([]byte, error) { +func BlockRootAtSlot(state state.ReadOnlyBeaconState, slot primitives.Slot) ([]byte, error) { if math.MaxUint64-slot < params.BeaconConfig().SlotsPerHistoricalRoot { return []byte{}, errors.New("slot overflows uint64") } @@ -33,7 +33,7 @@ func BlockRootAtSlot(state state.ReadOnlyBeaconState, slot types.Slot) ([]byte, // StateRootAtSlot returns the cached state root at that particular slot. If no state // root has been cached it will return a zero-hash. -func StateRootAtSlot(state state.ReadOnlyBeaconState, slot types.Slot) ([]byte, error) { +func StateRootAtSlot(state state.ReadOnlyBeaconState, slot primitives.Slot) ([]byte, error) { if slot >= state.Slot() || state.Slot() > slot+params.BeaconConfig().SlotsPerHistoricalRoot { return []byte{}, errors.Errorf("slot %d out of bounds", slot) } @@ -49,7 +49,7 @@ func StateRootAtSlot(state state.ReadOnlyBeaconState, slot types.Slot) ([]byte, // 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 state.ReadOnlyBeaconState, epoch types.Epoch) ([]byte, error) { +func BlockRoot(state state.ReadOnlyBeaconState, epoch primitives.Epoch) ([]byte, error) { s, err := slots.EpochStart(epoch) if err != nil { return nil, err diff --git a/beacon-chain/core/helpers/block_test.go b/beacon-chain/core/helpers/block_test.go index a0553704a7..16da474e7e 100644 --- a/beacon-chain/core/helpers/block_test.go +++ b/beacon-chain/core/helpers/block_test.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -25,8 +25,8 @@ func TestBlockRootAtSlot_CorrectBlockRoot(t *testing.T) { } tests := []struct { - slot types.Slot - stateSlot types.Slot + slot primitives.Slot + stateSlot primitives.Slot expectedRoot [32]byte }{ { @@ -82,8 +82,8 @@ func TestBlockRootAtSlot_OutOfBounds(t *testing.T) { } tests := []struct { - slot types.Slot - stateSlot types.Slot + slot primitives.Slot + stateSlot primitives.Slot expectedErr string }{ { diff --git a/beacon-chain/core/helpers/randao.go b/beacon-chain/core/helpers/randao.go index 6796cee999..59f88b58f3 100644 --- a/beacon-chain/core/helpers/randao.go +++ b/beacon-chain/core/helpers/randao.go @@ -3,7 +3,7 @@ package helpers import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -19,7 +19,7 @@ import ( // """ // mix = get_randao_mix(state, Epoch(epoch + EPOCHS_PER_HISTORICAL_VECTOR - MIN_SEED_LOOKAHEAD - 1)) # Avoid underflow // return hash(domain_type + uint_to_bytes(epoch) + mix) -func Seed(state state.ReadOnlyBeaconState, epoch types.Epoch, domain [bls.DomainByteLength]byte) ([32]byte, error) { +func Seed(state state.ReadOnlyBeaconState, epoch primitives.Epoch, domain [bls.DomainByteLength]byte) ([32]byte, error) { // See https://github.com/ethereum/consensus-specs/pull/1296 for // rationale on why offset has to look down by 1. lookAheadEpoch := epoch + params.BeaconConfig().EpochsPerHistoricalVector - @@ -47,6 +47,6 @@ func Seed(state state.ReadOnlyBeaconState, epoch types.Epoch, domain [bls.Domain // Return the randao mix at a recent ``epoch``. // """ // return state.randao_mixes[epoch % EPOCHS_PER_HISTORICAL_VECTOR] -func RandaoMix(state state.ReadOnlyBeaconState, epoch types.Epoch) ([]byte, error) { +func RandaoMix(state state.ReadOnlyBeaconState, epoch primitives.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 3c7cef6366..8e988843b6 100644 --- a/beacon-chain/core/helpers/randao_test.go +++ b/beacon-chain/core/helpers/randao_test.go @@ -6,7 +6,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -23,7 +23,7 @@ func TestRandaoMix_OK(t *testing.T) { state, err := state_native.InitializeFromProtoPhase0(ðpb.BeaconState{RandaoMixes: randaoMixes}) require.NoError(t, err) tests := []struct { - epoch types.Epoch + epoch primitives.Epoch randaoMix []byte }{ { @@ -57,7 +57,7 @@ func TestRandaoMix_CopyOK(t *testing.T) { state, err := state_native.InitializeFromProtoPhase0(ðpb.BeaconState{RandaoMixes: randaoMixes}) require.NoError(t, err) tests := []struct { - epoch types.Epoch + epoch primitives.Epoch randaoMix []byte }{ { diff --git a/beacon-chain/core/helpers/rewards_penalties.go b/beacon-chain/core/helpers/rewards_penalties.go index a12a7471b8..ff12ce5baa 100644 --- a/beacon-chain/core/helpers/rewards_penalties.go +++ b/beacon-chain/core/helpers/rewards_penalties.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/cache" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" mathutil "github.com/prysmaticlabs/prysm/v3/math" "github.com/prysmaticlabs/prysm/v3/time/slots" ) @@ -25,7 +25,7 @@ var balanceCache = cache.NewEffectiveBalanceCache() // Math safe up to ~10B ETH, afterwhich this overflows uint64. // """ // return Gwei(max(EFFECTIVE_BALANCE_INCREMENT, sum([state.validators[index].effective_balance for index in indices]))) -func TotalBalance(state state.ReadOnlyValidators, indices []types.ValidatorIndex) uint64 { +func TotalBalance(state state.ReadOnlyValidators, indices []primitives.ValidatorIndex) uint64 { total := uint64(0) for _, idx := range indices { @@ -96,7 +96,7 @@ func TotalActiveBalance(s state.ReadOnlyBeaconState) (uint64, error) { // Increase the validator balance at index ``index`` by ``delta``. // """ // state.balances[index] += delta -func IncreaseBalance(state state.BeaconState, idx types.ValidatorIndex, delta uint64) error { +func IncreaseBalance(state state.BeaconState, idx primitives.ValidatorIndex, delta uint64) error { balAtIdx, err := state.BalanceAtIndex(idx) if err != nil { return err @@ -132,7 +132,7 @@ func IncreaseBalanceWithVal(currBalance, delta uint64) (uint64, error) { // Decrease the validator balance at index ``index`` by ``delta``, with underflow protection. // """ // state.balances[index] = 0 if delta > state.balances[index] else state.balances[index] - delta -func DecreaseBalance(state state.BeaconState, idx types.ValidatorIndex, delta uint64) error { +func DecreaseBalance(state state.BeaconState, idx primitives.ValidatorIndex, delta uint64) error { balAtIdx, err := state.BalanceAtIndex(idx) if err != nil { return err @@ -164,7 +164,7 @@ func DecreaseBalanceWithVal(currBalance, delta uint64) uint64 { // def is_in_inactivity_leak(state: BeaconState) -> bool: // // return get_finality_delay(state) > MIN_EPOCHS_TO_INACTIVITY_PENALTY -func IsInInactivityLeak(prevEpoch, finalizedEpoch types.Epoch) bool { +func IsInInactivityLeak(prevEpoch, finalizedEpoch primitives.Epoch) bool { return FinalityDelay(prevEpoch, finalizedEpoch) > params.BeaconConfig().MinEpochsToInactivityPenalty } @@ -174,6 +174,6 @@ func IsInInactivityLeak(prevEpoch, finalizedEpoch types.Epoch) bool { // def get_finality_delay(state: BeaconState) -> uint64: // // return get_previous_epoch(state) - state.finalized_checkpoint.epoch -func FinalityDelay(prevEpoch, finalizedEpoch types.Epoch) types.Epoch { +func FinalityDelay(prevEpoch, finalizedEpoch primitives.Epoch) primitives.Epoch { return prevEpoch - finalizedEpoch } diff --git a/beacon-chain/core/helpers/rewards_penalties_test.go b/beacon-chain/core/helpers/rewards_penalties_test.go index 692517d6df..47ebe5a682 100644 --- a/beacon-chain/core/helpers/rewards_penalties_test.go +++ b/beacon-chain/core/helpers/rewards_penalties_test.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -20,7 +20,7 @@ func TestTotalBalance_OK(t *testing.T) { }}) require.NoError(t, err) - balance := TotalBalance(state, []types.ValidatorIndex{0, 1, 2, 3}) + balance := TotalBalance(state, []primitives.ValidatorIndex{0, 1, 2, 3}) wanted := state.Validators()[0].EffectiveBalance + state.Validators()[1].EffectiveBalance + state.Validators()[2].EffectiveBalance + state.Validators()[3].EffectiveBalance assert.Equal(t, wanted, balance, "Incorrect TotalBalance") @@ -30,7 +30,7 @@ func TestTotalBalance_ReturnsEffectiveBalanceIncrement(t *testing.T) { state, err := state_native.InitializeFromProtoPhase0(ðpb.BeaconState{Validators: []*ethpb.Validator{}}) require.NoError(t, err) - balance := TotalBalance(state, []types.ValidatorIndex{}) + balance := TotalBalance(state, []primitives.ValidatorIndex{}) wanted := params.BeaconConfig().EffectiveBalanceIncrement assert.Equal(t, wanted, balance, "Incorrect TotalBalance") } @@ -119,7 +119,7 @@ func TestTotalActiveBalance_WithCache(t *testing.T) { func TestIncreaseBalance_OK(t *testing.T) { tests := []struct { - i types.ValidatorIndex + i primitives.ValidatorIndex b []uint64 nb uint64 eb uint64 @@ -142,7 +142,7 @@ func TestIncreaseBalance_OK(t *testing.T) { func TestDecreaseBalance_OK(t *testing.T) { tests := []struct { - i types.ValidatorIndex + i primitives.ValidatorIndex b []uint64 nb uint64 eb uint64 @@ -169,8 +169,8 @@ func TestFinalityDelay(t *testing.T) { base.FinalizedCheckpoint = ðpb.Checkpoint{Epoch: 3} beaconState, err := state_native.InitializeFromProtoPhase0(base) require.NoError(t, err) - prevEpoch := types.Epoch(0) - finalizedEpoch := types.Epoch(0) + prevEpoch := primitives.Epoch(0) + finalizedEpoch := primitives.Epoch(0) // Set values for each test case setVal := func() { prevEpoch = time.PrevEpoch(beaconState) @@ -199,8 +199,8 @@ func TestIsInInactivityLeak(t *testing.T) { base.FinalizedCheckpoint = ðpb.Checkpoint{Epoch: 3} beaconState, err := state_native.InitializeFromProtoPhase0(base) require.NoError(t, err) - prevEpoch := types.Epoch(0) - finalizedEpoch := types.Epoch(0) + prevEpoch := primitives.Epoch(0) + finalizedEpoch := primitives.Epoch(0) // Set values for each test case setVal := func() { prevEpoch = time.PrevEpoch(beaconState) @@ -216,7 +216,7 @@ func TestIsInInactivityLeak(t *testing.T) { assert.Equal(t, false, IsInInactivityLeak(prevEpoch, finalizedEpoch), "Wanted inactivity leak false") } -func buildState(slot types.Slot, validatorCount uint64) *ethpb.BeaconState { +func buildState(slot primitives.Slot, validatorCount uint64) *ethpb.BeaconState { validators := make([]*ethpb.Validator, validatorCount) for i := 0; i < len(validators); i++ { validators[i] = ðpb.Validator{ @@ -257,7 +257,7 @@ func buildState(slot types.Slot, validatorCount uint64) *ethpb.BeaconState { func TestIncreaseBadBalance_NotOK(t *testing.T) { tests := []struct { - i types.ValidatorIndex + i primitives.ValidatorIndex b []uint64 nb uint64 }{ diff --git a/beacon-chain/core/helpers/shuffle.go b/beacon-chain/core/helpers/shuffle.go index 8bdfa3da3e..30860dd720 100644 --- a/beacon-chain/core/helpers/shuffle.go +++ b/beacon-chain/core/helpers/shuffle.go @@ -5,7 +5,7 @@ import ( "fmt" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -35,13 +35,13 @@ func SplitIndices(l []uint64, n uint64) [][]uint64 { // We utilize 'swap or not' shuffling in this implementation; we are allocating the memory with the seed that stays // constant between iterations instead of reallocating it each iteration as in the spec. This implementation is based // on the original implementation from protolambda, https://github.com/protolambda/eth2-shuffle -func ShuffledIndex(index types.ValidatorIndex, indexCount uint64, seed [32]byte) (types.ValidatorIndex, error) { +func ShuffledIndex(index primitives.ValidatorIndex, indexCount uint64, seed [32]byte) (primitives.ValidatorIndex, error) { return ComputeShuffledIndex(index, indexCount, seed, true /* shuffle */) } // UnShuffledIndex returns the inverse of ShuffledIndex. This implementation is based // on the original implementation from protolambda, https://github.com/protolambda/eth2-shuffle -func UnShuffledIndex(index types.ValidatorIndex, indexCount uint64, seed [32]byte) (types.ValidatorIndex, error) { +func UnShuffledIndex(index primitives.ValidatorIndex, indexCount uint64, seed [32]byte) (primitives.ValidatorIndex, error) { return ComputeShuffledIndex(index, indexCount, seed, false /* un-shuffle */) } @@ -70,7 +70,7 @@ func UnShuffledIndex(index types.ValidatorIndex, indexCount uint64, seed [32]byt // index = flip if bit else index // // return index -func ComputeShuffledIndex(index types.ValidatorIndex, indexCount uint64, seed [32]byte, shuffle bool) (types.ValidatorIndex, error) { +func ComputeShuffledIndex(index primitives.ValidatorIndex, indexCount uint64, seed [32]byte, shuffle bool) (primitives.ValidatorIndex, error) { if params.BeaconConfig().ShuffleRoundCount == 0 { return index, nil } @@ -119,7 +119,7 @@ func ComputeShuffledIndex(index types.ValidatorIndex, indexCount uint64, seed [3 bitV := (byteV >> (position & 0x7)) & 0x1 // index = flip if bit else index if bitV == 1 { - index = types.ValidatorIndex(flip) + index = primitives.ValidatorIndex(flip) } if shuffle { round++ @@ -151,17 +151,17 @@ func ComputeShuffledIndex(index types.ValidatorIndex, indexCount uint64, seed [3 // - change byteV every 8 iterations. // - we start at the edges, and work back to the mirror point. // this makes us process each pear exactly once (instead of unnecessarily twice, like in the spec). -func ShuffleList(input []types.ValidatorIndex, seed [32]byte) ([]types.ValidatorIndex, error) { +func ShuffleList(input []primitives.ValidatorIndex, seed [32]byte) ([]primitives.ValidatorIndex, error) { return innerShuffleList(input, seed, true /* shuffle */) } // UnshuffleList un-shuffles the list by running backwards through the round count. -func UnshuffleList(input []types.ValidatorIndex, seed [32]byte) ([]types.ValidatorIndex, error) { +func UnshuffleList(input []primitives.ValidatorIndex, seed [32]byte) ([]primitives.ValidatorIndex, error) { return innerShuffleList(input, seed, false /* un-shuffle */) } // shuffles or unshuffles, shuffle=false to un-shuffle. -func innerShuffleList(input []types.ValidatorIndex, seed [32]byte, shuffle bool) ([]types.ValidatorIndex, error) { +func innerShuffleList(input []primitives.ValidatorIndex, seed [32]byte, shuffle bool) ([]primitives.ValidatorIndex, error) { if len(input) <= 1 { return input, nil } @@ -190,7 +190,7 @@ func innerShuffleList(input []types.ValidatorIndex, seed [32]byte, shuffle bool) source := hashfunc(buf) byteV := source[(pivot&0xff)>>3] for i, j := uint64(0), pivot; i < mirror; i, j = i+1, j-1 { - byteV, source = swapOrNot(buf, byteV, types.ValidatorIndex(i), input, types.ValidatorIndex(j), source, hashfunc) + byteV, source = swapOrNot(buf, byteV, primitives.ValidatorIndex(i), input, primitives.ValidatorIndex(j), source, hashfunc) } // Now repeat, but for the part after the pivot. mirror = (pivot + listSize + 1) >> 1 @@ -199,7 +199,7 @@ func innerShuffleList(input []types.ValidatorIndex, seed [32]byte, shuffle bool) source = hashfunc(buf) byteV = source[(end&0xff)>>3] for i, j := pivot+1, end; i < mirror; i, j = i+1, j-1 { - byteV, source = swapOrNot(buf, byteV, types.ValidatorIndex(i), input, types.ValidatorIndex(j), source, hashfunc) + byteV, source = swapOrNot(buf, byteV, primitives.ValidatorIndex(i), input, primitives.ValidatorIndex(j), source, hashfunc) } if shuffle { r++ @@ -218,8 +218,8 @@ func innerShuffleList(input []types.ValidatorIndex, seed [32]byte, shuffle bool) // swapOrNot describes the main algorithm behind the shuffle where we swap bytes in the inputted value // depending on if the conditions are met. -func swapOrNot(buf []byte, byteV byte, i types.ValidatorIndex, input []types.ValidatorIndex, - j types.ValidatorIndex, source [32]byte, hashFunc func([]byte) [32]byte) (byte, [32]byte) { +func swapOrNot(buf []byte, byteV byte, i primitives.ValidatorIndex, input []primitives.ValidatorIndex, + j primitives.ValidatorIndex, source [32]byte, hashFunc func([]byte) [32]byte) (byte, [32]byte) { if j&0xff == 0xff { // just overwrite the last part of the buffer, reuse the start (seed, round) binary.LittleEndian.PutUint32(buf[pivotViewSize:], uint32(j>>8)) diff --git a/beacon-chain/core/helpers/shuffle_test.go b/beacon-chain/core/helpers/shuffle_test.go index a0be7421a6..bb2f65eb3e 100644 --- a/beacon-chain/core/helpers/shuffle_test.go +++ b/beacon-chain/core/helpers/shuffle_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -14,7 +14,7 @@ import ( func TestShuffleList_InvalidValidatorCount(t *testing.T) { maxShuffleListSize = 20 - list := make([]types.ValidatorIndex, 21) + list := make([]primitives.ValidatorIndex, 21) if _, err := ShuffleList(list, [32]byte{123, 125}); err == nil { t.Error("Shuffle should have failed when validator count exceeds ModuloBias") maxShuffleListSize = 1 << 40 @@ -23,14 +23,14 @@ func TestShuffleList_InvalidValidatorCount(t *testing.T) { } func TestShuffleList_OK(t *testing.T) { - var list1 []types.ValidatorIndex + var list1 []primitives.ValidatorIndex seed1 := [32]byte{1, 128, 12} seed2 := [32]byte{2, 128, 12} for i := 0; i < 10; i++ { - list1 = append(list1, types.ValidatorIndex(i)) + list1 = append(list1, primitives.ValidatorIndex(i)) } - list2 := make([]types.ValidatorIndex, len(list1)) + list2 := make([]primitives.ValidatorIndex, len(list1)) copy(list2, list1) list1, err := ShuffleList(list1, seed1) @@ -42,8 +42,8 @@ func TestShuffleList_OK(t *testing.T) { if reflect.DeepEqual(list1, list2) { t.Errorf("2 shuffled lists shouldn't be equal") } - assert.DeepEqual(t, []types.ValidatorIndex{0, 7, 8, 6, 3, 9, 4, 5, 2, 1}, list1, "List 1 was incorrectly shuffled got") - assert.DeepEqual(t, []types.ValidatorIndex{0, 5, 2, 1, 6, 8, 7, 3, 4, 9}, list2, "List 2 was incorrectly shuffled got") + assert.DeepEqual(t, []primitives.ValidatorIndex{0, 7, 8, 6, 3, 9, 4, 5, 2, 1}, list1, "List 1 was incorrectly shuffled got") + assert.DeepEqual(t, []primitives.ValidatorIndex{0, 5, 2, 1, 6, 8, 7, 3, 4, 9}, list2, "List 2 was incorrectly shuffled got") } func TestSplitIndices_OK(t *testing.T) { @@ -61,14 +61,14 @@ func TestSplitIndices_OK(t *testing.T) { } func TestShuffleList_Vs_ShuffleIndex(t *testing.T) { - var list []types.ValidatorIndex + var list []primitives.ValidatorIndex listSize := uint64(1000) seed := [32]byte{123, 42} - for i := types.ValidatorIndex(0); uint64(i) < listSize; i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < listSize; i++ { list = append(list, i) } - shuffledListByIndex := make([]types.ValidatorIndex, listSize) - for i := types.ValidatorIndex(0); uint64(i) < listSize; i++ { + shuffledListByIndex := make([]primitives.ValidatorIndex, listSize) + for i := primitives.ValidatorIndex(0); uint64(i) < listSize; i++ { si, err := ShuffledIndex(i, listSize, seed) assert.NoError(t, err) shuffledListByIndex[si] = i @@ -84,7 +84,7 @@ func BenchmarkShuffledIndex(b *testing.B) { for _, listSize := range listSizes { b.Run(fmt.Sprintf("ShuffledIndex_%d", listSize), func(ib *testing.B) { for i := uint64(0); i < uint64(ib.N); i++ { - _, err := ShuffledIndex(types.ValidatorIndex(i%listSize), listSize, seed) + _, err := ShuffledIndex(primitives.ValidatorIndex(i%listSize), listSize, seed) assert.NoError(b, err) } }) @@ -98,7 +98,7 @@ func BenchmarkIndexComparison(b *testing.B) { b.Run(fmt.Sprintf("Indexwise_ShuffleList_%d", listSize), func(ib *testing.B) { for i := 0; i < ib.N; i++ { // Simulate a list-shuffle by running shuffle-index listSize times. - for j := types.ValidatorIndex(0); uint64(j) < listSize; j++ { + for j := primitives.ValidatorIndex(0); uint64(j) < listSize; j++ { _, err := ShuffledIndex(j, listSize, seed) assert.NoError(b, err) } @@ -111,9 +111,9 @@ func BenchmarkShuffleList(b *testing.B) { listSizes := []uint64{400000, 40000, 400} seed := [32]byte{123, 42} for _, listSize := range listSizes { - testIndices := make([]types.ValidatorIndex, listSize) + testIndices := make([]primitives.ValidatorIndex, listSize) for i := uint64(0); i < listSize; i++ { - testIndices[i] = types.ValidatorIndex(i) + testIndices[i] = primitives.ValidatorIndex(i) } b.Run(fmt.Sprintf("ShuffleList_%d", listSize), func(ib *testing.B) { for i := 0; i < ib.N; i++ { @@ -125,20 +125,20 @@ func BenchmarkShuffleList(b *testing.B) { } func TestShuffledIndex(t *testing.T) { - var list []types.ValidatorIndex + var list []primitives.ValidatorIndex listSize := uint64(399) - for i := types.ValidatorIndex(0); uint64(i) < listSize; i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < listSize; i++ { list = append(list, i) } - shuffledList := make([]types.ValidatorIndex, listSize) - unshuffledlist := make([]types.ValidatorIndex, listSize) + shuffledList := make([]primitives.ValidatorIndex, listSize) + unshuffledlist := make([]primitives.ValidatorIndex, listSize) seed := [32]byte{123, 42} - for i := types.ValidatorIndex(0); uint64(i) < listSize; i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < listSize; i++ { si, err := ShuffledIndex(i, listSize, seed) assert.NoError(t, err) shuffledList[si] = i } - for i := types.ValidatorIndex(0); uint64(i) < listSize; i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < listSize; i++ { ui, err := UnShuffledIndex(i, listSize, seed) assert.NoError(t, err) unshuffledlist[ui] = shuffledList[i] diff --git a/beacon-chain/core/helpers/sync_committee.go b/beacon-chain/core/helpers/sync_committee.go index 515d1f17ca..c7e7e1c187 100644 --- a/beacon-chain/core/helpers/sync_committee.go +++ b/beacon-chain/core/helpers/sync_committee.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -26,7 +26,7 @@ var ( // 1. Checks if the public key exists in the sync committee cache // 2. If 1 fails, checks if the public key exists in the input current sync committee object func IsCurrentPeriodSyncCommittee( - st state.BeaconState, valIdx types.ValidatorIndex, + st state.BeaconState, valIdx primitives.ValidatorIndex, ) (bool, error) { root, err := syncPeriodBoundaryRoot(st) if err != nil { @@ -63,7 +63,7 @@ func IsCurrentPeriodSyncCommittee( // 1. Checks if the public key exists in the sync committee cache // 2. If 1 fails, checks if the public key exists in the input next sync committee object func IsNextPeriodSyncCommittee( - st state.BeaconState, valIdx types.ValidatorIndex, + st state.BeaconState, valIdx primitives.ValidatorIndex, ) (bool, error) { root, err := syncPeriodBoundaryRoot(st) if err != nil { @@ -90,8 +90,8 @@ func IsNextPeriodSyncCommittee( // CurrentPeriodSyncSubcommitteeIndices returns the subcommittee indices of the // current period sync committee for input validator. func CurrentPeriodSyncSubcommitteeIndices( - st state.BeaconState, valIdx types.ValidatorIndex, -) ([]types.CommitteeIndex, error) { + st state.BeaconState, valIdx primitives.ValidatorIndex, +) ([]primitives.CommitteeIndex, error) { root, err := syncPeriodBoundaryRoot(st) if err != nil { return nil, err @@ -124,8 +124,8 @@ func CurrentPeriodSyncSubcommitteeIndices( // NextPeriodSyncSubcommitteeIndices returns the subcommittee indices of the next period sync committee for input validator. func NextPeriodSyncSubcommitteeIndices( - st state.BeaconState, valIdx types.ValidatorIndex, -) ([]types.CommitteeIndex, error) { + st state.BeaconState, valIdx primitives.ValidatorIndex, +) ([]primitives.CommitteeIndex, error) { root, err := syncPeriodBoundaryRoot(st) if err != nil { return nil, err @@ -174,11 +174,11 @@ func UpdateSyncCommitteeCache(st state.BeaconState) error { } // Loop through `pubKeys` for matching `pubKey` and get the indices where it matches. -func findSubCommitteeIndices(pubKey []byte, pubKeys [][]byte) []types.CommitteeIndex { - var indices []types.CommitteeIndex +func findSubCommitteeIndices(pubKey []byte, pubKeys [][]byte) []primitives.CommitteeIndex { + var indices []primitives.CommitteeIndex for i, k := range pubKeys { if bytes.Equal(k, pubKey) { - indices = append(indices, types.CommitteeIndex(i)) + indices = append(indices, primitives.CommitteeIndex(i)) } } return indices diff --git a/beacon-chain/core/helpers/sync_committee_test.go b/beacon-chain/core/helpers/sync_committee_test.go index 63d5b0bca2..3d60ce25a0 100644 --- a/beacon-chain/core/helpers/sync_committee_test.go +++ b/beacon-chain/core/helpers/sync_committee_test.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/cache" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -207,7 +207,7 @@ func TestCurrentEpochSyncSubcommitteeIndices_UsingCache(t *testing.T) { index, err := CurrentPeriodSyncSubcommitteeIndices(state, 0) require.NoError(t, err) - require.DeepEqual(t, []types.CommitteeIndex{0}, index) + require.DeepEqual(t, []primitives.CommitteeIndex{0}, index) } func TestCurrentEpochSyncSubcommitteeIndices_UsingCommittee(t *testing.T) { @@ -241,13 +241,13 @@ func TestCurrentEpochSyncSubcommitteeIndices_UsingCommittee(t *testing.T) { // Test that helper can retrieve the index given empty cache. index, err := CurrentPeriodSyncSubcommitteeIndices(state, 0) require.NoError(t, err) - require.DeepEqual(t, []types.CommitteeIndex{0}, index) + require.DeepEqual(t, []primitives.CommitteeIndex{0}, index) // Test that cache was able to fill on miss. time.Sleep(100 * time.Millisecond) index, err = syncCommitteeCache.CurrentPeriodIndexPosition(root, 0) require.NoError(t, err) - require.DeepEqual(t, []types.CommitteeIndex{0}, index) + require.DeepEqual(t, []primitives.CommitteeIndex{0}, index) } func TestCurrentEpochSyncSubcommitteeIndices_DoesNotExist(t *testing.T) { @@ -274,7 +274,7 @@ func TestCurrentEpochSyncSubcommitteeIndices_DoesNotExist(t *testing.T) { index, err := CurrentPeriodSyncSubcommitteeIndices(state, 129301923) require.NoError(t, err) - require.DeepEqual(t, []types.CommitteeIndex(nil), index) + require.DeepEqual(t, []primitives.CommitteeIndex(nil), index) } func TestNextEpochSyncSubcommitteeIndices_UsingCache(t *testing.T) { @@ -304,7 +304,7 @@ func TestNextEpochSyncSubcommitteeIndices_UsingCache(t *testing.T) { index, err := NextPeriodSyncSubcommitteeIndices(state, 0) require.NoError(t, err) - require.DeepEqual(t, []types.CommitteeIndex{0}, index) + require.DeepEqual(t, []primitives.CommitteeIndex{0}, index) } func TestNextEpochSyncSubcommitteeIndices_UsingCommittee(t *testing.T) { @@ -330,7 +330,7 @@ func TestNextEpochSyncSubcommitteeIndices_UsingCommittee(t *testing.T) { index, err := NextPeriodSyncSubcommitteeIndices(state, 0) require.NoError(t, err) - require.DeepEqual(t, []types.CommitteeIndex{0}, index) + require.DeepEqual(t, []primitives.CommitteeIndex{0}, index) } func TestNextEpochSyncSubcommitteeIndices_DoesNotExist(t *testing.T) { @@ -357,7 +357,7 @@ func TestNextEpochSyncSubcommitteeIndices_DoesNotExist(t *testing.T) { index, err := NextPeriodSyncSubcommitteeIndices(state, 21093019) require.NoError(t, err) - require.DeepEqual(t, []types.CommitteeIndex(nil), index) + require.DeepEqual(t, []primitives.CommitteeIndex(nil), index) } func TestUpdateSyncCommitteeCache_BadSlot(t *testing.T) { @@ -378,7 +378,7 @@ func TestUpdateSyncCommitteeCache_BadSlot(t *testing.T) { func TestUpdateSyncCommitteeCache_BadRoot(t *testing.T) { state, err := state_native.InitializeFromProtoPhase0(ðpb.BeaconState{ - Slot: types.Slot(params.BeaconConfig().EpochsPerSyncCommitteePeriod)*params.BeaconConfig().SlotsPerEpoch - 1, + Slot: primitives.Slot(params.BeaconConfig().EpochsPerSyncCommitteePeriod)*params.BeaconConfig().SlotsPerEpoch - 1, LatestBlockHeader: ðpb.BeaconBlockHeader{StateRoot: params.BeaconConfig().ZeroHash[:]}, }) require.NoError(t, err) @@ -417,7 +417,7 @@ func TestIsCurrentEpochSyncCommittee_SameBlockRoot(t *testing.T) { require.NoError(t, err) wantedSlot := params.BeaconConfig().EpochsPerSyncCommitteePeriod.Mul(uint64(params.BeaconConfig().SlotsPerEpoch)) - assert.NoError(t, state.SetSlot(types.Slot(wantedSlot))) + assert.NoError(t, state.SetSlot(primitives.Slot(wantedSlot))) syncCommittee, err = state.CurrentSyncCommittee() assert.NoError(t, err) rand.Shuffle(len(syncCommittee.Pubkeys), func(i, j int) { diff --git a/beacon-chain/core/helpers/validators.go b/beacon-chain/core/helpers/validators.go index d3e021fe9e..6978ee0c44 100644 --- a/beacon-chain/core/helpers/validators.go +++ b/beacon-chain/core/helpers/validators.go @@ -11,7 +11,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -34,16 +34,16 @@ var CommitteeCacheInProgressHit = promauto.NewCounter(prometheus.CounterOpts{ // Check if ``validator`` is active. // """ // return validator.activation_epoch <= epoch < validator.exit_epoch -func IsActiveValidator(validator *ethpb.Validator, epoch types.Epoch) bool { +func IsActiveValidator(validator *ethpb.Validator, epoch primitives.Epoch) bool { return checkValidatorActiveStatus(validator.ActivationEpoch, validator.ExitEpoch, epoch) } // IsActiveValidatorUsingTrie checks if a read only validator is active. -func IsActiveValidatorUsingTrie(validator state.ReadOnlyValidator, epoch types.Epoch) bool { +func IsActiveValidatorUsingTrie(validator state.ReadOnlyValidator, epoch primitives.Epoch) bool { return checkValidatorActiveStatus(validator.ActivationEpoch(), validator.ExitEpoch(), epoch) } -func checkValidatorActiveStatus(activationEpoch, exitEpoch, epoch types.Epoch) bool { +func checkValidatorActiveStatus(activationEpoch, exitEpoch, epoch primitives.Epoch) bool { return activationEpoch <= epoch && epoch < exitEpoch } @@ -57,16 +57,16 @@ func checkValidatorActiveStatus(activationEpoch, exitEpoch, epoch types.Epoch) b // Check if ``validator`` is slashable. // """ // return (not validator.slashed) and (validator.activation_epoch <= epoch < validator.withdrawable_epoch) -func IsSlashableValidator(activationEpoch, withdrawableEpoch types.Epoch, slashed bool, epoch types.Epoch) bool { +func IsSlashableValidator(activationEpoch, withdrawableEpoch primitives.Epoch, slashed bool, epoch primitives.Epoch) bool { return checkValidatorSlashable(activationEpoch, withdrawableEpoch, slashed, epoch) } // IsSlashableValidatorUsingTrie checks if a read only validator is slashable. -func IsSlashableValidatorUsingTrie(val state.ReadOnlyValidator, epoch types.Epoch) bool { +func IsSlashableValidatorUsingTrie(val state.ReadOnlyValidator, epoch primitives.Epoch) bool { return checkValidatorSlashable(val.ActivationEpoch(), val.WithdrawableEpoch(), val.Slashed(), epoch) } -func checkValidatorSlashable(activationEpoch, withdrawableEpoch types.Epoch, slashed bool, epoch types.Epoch) bool { +func checkValidatorSlashable(activationEpoch, withdrawableEpoch primitives.Epoch, slashed bool, epoch primitives.Epoch) bool { active := activationEpoch <= epoch beforeWithdrawable := epoch < withdrawableEpoch return beforeWithdrawable && active && !slashed @@ -86,7 +86,7 @@ func checkValidatorSlashable(activationEpoch, withdrawableEpoch types.Epoch, sla // Return the sequence of active validator indices at ``epoch``. // """ // return [ValidatorIndex(i) for i, v in enumerate(state.validators) if is_active_validator(v, epoch)] -func ActiveValidatorIndices(ctx context.Context, s state.ReadOnlyBeaconState, epoch types.Epoch) ([]types.ValidatorIndex, error) { +func ActiveValidatorIndices(ctx context.Context, s state.ReadOnlyBeaconState, epoch primitives.Epoch) ([]primitives.ValidatorIndex, error) { seed, err := Seed(s, epoch, params.BeaconConfig().DomainBeaconAttester) if err != nil { return nil, errors.Wrap(err, "could not get seed") @@ -119,10 +119,10 @@ func ActiveValidatorIndices(ctx context.Context, s state.ReadOnlyBeaconState, ep } }() - var indices []types.ValidatorIndex + var indices []primitives.ValidatorIndex if err := s.ReadFromEveryValidator(func(idx int, val state.ReadOnlyValidator) error { if IsActiveValidatorUsingTrie(val, epoch) { - indices = append(indices, types.ValidatorIndex(idx)) + indices = append(indices, primitives.ValidatorIndex(idx)) } return nil }); err != nil { @@ -138,7 +138,7 @@ func ActiveValidatorIndices(ctx context.Context, s state.ReadOnlyBeaconState, ep // ActiveValidatorCount returns the number of active validators in the state // at the given epoch. -func ActiveValidatorCount(ctx context.Context, s state.ReadOnlyBeaconState, epoch types.Epoch) (uint64, error) { +func ActiveValidatorCount(ctx context.Context, s state.ReadOnlyBeaconState, epoch primitives.Epoch) (uint64, error) { seed, err := Seed(s, epoch, params.BeaconConfig().DomainBeaconAttester) if err != nil { return 0, errors.Wrap(err, "could not get seed") @@ -195,7 +195,7 @@ func ActiveValidatorCount(ctx context.Context, s state.ReadOnlyBeaconState, epoc // Return the epoch during which validator activations and exits initiated in ``epoch`` take effect. // """ // return Epoch(epoch + 1 + MAX_SEED_LOOKAHEAD) -func ActivationExitEpoch(epoch types.Epoch) types.Epoch { +func ActivationExitEpoch(epoch primitives.Epoch) primitives.Epoch { return epoch + 1 + params.BeaconConfig().MaxSeedLookahead } @@ -230,7 +230,7 @@ func ValidatorChurnLimit(activeValidatorCount uint64) (uint64, error) { // seed = hash(get_seed(state, epoch, DOMAIN_BEACON_PROPOSER) + uint_to_bytes(state.slot)) // indices = get_active_validator_indices(state, epoch) // return compute_proposer_index(state, indices, seed) -func BeaconProposerIndex(ctx context.Context, state state.ReadOnlyBeaconState) (types.ValidatorIndex, error) { +func BeaconProposerIndex(ctx context.Context, state state.ReadOnlyBeaconState) (primitives.ValidatorIndex, error) { e := time.CurrentEpoch(state) // The cache uses the state root of the previous epoch - minimum_seed_lookahead last slot as key. (e.g. Starting epoch 1, slot 32, the key would be block root at slot 31) // For simplicity, the node will skip caching of genesis epoch. @@ -296,7 +296,7 @@ func BeaconProposerIndex(ctx context.Context, state state.ReadOnlyBeaconState) ( // if effective_balance * MAX_RANDOM_BYTE >= MAX_EFFECTIVE_BALANCE * random_byte: // return candidate_index // i += 1 -func ComputeProposerIndex(bState state.ReadOnlyValidators, activeIndices []types.ValidatorIndex, seed [32]byte) (types.ValidatorIndex, error) { +func ComputeProposerIndex(bState state.ReadOnlyValidators, activeIndices []primitives.ValidatorIndex, seed [32]byte) (primitives.ValidatorIndex, error) { length := uint64(len(activeIndices)) if length == 0 { return 0, errors.New("empty active indices list") @@ -305,7 +305,7 @@ func ComputeProposerIndex(bState state.ReadOnlyValidators, activeIndices []types hashFunc := hash.CustomSHA256Hasher() for i := uint64(0); ; i++ { - candidateIndex, err := ComputeShuffledIndex(types.ValidatorIndex(i%length), length, seed, true /* shuffle */) + candidateIndex, err := ComputeShuffledIndex(primitives.ValidatorIndex(i%length), length, seed, true /* shuffle */) if err != nil { return 0, err } @@ -351,7 +351,7 @@ func IsEligibleForActivationQueueUsingTrie(validator state.ReadOnlyValidator) bo } // isEligibleForActivationQueue carries out the logic for IsEligibleForActivationQueue* -func isEligibileForActivationQueue(activationEligibilityEpoch types.Epoch, effectiveBalance uint64) bool { +func isEligibileForActivationQueue(activationEligibilityEpoch primitives.Epoch, effectiveBalance uint64) bool { return activationEligibilityEpoch == params.BeaconConfig().FarFutureEpoch && effectiveBalance == params.BeaconConfig().MaxEffectiveBalance } @@ -385,7 +385,7 @@ func IsEligibleForActivationUsingTrie(state state.ReadOnlyCheckpoint, validator } // isEligibleForActivation carries out the logic for IsEligibleForActivation* -func isEligibleForActivation(activationEligibilityEpoch, activationEpoch, finalizedEpoch types.Epoch) bool { +func isEligibleForActivation(activationEligibilityEpoch, activationEpoch, finalizedEpoch primitives.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 61a4ae20f1..6341d724b4 100644 --- a/beacon-chain/core/helpers/validators_test.go +++ b/beacon-chain/core/helpers/validators_test.go @@ -10,7 +10,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -20,7 +20,7 @@ import ( func TestIsActiveValidator_OK(t *testing.T) { tests := []struct { - a types.Epoch + a primitives.Epoch b bool }{ {a: 0, b: false}, @@ -37,7 +37,7 @@ func TestIsActiveValidator_OK(t *testing.T) { func TestIsActiveValidatorUsingTrie_OK(t *testing.T) { tests := []struct { - a types.Epoch + a primitives.Epoch b bool }{ {a: 0, b: false}, @@ -60,7 +60,7 @@ func TestIsSlashableValidator_OK(t *testing.T) { tests := []struct { name string validator *ethpb.Validator - epoch types.Epoch + epoch primitives.Epoch slashable bool }{ { @@ -169,8 +169,8 @@ func TestBeaconProposerIndex_OK(t *testing.T) { require.NoError(t, err) tests := []struct { - slot types.Slot - index types.ValidatorIndex + slot primitives.Slot + index primitives.ValidatorIndex }{ { slot: 1, @@ -253,7 +253,7 @@ func TestComputeProposerIndex_Compatibility(t *testing.T) { indices, err := ActiveValidatorIndices(context.Background(), state, 0) require.NoError(t, err) - var proposerIndices []types.ValidatorIndex + var proposerIndices []primitives.ValidatorIndex seed, err := Seed(state, 0, params.BeaconConfig().DomainBeaconProposer) require.NoError(t, err) for i := uint64(0); i < uint64(params.BeaconConfig().SlotsPerEpoch); i++ { @@ -264,7 +264,7 @@ func TestComputeProposerIndex_Compatibility(t *testing.T) { proposerIndices = append(proposerIndices, index) } - var wantedProposerIndices []types.ValidatorIndex + var wantedProposerIndices []primitives.ValidatorIndex seed, err = Seed(state, 0, params.BeaconConfig().DomainBeaconProposer) require.NoError(t, err) for i := uint64(0); i < uint64(params.BeaconConfig().SlotsPerEpoch); i++ { @@ -278,7 +278,7 @@ func TestComputeProposerIndex_Compatibility(t *testing.T) { } func TestDelayedActivationExitEpoch_OK(t *testing.T) { - epoch := types.Epoch(9999) + epoch := primitives.Epoch(9999) wanted := epoch + 1 + params.BeaconConfig().MaxSeedLookahead assert.Equal(t, wanted, ActivationExitEpoch(epoch)) } @@ -301,7 +301,7 @@ func TestActiveValidatorCount_Genesis(t *testing.T) { // Preset cache to a bad count. seed, err := Seed(beaconState, 0, params.BeaconConfig().DomainBeaconAttester) require.NoError(t, err) - require.NoError(t, committeeCache.AddCommitteeShuffledList(context.Background(), &cache.Committees{Seed: seed, ShuffledIndices: []types.ValidatorIndex{1, 2, 3}})) + require.NoError(t, committeeCache.AddCommitteeShuffledList(context.Background(), &cache.Committees{Seed: seed, ShuffledIndices: []primitives.ValidatorIndex{1, 2, 3}})) validatorCount, err := ActiveValidatorCount(context.Background(), beaconState, time.CurrentEpoch(beaconState)) require.NoError(t, err) assert.Equal(t, uint64(c), validatorCount, "Did not get the correct validator count") @@ -347,12 +347,12 @@ func TestActiveValidatorIndices(t *testing.T) { farFutureEpoch := params.BeaconConfig().FarFutureEpoch type args struct { state *ethpb.BeaconState - epoch types.Epoch + epoch primitives.Epoch } tests := []struct { name string args args - want []types.ValidatorIndex + want []primitives.ValidatorIndex wantedErr string }{ { @@ -377,7 +377,7 @@ func TestActiveValidatorIndices(t *testing.T) { }, epoch: 10, }, - want: []types.ValidatorIndex{0, 1, 2}, + want: []primitives.ValidatorIndex{0, 1, 2}, }, { name: "some_active_epoch_10", @@ -401,7 +401,7 @@ func TestActiveValidatorIndices(t *testing.T) { }, epoch: 10, }, - want: []types.ValidatorIndex{0, 1}, + want: []primitives.ValidatorIndex{0, 1}, }, { name: "some_active_with_recent_new_epoch_10", @@ -429,7 +429,7 @@ func TestActiveValidatorIndices(t *testing.T) { }, epoch: 10, }, - want: []types.ValidatorIndex{0, 1, 3}, + want: []primitives.ValidatorIndex{0, 1, 3}, }, { name: "some_active_with_recent_new_epoch_10", @@ -457,7 +457,7 @@ func TestActiveValidatorIndices(t *testing.T) { }, epoch: 10, }, - want: []types.ValidatorIndex{0, 1, 3}, + want: []primitives.ValidatorIndex{0, 1, 3}, }, { name: "some_active_with_recent_new_epoch_10", @@ -485,7 +485,7 @@ func TestActiveValidatorIndices(t *testing.T) { }, epoch: 10, }, - want: []types.ValidatorIndex{0, 2, 3}, + want: []primitives.ValidatorIndex{0, 2, 3}, }, } for _, tt := range tests { @@ -507,13 +507,13 @@ func TestComputeProposerIndex(t *testing.T) { seed := bytesutil.ToBytes32([]byte("seed")) type args struct { validators []*ethpb.Validator - indices []types.ValidatorIndex + indices []primitives.ValidatorIndex seed [32]byte } tests := []struct { name string args args - want types.ValidatorIndex + want primitives.ValidatorIndex wantedErr string }{ { @@ -526,7 +526,7 @@ func TestComputeProposerIndex(t *testing.T) { {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, }, - indices: []types.ValidatorIndex{0, 1, 2, 3, 4}, + indices: []primitives.ValidatorIndex{0, 1, 2, 3, 4}, seed: seed, }, want: 2, @@ -541,7 +541,7 @@ func TestComputeProposerIndex(t *testing.T) { {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, }, - indices: []types.ValidatorIndex{3}, + indices: []primitives.ValidatorIndex{3}, seed: seed, }, want: 3, @@ -556,7 +556,7 @@ func TestComputeProposerIndex(t *testing.T) { {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, }, - indices: []types.ValidatorIndex{}, + indices: []primitives.ValidatorIndex{}, seed: seed, }, wantedErr: "empty active indices list", @@ -571,7 +571,7 @@ func TestComputeProposerIndex(t *testing.T) { {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, }, - indices: []types.ValidatorIndex{100}, + indices: []primitives.ValidatorIndex{100}, seed: seed, }, wantedErr: "active index out of range", @@ -591,7 +591,7 @@ func TestComputeProposerIndex(t *testing.T) { {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, {EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance}, }, - indices: []types.ValidatorIndex{5, 6, 7, 8, 9}, + indices: []primitives.ValidatorIndex{5, 6, 7, 8, 9}, seed: seed, }, want: 7, @@ -665,7 +665,7 @@ func TestIsIsEligibleForActivation(t *testing.T) { } } -func computeProposerIndexWithValidators(validators []*ethpb.Validator, activeIndices []types.ValidatorIndex, seed [32]byte) (types.ValidatorIndex, error) { +func computeProposerIndexWithValidators(validators []*ethpb.Validator, activeIndices []primitives.ValidatorIndex, seed [32]byte) (primitives.ValidatorIndex, error) { length := uint64(len(activeIndices)) if length == 0 { return 0, errors.New("empty active indices list") @@ -674,7 +674,7 @@ func computeProposerIndexWithValidators(validators []*ethpb.Validator, activeInd hashFunc := hash.CustomSHA256Hasher() for i := uint64(0); ; i++ { - candidateIndex, err := ComputeShuffledIndex(types.ValidatorIndex(i%length), length, seed, true /* shuffle */) + candidateIndex, err := ComputeShuffledIndex(primitives.ValidatorIndex(i%length), length, seed, true /* shuffle */) if err != nil { return 0, err } diff --git a/beacon-chain/core/helpers/weak_subjectivity.go b/beacon-chain/core/helpers/weak_subjectivity.go index 162f2c7cad..016be170dc 100644 --- a/beacon-chain/core/helpers/weak_subjectivity.go +++ b/beacon-chain/core/helpers/weak_subjectivity.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/math" v1alpha1 "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -56,7 +56,7 @@ import ( // ) // // return ws_period -func ComputeWeakSubjectivityPeriod(ctx context.Context, st state.ReadOnlyBeaconState, cfg *params.BeaconChainConfig) (types.Epoch, error) { +func ComputeWeakSubjectivityPeriod(ctx context.Context, st state.ReadOnlyBeaconState, cfg *params.BeaconChainConfig) (primitives.Epoch, error) { // Weak subjectivity period cannot be smaller than withdrawal delay. wsp := uint64(cfg.MinValidatorWithdrawabilityDelay) @@ -103,7 +103,7 @@ func ComputeWeakSubjectivityPeriod(ctx context.Context, st state.ReadOnlyBeaconS wsp += 3 * N * D * t / (200 * Delta * (T - t)) } - return types.Epoch(wsp), nil + return primitives.Epoch(wsp), nil } // IsWithinWeakSubjectivityPeriod verifies if a given weak subjectivity checkpoint is not stale i.e. @@ -125,7 +125,7 @@ func ComputeWeakSubjectivityPeriod(ctx context.Context, st state.ReadOnlyBeaconS // current_epoch = compute_epoch_at_slot(get_current_slot(store)) // return current_epoch <= ws_state_epoch + ws_period func IsWithinWeakSubjectivityPeriod( - ctx context.Context, currentEpoch types.Epoch, wsState state.ReadOnlyBeaconState, wsStateRoot [fieldparams.RootLength]byte, wsEpoch types.Epoch, cfg *params.BeaconChainConfig) (bool, error) { + ctx context.Context, currentEpoch primitives.Epoch, wsState state.ReadOnlyBeaconState, wsStateRoot [fieldparams.RootLength]byte, wsEpoch primitives.Epoch, cfg *params.BeaconChainConfig) (bool, error) { // Make sure that incoming objects are not nil. if wsState == nil || wsState.IsNil() || wsState.LatestBlockHeader() == nil { return false, errors.New("invalid weak subjectivity state or checkpoint") @@ -156,7 +156,7 @@ func IsWithinWeakSubjectivityPeriod( // Within the weak subjectivity period, if two conflicting blocks are finalized, 1/3 - D (D := safety decay) // of validators will get slashed. Therefore, it is safe to assume that any finalized checkpoint within that // period is protected by this safety margin. -func LatestWeakSubjectivityEpoch(ctx context.Context, st state.ReadOnlyBeaconState, cfg *params.BeaconChainConfig) (types.Epoch, error) { +func LatestWeakSubjectivityEpoch(ctx context.Context, st state.ReadOnlyBeaconState, cfg *params.BeaconChainConfig) (primitives.Epoch, error) { wsPeriod, err := ComputeWeakSubjectivityPeriod(ctx, st, cfg) if err != nil { return 0, err @@ -201,7 +201,7 @@ func ParseWeakSubjectivityInputString(wsCheckpointString string) (*v1alpha1.Chec } return &v1alpha1.Checkpoint{ - Epoch: types.Epoch(epoch), + Epoch: primitives.Epoch(epoch), Root: bRoot, }, nil } diff --git a/beacon-chain/core/helpers/weak_subjectivity_test.go b/beacon-chain/core/helpers/weak_subjectivity_test.go index aa5fc7bdc4..451de8f393 100644 --- a/beacon-chain/core/helpers/weak_subjectivity_test.go +++ b/beacon-chain/core/helpers/weak_subjectivity_test.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -20,7 +20,7 @@ func TestWeakSubjectivity_ComputeWeakSubjectivityPeriod(t *testing.T) { tests := []struct { valCount uint64 avgBalance uint64 - want types.Epoch + want primitives.Epoch }{ // Asserting that we get the same numbers as defined in the reference table: // https://github.com/ethereum/consensus-specs/blob/master/specs/phase0/weak-subjectivity.md#calculating-the-weak-subjectivity-period @@ -55,12 +55,12 @@ func TestWeakSubjectivity_ComputeWeakSubjectivityPeriod(t *testing.T) { } } -type mockWsCheckpoint func() (stateRoot [32]byte, blockRoot [32]byte, e types.Epoch) +type mockWsCheckpoint func() (stateRoot [32]byte, blockRoot [32]byte, e primitives.Epoch) func TestWeakSubjectivity_IsWithinWeakSubjectivityPeriod(t *testing.T) { tests := []struct { name string - epoch types.Epoch + epoch primitives.Epoch genWsState func() state.ReadOnlyBeaconState genWsCheckpoint mockWsCheckpoint want bool @@ -71,7 +71,7 @@ func TestWeakSubjectivity_IsWithinWeakSubjectivityPeriod(t *testing.T) { genWsState: func() state.ReadOnlyBeaconState { return nil }, - genWsCheckpoint: func() ([32]byte, [32]byte, types.Epoch) { + genWsCheckpoint: func() ([32]byte, [32]byte, primitives.Epoch) { return [32]byte{}, [32]byte{}, 42 }, wantedErr: "invalid weak subjectivity state or checkpoint", @@ -88,7 +88,7 @@ func TestWeakSubjectivity_IsWithinWeakSubjectivityPeriod(t *testing.T) { require.NoError(t, err) return beaconState }, - genWsCheckpoint: func() ([32]byte, [32]byte, types.Epoch) { + genWsCheckpoint: func() ([32]byte, [32]byte, primitives.Epoch) { var sr [32]byte copy(sr[:], bytesutil.PadTo([]byte("stateroot2"), 32)) return sr, [32]byte{}, 42 @@ -108,7 +108,7 @@ func TestWeakSubjectivity_IsWithinWeakSubjectivityPeriod(t *testing.T) { require.NoError(t, err) return beaconState }, - genWsCheckpoint: func() ([32]byte, [32]byte, types.Epoch) { + genWsCheckpoint: func() ([32]byte, [32]byte, primitives.Epoch) { var sr [32]byte copy(sr[:], bytesutil.PadTo([]byte("stateroot"), 32)) return sr, [32]byte{}, 43 @@ -127,7 +127,7 @@ func TestWeakSubjectivity_IsWithinWeakSubjectivityPeriod(t *testing.T) { require.NoError(t, err) return beaconState }, - genWsCheckpoint: func() ([32]byte, [32]byte, types.Epoch) { + genWsCheckpoint: func() ([32]byte, [32]byte, primitives.Epoch) { var sr [32]byte copy(sr[:], bytesutil.PadTo([]byte("stateroot"), 32)) return sr, [32]byte{}, 42 @@ -147,7 +147,7 @@ func TestWeakSubjectivity_IsWithinWeakSubjectivityPeriod(t *testing.T) { require.NoError(t, err) return beaconState }, - genWsCheckpoint: func() ([32]byte, [32]byte, types.Epoch) { + genWsCheckpoint: func() ([32]byte, [32]byte, primitives.Epoch) { var sr [32]byte copy(sr[:], bytesutil.PadTo([]byte("stateroot"), 32)) return sr, [32]byte{}, 42 @@ -167,7 +167,7 @@ func TestWeakSubjectivity_IsWithinWeakSubjectivityPeriod(t *testing.T) { require.NoError(t, err) return beaconState }, - genWsCheckpoint: func() ([32]byte, [32]byte, types.Epoch) { + genWsCheckpoint: func() ([32]byte, [32]byte, primitives.Epoch) { var sr [32]byte copy(sr[:], bytesutil.PadTo([]byte("stateroot"), 32)) return sr, [32]byte{}, 42 @@ -217,7 +217,7 @@ func TestWeakSubjectivity_ParseWeakSubjectivityInputString(t *testing.T) { input: "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:123456789", checkpt: ðpb.Checkpoint{ Root: []byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, - Epoch: types.Epoch(123456789), + Epoch: primitives.Epoch(123456789), }, }, { @@ -225,7 +225,7 @@ func TestWeakSubjectivity_ParseWeakSubjectivityInputString(t *testing.T) { input: "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:123456789", checkpt: ðpb.Checkpoint{ Root: []byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, - Epoch: types.Epoch(123456789), + Epoch: primitives.Epoch(123456789), }, }, { @@ -233,7 +233,7 @@ func TestWeakSubjectivity_ParseWeakSubjectivityInputString(t *testing.T) { input: "0xF0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:123456789", checkpt: ðpb.Checkpoint{ Root: []byte{0xf0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, - Epoch: types.Epoch(123456789), + Epoch: primitives.Epoch(123456789), }, }, { @@ -241,7 +241,7 @@ func TestWeakSubjectivity_ParseWeakSubjectivityInputString(t *testing.T) { input: "F0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:123456789", checkpt: ðpb.Checkpoint{ Root: []byte{0xf0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, - Epoch: types.Epoch(123456789), + Epoch: primitives.Epoch(123456789), }, }, } diff --git a/beacon-chain/core/signing/domain.go b/beacon-chain/core/signing/domain.go index 97ce9925e8..479895bfba 100644 --- a/beacon-chain/core/signing/domain.go +++ b/beacon-chain/core/signing/domain.go @@ -2,7 +2,7 @@ package signing import ( "github.com/pkg/errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -18,7 +18,7 @@ import ( // 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 *eth.Fork, epoch types.Epoch, domainType [bls.DomainByteLength]byte, genesisRoot []byte) ([]byte, error) { +func Domain(fork *eth.Fork, epoch primitives.Epoch, domainType [bls.DomainByteLength]byte, genesisRoot []byte) ([]byte, error) { if fork == nil { return []byte{}, errors.New("nil fork or domain type") } diff --git a/beacon-chain/core/signing/domain_test.go b/beacon-chain/core/signing/domain_test.go index 70eb1ea6fd..096fa46235 100644 --- a/beacon-chain/core/signing/domain_test.go +++ b/beacon-chain/core/signing/domain_test.go @@ -3,7 +3,7 @@ package signing import ( "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -19,7 +19,7 @@ func TestDomain_OK(t *testing.T) { }, } tests := []struct { - epoch types.Epoch + epoch primitives.Epoch domainType [4]byte result []byte }{ diff --git a/beacon-chain/core/signing/signing_root.go b/beacon-chain/core/signing/signing_root.go index 4d1a91f404..4e57f8cda9 100644 --- a/beacon-chain/core/signing/signing_root.go +++ b/beacon-chain/core/signing/signing_root.go @@ -5,7 +5,7 @@ import ( fssz "github.com/prysmaticlabs/fastssz" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -48,7 +48,7 @@ const ( ) // ComputeDomainAndSign computes the domain and signing root and sign it using the passed in private key. -func ComputeDomainAndSign(st state.ReadOnlyBeaconState, epoch types.Epoch, obj fssz.HashRoot, domain [4]byte, key bls.SecretKey) ([]byte, error) { +func ComputeDomainAndSign(st state.ReadOnlyBeaconState, epoch primitives.Epoch, obj fssz.HashRoot, domain [4]byte, key bls.SecretKey) ([]byte, error) { d, err := Domain(st.Fork(), epoch, domain, st.GenesisValidatorsRoot()) if err != nil { return nil, err @@ -91,7 +91,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.ReadOnlyBeaconState, index types.ValidatorIndex, epoch types.Epoch, obj fssz.HashRoot, domain [4]byte, sig []byte) error { +func ComputeDomainVerifySigningRoot(st state.ReadOnlyBeaconState, index primitives.ValidatorIndex, epoch primitives.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/time/slot_epoch.go b/beacon-chain/core/time/slot_epoch.go index 1bbb2319d8..2dcec7fe47 100644 --- a/beacon-chain/core/time/slot_epoch.go +++ b/beacon-chain/core/time/slot_epoch.go @@ -3,7 +3,7 @@ package time import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/runtime/version" "github.com/prysmaticlabs/prysm/v3/time/slots" ) @@ -18,7 +18,7 @@ import ( // Return the current epoch. // """ // return compute_epoch_at_slot(state.slot) -func CurrentEpoch(state state.ReadOnlyBeaconState) types.Epoch { +func CurrentEpoch(state state.ReadOnlyBeaconState) primitives.Epoch { return slots.ToEpoch(state.Slot()) } @@ -34,7 +34,7 @@ func CurrentEpoch(state state.ReadOnlyBeaconState) types.Epoch { // """ // current_epoch = get_current_epoch(state) // return GENESIS_EPOCH if current_epoch == GENESIS_EPOCH else Epoch(current_epoch - 1) -func PrevEpoch(state state.ReadOnlyBeaconState) types.Epoch { +func PrevEpoch(state state.ReadOnlyBeaconState) primitives.Epoch { currentEpoch := CurrentEpoch(state) if currentEpoch == 0 { return 0 @@ -44,19 +44,19 @@ func PrevEpoch(state state.ReadOnlyBeaconState) types.Epoch { // NextEpoch returns the next epoch number calculated from // the slot number stored in beacon state. -func NextEpoch(state state.ReadOnlyBeaconState) types.Epoch { +func NextEpoch(state state.ReadOnlyBeaconState) primitives.Epoch { return slots.ToEpoch(state.Slot()) + 1 } // HigherEqualThanAltairVersionAndEpoch returns if the input state `s` has a higher version number than Altair state and input epoch `e` is higher equal than fork epoch. -func HigherEqualThanAltairVersionAndEpoch(s state.BeaconState, e types.Epoch) bool { +func HigherEqualThanAltairVersionAndEpoch(s state.BeaconState, e primitives.Epoch) bool { return s.Version() >= version.Altair && e >= params.BeaconConfig().AltairForkEpoch } // CanUpgradeToAltair returns true if the input `slot` can upgrade to Altair. // Spec code: // If state.slot % SLOTS_PER_EPOCH == 0 and compute_epoch_at_slot(state.slot) == ALTAIR_FORK_EPOCH -func CanUpgradeToAltair(slot types.Slot) bool { +func CanUpgradeToAltair(slot primitives.Slot) bool { epochStart := slots.IsEpochStart(slot) altairEpoch := slots.ToEpoch(slot) == params.BeaconConfig().AltairForkEpoch return epochStart && altairEpoch @@ -66,7 +66,7 @@ func CanUpgradeToAltair(slot types.Slot) bool { // // Spec code: // If state.slot % SLOTS_PER_EPOCH == 0 and compute_epoch_at_slot(state.slot) == BELLATRIX_FORK_EPOCH -func CanUpgradeToBellatrix(slot types.Slot) bool { +func CanUpgradeToBellatrix(slot primitives.Slot) bool { epochStart := slots.IsEpochStart(slot) bellatrixEpoch := slots.ToEpoch(slot) == params.BeaconConfig().BellatrixForkEpoch return epochStart && bellatrixEpoch @@ -75,7 +75,7 @@ func CanUpgradeToBellatrix(slot types.Slot) bool { // CanUpgradeToCapella returns true if the input `slot` can upgrade to Capella. // Spec code: // If state.slot % SLOTS_PER_EPOCH == 0 and compute_epoch_at_slot(state.slot) == CAPELLA_FORK_EPOCH -func CanUpgradeToCapella(slot types.Slot) bool { +func CanUpgradeToCapella(slot primitives.Slot) bool { epochStart := slots.IsEpochStart(slot) capellaEpoch := slots.ToEpoch(slot) == params.BeaconConfig().CapellaForkEpoch return epochStart && capellaEpoch diff --git a/beacon-chain/core/time/slot_epoch_test.go b/beacon-chain/core/time/slot_epoch_test.go index cbcf8185df..eb5d1f0f2b 100644 --- a/beacon-chain/core/time/slot_epoch_test.go +++ b/beacon-chain/core/time/slot_epoch_test.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -17,8 +17,8 @@ import ( func TestSlotToEpoch_OK(t *testing.T) { tests := []struct { - slot types.Slot - epoch types.Epoch + slot primitives.Slot + epoch primitives.Epoch }{ {slot: 0, epoch: 0}, {slot: 50, epoch: 1}, @@ -33,8 +33,8 @@ func TestSlotToEpoch_OK(t *testing.T) { func TestCurrentEpoch_OK(t *testing.T) { tests := []struct { - slot types.Slot - epoch types.Epoch + slot primitives.Slot + epoch primitives.Epoch }{ {slot: 0, epoch: 0}, {slot: 50, epoch: 1}, @@ -51,8 +51,8 @@ func TestCurrentEpoch_OK(t *testing.T) { func TestPrevEpoch_OK(t *testing.T) { tests := []struct { - slot types.Slot - epoch types.Epoch + slot primitives.Slot + epoch primitives.Epoch }{ {slot: 0, epoch: 0}, {slot: 0 + params.BeaconConfig().SlotsPerEpoch + 1, epoch: 0}, @@ -67,14 +67,14 @@ func TestPrevEpoch_OK(t *testing.T) { func TestNextEpoch_OK(t *testing.T) { tests := []struct { - slot types.Slot - epoch types.Epoch + slot primitives.Slot + epoch primitives.Epoch }{ - {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)}, + {slot: 0, epoch: primitives.Epoch(0/params.BeaconConfig().SlotsPerEpoch + 1)}, + {slot: 50, epoch: primitives.Epoch(0/params.BeaconConfig().SlotsPerEpoch + 2)}, + {slot: 64, epoch: primitives.Epoch(64/params.BeaconConfig().SlotsPerEpoch + 1)}, + {slot: 128, epoch: primitives.Epoch(128/params.BeaconConfig().SlotsPerEpoch + 1)}, + {slot: 200, epoch: primitives.Epoch(200/params.BeaconConfig().SlotsPerEpoch + 1)}, } for _, tt := range tests { st, err := state_native.InitializeFromProtoPhase0(ð.BeaconState{Slot: tt.slot}) @@ -90,7 +90,7 @@ func TestCanUpgradeToAltair(t *testing.T) { params.OverrideBeaconConfig(bc) tests := []struct { name string - slot types.Slot + slot primitives.Slot want bool }{ { @@ -105,7 +105,7 @@ func TestCanUpgradeToAltair(t *testing.T) { }, { name: "altair epoch", - slot: types.Slot(params.BeaconConfig().AltairForkEpoch) * params.BeaconConfig().SlotsPerEpoch, + slot: primitives.Slot(params.BeaconConfig().AltairForkEpoch) * params.BeaconConfig().SlotsPerEpoch, want: true, }, } @@ -125,7 +125,7 @@ func TestCanUpgradeBellatrix(t *testing.T) { params.OverrideBeaconConfig(bc) tests := []struct { name string - slot types.Slot + slot primitives.Slot want bool }{ { @@ -140,7 +140,7 @@ func TestCanUpgradeBellatrix(t *testing.T) { }, { name: "bellatrix epoch", - slot: types.Slot(params.BeaconConfig().BellatrixForkEpoch) * params.BeaconConfig().SlotsPerEpoch, + slot: primitives.Slot(params.BeaconConfig().BellatrixForkEpoch) * params.BeaconConfig().SlotsPerEpoch, want: true, }, } @@ -155,7 +155,7 @@ func TestCanUpgradeBellatrix(t *testing.T) { func TestCanProcessEpoch_TrueOnEpochsLastSlot(t *testing.T) { tests := []struct { - slot types.Slot + slot primitives.Slot canProcessEpoch bool }{ { @@ -194,7 +194,7 @@ func TestAltairCompatible(t *testing.T) { type args struct { s state.BeaconState - e types.Epoch + e primitives.Epoch } tests := []struct { name string @@ -271,7 +271,7 @@ func TestCanUpgradeToCapella(t *testing.T) { params.OverrideBeaconConfig(bc) tests := []struct { name string - slot types.Slot + slot primitives.Slot want bool }{ { @@ -286,7 +286,7 @@ func TestCanUpgradeToCapella(t *testing.T) { }, { name: "capella epoch", - slot: types.Slot(params.BeaconConfig().CapellaForkEpoch) * params.BeaconConfig().SlotsPerEpoch, + slot: primitives.Slot(params.BeaconConfig().CapellaForkEpoch) * params.BeaconConfig().SlotsPerEpoch, want: true, }, } diff --git a/beacon-chain/core/transition/state_test.go b/beacon-chain/core/transition/state_test.go index 96707cb34b..ea5e53dba9 100644 --- a/beacon-chain/core/transition/state_test.go +++ b/beacon-chain/core/transition/state_test.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/transition" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/hash" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -17,19 +17,19 @@ import ( ) func TestGenesisBeaconState_OK(t *testing.T) { - genesisEpoch := types.Epoch(0) + genesisEpoch := primitives.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, types.Epoch(65536), params.BeaconConfig().EpochsPerHistoricalVector, "EpochsPerHistoricalVector should be 8192 for these tests to pass") + assert.Equal(t, primitives.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, types.Epoch(8192), params.BeaconConfig().EpochsPerSlashingsVector, "EpochsPerSlashingsVector should be 8192 for these tests to pass") + assert.Equal(t, primitives.Epoch(8192), params.BeaconConfig().EpochsPerSlashingsVector, "EpochsPerSlashingsVector should be 8192 for these tests to pass") genesisTime := uint64(99999) deposits, _, err := util.DeterministicDepositsAndKeys(uint64(depositsForChainStart)) @@ -40,7 +40,7 @@ func TestGenesisBeaconState_OK(t *testing.T) { require.NoError(t, err, "Could not execute GenesisBeaconState") // Misc fields checks. - assert.Equal(t, types.Slot(0), newState.Slot(), "Slot was not correctly initialized") + assert.Equal(t, primitives.Slot(0), newState.Slot(), "Slot was not correctly initialized") if !proto.Equal(newState.Fork(), ðpb.Fork{ PreviousVersion: genesisForkVersion, CurrentVersion: genesisForkVersion, @@ -53,14 +53,14 @@ 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, types.Epoch(0), v.ActivationEpoch, "Validators was not correctly initialized") + assert.Equal(t, primitives.Epoch(0), v.ActivationEpoch, "Validators was not correctly initialized") v, err = newState.ValidatorAtIndex(0) require.NoError(t, err) - assert.Equal(t, types.Epoch(0), v.ActivationEligibilityEpoch, "Validators was not correctly initialized") + assert.Equal(t, primitives.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, types.Epoch(len(newState.RandaoMixes())), "Length of RandaoMixes was not correctly initialized") + assert.Equal(t, latestRandaoMixesLength, primitives.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") diff --git a/beacon-chain/core/transition/stateutils/validator_index_map.go b/beacon-chain/core/transition/stateutils/validator_index_map.go index 0e14646212..dd5085c95e 100644 --- a/beacon-chain/core/transition/stateutils/validator_index_map.go +++ b/beacon-chain/core/transition/stateutils/validator_index_map.go @@ -5,15 +5,15 @@ package stateutils import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) // ValidatorIndexMap builds a lookup map for quickly determining the index of // a validator by their public key. -func ValidatorIndexMap(validators []*ethpb.Validator) map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex { - m := make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex, len(validators)) +func ValidatorIndexMap(validators []*ethpb.Validator) map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex { + m := make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex, len(validators)) if validators == nil { return m } @@ -22,7 +22,7 @@ func ValidatorIndexMap(validators []*ethpb.Validator) map[[fieldparams.BLSPubkey continue } key := bytesutil.ToBytes48(record.PublicKey) - m[key] = types.ValidatorIndex(idx) + m[key] = primitives.ValidatorIndex(idx) } return m } diff --git a/beacon-chain/core/transition/stateutils/validator_index_map_test.go b/beacon-chain/core/transition/stateutils/validator_index_map_test.go index 5c88460dad..c92a0b1421 100644 --- a/beacon-chain/core/transition/stateutils/validator_index_map_test.go +++ b/beacon-chain/core/transition/stateutils/validator_index_map_test.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/transition/stateutils" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -29,7 +29,7 @@ func TestValidatorIndexMap_OK(t *testing.T) { tests := []struct { key [fieldparams.BLSPubkeyLength]byte - val types.ValidatorIndex + val primitives.ValidatorIndex ok bool }{ { diff --git a/beacon-chain/core/transition/trailing_slot_state_cache_test.go b/beacon-chain/core/transition/trailing_slot_state_cache_test.go index 49536f0827..bf67ab45a5 100644 --- a/beacon-chain/core/transition/trailing_slot_state_cache_test.go +++ b/beacon-chain/core/transition/trailing_slot_state_cache_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/transition" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" ) @@ -21,10 +21,10 @@ func TestTrailingSlotState_RoundTrip(t *testing.T) { require.NoError(t, transition.UpdateNextSlotCache(ctx, r, s)) s, err = transition.NextSlotState(ctx, r) require.NoError(t, err) - require.Equal(t, types.Slot(1), s.Slot()) + require.Equal(t, primitives.Slot(1), s.Slot()) require.NoError(t, transition.UpdateNextSlotCache(ctx, r, s)) s, err = transition.NextSlotState(ctx, r) require.NoError(t, err) - require.Equal(t, types.Slot(2), s.Slot()) + require.Equal(t, primitives.Slot(2), s.Slot()) } diff --git a/beacon-chain/core/transition/transition.go b/beacon-chain/core/transition/transition.go index 27e28051d0..79b2138871 100644 --- a/beacon-chain/core/transition/transition.go +++ b/beacon-chain/core/transition/transition.go @@ -21,7 +21,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/math" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -143,7 +143,7 @@ func ProcessSlotsUsingNextSlotCache( ctx context.Context, parentState state.BeaconState, parentRoot []byte, - slot types.Slot) (state.BeaconState, error) { + slot primitives.Slot) (state.BeaconState, error) { ctx, span := trace.StartSpan(ctx, "core.state.ProcessSlotsUsingNextSlotCache") defer span.End() @@ -175,7 +175,7 @@ func ProcessSlotsUsingNextSlotCache( // ProcessSlotsIfPossible executes ProcessSlots on the input state when target slot is above the state's slot. // Otherwise, it returns the input state unchanged. -func ProcessSlotsIfPossible(ctx context.Context, state state.BeaconState, targetSlot types.Slot) (state.BeaconState, error) { +func ProcessSlotsIfPossible(ctx context.Context, state state.BeaconState, targetSlot primitives.Slot) (state.BeaconState, error) { if targetSlot > state.Slot() { return ProcessSlots(ctx, state, targetSlot) } @@ -194,7 +194,7 @@ func ProcessSlotsIfPossible(ctx context.Context, state state.BeaconState, target // if (state.slot + 1) % SLOTS_PER_EPOCH == 0: // process_epoch(state) // state.slot = Slot(state.slot + 1) -func ProcessSlots(ctx context.Context, state state.BeaconState, slot types.Slot) (state.BeaconState, error) { +func ProcessSlots(ctx context.Context, state state.BeaconState, slot primitives.Slot) (state.BeaconState, error) { ctx, span := trace.StartSpan(ctx, "core.state.ProcessSlots") defer span.End() if state == nil || state.IsNil() { diff --git a/beacon-chain/core/transition/transition_fuzz_test.go b/beacon-chain/core/transition/transition_fuzz_test.go index 2ca61d2658..cc0ddfe9c4 100644 --- a/beacon-chain/core/transition/transition_fuzz_test.go +++ b/beacon-chain/core/transition/transition_fuzz_test.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -84,7 +84,7 @@ func TestFuzzProcessSlots_1000(t *testing.T) { ctx := context.Background() state, err := state_native.InitializeFromProtoUnsafePhase0(ðpb.BeaconState{}) require.NoError(t, err) - slot := types.Slot(0) + slot := primitives.Slot(0) fuzzer := fuzz.NewWithSeed(0) fuzzer.NilChance(0.1) for i := 0; i < 1000; i++ { diff --git a/beacon-chain/core/transition/transition_test.go b/beacon-chain/core/transition/transition_test.go index 554893ccf0..ed23314c99 100644 --- a/beacon-chain/core/transition/transition_test.go +++ b/beacon-chain/core/transition/transition_test.go @@ -16,7 +16,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -218,7 +218,7 @@ func createFullBlockWithOperations(t *testing.T) (state.BeaconState, require.NoError(t, beaconState.SetCurrentJustifiedCheckpoint(cp)) require.NoError(t, beaconState.AppendCurrentEpochAttestations(ðpb.PendingAttestation{})) - proposerSlashIdx := types.ValidatorIndex(3) + proposerSlashIdx := primitives.ValidatorIndex(3) slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch err = beaconState.SetSlot(slotsPerEpoch.Mul(uint64(params.BeaconConfig().ShardCommitteePeriod)) + params.BeaconConfig().MinAttestationInclusionDelay) require.NoError(t, err) @@ -369,7 +369,7 @@ func createFullBlockWithOperations(t *testing.T) (state.BeaconState, } func TestProcessEpochPrecompute_CanProcess(t *testing.T) { - epoch := types.Epoch(1) + epoch := primitives.Epoch(1) atts := []*ethpb.PendingAttestation{{Data: ðpb.AttestationData{Target: ðpb.Checkpoint{Root: make([]byte, 32)}}, InclusionDelay: 1}} slashing := make([]uint64, params.BeaconConfig().EpochsPerSlashingsVector) @@ -489,7 +489,7 @@ func TestProcessBlock_IncorrectDeposits(t *testing.T) { } func TestProcessSlots_SameSlotAsParentState(t *testing.T) { - slot := types.Slot(2) + slot := primitives.Slot(2) parentState, err := state_native.InitializeFromProtoPhase0(ðpb.BeaconState{Slot: slot}) require.NoError(t, err) @@ -498,7 +498,7 @@ func TestProcessSlots_SameSlotAsParentState(t *testing.T) { } func TestProcessSlots_LowerSlotAsParentState(t *testing.T) { - slot := types.Slot(2) + slot := primitives.Slot(2) parentState, err := state_native.InitializeFromProtoPhase0(ðpb.BeaconState{Slot: slot}) require.NoError(t, err) @@ -634,7 +634,7 @@ func TestProcessSlotsUsingNextSlotCache(t *testing.T) { r := []byte{'a'} s, err := transition.ProcessSlotsUsingNextSlotCache(context.Background(), s, r, 5) require.NoError(t, err) - require.Equal(t, types.Slot(5), s.Slot()) + require.Equal(t, primitives.Slot(5), s.Slot()) } func TestProcessSlotsConditionally(t *testing.T) { @@ -645,20 +645,20 @@ func TestProcessSlotsConditionally(t *testing.T) { require.NoError(t, s.SetSlot(5)) s, err := transition.ProcessSlotsIfPossible(ctx, s, 4) require.NoError(t, err) - assert.Equal(t, types.Slot(5), s.Slot()) + assert.Equal(t, primitives.Slot(5), s.Slot()) }) t.Run("target slot equal current slot", func(t *testing.T) { require.NoError(t, s.SetSlot(5)) s, err := transition.ProcessSlotsIfPossible(ctx, s, 5) require.NoError(t, err) - assert.Equal(t, types.Slot(5), s.Slot()) + assert.Equal(t, primitives.Slot(5), s.Slot()) }) t.Run("target slot above current slot", func(t *testing.T) { require.NoError(t, s.SetSlot(5)) s, err := transition.ProcessSlotsIfPossible(ctx, s, 6) require.NoError(t, err) - assert.Equal(t, types.Slot(6), s.Slot()) + assert.Equal(t, primitives.Slot(6), s.Slot()) }) } diff --git a/beacon-chain/core/validators/validator.go b/beacon-chain/core/validators/validator.go index d196b3e6ff..67e74142d6 100644 --- a/beacon-chain/core/validators/validator.go +++ b/beacon-chain/core/validators/validator.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" mathutil "github.com/prysmaticlabs/prysm/v3/math" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -42,7 +42,7 @@ import ( // # Set validator exit epoch and withdrawable epoch // validator.exit_epoch = exit_queue_epoch // validator.withdrawable_epoch = Epoch(validator.exit_epoch + MIN_VALIDATOR_WITHDRAWABILITY_DELAY) -func InitiateValidatorExit(ctx context.Context, s state.BeaconState, idx types.ValidatorIndex) (state.BeaconState, error) { +func InitiateValidatorExit(ctx context.Context, s state.BeaconState, idx primitives.ValidatorIndex) (state.BeaconState, error) { validator, err := s.ValidatorAtIndex(idx) if err != nil { return nil, err @@ -50,7 +50,7 @@ func InitiateValidatorExit(ctx context.Context, s state.BeaconState, idx types.V if validator.ExitEpoch != params.BeaconConfig().FarFutureEpoch { return s, nil } - var exitEpochs []types.Epoch + var exitEpochs []primitives.Epoch err = s.ReadFromEveryValidator(func(idx int, val state.ReadOnlyValidator) error { if val.ExitEpoch() != params.BeaconConfig().FarFutureEpoch { exitEpochs = append(exitEpochs, val.ExitEpoch()) @@ -63,7 +63,7 @@ func InitiateValidatorExit(ctx context.Context, s state.BeaconState, idx types.V exitEpochs = append(exitEpochs, helpers.ActivationExitEpoch(time.CurrentEpoch(s))) // Obtain the exit queue epoch as the maximum number in the exit epochs array. - exitQueueEpoch := types.Epoch(0) + exitQueueEpoch := primitives.Epoch(0) for _, i := range exitEpochs { if exitQueueEpoch < i { exitQueueEpoch = i @@ -141,7 +141,7 @@ func InitiateValidatorExit(ctx context.Context, s state.BeaconState, idx types.V func SlashValidator( ctx context.Context, s state.BeaconState, - slashedIdx types.ValidatorIndex, + slashedIdx primitives.ValidatorIndex, penaltyQuotient uint64, proposerRewardQuotient uint64) (state.BeaconState, error) { s, err := InitiateValidatorExit(ctx, s, slashedIdx) @@ -154,7 +154,7 @@ func SlashValidator( return nil, err } validator.Slashed = true - maxWithdrawableEpoch := types.MaxEpoch(validator.WithdrawableEpoch, currentEpoch+params.BeaconConfig().EpochsPerSlashingsVector) + maxWithdrawableEpoch := primitives.MaxEpoch(validator.WithdrawableEpoch, currentEpoch+params.BeaconConfig().EpochsPerSlashingsVector) validator.WithdrawableEpoch = maxWithdrawableEpoch if err := s.UpdateValidatorAtIndex(slashedIdx, validator); err != nil { @@ -194,41 +194,41 @@ func SlashValidator( } // ActivatedValidatorIndices determines the indices activated during the given epoch. -func ActivatedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []types.ValidatorIndex { - activations := make([]types.ValidatorIndex, 0) +func ActivatedValidatorIndices(epoch primitives.Epoch, validators []*ethpb.Validator) []primitives.ValidatorIndex { + activations := make([]primitives.ValidatorIndex, 0) for i := 0; i < len(validators); i++ { val := validators[i] if val.ActivationEpoch <= epoch && epoch < val.ExitEpoch { - activations = append(activations, types.ValidatorIndex(i)) + activations = append(activations, primitives.ValidatorIndex(i)) } } return activations } // SlashedValidatorIndices determines the indices slashed during the given epoch. -func SlashedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator) []types.ValidatorIndex { - slashed := make([]types.ValidatorIndex, 0) +func SlashedValidatorIndices(epoch primitives.Epoch, validators []*ethpb.Validator) []primitives.ValidatorIndex { + slashed := make([]primitives.ValidatorIndex, 0) for i := 0; i < len(validators); i++ { val := validators[i] - maxWithdrawableEpoch := types.MaxEpoch(val.WithdrawableEpoch, epoch+params.BeaconConfig().EpochsPerSlashingsVector) + maxWithdrawableEpoch := primitives.MaxEpoch(val.WithdrawableEpoch, epoch+params.BeaconConfig().EpochsPerSlashingsVector) if val.WithdrawableEpoch == maxWithdrawableEpoch && val.Slashed { - slashed = append(slashed, types.ValidatorIndex(i)) + slashed = append(slashed, primitives.ValidatorIndex(i)) } } return slashed } // ExitedValidatorIndices determines the indices exited during the current epoch. -func ExitedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]types.ValidatorIndex, error) { - exited := make([]types.ValidatorIndex, 0) - exitEpochs := make([]types.Epoch, 0) +func ExitedValidatorIndices(epoch primitives.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]primitives.ValidatorIndex, error) { + exited := make([]primitives.ValidatorIndex, 0) + exitEpochs := make([]primitives.Epoch, 0) for i := 0; i < len(validators); i++ { val := validators[i] if val.ExitEpoch != params.BeaconConfig().FarFutureEpoch { exitEpochs = append(exitEpochs, val.ExitEpoch) } } - exitQueueEpoch := types.Epoch(0) + exitQueueEpoch := primitives.Epoch(0) for _, i := range exitEpochs { if exitQueueEpoch < i { exitQueueEpoch = i @@ -253,23 +253,23 @@ func ExitedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, ac for i, val := range validators { if val.ExitEpoch == epoch && val.WithdrawableEpoch == withdrawableEpoch && val.EffectiveBalance > params.BeaconConfig().EjectionBalance { - exited = append(exited, types.ValidatorIndex(i)) + exited = append(exited, primitives.ValidatorIndex(i)) } } return exited, nil } // EjectedValidatorIndices determines the indices ejected during the given epoch. -func EjectedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]types.ValidatorIndex, error) { - ejected := make([]types.ValidatorIndex, 0) - exitEpochs := make([]types.Epoch, 0) +func EjectedValidatorIndices(epoch primitives.Epoch, validators []*ethpb.Validator, activeValidatorCount uint64) ([]primitives.ValidatorIndex, error) { + ejected := make([]primitives.ValidatorIndex, 0) + exitEpochs := make([]primitives.Epoch, 0) for i := 0; i < len(validators); i++ { val := validators[i] if val.ExitEpoch != params.BeaconConfig().FarFutureEpoch { exitEpochs = append(exitEpochs, val.ExitEpoch) } } - exitQueueEpoch := types.Epoch(0) + exitQueueEpoch := primitives.Epoch(0) for _, i := range exitEpochs { if exitQueueEpoch < i { exitQueueEpoch = i @@ -294,7 +294,7 @@ func EjectedValidatorIndices(epoch types.Epoch, validators []*ethpb.Validator, a for i, val := range validators { if val.ExitEpoch == epoch && val.WithdrawableEpoch == withdrawableEpoch && val.EffectiveBalance <= params.BeaconConfig().EjectionBalance { - ejected = append(ejected, types.ValidatorIndex(i)) + ejected = append(ejected, primitives.ValidatorIndex(i)) } } return ejected, nil diff --git a/beacon-chain/core/validators/validator_test.go b/beacon-chain/core/validators/validator_test.go index e297f7e4a9..f3ec711b2f 100644 --- a/beacon-chain/core/validators/validator_test.go +++ b/beacon-chain/core/validators/validator_test.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -42,7 +42,7 @@ func TestHasVoted_OK(t *testing.T) { } func TestInitiateValidatorExit_AlreadyExited(t *testing.T) { - exitEpoch := types.Epoch(199) + exitEpoch := primitives.Epoch(199) base := ðpb.BeaconState{Validators: []*ethpb.Validator{{ ExitEpoch: exitEpoch}, }} @@ -56,8 +56,8 @@ func TestInitiateValidatorExit_AlreadyExited(t *testing.T) { } func TestInitiateValidatorExit_ProperExit(t *testing.T) { - exitedEpoch := types.Epoch(100) - idx := types.ValidatorIndex(3) + exitedEpoch := primitives.Epoch(100) + idx := primitives.ValidatorIndex(3) base := ðpb.BeaconState{Validators: []*ethpb.Validator{ {ExitEpoch: exitedEpoch}, {ExitEpoch: exitedEpoch + 1}, @@ -74,8 +74,8 @@ func TestInitiateValidatorExit_ProperExit(t *testing.T) { } func TestInitiateValidatorExit_ChurnOverflow(t *testing.T) { - exitedEpoch := types.Epoch(100) - idx := types.ValidatorIndex(4) + exitedEpoch := primitives.Epoch(100) + idx := primitives.ValidatorIndex(4) base := ðpb.BeaconState{Validators: []*ethpb.Validator{ {ExitEpoch: exitedEpoch + 2}, {ExitEpoch: exitedEpoch + 2}, @@ -132,7 +132,7 @@ func TestSlashValidator_OK(t *testing.T) { state, err := state_native.InitializeFromProtoPhase0(base) require.NoError(t, err) - slashedIdx := types.ValidatorIndex(3) + slashedIdx := primitives.ValidatorIndex(3) proposer, err := helpers.BeaconProposerIndex(context.Background(), state) require.NoError(t, err, "Could not get proposer") @@ -167,7 +167,7 @@ func TestSlashValidator_OK(t *testing.T) { func TestActivatedValidatorIndices(t *testing.T) { tests := []struct { state *ethpb.BeaconState - wanted []types.ValidatorIndex + wanted []primitives.ValidatorIndex }{ { state: ðpb.BeaconState{ @@ -189,7 +189,7 @@ func TestActivatedValidatorIndices(t *testing.T) { }, }, }, - wanted: []types.ValidatorIndex{0, 1, 3}, + wanted: []primitives.ValidatorIndex{0, 1, 3}, }, { state: ðpb.BeaconState{ @@ -199,7 +199,7 @@ func TestActivatedValidatorIndices(t *testing.T) { }, }, }, - wanted: []types.ValidatorIndex{}, + wanted: []primitives.ValidatorIndex{}, }, { state: ðpb.BeaconState{ @@ -210,7 +210,7 @@ func TestActivatedValidatorIndices(t *testing.T) { }, }, }, - wanted: []types.ValidatorIndex{0}, + wanted: []primitives.ValidatorIndex{0}, }, } for _, tt := range tests { @@ -224,7 +224,7 @@ func TestActivatedValidatorIndices(t *testing.T) { func TestSlashedValidatorIndices(t *testing.T) { tests := []struct { state *ethpb.BeaconState - wanted []types.ValidatorIndex + wanted []primitives.ValidatorIndex }{ { state: ðpb.BeaconState{ @@ -243,7 +243,7 @@ func TestSlashedValidatorIndices(t *testing.T) { }, }, }, - wanted: []types.ValidatorIndex{0, 2}, + wanted: []primitives.ValidatorIndex{0, 2}, }, { state: ðpb.BeaconState{ @@ -253,7 +253,7 @@ func TestSlashedValidatorIndices(t *testing.T) { }, }, }, - wanted: []types.ValidatorIndex{}, + wanted: []primitives.ValidatorIndex{}, }, { state: ðpb.BeaconState{ @@ -264,7 +264,7 @@ func TestSlashedValidatorIndices(t *testing.T) { }, }, }, - wanted: []types.ValidatorIndex{0}, + wanted: []primitives.ValidatorIndex{0}, }, } for _, tt := range tests { @@ -278,7 +278,7 @@ func TestSlashedValidatorIndices(t *testing.T) { func TestExitedValidatorIndices(t *testing.T) { tests := []struct { state *ethpb.BeaconState - wanted []types.ValidatorIndex + wanted []primitives.ValidatorIndex }{ { state: ðpb.BeaconState{ @@ -300,7 +300,7 @@ func TestExitedValidatorIndices(t *testing.T) { }, }, }, - wanted: []types.ValidatorIndex{0, 2}, + wanted: []primitives.ValidatorIndex{0, 2}, }, { state: ðpb.BeaconState{ @@ -312,7 +312,7 @@ func TestExitedValidatorIndices(t *testing.T) { }, }, }, - wanted: []types.ValidatorIndex{}, + wanted: []primitives.ValidatorIndex{}, }, { state: ðpb.BeaconState{ @@ -324,7 +324,7 @@ func TestExitedValidatorIndices(t *testing.T) { }, }, }, - wanted: []types.ValidatorIndex{0}, + wanted: []primitives.ValidatorIndex{0}, }, } for _, tt := range tests { diff --git a/beacon-chain/db/filters/filter.go b/beacon-chain/db/filters/filter.go index fa8b7d6860..0a10bd8271 100644 --- a/beacon-chain/db/filters/filter.go +++ b/beacon-chain/db/filters/filter.go @@ -14,7 +14,7 @@ // } package filters -import types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" +import primitives "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" // 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. @@ -91,37 +91,37 @@ func (q *QueryFilter) SetTargetRoot(val []byte) *QueryFilter { } // SetSourceEpoch enables filtering by the source epoch data attribute of an object. -func (q *QueryFilter) SetSourceEpoch(val types.Epoch) *QueryFilter { +func (q *QueryFilter) SetSourceEpoch(val primitives.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 types.Epoch) *QueryFilter { +func (q *QueryFilter) SetTargetEpoch(val primitives.Epoch) *QueryFilter { q.queries[TargetEpoch] = val return q } // SetStartSlot enables filtering by all the items that begin at a slot (inclusive). -func (q *QueryFilter) SetStartSlot(val types.Slot) *QueryFilter { +func (q *QueryFilter) SetStartSlot(val primitives.Slot) *QueryFilter { q.queries[StartSlot] = val return q } // SetEndSlot enables filtering by all the items that end at a slot (inclusive). -func (q *QueryFilter) SetEndSlot(val types.Slot) *QueryFilter { +func (q *QueryFilter) SetEndSlot(val primitives.Slot) *QueryFilter { q.queries[EndSlot] = val return q } // SetStartEpoch enables filtering by the StartEpoch attribute of an object (inclusive). -func (q *QueryFilter) SetStartEpoch(val types.Epoch) *QueryFilter { +func (q *QueryFilter) SetStartEpoch(val primitives.Epoch) *QueryFilter { q.queries[StartEpoch] = val return q } // SetEndEpoch enables filtering by the EndEpoch attribute of an object (inclusive). -func (q *QueryFilter) SetEndEpoch(val types.Epoch) *QueryFilter { +func (q *QueryFilter) SetEndEpoch(val primitives.Epoch) *QueryFilter { q.queries[EndEpoch] = val return q } diff --git a/beacon-chain/db/filters/filter_test.go b/beacon-chain/db/filters/filter_test.go index cc482be74a..15b8d91799 100644 --- a/beacon-chain/db/filters/filter_test.go +++ b/beacon-chain/db/filters/filter_test.go @@ -3,7 +3,7 @@ package filters import ( "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" ) @@ -18,9 +18,9 @@ func TestQueryFilter_ChainsCorrectly(t *testing.T) { for k, v := range filterSet { switch k { case StartSlot: - t.Log(v.(types.Slot)) + t.Log(v.(primitives.Slot)) case EndSlot: - t.Log(v.(types.Slot)) + t.Log(v.(primitives.Slot)) case ParentRoot: t.Log(v.([]byte)) default: diff --git a/beacon-chain/db/iface/interface.go b/beacon-chain/db/iface/interface.go index 21bb479741..098be916be 100644 --- a/beacon-chain/db/iface/interface.go +++ b/beacon-chain/db/iface/interface.go @@ -12,7 +12,7 @@ import ( slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/monitoring/backup" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -23,14 +23,14 @@ type ReadOnlyDatabase interface { Block(ctx context.Context, blockRoot [32]byte) (interfaces.SignedBeaconBlock, error) Blocks(ctx context.Context, f *filters.QueryFilter) ([]interfaces.SignedBeaconBlock, [][32]byte, error) BlockRoots(ctx context.Context, f *filters.QueryFilter) ([][32]byte, error) - BlocksBySlot(ctx context.Context, slot types.Slot) ([]interfaces.SignedBeaconBlock, error) - BlockRootsBySlot(ctx context.Context, slot types.Slot) (bool, [][32]byte, error) + BlocksBySlot(ctx context.Context, slot primitives.Slot) ([]interfaces.SignedBeaconBlock, error) + BlockRootsBySlot(ctx context.Context, slot primitives.Slot) (bool, [][32]byte, error) HasBlock(ctx context.Context, blockRoot [32]byte) bool GenesisBlock(ctx context.Context) (interfaces.SignedBeaconBlock, error) GenesisBlockRoot(ctx context.Context) ([32]byte, error) IsFinalizedBlock(ctx context.Context, blockRoot [32]byte) bool FinalizedChildBlock(ctx context.Context, blockRoot [32]byte) (interfaces.SignedBeaconBlock, error) - HighestRootsBelowSlot(ctx context.Context, slot types.Slot) (types.Slot, [][32]byte, error) + HighestRootsBelowSlot(ctx context.Context, slot primitives.Slot) (primitives.Slot, [][32]byte, error) // State related methods. State(ctx context.Context, blockRoot [32]byte) (state.BeaconState, error) StateOrError(ctx context.Context, blockRoot [32]byte) (state.BeaconState, error) @@ -38,22 +38,22 @@ type ReadOnlyDatabase interface { HasState(ctx context.Context, blockRoot [32]byte) bool StateSummary(ctx context.Context, blockRoot [32]byte) (*ethpb.StateSummary, error) HasStateSummary(ctx context.Context, blockRoot [32]byte) bool - HighestSlotStatesBelow(ctx context.Context, slot types.Slot) ([]state.ReadOnlyBeaconState, error) + HighestSlotStatesBelow(ctx context.Context, slot primitives.Slot) ([]state.ReadOnlyBeaconState, error) // Checkpoint operations. JustifiedCheckpoint(ctx context.Context) (*ethpb.Checkpoint, error) FinalizedCheckpoint(ctx context.Context) (*ethpb.Checkpoint, error) - ArchivedPointRoot(ctx context.Context, slot types.Slot) [32]byte - HasArchivedPoint(ctx context.Context, slot types.Slot) bool + ArchivedPointRoot(ctx context.Context, slot primitives.Slot) [32]byte + HasArchivedPoint(ctx context.Context, slot primitives.Slot) bool LastArchivedRoot(ctx context.Context) [32]byte - LastArchivedSlot(ctx context.Context) (types.Slot, error) + LastArchivedSlot(ctx context.Context) (primitives.Slot, error) LastValidatedCheckpoint(ctx context.Context) (*ethpb.Checkpoint, error) // Deposit contract related handlers. DepositContractAddress(ctx context.Context) ([]byte, error) // ExecutionChainData operations. ExecutionChainData(ctx context.Context) (*ethpb.ETH1ChainData, error) // Fee recipients operations. - FeeRecipientByValidatorID(ctx context.Context, id types.ValidatorIndex) (common.Address, error) - RegistrationByValidatorID(ctx context.Context, id types.ValidatorIndex) (*ethpb.ValidatorRegistrationV1, error) + FeeRecipientByValidatorID(ctx context.Context, id primitives.ValidatorIndex) (common.Address, error) + RegistrationByValidatorID(ctx context.Context, id primitives.ValidatorIndex) (*ethpb.ValidatorRegistrationV1, error) // origin checkpoint sync support OriginCheckpointBlockRoot(ctx context.Context) ([32]byte, error) BackfillBlockRoot(ctx context.Context) ([32]byte, error) @@ -86,10 +86,10 @@ type NoHeadAccessDatabase interface { // Run any required database migrations. RunMigrations(ctx context.Context) error // Fee recipients operations. - SaveFeeRecipientsByValidatorIDs(ctx context.Context, ids []types.ValidatorIndex, addrs []common.Address) error - SaveRegistrationsByValidatorIDs(ctx context.Context, ids []types.ValidatorIndex, regs []*ethpb.ValidatorRegistrationV1) error + SaveFeeRecipientsByValidatorIDs(ctx context.Context, ids []primitives.ValidatorIndex, addrs []common.Address) error + SaveRegistrationsByValidatorIDs(ctx context.Context, ids []primitives.ValidatorIndex, regs []*ethpb.ValidatorRegistrationV1) error - CleanUpDirtyStates(ctx context.Context, slotsPerArchivedPoint types.Slot) error + CleanUpDirtyStates(ctx context.Context, slotsPerArchivedPoint primitives.Slot) error } // HeadAccessDatabase defines a struct with access to reading chain head data. @@ -114,7 +114,7 @@ type HeadAccessDatabase interface { type SlasherDatabase interface { io.Closer SaveLastEpochsWrittenForValidators( - ctx context.Context, epochByValidator map[types.ValidatorIndex]types.Epoch, + ctx context.Context, epochByValidator map[primitives.ValidatorIndex]primitives.Epoch, ) error SaveAttestationRecordsForValidators( ctx context.Context, @@ -127,13 +127,13 @@ type SlasherDatabase interface { ctx context.Context, proposal []*slashertypes.SignedBlockHeaderWrapper, ) error LastEpochWrittenForValidators( - ctx context.Context, validatorIndices []types.ValidatorIndex, + ctx context.Context, validatorIndices []primitives.ValidatorIndex, ) ([]*slashertypes.AttestedEpochForValidator, error) AttestationRecordForValidator( - ctx context.Context, validatorIdx types.ValidatorIndex, targetEpoch types.Epoch, + ctx context.Context, validatorIdx primitives.ValidatorIndex, targetEpoch primitives.Epoch, ) (*slashertypes.IndexedAttestationWrapper, error) BlockProposalForValidator( - ctx context.Context, validatorIdx types.ValidatorIndex, slot types.Slot, + ctx context.Context, validatorIdx primitives.ValidatorIndex, slot primitives.Slot, ) (*slashertypes.SignedBlockHeaderWrapper, error) CheckAttesterDoubleVotes( ctx context.Context, attestations []*slashertypes.IndexedAttestationWrapper, @@ -145,14 +145,14 @@ type SlasherDatabase interface { ctx context.Context, proposals []*slashertypes.SignedBlockHeaderWrapper, ) ([]*ethpb.ProposerSlashing, error) PruneAttestationsAtEpoch( - ctx context.Context, maxEpoch types.Epoch, + ctx context.Context, maxEpoch primitives.Epoch, ) (numPruned uint, err error) PruneProposalsAtEpoch( - ctx context.Context, maxEpoch types.Epoch, + ctx context.Context, maxEpoch primitives.Epoch, ) (numPruned uint, err error) HighestAttestations( ctx context.Context, - indices []types.ValidatorIndex, + indices []primitives.ValidatorIndex, ) ([]*ethpb.HighestAttestation, error) DatabasePath() string ClearDB() error diff --git a/beacon-chain/db/kv/archived_point.go b/beacon-chain/db/kv/archived_point.go index 310b16b01b..2146719f45 100644 --- a/beacon-chain/db/kv/archived_point.go +++ b/beacon-chain/db/kv/archived_point.go @@ -3,17 +3,17 @@ package kv import ( "context" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" bolt "go.etcd.io/bbolt" "go.opencensus.io/trace" ) // LastArchivedSlot from the db. -func (s *Store) LastArchivedSlot(ctx context.Context) (types.Slot, error) { +func (s *Store) LastArchivedSlot(ctx context.Context) (primitives.Slot, error) { ctx, span := trace.StartSpan(ctx, "BeaconDB.LastArchivedSlot") defer span.End() - var index types.Slot + var index primitives.Slot err := s.db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket(stateSlotIndicesBucket) b, _ := bkt.Cursor().Last() @@ -43,7 +43,7 @@ func (s *Store) LastArchivedRoot(ctx context.Context) [32]byte { // ArchivedPointRoot returns the block root of an archived point from the DB. // This is essential for cold state management and to restore a cold state. -func (s *Store) ArchivedPointRoot(ctx context.Context, slot types.Slot) [32]byte { +func (s *Store) ArchivedPointRoot(ctx context.Context, slot primitives.Slot) [32]byte { ctx, span := trace.StartSpan(ctx, "BeaconDB.ArchivedPointRoot") defer span.End() @@ -60,7 +60,7 @@ func (s *Store) ArchivedPointRoot(ctx context.Context, slot types.Slot) [32]byte } // HasArchivedPoint returns true if an archived point exists in DB. -func (s *Store) HasArchivedPoint(ctx context.Context, slot types.Slot) bool { +func (s *Store) HasArchivedPoint(ctx context.Context, slot primitives.Slot) bool { ctx, span := trace.StartSpan(ctx, "BeaconDB.HasArchivedPoint") defer span.End() var exists bool diff --git a/beacon-chain/db/kv/archived_point_test.go b/beacon-chain/db/kv/archived_point_test.go index 9f7a7d2fd2..63f00daf1d 100644 --- a/beacon-chain/db/kv/archived_point_test.go +++ b/beacon-chain/db/kv/archived_point_test.go @@ -4,7 +4,7 @@ import ( "context" "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -13,7 +13,7 @@ import ( func TestArchivedPointIndexRoot_CanSaveRetrieve(t *testing.T) { db := setupDB(t) ctx := context.Background() - i1 := types.Slot(100) + i1 := primitives.Slot(100) r1 := [32]byte{'A'} received := db.ArchivedPointRoot(ctx, i1) @@ -31,7 +31,7 @@ func TestLastArchivedPoint_CanRetrieve(t *testing.T) { ctx := context.Background() i, err := db.LastArchivedSlot(ctx) require.NoError(t, err) - assert.Equal(t, types.Slot(0), i, "Did not get correct index") + assert.Equal(t, primitives.Slot(0), i, "Did not get correct index") st, err := util.NewBeaconState() require.NoError(t, err) @@ -47,5 +47,5 @@ func TestLastArchivedPoint_CanRetrieve(t *testing.T) { i, err = db.LastArchivedSlot(ctx) require.NoError(t, err) - assert.Equal(t, types.Slot(3), i, "Did not get correct index") + assert.Equal(t, primitives.Slot(3), i, "Did not get correct index") } diff --git a/beacon-chain/db/kv/backup_test.go b/beacon-chain/db/kv/backup_test.go index 05c84146b9..70e946e974 100644 --- a/beacon-chain/db/kv/backup_test.go +++ b/beacon-chain/db/kv/backup_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" ) @@ -57,7 +57,7 @@ func TestStore_BackupMultipleBuckets(t *testing.T) { require.NoError(t, err, "Failed to instantiate DB") ctx := context.Background() - startSlot := types.Slot(5000) + startSlot := primitives.Slot(5000) for i := startSlot; i < 5200; i++ { head := util.NewBeaconBlock() diff --git a/beacon-chain/db/kv/blocks.go b/beacon-chain/db/kv/blocks.go index 0b4105ebf6..58b5734206 100644 --- a/beacon-chain/db/kv/blocks.go +++ b/beacon-chain/db/kv/blocks.go @@ -14,7 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -186,7 +186,7 @@ func (s *Store) HasBlock(ctx context.Context, blockRoot [32]byte) bool { } // BlocksBySlot retrieves a list of beacon blocks and its respective roots by slot. -func (s *Store) BlocksBySlot(ctx context.Context, slot types.Slot) ([]interfaces.SignedBeaconBlock, error) { +func (s *Store) BlocksBySlot(ctx context.Context, slot primitives.Slot) ([]interfaces.SignedBeaconBlock, error) { ctx, span := trace.StartSpan(ctx, "BeaconDB.BlocksBySlot") defer span.End() @@ -211,7 +211,7 @@ func (s *Store) BlocksBySlot(ctx context.Context, slot types.Slot) ([]interfaces } // BlockRootsBySlot retrieves a list of beacon block roots by slot -func (s *Store) BlockRootsBySlot(ctx context.Context, slot types.Slot) (bool, [][32]byte, error) { +func (s *Store) BlockRootsBySlot(ctx context.Context, slot primitives.Slot) (bool, [][32]byte, error) { ctx, span := trace.StartSpan(ctx, "BeaconDB.BlockRootsBySlot") defer span.End() blockRoots := make([][32]byte, 0) @@ -414,7 +414,7 @@ func (s *Store) SaveBackfillBlockRoot(ctx context.Context, blockRoot [32]byte) e // calling code can make decisions based on the slot without resolving the blocks to discover their slot (for instance // checking which root is canonical in fork choice, which operates purely on roots, // then if no canonical block is found, continuing to search through lower slots). -func (s *Store) HighestRootsBelowSlot(ctx context.Context, slot types.Slot) (fs types.Slot, roots [][32]byte, err error) { +func (s *Store) HighestRootsBelowSlot(ctx context.Context, slot primitives.Slot) (fs primitives.Slot, roots [][32]byte, err error) { ctx, span := trace.StartSpan(ctx, "BeaconDB.HighestRootsBelowSlot") defer span.End() @@ -470,7 +470,7 @@ func (s *Store) HighestRootsBelowSlot(ctx context.Context, slot types.Slot) (fs // FeeRecipientByValidatorID returns the fee recipient for a validator id. // `ErrNotFoundFeeRecipient` is returned if the validator id is not found. -func (s *Store) FeeRecipientByValidatorID(ctx context.Context, id types.ValidatorIndex) (common.Address, error) { +func (s *Store) FeeRecipientByValidatorID(ctx context.Context, id primitives.ValidatorIndex) (common.Address, error) { ctx, span := trace.StartSpan(ctx, "BeaconDB.FeeRecipientByValidatorID") defer span.End() var addr []byte @@ -499,7 +499,7 @@ func (s *Store) FeeRecipientByValidatorID(ctx context.Context, id types.Validato // SaveFeeRecipientsByValidatorIDs saves the fee recipients for validator ids. // Error is returned if `ids` and `recipients` are not the same length. -func (s *Store) SaveFeeRecipientsByValidatorIDs(ctx context.Context, ids []types.ValidatorIndex, feeRecipients []common.Address) error { +func (s *Store) SaveFeeRecipientsByValidatorIDs(ctx context.Context, ids []primitives.ValidatorIndex, feeRecipients []common.Address) error { ctx, span := trace.StartSpan(ctx, "BeaconDB.SaveFeeRecipientByValidatorID") defer span.End() @@ -520,7 +520,7 @@ func (s *Store) SaveFeeRecipientsByValidatorIDs(ctx context.Context, ids []types // RegistrationByValidatorID returns the validator registration object for a validator id. // `ErrNotFoundFeeRecipient` is returned if the validator id is not found. -func (s *Store) RegistrationByValidatorID(ctx context.Context, id types.ValidatorIndex) (*ethpb.ValidatorRegistrationV1, error) { +func (s *Store) RegistrationByValidatorID(ctx context.Context, id primitives.ValidatorIndex) (*ethpb.ValidatorRegistrationV1, error) { ctx, span := trace.StartSpan(ctx, "BeaconDB.RegistrationByValidatorID") defer span.End() reg := ðpb.ValidatorRegistrationV1{} @@ -537,7 +537,7 @@ func (s *Store) RegistrationByValidatorID(ctx context.Context, id types.Validato // SaveRegistrationsByValidatorIDs saves the validator registrations for validator ids. // Error is returned if `ids` and `registrations` are not the same length. -func (s *Store) SaveRegistrationsByValidatorIDs(ctx context.Context, ids []types.ValidatorIndex, regs []*ethpb.ValidatorRegistrationV1) error { +func (s *Store) SaveRegistrationsByValidatorIDs(ctx context.Context, ids []primitives.ValidatorIndex, regs []*ethpb.ValidatorRegistrationV1) error { ctx, span := trace.StartSpan(ctx, "BeaconDB.SaveRegistrationsByValidatorIDs") defer span.End() @@ -633,20 +633,20 @@ func blockRootsBySlotRange( return [][]byte{}, nil } - var startSlot, endSlot types.Slot + var startSlot, endSlot primitives.Slot var step uint64 var ok bool - if startSlot, ok = startSlotEncoded.(types.Slot); !ok { + if startSlot, ok = startSlotEncoded.(primitives.Slot); !ok { startSlot = 0 } - if endSlot, ok = endSlotEncoded.(types.Slot); !ok { + if endSlot, ok = endSlotEncoded.(primitives.Slot); !ok { endSlot = 0 } if step, ok = slotStepEncoded.(uint64); !ok || step == 0 { step = 1 } - startEpoch, startEpochOk := startEpochEncoded.(types.Epoch) - endEpoch, endEpochOk := endEpochEncoded.(types.Epoch) + startEpoch, startEpochOk := startEpochEncoded.(primitives.Epoch) + endEpoch, endEpochOk := endEpochEncoded.(primitives.Epoch) var err error if startEpochOk && endEpochOk { startSlot, err = slots.EpochStart(startEpoch) @@ -689,7 +689,7 @@ func blockRootsBySlotRange( } // blockRootsBySlot retrieves the block roots by slot -func blockRootsBySlot(ctx context.Context, tx *bolt.Tx, slot types.Slot) ([][32]byte, error) { +func blockRootsBySlot(ctx context.Context, tx *bolt.Tx, slot primitives.Slot) ([][32]byte, error) { ctx, span := trace.StartSpan(ctx, "BeaconDB.blockRootsBySlot") defer span.End() diff --git a/beacon-chain/db/kv/blocks_test.go b/beacon-chain/db/kv/blocks_test.go index 2402d7d5fd..c083933b22 100644 --- a/beacon-chain/db/kv/blocks_test.go +++ b/beacon-chain/db/kv/blocks_test.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -21,11 +21,11 @@ import ( var blockTests = []struct { name string - newBlock func(types.Slot, []byte) (interfaces.SignedBeaconBlock, error) + newBlock func(primitives.Slot, []byte) (interfaces.SignedBeaconBlock, error) }{ { name: "phase0", - newBlock: func(slot types.Slot, root []byte) (interfaces.SignedBeaconBlock, error) { + newBlock: func(slot primitives.Slot, root []byte) (interfaces.SignedBeaconBlock, error) { b := util.NewBeaconBlock() b.Block.Slot = slot if root != nil { @@ -36,7 +36,7 @@ var blockTests = []struct { }, { name: "altair", - newBlock: func(slot types.Slot, root []byte) (interfaces.SignedBeaconBlock, error) { + newBlock: func(slot primitives.Slot, root []byte) (interfaces.SignedBeaconBlock, error) { b := util.NewBeaconBlockAltair() b.Block.Slot = slot if root != nil { @@ -47,7 +47,7 @@ var blockTests = []struct { }, { name: "bellatrix", - newBlock: func(slot types.Slot, root []byte) (interfaces.SignedBeaconBlock, error) { + newBlock: func(slot primitives.Slot, root []byte) (interfaces.SignedBeaconBlock, error) { b := util.NewBeaconBlockBellatrix() b.Block.Slot = slot if root != nil { @@ -58,7 +58,7 @@ var blockTests = []struct { }, { name: "bellatrix blind", - newBlock: func(slot types.Slot, root []byte) (interfaces.SignedBeaconBlock, error) { + newBlock: func(slot primitives.Slot, root []byte) (interfaces.SignedBeaconBlock, error) { b := util.NewBlindedBeaconBlockBellatrix() b.Block.Slot = slot if root != nil { @@ -69,7 +69,7 @@ var blockTests = []struct { }, { name: "capella", - newBlock: func(slot types.Slot, root []byte) (interfaces.SignedBeaconBlock, error) { + newBlock: func(slot primitives.Slot, root []byte) (interfaces.SignedBeaconBlock, error) { b := util.NewBeaconBlockCapella() b.Block.Slot = slot if root != nil { @@ -80,7 +80,7 @@ var blockTests = []struct { }, { name: "capella blind", - newBlock: func(slot types.Slot, root []byte) (interfaces.SignedBeaconBlock, error) { + newBlock: func(slot primitives.Slot, root []byte) (interfaces.SignedBeaconBlock, error) { b := util.NewBlindedBeaconBlockCapella() b.Block.Slot = slot if root != nil { @@ -110,7 +110,7 @@ func TestStore_SaveBackfillBlockRoot(t *testing.T) { func TestStore_SaveBlock_NoDuplicates(t *testing.T) { BlockCacheSize = 1 - slot := types.Slot(20) + slot := primitives.Slot(20) ctx := context.Background() for _, tt := range blockTests { @@ -148,7 +148,7 @@ func TestStore_BlocksCRUD(t *testing.T) { t.Run(tt.name, func(t *testing.T) { db := setupDB(t) - blk, err := tt.newBlock(types.Slot(20), bytesutil.PadTo([]byte{1, 2, 3}, 32)) + blk, err := tt.newBlock(primitives.Slot(20), bytesutil.PadTo([]byte{1, 2, 3}, 32)) require.NoError(t, err) blockRoot, err := blk.Block().HashTreeRoot() require.NoError(t, err) @@ -183,7 +183,7 @@ func TestStore_BlocksHandleZeroCase(t *testing.T) { numBlocks := 10 totalBlocks := make([]interfaces.SignedBeaconBlock, numBlocks) for i := 0; i < len(totalBlocks); i++ { - b, err := tt.newBlock(types.Slot(i), bytesutil.PadTo([]byte("parent"), 32)) + b, err := tt.newBlock(primitives.Slot(i), bytesutil.PadTo([]byte("parent"), 32)) require.NoError(t, err) totalBlocks[i] = b _, err = totalBlocks[i].Block().HashTreeRoot() @@ -207,7 +207,7 @@ func TestStore_BlocksHandleInvalidEndSlot(t *testing.T) { totalBlocks := make([]interfaces.SignedBeaconBlock, numBlocks) // Save blocks from slot 1 onwards. for i := 0; i < len(totalBlocks); i++ { - b, err := tt.newBlock(types.Slot(i+1), bytesutil.PadTo([]byte("parent"), 32)) + b, err := tt.newBlock(primitives.Slot(i+1), bytesutil.PadTo([]byte("parent"), 32)) require.NoError(t, err) totalBlocks[i] = b _, err = totalBlocks[i].Block().HashTreeRoot() @@ -336,7 +336,7 @@ func TestStore_BlocksCRUD_NoCache(t *testing.T) { t.Run(tt.name, func(t *testing.T) { db := setupDB(t) ctx := context.Background() - blk, err := tt.newBlock(types.Slot(20), bytesutil.PadTo([]byte{1, 2, 3}, 32)) + blk, err := tt.newBlock(primitives.Slot(20), bytesutil.PadTo([]byte{1, 2, 3}, 32)) require.NoError(t, err) blockRoot, err := blk.Block().HashTreeRoot() require.NoError(t, err) @@ -371,15 +371,15 @@ func TestStore_Blocks_FiltersCorrectly(t *testing.T) { for _, tt := range blockTests { t.Run(tt.name, func(t *testing.T) { db := setupDB(t) - b4, err := tt.newBlock(types.Slot(4), bytesutil.PadTo([]byte("parent"), 32)) + b4, err := tt.newBlock(primitives.Slot(4), bytesutil.PadTo([]byte("parent"), 32)) require.NoError(t, err) - b5, err := tt.newBlock(types.Slot(5), bytesutil.PadTo([]byte("parent2"), 32)) + b5, err := tt.newBlock(primitives.Slot(5), bytesutil.PadTo([]byte("parent2"), 32)) require.NoError(t, err) - b6, err := tt.newBlock(types.Slot(6), bytesutil.PadTo([]byte("parent2"), 32)) + b6, err := tt.newBlock(primitives.Slot(6), bytesutil.PadTo([]byte("parent2"), 32)) require.NoError(t, err) - b7, err := tt.newBlock(types.Slot(7), bytesutil.PadTo([]byte("parent3"), 32)) + b7, err := tt.newBlock(primitives.Slot(7), bytesutil.PadTo([]byte("parent3"), 32)) require.NoError(t, err) - b8, err := tt.newBlock(types.Slot(8), bytesutil.PadTo([]byte("parent4"), 32)) + b8, err := tt.newBlock(primitives.Slot(8), bytesutil.PadTo([]byte("parent4"), 32)) require.NoError(t, err) blocks := []interfaces.SignedBeaconBlock{ b4, @@ -460,11 +460,11 @@ func TestStore_Blocks_VerifyBlockRoots(t *testing.T) { t.Run(tt.name, func(t *testing.T) { ctx := context.Background() db := setupDB(t) - b1, err := tt.newBlock(types.Slot(1), nil) + b1, err := tt.newBlock(primitives.Slot(1), nil) require.NoError(t, err) r1, err := b1.Block().HashTreeRoot() require.NoError(t, err) - b2, err := tt.newBlock(types.Slot(2), nil) + b2, err := tt.newBlock(primitives.Slot(2), nil) require.NoError(t, err) r2, err := b2.Block().HashTreeRoot() require.NoError(t, err) @@ -487,7 +487,7 @@ func TestStore_Blocks_Retrieve_SlotRange(t *testing.T) { db := setupDB(t) totalBlocks := make([]interfaces.SignedBeaconBlock, 500) for i := 0; i < 500; i++ { - b, err := tt.newBlock(types.Slot(i), bytesutil.PadTo([]byte("parent"), 32)) + b, err := tt.newBlock(primitives.Slot(i), bytesutil.PadTo([]byte("parent"), 32)) require.NoError(t, err) totalBlocks[i] = b } @@ -506,7 +506,7 @@ func TestStore_Blocks_Retrieve_Epoch(t *testing.T) { db := setupDB(t) slots := params.BeaconConfig().SlotsPerEpoch.Mul(7) totalBlocks := make([]interfaces.SignedBeaconBlock, slots) - for i := types.Slot(0); i < slots; i++ { + for i := primitives.Slot(0); i < slots; i++ { b, err := tt.newBlock(i, bytesutil.PadTo([]byte("parent"), 32)) require.NoError(t, err) totalBlocks[i] = b @@ -531,7 +531,7 @@ func TestStore_Blocks_Retrieve_SlotRangeWithStep(t *testing.T) { db := setupDB(t) totalBlocks := make([]interfaces.SignedBeaconBlock, 500) for i := 0; i < 500; i++ { - b, err := tt.newBlock(types.Slot(i), bytesutil.PadTo([]byte("parent"), 32)) + b, err := tt.newBlock(primitives.Slot(i), bytesutil.PadTo([]byte("parent"), 32)) require.NoError(t, err) totalBlocks[i] = b } @@ -542,7 +542,7 @@ func TestStore_Blocks_Retrieve_SlotRangeWithStep(t *testing.T) { require.NoError(t, err) assert.Equal(t, 150, len(retrieved)) for _, b := range retrieved { - assert.Equal(t, types.Slot(0), (b.Block().Slot()-100)%step, "Unexpect block slot %d", b.Block().Slot()) + assert.Equal(t, primitives.Slot(0), (b.Block().Slot()-100)%step, "Unexpect block slot %d", b.Block().Slot()) } }) } @@ -554,11 +554,11 @@ func TestStore_SaveBlock_CanGetHighestAt(t *testing.T) { db := setupDB(t) ctx := context.Background() - block1, err := tt.newBlock(types.Slot(1), nil) + block1, err := tt.newBlock(primitives.Slot(1), nil) require.NoError(t, err) - block2, err := tt.newBlock(types.Slot(10), nil) + block2, err := tt.newBlock(primitives.Slot(10), nil) require.NoError(t, err) - block3, err := tt.newBlock(types.Slot(100), nil) + block3, err := tt.newBlock(primitives.Slot(100), nil) require.NoError(t, err) require.NoError(t, db.SaveBlock(ctx, block1)) @@ -640,13 +640,13 @@ func TestStore_GenesisBlock_CanGetHighestAt(t *testing.T) { db := setupDB(t) ctx := context.Background() - genesisBlock, err := tt.newBlock(types.Slot(0), nil) + genesisBlock, err := tt.newBlock(primitives.Slot(0), nil) require.NoError(t, err) genesisRoot, err := genesisBlock.Block().HashTreeRoot() require.NoError(t, err) require.NoError(t, db.SaveGenesisBlockRoot(ctx, genesisRoot)) require.NoError(t, db.SaveBlock(ctx, genesisBlock)) - block1, err := tt.newBlock(types.Slot(1), nil) + block1, err := tt.newBlock(primitives.Slot(1), nil) require.NoError(t, err) require.NoError(t, db.SaveBlock(ctx, block1)) @@ -724,7 +724,7 @@ func TestStore_SaveBlocks_HasCachedBlocks(t *testing.T) { b := make([]interfaces.SignedBeaconBlock, 500) for i := 0; i < 500; i++ { - blk, err := tt.newBlock(types.Slot(i), bytesutil.PadTo([]byte("parent"), 32)) + blk, err := tt.newBlock(primitives.Slot(i), bytesutil.PadTo([]byte("parent"), 32)) require.NoError(t, err) b[i] = blk } @@ -748,7 +748,7 @@ func TestStore_SaveBlocks_HasRootsMatched(t *testing.T) { b := make([]interfaces.SignedBeaconBlock, 500) for i := 0; i < 500; i++ { - blk, err := tt.newBlock(types.Slot(i), bytesutil.PadTo([]byte("parent"), 32)) + blk, err := tt.newBlock(primitives.Slot(i), bytesutil.PadTo([]byte("parent"), 32)) require.NoError(t, err) b[i] = blk } @@ -775,13 +775,13 @@ func TestStore_BlocksBySlot_BlockRootsBySlot(t *testing.T) { db := setupDB(t) ctx := context.Background() - b1, err := tt.newBlock(types.Slot(20), nil) + b1, err := tt.newBlock(primitives.Slot(20), nil) require.NoError(t, err) require.NoError(t, db.SaveBlock(ctx, b1)) - b2, err := tt.newBlock(types.Slot(100), bytesutil.PadTo([]byte("parent1"), 32)) + b2, err := tt.newBlock(primitives.Slot(100), bytesutil.PadTo([]byte("parent1"), 32)) require.NoError(t, err) require.NoError(t, db.SaveBlock(ctx, b2)) - b3, err := tt.newBlock(types.Slot(100), bytesutil.PadTo([]byte("parent2"), 32)) + b3, err := tt.newBlock(primitives.Slot(100), bytesutil.PadTo([]byte("parent2"), 32)) require.NoError(t, err) require.NoError(t, db.SaveBlock(ctx, b3)) @@ -867,11 +867,11 @@ func TestStore_BlocksBySlot_BlockRootsBySlot(t *testing.T) { func TestStore_FeeRecipientByValidatorID(t *testing.T) { db := setupDB(t) ctx := context.Background() - ids := []types.ValidatorIndex{0, 0, 0} + ids := []primitives.ValidatorIndex{0, 0, 0} feeRecipients := []common.Address{{}, {}, {}, {}} require.ErrorContains(t, "validatorIDs and feeRecipients must be the same length", db.SaveFeeRecipientsByValidatorIDs(ctx, ids, feeRecipients)) - ids = []types.ValidatorIndex{0, 1, 2} + ids = []primitives.ValidatorIndex{0, 1, 2} feeRecipients = []common.Address{{'a'}, {'b'}, {'c'}} require.NoError(t, db.SaveFeeRecipientsByValidatorIDs(ctx, ids, feeRecipients)) f, err := db.FeeRecipientByValidatorID(ctx, 0) @@ -894,7 +894,7 @@ func TestStore_FeeRecipientByValidatorID(t *testing.T) { Timestamp: 2, Pubkey: bytesutil.PadTo([]byte("b"), 48), }} - require.NoError(t, db.SaveRegistrationsByValidatorIDs(ctx, []types.ValidatorIndex{3}, regs)) + require.NoError(t, db.SaveRegistrationsByValidatorIDs(ctx, []primitives.ValidatorIndex{3}, regs)) f, err = db.FeeRecipientByValidatorID(ctx, 3) require.NoError(t, err) require.Equal(t, common.Address{'a'}, f) @@ -907,11 +907,11 @@ func TestStore_FeeRecipientByValidatorID(t *testing.T) { func TestStore_RegistrationsByValidatorID(t *testing.T) { db := setupDB(t) ctx := context.Background() - ids := []types.ValidatorIndex{0, 0, 0} + ids := []primitives.ValidatorIndex{0, 0, 0} regs := []*ethpb.ValidatorRegistrationV1{{}, {}, {}, {}} require.ErrorContains(t, "ids and registrations must be the same length", db.SaveRegistrationsByValidatorIDs(ctx, ids, regs)) - ids = []types.ValidatorIndex{0, 1, 2} + ids = []primitives.ValidatorIndex{0, 1, 2} regs = []*ethpb.ValidatorRegistrationV1{ { FeeRecipient: bytesutil.PadTo([]byte("a"), 20), diff --git a/beacon-chain/db/kv/finalized_block_roots_test.go b/beacon-chain/db/kv/finalized_block_roots_test.go index 85f36153c0..965963223d 100644 --- a/beacon-chain/db/kv/finalized_block_roots_test.go +++ b/beacon-chain/db/kv/finalized_block_roots_test.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -206,7 +206,7 @@ func makeBlocks(t *testing.T, i, n uint64, previousRoot [32]byte) []interfaces.S parentRoot := make([]byte, fieldparams.RootLength) copy(parentRoot, previousRoot[:]) blocks[j-i] = util.NewBeaconBlock() - blocks[j-i].Block.Slot = types.Slot(j + 1) + blocks[j-i].Block.Slot = primitives.Slot(j + 1) blocks[j-i].Block.ParentRoot = parentRoot var err error previousRoot, err = blocks[j-i].Block.HashTreeRoot() @@ -224,7 +224,7 @@ func makeBlocksAltair(t *testing.T, startIdx, num uint64, previousRoot [32]byte) parentRoot := make([]byte, fieldparams.RootLength) copy(parentRoot, previousRoot[:]) blocks[j-startIdx] = util.NewBeaconBlockAltair() - blocks[j-startIdx].Block.Slot = types.Slot(j + 1) + blocks[j-startIdx].Block.Slot = primitives.Slot(j + 1) blocks[j-startIdx].Block.ParentRoot = parentRoot var err error previousRoot, err = blocks[j-startIdx].Block.HashTreeRoot() diff --git a/beacon-chain/db/kv/migration_archived_index.go b/beacon-chain/db/kv/migration_archived_index.go index ce73ddf014..04a1f24ec5 100644 --- a/beacon-chain/db/kv/migration_archived_index.go +++ b/beacon-chain/db/kv/migration_archived_index.go @@ -4,7 +4,7 @@ import ( "bytes" "context" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" bolt "go.etcd.io/bbolt" @@ -28,7 +28,7 @@ func migrateArchivedIndex(ctx context.Context, db *bolt.DB) error { return err } - var highest types.Slot + var highest primitives.Slot c := bkt.Cursor() for k, v := c.First(); k != nil; k, v = c.Next() { // Look up actual slot from block diff --git a/beacon-chain/db/kv/state.go b/beacon-chain/db/kv/state.go index b4138b5d18..8140703e89 100644 --- a/beacon-chain/db/kv/state.go +++ b/beacon-chain/db/kv/state.go @@ -13,7 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/features" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -676,7 +676,7 @@ func (s *Store) stateBytes(ctx context.Context, blockRoot [32]byte) ([]byte, err } // slotByBlockRoot retrieves the corresponding slot of the input block root. -func (s *Store) slotByBlockRoot(ctx context.Context, tx *bolt.Tx, blockRoot []byte) (types.Slot, error) { +func (s *Store) slotByBlockRoot(ctx context.Context, tx *bolt.Tx, blockRoot []byte) (primitives.Slot, error) { ctx, span := trace.StartSpan(ctx, "BeaconDB.slotByBlockRoot") defer span.End() @@ -730,7 +730,7 @@ func (s *Store) slotByBlockRoot(ctx context.Context, tx *bolt.Tx, blockRoot []by // from the db. Ideally there should just be one state per slot, but given validator // can double propose, a single slot could have multiple block roots and // results states. This returns a list of states. -func (s *Store) HighestSlotStatesBelow(ctx context.Context, slot types.Slot) ([]state.ReadOnlyBeaconState, error) { +func (s *Store) HighestSlotStatesBelow(ctx context.Context, slot primitives.Slot) ([]state.ReadOnlyBeaconState, error) { ctx, span := trace.StartSpan(ctx, "BeaconDB.HighestSlotStatesBelow") defer span.End() @@ -777,7 +777,7 @@ func (s *Store) HighestSlotStatesBelow(ctx context.Context, slot types.Slot) ([] // createStateIndicesFromStateSlot takes in a state slot and returns // a map of bolt DB index buckets corresponding to each particular key for indices for // data, such as (shard indices bucket -> shard 5). -func createStateIndicesFromStateSlot(ctx context.Context, slot types.Slot) map[string][]byte { +func createStateIndicesFromStateSlot(ctx context.Context, slot primitives.Slot) map[string][]byte { ctx, span := trace.StartSpan(ctx, "BeaconDB.createStateIndicesFromState") defer span.End() indicesByBucket := make(map[string][]byte) @@ -806,7 +806,7 @@ func createStateIndicesFromStateSlot(ctx context.Context, slot types.Slot) map[s // // 3.) state with current finalized root // 4.) unfinalized States -func (s *Store) CleanUpDirtyStates(ctx context.Context, slotsPerArchivedPoint types.Slot) error { +func (s *Store) CleanUpDirtyStates(ctx context.Context, slotsPerArchivedPoint primitives.Slot) error { ctx, span := trace.StartSpan(ctx, "BeaconDB. CleanUpDirtyStates") defer span.End() diff --git a/beacon-chain/db/kv/state_summary_test.go b/beacon-chain/db/kv/state_summary_test.go index 3e18585767..c4cd28d491 100644 --- a/beacon-chain/db/kv/state_summary_test.go +++ b/beacon-chain/db/kv/state_summary_test.go @@ -4,7 +4,7 @@ import ( "context" "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -45,7 +45,7 @@ func TestStateSummary_CacheToDB(t *testing.T) { summaries := make([]*ethpb.StateSummary, stateSummaryCachePruneCount-1) for i := range summaries { - summaries[i] = ðpb.StateSummary{Slot: types.Slot(i), Root: bytesutil.PadTo(bytesutil.Uint64ToBytesLittleEndian(uint64(i)), 32)} + summaries[i] = ðpb.StateSummary{Slot: primitives.Slot(i), Root: bytesutil.PadTo(bytesutil.Uint64ToBytesLittleEndian(uint64(i)), 32)} } require.NoError(t, db.SaveStateSummaries(context.Background(), summaries)) diff --git a/beacon-chain/db/kv/state_test.go b/beacon-chain/db/kv/state_test.go index d9eb146f1c..81aa7c3e72 100644 --- a/beacon-chain/db/kv/state_test.go +++ b/beacon-chain/db/kv/state_test.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -373,7 +373,7 @@ func TestStore_StatesBatchDelete(t *testing.T) { evenBlockRoots := make([][32]byte, 0) for i := 0; i < len(totalBlocks); i++ { b := util.NewBeaconBlock() - b.Block.Slot = types.Slot(i) + b.Block.Slot = primitives.Slot(i) var err error totalBlocks[i], err = blocks.NewSignedBeaconBlock(b) require.NoError(t, err) @@ -381,7 +381,7 @@ func TestStore_StatesBatchDelete(t *testing.T) { require.NoError(t, err) st, err := util.NewBeaconState() require.NoError(t, err) - require.NoError(t, st.SetSlot(types.Slot(i))) + require.NoError(t, st.SetSlot(primitives.Slot(i))) require.NoError(t, db.SaveState(context.Background(), st, r)) blockRoots = append(blockRoots, r) if i%2 == 0 { @@ -398,7 +398,7 @@ func TestStore_StatesBatchDelete(t *testing.T) { if s == nil { continue } - assert.Equal(t, types.Slot(1), s.Slot()%2, "State with slot %d should have been deleted", s.Slot()) + assert.Equal(t, primitives.Slot(1), s.Slot()%2, "State with slot %d should have been deleted", s.Slot()) } } @@ -566,9 +566,9 @@ func TestStore_CleanUpDirtyStates_AboveThreshold(t *testing.T) { require.NoError(t, db.SaveState(context.Background(), genesisState, genesisRoot)) bRoots := make([][32]byte, 0) - slotsPerArchivedPoint := types.Slot(128) + slotsPerArchivedPoint := primitives.Slot(128) prevRoot := genesisRoot - for i := types.Slot(1); i <= slotsPerArchivedPoint; i++ { + for i := primitives.Slot(1); i <= slotsPerArchivedPoint; i++ { b := util.NewBeaconBlock() b.Block.Slot = i b.Block.ParentRoot = prevRoot[:] @@ -588,12 +588,12 @@ func TestStore_CleanUpDirtyStates_AboveThreshold(t *testing.T) { require.NoError(t, db.SaveFinalizedCheckpoint(context.Background(), ðpb.Checkpoint{ Root: bRoots[len(bRoots)-1][:], - Epoch: types.Epoch(slotsPerArchivedPoint / params.BeaconConfig().SlotsPerEpoch), + Epoch: primitives.Epoch(slotsPerArchivedPoint / params.BeaconConfig().SlotsPerEpoch), })) require.NoError(t, db.CleanUpDirtyStates(context.Background(), slotsPerArchivedPoint)) for i, root := range bRoots { - if types.Slot(i) >= slotsPerArchivedPoint.SubSlot(slotsPerArchivedPoint.Div(3)) { + if primitives.Slot(i) >= slotsPerArchivedPoint.SubSlot(slotsPerArchivedPoint.Div(3)) { require.Equal(t, true, db.HasState(context.Background(), root)) } else { require.Equal(t, false, db.HasState(context.Background(), root)) @@ -610,7 +610,7 @@ func TestStore_CleanUpDirtyStates_Finalized(t *testing.T) { require.NoError(t, db.SaveGenesisBlockRoot(context.Background(), genesisRoot)) require.NoError(t, db.SaveState(context.Background(), genesisState, genesisRoot)) - for i := types.Slot(1); i <= params.BeaconConfig().SlotsPerEpoch; i++ { + for i := primitives.Slot(1); i <= params.BeaconConfig().SlotsPerEpoch; i++ { b := util.NewBeaconBlock() b.Block.Slot = i r, err := b.Block.HashTreeRoot() @@ -640,7 +640,7 @@ func TestStore_CleanUpDirtyStates_DontDeleteNonFinalized(t *testing.T) { require.NoError(t, db.SaveState(context.Background(), genesisState, genesisRoot)) var unfinalizedRoots [][32]byte - for i := types.Slot(1); i <= params.BeaconConfig().SlotsPerEpoch; i++ { + for i := primitives.Slot(1); i <= params.BeaconConfig().SlotsPerEpoch; i++ { b := util.NewBeaconBlock() b.Block.Slot = i r, err := b.Block.HashTreeRoot() @@ -716,10 +716,10 @@ func validators(limit int) []*ethpb.Validator { WithdrawalCredentials: bytesutil.ToBytes(rand.Uint64(), 32), EffectiveBalance: rand.Uint64(), Slashed: i%2 != 0, - ActivationEligibilityEpoch: types.Epoch(rand.Uint64()), - ActivationEpoch: types.Epoch(rand.Uint64()), - ExitEpoch: types.Epoch(rand.Uint64()), - WithdrawableEpoch: types.Epoch(rand.Uint64()), + ActivationEligibilityEpoch: primitives.Epoch(rand.Uint64()), + ActivationEpoch: primitives.Epoch(rand.Uint64()), + ExitEpoch: primitives.Epoch(rand.Uint64()), + WithdrawableEpoch: primitives.Epoch(rand.Uint64()), } vals = append(vals, val) } diff --git a/beacon-chain/db/kv/wss.go b/beacon-chain/db/kv/wss.go index bc02c23ee0..cfc64c08e3 100644 --- a/beacon-chain/db/kv/wss.go +++ b/beacon-chain/db/kv/wss.go @@ -6,7 +6,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/ssz/detect" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -90,7 +90,7 @@ func (s *Store) SaveOrigin(ctx context.Context, serState, serBlock []byte) error return err } chkpt := ðpb.Checkpoint{ - Epoch: types.Epoch(slotEpoch), + Epoch: primitives.Epoch(slotEpoch), Root: blockRoot[:], } if err = s.SaveJustifiedCheckpoint(ctx, chkpt); err != nil { diff --git a/beacon-chain/db/restore_test.go b/beacon-chain/db/restore_test.go index 8484231661..eba8d058f6 100644 --- a/beacon-chain/db/restore_test.go +++ b/beacon-chain/db/restore_test.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/kv" "github.com/prysmaticlabs/prysm/v3/cmd" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -65,7 +65,7 @@ func TestRestore(t *testing.T) { require.NoError(t, err) headBlock, err := restoredDb.HeadBlock(ctx) require.NoError(t, err) - assert.Equal(t, types.Slot(5000), headBlock.Block().Slot(), "Restored database has incorrect data") + assert.Equal(t, primitives.Slot(5000), headBlock.Block().Slot(), "Restored database has incorrect data") assert.LogsContain(t, logHook, "Restore completed successfully") } diff --git a/beacon-chain/db/slasherkv/pruning.go b/beacon-chain/db/slasherkv/pruning.go index a9ff0675d5..b0323f3da5 100644 --- a/beacon-chain/db/slasherkv/pruning.go +++ b/beacon-chain/db/slasherkv/pruning.go @@ -6,7 +6,7 @@ import ( "encoding/binary" fssz "github.com/prysmaticlabs/fastssz" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/time/slots" bolt "go.etcd.io/bbolt" ) @@ -14,13 +14,13 @@ import ( // PruneAttestationsAtEpoch deletes all attestations from the slasher DB with target epoch // less than or equal to the specified epoch. func (s *Store) PruneAttestationsAtEpoch( - _ context.Context, maxEpoch types.Epoch, + _ context.Context, maxEpoch primitives.Epoch, ) (numPruned uint, err error) { // We can prune everything less than the current epoch - history length. encodedEndPruneEpoch := fssz.MarshalUint64([]byte{}, uint64(maxEpoch)) // We retrieve the lowest stored epoch in the attestations bucket. - var lowestEpoch types.Epoch + var lowestEpoch primitives.Epoch var hasData bool if err = s.db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket(attestationDataRootsBucket) @@ -30,7 +30,7 @@ func (s *Store) PruneAttestationsAtEpoch( return nil } hasData = true - lowestEpoch = types.Epoch(binary.LittleEndian.Uint64(k)) + lowestEpoch = primitives.Epoch(binary.LittleEndian.Uint64(k)) return nil }); err != nil { return @@ -85,9 +85,9 @@ func (s *Store) PruneAttestationsAtEpoch( // PruneProposalsAtEpoch deletes all proposals from the slasher DB with epoch // less than or equal to the specified epoch. func (s *Store) PruneProposalsAtEpoch( - ctx context.Context, maxEpoch types.Epoch, + ctx context.Context, maxEpoch primitives.Epoch, ) (numPruned uint, err error) { - var endPruneSlot types.Slot + var endPruneSlot primitives.Slot endPruneSlot, err = slots.EpochEnd(maxEpoch) if err != nil { return @@ -95,7 +95,7 @@ func (s *Store) PruneProposalsAtEpoch( encodedEndPruneSlot := fssz.MarshalUint64([]byte{}, uint64(endPruneSlot)) // We retrieve the lowest stored slot in the proposals bucket. - var lowestSlot types.Slot + var lowestSlot primitives.Slot var hasData bool if err = s.db.View(func(tx *bolt.Tx) error { proposalBkt := tx.Bucket(proposalRecordsBucket) @@ -156,8 +156,8 @@ func (s *Store) PruneProposalsAtEpoch( return } -func slotFromProposalKey(key []byte) types.Slot { - return types.Slot(binary.LittleEndian.Uint64(key[:8])) +func slotFromProposalKey(key []byte) primitives.Slot { + return primitives.Slot(binary.LittleEndian.Uint64(key[:8])) } func uint64PrefixGreaterThan(key, lessThan []byte) bool { diff --git a/beacon-chain/db/slasherkv/pruning_test.go b/beacon-chain/db/slasherkv/pruning_test.go index c1af8e8035..f86708ac3d 100644 --- a/beacon-chain/db/slasherkv/pruning_test.go +++ b/beacon-chain/db/slasherkv/pruning_test.go @@ -7,7 +7,7 @@ import ( slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/time/slots" logTest "github.com/sirupsen/logrus/hooks/test" @@ -25,8 +25,8 @@ func TestStore_PruneProposalsAtEpoch(t *testing.T) { // With a current epoch of 20 and a history length of 10, we should be pruning // everything before epoch (20 - 10) = 10. - currentEpoch := types.Epoch(20) - historyLength := types.Epoch(10) + currentEpoch := primitives.Epoch(20) + historyLength := primitives.Epoch(10) pruningLimitEpoch := currentEpoch - historyLength lowestStoredSlot, err := slots.EpochEnd(pruningLimitEpoch) @@ -58,15 +58,15 @@ func TestStore_PruneProposalsAtEpoch(t *testing.T) { config.SlotsPerEpoch = 2 params.OverrideBeaconConfig(config) - historyLength := types.Epoch(10) - currentEpoch := types.Epoch(20) + historyLength := primitives.Epoch(10) + currentEpoch := primitives.Epoch(20) pruningLimitEpoch := currentEpoch - historyLength // We create proposals from genesis to the current epoch, with 2 proposals // at each slot to ensure the entire pruning logic works correctly. slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch proposals := make([]*slashertypes.SignedBlockHeaderWrapper, 0, uint64(currentEpoch)*uint64(slotsPerEpoch)*2) - for i := types.Epoch(0); i < currentEpoch; i++ { + for i := primitives.Epoch(0); i < currentEpoch; i++ { startSlot, err := slots.EpochStart(i) require.NoError(t, err) endSlot, err := slots.EpochStart(i + 1) @@ -85,7 +85,7 @@ func TestStore_PruneProposalsAtEpoch(t *testing.T) { require.NoError(t, err) // Everything before epoch 10 should be deleted. - for i := types.Epoch(0); i < pruningLimitEpoch; i++ { + for i := primitives.Epoch(0); i < pruningLimitEpoch; i++ { err = beaconDB.db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket(proposalRecordsBucket) startSlot, err := slots.EpochStart(i) @@ -126,15 +126,15 @@ func TestStore_PruneAttestations_OK(t *testing.T) { // With a current epoch of 20 and a history length of 10, we should be pruning // everything before epoch (20 - 10) = 10. - currentEpoch := types.Epoch(20) - historyLength := types.Epoch(10) + currentEpoch := primitives.Epoch(20) + historyLength := primitives.Epoch(10) pruningLimitEpoch := currentEpoch - historyLength lowestStoredEpoch := pruningLimitEpoch err := beaconDB.db.Update(func(tx *bolt.Tx) error { bkt := tx.Bucket(attestationDataRootsBucket) - encIdx := encodeValidatorIndex(types.ValidatorIndex(0)) + encIdx := encodeValidatorIndex(primitives.ValidatorIndex(0)) encodedTargetEpoch := encodeTargetEpoch(lowestStoredEpoch + 1) key := append(encodedTargetEpoch, encIdx...) return bkt.Put(key, []byte("hi")) @@ -157,15 +157,15 @@ func TestStore_PruneAttestations_OK(t *testing.T) { config.SlotsPerEpoch = 2 params.OverrideBeaconConfig(config) - historyLength := types.Epoch(10) - currentEpoch := types.Epoch(20) + historyLength := primitives.Epoch(10) + currentEpoch := primitives.Epoch(20) pruningLimitEpoch := currentEpoch - historyLength // We create attestations from genesis to the current epoch, with 2 attestations // at each slot to ensure the entire pruning logic works correctly. slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch attestations := make([]*slashertypes.IndexedAttestationWrapper, 0, uint64(currentEpoch)*uint64(slotsPerEpoch)*2) - for i := types.Epoch(0); i < currentEpoch; i++ { + for i := primitives.Epoch(0); i < currentEpoch; i++ { startSlot, err := slots.EpochStart(i) require.NoError(t, err) endSlot, err := slots.EpochStart(i + 1) @@ -174,7 +174,7 @@ func TestStore_PruneAttestations_OK(t *testing.T) { attester1 := uint64(j + 10) attester2 := uint64(j + 11) target := i - var source types.Epoch + var source primitives.Epoch if i > 0 { source = target - 1 } @@ -191,7 +191,7 @@ func TestStore_PruneAttestations_OK(t *testing.T) { require.NoError(t, err) // Everything before epoch 10 should be deleted. - for i := types.Epoch(0); i < pruningLimitEpoch; i++ { + for i := primitives.Epoch(0); i < pruningLimitEpoch; i++ { err = beaconDB.db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket(attestationDataRootsBucket) startSlot, err := slots.EpochStart(i) @@ -199,8 +199,8 @@ func TestStore_PruneAttestations_OK(t *testing.T) { endSlot, err := slots.EpochStart(i + 1) require.NoError(t, err) for j := startSlot; j < endSlot; j++ { - attester1 := types.ValidatorIndex(j + 10) - attester2 := types.ValidatorIndex(j + 11) + attester1 := primitives.ValidatorIndex(j + 10) + attester2 := primitives.ValidatorIndex(j + 11) key1 := append(encodeTargetEpoch(i), encodeValidatorIndex(attester1)...) key2 := append(encodeTargetEpoch(i), encodeValidatorIndex(attester2)...) if bkt.Get(key1) != nil { diff --git a/beacon-chain/db/slasherkv/slasher.go b/beacon-chain/db/slasherkv/slasher.go index 4d38bae1e3..144c9ba271 100644 --- a/beacon-chain/db/slasherkv/slasher.go +++ b/beacon-chain/db/slasherkv/slasher.go @@ -12,7 +12,7 @@ import ( "github.com/pkg/errors" ssz "github.com/prysmaticlabs/fastssz" slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" bolt "go.etcd.io/bbolt" @@ -29,7 +29,7 @@ const ( // LastEpochWrittenForValidators given a list of validator indices returns the latest // epoch we have recorded the validators writing data for. func (s *Store) LastEpochWrittenForValidators( - ctx context.Context, validatorIndices []types.ValidatorIndex, + ctx context.Context, validatorIndices []primitives.ValidatorIndex, ) ([]*slashertypes.AttestedEpochForValidator, error) { ctx, span := trace.StartSpan(ctx, "BeaconDB.LastEpochWrittenForValidators") defer span.End() @@ -41,7 +41,7 @@ func (s *Store) LastEpochWrittenForValidators( err := s.db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket(attestedEpochsByValidator) for i, encodedIndex := range encodedIndices { - var epoch types.Epoch + var epoch primitives.Epoch epochBytes := bkt.Get(encodedIndex) if epochBytes != nil { if err := epoch.UnmarshalSSZ(epochBytes); err != nil { @@ -61,7 +61,7 @@ func (s *Store) LastEpochWrittenForValidators( // SaveLastEpochsWrittenForValidators updates the latest epoch a slice // of validator indices has attested to. func (s *Store) SaveLastEpochsWrittenForValidators( - ctx context.Context, epochByValidator map[types.ValidatorIndex]types.Epoch, + ctx context.Context, epochByValidator map[primitives.ValidatorIndex]primitives.Epoch, ) error { ctx, span := trace.StartSpan(ctx, "BeaconDB.SaveLastEpochsWrittenForValidators") defer span.End() @@ -132,7 +132,7 @@ func (s *Store) CheckAttesterDoubleVotes( encEpoch := encodeTargetEpoch(attToProcess.IndexedAttestation.Data.Target.Epoch) localDoubleVotes := make([]*slashertypes.AttesterDoubleVote, 0) for _, valIdx := range attToProcess.IndexedAttestation.AttestingIndices { - encIdx := encodeValidatorIndex(types.ValidatorIndex(valIdx)) + encIdx := encodeValidatorIndex(primitives.ValidatorIndex(valIdx)) validatorEpochKey := append(encEpoch, encIdx...) attRecordsKey := signingRootsBkt.Get(validatorEpochKey) // An attestation record key is comprised of a signing root (32 bytes). @@ -150,7 +150,7 @@ func (s *Store) CheckAttesterDoubleVotes( return err } slashAtt := &slashertypes.AttesterDoubleVote{ - ValidatorIndex: types.ValidatorIndex(valIdx), + ValidatorIndex: primitives.ValidatorIndex(valIdx), Target: attToProcess.IndexedAttestation.Data.Target.Epoch, PrevAttestationWrapper: existingAttRecord, AttestationWrapper: attToProcess, @@ -181,7 +181,7 @@ func (s *Store) CheckAttesterDoubleVotes( // AttestationRecordForValidator given a validator index and a target epoch, // retrieves an existing attestation record we have stored in the database. func (s *Store) AttestationRecordForValidator( - ctx context.Context, validatorIdx types.ValidatorIndex, targetEpoch types.Epoch, + ctx context.Context, validatorIdx primitives.ValidatorIndex, targetEpoch primitives.Epoch, ) (*slashertypes.IndexedAttestationWrapper, error) { ctx, span := trace.StartSpan(ctx, "BeaconDB.AttestationRecordForValidator") defer span.End() @@ -228,7 +228,7 @@ func (s *Store) SaveAttestationRecordsForValidators( } indicesBytes := make([]byte, len(att.IndexedAttestation.AttestingIndices)*8) for _, idx := range att.IndexedAttestation.AttestingIndices { - encodedIdx := encodeValidatorIndex(types.ValidatorIndex(idx)) + encodedIdx := encodeValidatorIndex(primitives.ValidatorIndex(idx)) indicesBytes = append(indicesBytes, encodedIdx...) } encodedIndices[i] = indicesBytes @@ -243,7 +243,7 @@ func (s *Store) SaveAttestationRecordsForValidators( return err } for _, valIdx := range att.IndexedAttestation.AttestingIndices { - encIdx := encodeValidatorIndex(types.ValidatorIndex(valIdx)) + encIdx := encodeValidatorIndex(primitives.ValidatorIndex(valIdx)) key := append(encodedTargetEpoch[i], encIdx...) if err := signingRootsBkt.Put(key, att.SigningRoot[:]); err != nil { return err @@ -357,7 +357,7 @@ func (s *Store) CheckDoubleBlockProposals( // BlockProposalForValidator given a validator index and a slot // retrieves an existing proposal record we have stored in the database. func (s *Store) BlockProposalForValidator( - ctx context.Context, validatorIdx types.ValidatorIndex, slot types.Slot, + ctx context.Context, validatorIdx primitives.ValidatorIndex, slot primitives.Slot, ) (*slashertypes.SignedBlockHeaderWrapper, error) { ctx, span := trace.StartSpan(ctx, "BeaconDB.BlockProposalForValidator") defer span.End() @@ -420,7 +420,7 @@ func (s *Store) SaveBlockProposals( // HighestAttestations retrieves the last attestation data from the database for all indices. func (s *Store) HighestAttestations( _ context.Context, - indices []types.ValidatorIndex, + indices []primitives.ValidatorIndex, ) ([]*ethpb.HighestAttestation, error) { if len(indices) == 0 { return nil, nil @@ -473,7 +473,7 @@ func suffixForAttestationRecordsKey(key, encodedValidatorIndex []byte) bool { } // Disk key for a validator proposal, including a slot+validatorIndex as a byte slice. -func keyForValidatorProposal(slot types.Slot, proposerIndex types.ValidatorIndex) ([]byte, error) { +func keyForValidatorProposal(slot primitives.Slot, proposerIndex primitives.ValidatorIndex) ([]byte, error) { encSlot, err := slot.MarshalSSZ() if err != nil { return nil, err @@ -579,7 +579,7 @@ func decodeProposalRecord(encoded []byte) (*slashertypes.SignedBlockHeaderWrappe } // Encodes an epoch into little-endian bytes. -func encodeTargetEpoch(epoch types.Epoch) []byte { +func encodeTargetEpoch(epoch primitives.Epoch) []byte { buf := make([]byte, 8) binary.LittleEndian.PutUint64(buf, uint64(epoch)) return buf @@ -588,7 +588,7 @@ func encodeTargetEpoch(epoch types.Epoch) []byte { // Encodes a validator index using 5 bytes instead of 8 as a // client optimization to save space in the database. Because the max validator // registry size is 2**40, this is a safe optimization. -func encodeValidatorIndex(index types.ValidatorIndex) []byte { +func encodeValidatorIndex(index primitives.ValidatorIndex) []byte { buf := make([]byte, 5) v := uint64(index) buf[0] = byte(v) diff --git a/beacon-chain/db/slasherkv/slasher_test.go b/beacon-chain/db/slasherkv/slasher_test.go index 8d19673abc..1626b448bc 100644 --- a/beacon-chain/db/slasherkv/slasher_test.go +++ b/beacon-chain/db/slasherkv/slasher_test.go @@ -11,7 +11,7 @@ import ( ssz "github.com/prysmaticlabs/fastssz" slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -21,9 +21,9 @@ import ( func TestStore_AttestationRecordForValidator_SaveRetrieve(t *testing.T) { ctx := context.Background() beaconDB := setupDB(t) - valIdx := types.ValidatorIndex(1) - target := types.Epoch(5) - source := types.Epoch(4) + valIdx := primitives.ValidatorIndex(1) + target := primitives.Epoch(5) + source := primitives.Epoch(4) attRecord, err := beaconDB.AttestationRecordForValidator(ctx, valIdx, target) require.NoError(t, err) require.Equal(t, true, attRecord == nil) @@ -46,17 +46,17 @@ func TestStore_AttestationRecordForValidator_SaveRetrieve(t *testing.T) { func TestStore_LastEpochWrittenForValidators(t *testing.T) { ctx := context.Background() beaconDB := setupDB(t) - indices := []types.ValidatorIndex{1, 2, 3} - epoch := types.Epoch(5) + indices := []primitives.ValidatorIndex{1, 2, 3} + epoch := primitives.Epoch(5) attestedEpochs, err := beaconDB.LastEpochWrittenForValidators(ctx, indices) require.NoError(t, err) require.Equal(t, true, len(attestedEpochs) == len(indices)) for _, item := range attestedEpochs { - require.Equal(t, types.Epoch(0), item.Epoch) + require.Equal(t, primitives.Epoch(0), item.Epoch) } - epochsByValidator := map[types.ValidatorIndex]types.Epoch{ + epochsByValidator := map[primitives.ValidatorIndex]primitives.Epoch{ 1: epoch, 2: epoch, 3: epoch, @@ -346,7 +346,7 @@ func TestStore_HighestAttestations(t *testing.T) { name string attestationsInDB []*slashertypes.IndexedAttestationWrapper expected []*ethpb.HighestAttestation - indices []types.ValidatorIndex + indices []primitives.ValidatorIndex wantErr bool }{ { @@ -354,7 +354,7 @@ func TestStore_HighestAttestations(t *testing.T) { attestationsInDB: []*slashertypes.IndexedAttestationWrapper{ createAttestationWrapper(0, 3, []uint64{1}, []byte{1}), }, - indices: []types.ValidatorIndex{1}, + indices: []primitives.ValidatorIndex{1}, expected: []*ethpb.HighestAttestation{ { ValidatorIndex: 1, @@ -371,7 +371,7 @@ func TestStore_HighestAttestations(t *testing.T) { createAttestationWrapper(2, 3, []uint64{4}, []byte{3}), createAttestationWrapper(5, 6, []uint64{5}, []byte{4}), }, - indices: []types.ValidatorIndex{2, 3, 4, 5}, + indices: []primitives.ValidatorIndex{2, 3, 4, 5}, expected: []*ethpb.HighestAttestation{ { ValidatorIndex: 2, @@ -403,7 +403,7 @@ func TestStore_HighestAttestations(t *testing.T) { createAttestationWrapper(4, 5, []uint64{1, 2}, []byte{3}), createAttestationWrapper(6, 7, []uint64{5}, []byte{4}), }, - indices: []types.ValidatorIndex{2, 3, 4, 5}, + indices: []primitives.ValidatorIndex{2, 3, 4, 5}, expected: []*ethpb.HighestAttestation{ { ValidatorIndex: 2, @@ -452,18 +452,18 @@ func BenchmarkHighestAttestations(b *testing.B) { } atts := make([]*slashertypes.IndexedAttestationWrapper, count) for i := 0; i < count; i++ { - atts[i] = createAttestationWrapper(types.Epoch(i), types.Epoch(i+2), indicesPerAtt[i], []byte{}) + atts[i] = createAttestationWrapper(primitives.Epoch(i), primitives.Epoch(i+2), indicesPerAtt[i], []byte{}) } ctx := context.Background() beaconDB := setupDB(b) require.NoError(b, beaconDB.SaveAttestationRecordsForValidators(ctx, atts)) - allIndices := make([]types.ValidatorIndex, valsPerAtt*count) + allIndices := make([]primitives.ValidatorIndex, valsPerAtt*count) for i := 0; i < count; i++ { - indicesForAtt := make([]types.ValidatorIndex, valsPerAtt) + indicesForAtt := make([]primitives.ValidatorIndex, valsPerAtt) for r := 0; r < valsPerAtt; r++ { - indicesForAtt[r] = types.ValidatorIndex(atts[i].IndexedAttestation.AttestingIndices[r]) + indicesForAtt[r] = primitives.ValidatorIndex(atts[i].IndexedAttestation.AttestingIndices[r]) } allIndices = append(allIndices, indicesForAtt...) } @@ -489,7 +489,7 @@ func BenchmarkStore_CheckDoubleBlockProposals(b *testing.B) { } atts := make([]*slashertypes.IndexedAttestationWrapper, count) for i := 0; i < count; i++ { - atts[i] = createAttestationWrapper(types.Epoch(i), types.Epoch(i+2), indicesPerAtt[i], []byte{}) + atts[i] = createAttestationWrapper(primitives.Epoch(i), primitives.Epoch(i+2), indicesPerAtt[i], []byte{}) } ctx := context.Background() @@ -507,7 +507,7 @@ func BenchmarkStore_CheckDoubleBlockProposals(b *testing.B) { } } -func createProposalWrapper(t *testing.T, slot types.Slot, proposerIndex types.ValidatorIndex, signingRoot []byte) *slashertypes.SignedBlockHeaderWrapper { +func createProposalWrapper(t *testing.T, slot primitives.Slot, proposerIndex primitives.ValidatorIndex, signingRoot []byte) *slashertypes.SignedBlockHeaderWrapper { header := ðpb.BeaconBlockHeader{ Slot: slot, ProposerIndex: proposerIndex, @@ -528,7 +528,7 @@ func createProposalWrapper(t *testing.T, slot types.Slot, proposerIndex types.Va } } -func createAttestationWrapper(source, target types.Epoch, indices []uint64, signingRoot []byte) *slashertypes.IndexedAttestationWrapper { +func createAttestationWrapper(source, target primitives.Epoch, indices []uint64, signingRoot []byte) *slashertypes.IndexedAttestationWrapper { signRoot := bytesutil.ToBytes32(signingRoot) if signingRoot == nil { signRoot = params.BeaconConfig().ZeroHash @@ -557,19 +557,19 @@ func createAttestationWrapper(source, target types.Epoch, indices []uint64, sign func Test_encodeValidatorIndex(t *testing.T) { tests := []struct { name string - index types.ValidatorIndex + index primitives.ValidatorIndex }{ { name: "0", - index: types.ValidatorIndex(0), + index: primitives.ValidatorIndex(0), }, { name: "genesis_validator_count", - index: types.ValidatorIndex(params.BeaconConfig().MinGenesisActiveValidatorCount), + index: primitives.ValidatorIndex(params.BeaconConfig().MinGenesisActiveValidatorCount), }, { name: "max_possible_value", - index: types.ValidatorIndex(params.BeaconConfig().ValidatorRegistryLimit - 1), + index: primitives.ValidatorIndex(params.BeaconConfig().ValidatorRegistryLimit - 1), }, } for _, tt := range tests { @@ -577,7 +577,7 @@ func Test_encodeValidatorIndex(t *testing.T) { got := encodeValidatorIndex(tt.index) encodedIndex := append(got[:5], 0, 0, 0) decoded := binary.LittleEndian.Uint64(encodedIndex) - require.DeepEqual(t, tt.index, types.ValidatorIndex(decoded)) + require.DeepEqual(t, tt.index, primitives.ValidatorIndex(decoded)) }) } } diff --git a/beacon-chain/deterministic-genesis/service.go b/beacon-chain/deterministic-genesis/service.go index ae16d18529..4e5822ec97 100644 --- a/beacon-chain/deterministic-genesis/service.go +++ b/beacon-chain/deterministic-genesis/service.go @@ -14,7 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/execution" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime" "github.com/prysmaticlabs/prysm/v3/runtime/interop" @@ -164,7 +164,7 @@ func (s *Service) saveGenesisState(ctx context.Context, genesisState state.Beaco s.chainStartDeposits = make([]*ethpb.Deposit, genesisState.NumValidators()) - for i := types.ValidatorIndex(0); uint64(i) < uint64(genesisState.NumValidators()); i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < uint64(genesisState.NumValidators()); i++ { pk := genesisState.PubkeyAtIndex(i) s.chainStartDeposits[i] = ðpb.Deposit{ Data: ðpb.Deposit_Data{ diff --git a/beacon-chain/execution/deposit_test.go b/beacon-chain/execution/deposit_test.go index 0c5b4f42ec..4c272dca3b 100644 --- a/beacon-chain/execution/deposit_test.go +++ b/beacon-chain/execution/deposit_test.go @@ -11,7 +11,7 @@ import ( testing2 "github.com/prysmaticlabs/prysm/v3/beacon-chain/execution/testing" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/trie" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -330,7 +330,7 @@ func TestProcessDeposit_AllDepositedSuccessfully(t *testing.T) { require.NoError(t, err) require.Equal(t, uint64(i+1), valCount, "Did not get correct active validator count") - val, err := web3Service.preGenesisState.ValidatorAtIndex(types.ValidatorIndex(i)) + val, err := web3Service.preGenesisState.ValidatorAtIndex(primitives.ValidatorIndex(i)) require.NoError(t, err) assert.Equal(t, params.BeaconConfig().MaxEffectiveBalance, val.EffectiveBalance) } diff --git a/beacon-chain/execution/engine_client.go b/beacon-chain/execution/engine_client.go index 9ae76352f5..7b6033c3b3 100644 --- a/beacon-chain/execution/engine_client.go +++ b/beacon-chain/execution/engine_client.go @@ -20,7 +20,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" payloadattribute "github.com/prysmaticlabs/prysm/v3/consensus-types/payload-attribute" - prysmType "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" pb "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -78,7 +78,7 @@ type EngineCaller interface { ForkchoiceUpdated( ctx context.Context, state *pb.ForkchoiceState, attrs payloadattribute.Attributer, ) (*pb.PayloadIDBytes, []byte, error) - GetPayload(ctx context.Context, payloadId [8]byte, slot prysmType.Slot) (interfaces.ExecutionData, error) + GetPayload(ctx context.Context, payloadId [8]byte, slot primitives.Slot) (interfaces.ExecutionData, error) ExchangeTransitionConfiguration( ctx context.Context, cfg *pb.TransitionConfiguration, ) error @@ -198,7 +198,7 @@ func (s *Service) ForkchoiceUpdated( } // GetPayload calls the engine_getPayloadVX method via JSON-RPC. -func (s *Service) GetPayload(ctx context.Context, payloadId [8]byte, slot prysmType.Slot) (interfaces.ExecutionData, error) { +func (s *Service) GetPayload(ctx context.Context, payloadId [8]byte, slot primitives.Slot) (interfaces.ExecutionData, error) { ctx, span := trace.StartSpan(ctx, "powchain.engine-api-client.GetPayload") defer span.End() start := time.Now() diff --git a/beacon-chain/execution/testing/mock_engine_client.go b/beacon-chain/execution/testing/mock_engine_client.go index 594398b0a3..2fcb2604ee 100644 --- a/beacon-chain/execution/testing/mock_engine_client.go +++ b/beacon-chain/execution/testing/mock_engine_client.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" payloadattribute "github.com/prysmaticlabs/prysm/v3/consensus-types/payload-attribute" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" pb "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -56,7 +56,7 @@ func (e *EngineClient) ForkchoiceUpdated( } // GetPayload -- -func (e *EngineClient) GetPayload(_ context.Context, _ [8]byte, s types.Slot) (interfaces.ExecutionData, error) { +func (e *EngineClient) GetPayload(_ context.Context, _ [8]byte, s primitives.Slot) (interfaces.ExecutionData, error) { if slots.ToEpoch(s) >= params.BeaconConfig().CapellaForkEpoch { return blocks.WrappedExecutionPayloadCapella(e.ExecutionPayloadCapella) } diff --git a/beacon-chain/forkchoice/doubly-linked-tree/ffg_update_test.go b/beacon-chain/forkchoice/doubly-linked-tree/ffg_update_test.go index b380e7c69b..9b3b7ac550 100644 --- a/beacon-chain/forkchoice/doubly-linked-tree/ffg_update_test.go +++ b/beacon-chain/forkchoice/doubly-linked-tree/ffg_update_test.go @@ -6,7 +6,7 @@ import ( forkchoicetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/types" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -215,7 +215,7 @@ func TestFFGUpdates_TwoBranches(t *testing.T) { assert.Equal(t, indexToHash(7), r, "Incorrect head with justified epoch at 0") } -func setup(justifiedEpoch, finalizedEpoch types.Epoch) *ForkChoice { +func setup(justifiedEpoch, finalizedEpoch primitives.Epoch) *ForkChoice { ctx := context.Background() f := New() f.store.justifiedCheckpoint = &forkchoicetypes.Checkpoint{Epoch: justifiedEpoch, Root: params.BeaconConfig().ZeroHash} diff --git a/beacon-chain/forkchoice/doubly-linked-tree/forkchoice.go b/beacon-chain/forkchoice/doubly-linked-tree/forkchoice.go index 1333c0e588..690cff5fd7 100644 --- a/beacon-chain/forkchoice/doubly-linked-tree/forkchoice.go +++ b/beacon-chain/forkchoice/doubly-linked-tree/forkchoice.go @@ -13,7 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/features" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" v1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -35,8 +35,8 @@ func New() *ForkChoice { proposerBoostRoot: [32]byte{}, nodeByRoot: make(map[[fieldparams.RootLength]byte]*Node), nodeByPayload: make(map[[fieldparams.RootLength]byte]*Node), - slashedIndices: make(map[types.ValidatorIndex]bool), - receivedBlocksLastEpoch: [fieldparams.SlotsPerEpoch]types.Slot{}, + slashedIndices: make(map[primitives.ValidatorIndex]bool), + receivedBlocksLastEpoch: [fieldparams.SlotsPerEpoch]primitives.Slot{}, } b := make([]uint64, 0) @@ -92,7 +92,7 @@ func (f *ForkChoice) Head( // 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 types.Epoch) { +func (f *ForkChoice) ProcessAttestation(ctx context.Context, validatorIndices []uint64, blockRoot [32]byte, targetEpoch primitives.Epoch) { _, span := trace.StartSpan(ctx, "doublyLinkedForkchoice.ProcessAttestation") defer span.End() f.votesLock.Lock() @@ -274,7 +274,7 @@ func (f *ForkChoice) IsOptimistic(root [32]byte) (bool, error) { } // AncestorRoot returns the ancestor root of input block root at a given slot. -func (f *ForkChoice) AncestorRoot(ctx context.Context, root [32]byte, slot types.Slot) ([32]byte, error) { +func (f *ForkChoice) AncestorRoot(ctx context.Context, root [32]byte, slot primitives.Slot) ([32]byte, error) { ctx, span := trace.StartSpan(ctx, "doublyLinkedForkchoice.AncestorRoot") defer span.End() @@ -307,7 +307,7 @@ func (f *ForkChoice) AncestorRoot(ctx context.Context, root [32]byte, slot types func (f *ForkChoice) updateBalances(newBalances []uint64) error { for index, vote := range f.votes { // Skip if validator has been slashed - if f.store.slashedIndices[types.ValidatorIndex(index)] { + if f.store.slashedIndices[primitives.ValidatorIndex(index)] { continue } // Skip if validator has never voted for current root and next root (i.e. if the @@ -374,7 +374,7 @@ func (f *ForkChoice) updateBalances(newBalances []uint64) error { // Tips returns a list of possible heads from fork choice store, it returns the // roots and the slots of the leaf nodes. -func (f *ForkChoice) Tips() ([][32]byte, []types.Slot) { +func (f *ForkChoice) Tips() ([][32]byte, []primitives.Slot) { return f.store.tips() } @@ -430,7 +430,7 @@ func (f *ForkChoice) SetOptimisticToInvalid(ctx context.Context, root, parentRoo // InsertSlashedIndex adds the given slashed validator index to the // store-tracked list. Votes from these validators are not accounted for // in forkchoice. -func (f *ForkChoice) InsertSlashedIndex(_ context.Context, index types.ValidatorIndex) { +func (f *ForkChoice) InsertSlashedIndex(_ context.Context, index primitives.ValidatorIndex) { f.votesLock.RLock() defer f.votesLock.RUnlock() @@ -444,11 +444,11 @@ func (f *ForkChoice) InsertSlashedIndex(_ context.Context, index types.Validator // Subtract last vote from this equivocating validator - if index >= types.ValidatorIndex(len(f.balances)) { + if index >= primitives.ValidatorIndex(len(f.balances)) { return } - if index >= types.ValidatorIndex(len(f.votes)) { + if index >= primitives.ValidatorIndex(len(f.votes)) { return } @@ -492,7 +492,7 @@ func (f *ForkChoice) UpdateFinalizedCheckpoint(fc *forkchoicetypes.Checkpoint) e } // CommonAncestor returns the common ancestor root and slot between the two block roots r1 and r2. -func (f *ForkChoice) CommonAncestor(ctx context.Context, r1 [32]byte, r2 [32]byte) ([32]byte, types.Slot, error) { +func (f *ForkChoice) CommonAncestor(ctx context.Context, r1 [32]byte, r2 [32]byte) ([32]byte, primitives.Slot, error) { ctx, span := trace.StartSpan(ctx, "doublyLinkedForkchoice.CommonAncestorRoot") defer span.End() diff --git a/beacon-chain/forkchoice/doubly-linked-tree/forkchoice_test.go b/beacon-chain/forkchoice/doubly-linked-tree/forkchoice_test.go index ccf9170bf2..da8d323319 100644 --- a/beacon-chain/forkchoice/doubly-linked-tree/forkchoice_test.go +++ b/beacon-chain/forkchoice/doubly-linked-tree/forkchoice_test.go @@ -12,7 +12,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/hash" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -25,12 +25,12 @@ import ( // insert into forkchoice func prepareForkchoiceState( _ context.Context, - slot types.Slot, + slot primitives.Slot, blockRoot [32]byte, parentRoot [32]byte, payloadHash [32]byte, - justifiedEpoch types.Epoch, - finalizedEpoch types.Epoch, + justifiedEpoch primitives.Epoch, + finalizedEpoch primitives.Epoch, ) (state.BeaconState, [32]byte, error) { blockHeader := ðpb.BeaconBlockHeader{ ParentRoot: parentRoot[:], @@ -338,8 +338,8 @@ func TestForkChoice_RemoveEquivocating(t *testing.T) { require.Equal(t, [32]byte{'c'}, head) // Process index where index == vote length. Should not panic. - f.InsertSlashedIndex(ctx, types.ValidatorIndex(len(f.balances))) - f.InsertSlashedIndex(ctx, types.ValidatorIndex(len(f.votes))) + f.InsertSlashedIndex(ctx, primitives.ValidatorIndex(len(f.balances))) + f.InsertSlashedIndex(ctx, primitives.ValidatorIndex(len(f.votes))) require.Equal(t, true, len(f.store.slashedIndices) > 0) } @@ -408,7 +408,7 @@ func TestStore_CommonAncestor(t *testing.T) { r1 [32]byte r2 [32]byte wantRoot [32]byte - wantSlot types.Slot + wantSlot primitives.Slot }{ { name: "Common ancestor between c and b is a", @@ -509,7 +509,7 @@ func TestStore_CommonAncestor(t *testing.T) { r1 [32]byte r2 [32]byte wantRoot [32]byte - wantSlot types.Slot + wantSlot primitives.Slot }{ { name: "Common ancestor between a and b is a", @@ -546,12 +546,12 @@ func TestStore_CommonAncestor(t *testing.T) { r, s, err := f.CommonAncestor(ctx, [32]byte{'b'}, [32]byte{'b'}) require.NoError(t, err) require.Equal(t, [32]byte{'b'}, r) - require.Equal(t, types.Slot(1), s) + require.Equal(t, primitives.Slot(1), s) // Requesting finalized root (last node) should return the same root. r, s, err = f.CommonAncestor(ctx, [32]byte{'a'}, [32]byte{'a'}) require.NoError(t, err) require.Equal(t, [32]byte{'a'}, r) - require.Equal(t, types.Slot(0), s) + require.Equal(t, primitives.Slot(0), s) // Requesting unknown root _, _, err = f.CommonAncestor(ctx, [32]byte{'a'}, [32]byte{'z'}) require.ErrorIs(t, err, forkchoice.ErrUnknownCommonAncestor) @@ -590,7 +590,7 @@ func TestStore_InsertOptimisticChain(t *testing.T) { }) for i := uint64(2); i < 11; i++ { blk := util.NewBeaconBlock() - blk.Block.Slot = types.Slot(i) + blk.Block.Slot = primitives.Slot(i) copiedRoot := root blk.Block.ParentRoot = copiedRoot[:] wsb, err = blocks.NewSignedBeaconBlock(blk) @@ -624,7 +624,7 @@ func TestForkChoice_UpdateCheckpoints(t *testing.T) { wantedJustified *forkchoicetypes.Checkpoint wantedBestJustified *forkchoicetypes.Checkpoint wantedFinalized *forkchoicetypes.Checkpoint - currentSlot types.Slot + currentSlot primitives.Slot wantedErr string }{ { diff --git a/beacon-chain/forkchoice/doubly-linked-tree/node.go b/beacon-chain/forkchoice/doubly-linked-tree/node.go index e6ed72410e..c012324079 100644 --- a/beacon-chain/forkchoice/doubly-linked-tree/node.go +++ b/beacon-chain/forkchoice/doubly-linked-tree/node.go @@ -7,7 +7,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/config/features" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" v1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ) @@ -35,7 +35,7 @@ func (n *Node) applyWeightChanges(ctx context.Context) error { // updateBestDescendant updates the best descendant of this node and its // children. This function assumes the caller has a lock on Store.nodesLock -func (n *Node) updateBestDescendant(ctx context.Context, justifiedEpoch, finalizedEpoch, currentEpoch types.Epoch) error { +func (n *Node) updateBestDescendant(ctx context.Context, justifiedEpoch, finalizedEpoch, currentEpoch primitives.Epoch) error { if ctx.Err() != nil { return ctx.Err() } @@ -89,7 +89,7 @@ func (n *Node) updateBestDescendant(ctx context.Context, justifiedEpoch, finaliz // viableForHead returns true if the node is viable to head. // Any node with different finalized or justified epoch than // the ones in fork choice store should not be viable to head. -func (n *Node) viableForHead(justifiedEpoch, finalizedEpoch, currentEpoch types.Epoch) bool { +func (n *Node) viableForHead(justifiedEpoch, finalizedEpoch, currentEpoch primitives.Epoch) bool { justified := justifiedEpoch == n.justifiedEpoch || justifiedEpoch == 0 finalized := finalizedEpoch == n.finalizedEpoch || finalizedEpoch == 0 if features.Get().EnableDefensivePull && !justified && justifiedEpoch+1 == currentEpoch { @@ -103,7 +103,7 @@ func (n *Node) viableForHead(justifiedEpoch, finalizedEpoch, currentEpoch types. return justified && finalized } -func (n *Node) leadsToViableHead(justifiedEpoch, finalizedEpoch, currentEpoch types.Epoch) bool { +func (n *Node) leadsToViableHead(justifiedEpoch, finalizedEpoch, currentEpoch primitives.Epoch) bool { if n.bestDescendant == nil { return n.viableForHead(justifiedEpoch, finalizedEpoch, currentEpoch) } diff --git a/beacon-chain/forkchoice/doubly-linked-tree/node_test.go b/beacon-chain/forkchoice/doubly-linked-tree/node_test.go index 40d4402b54..8051364784 100644 --- a/beacon-chain/forkchoice/doubly-linked-tree/node_test.go +++ b/beacon-chain/forkchoice/doubly-linked-tree/node_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" v1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -143,8 +143,8 @@ func TestNode_UpdateBestDescendant_LowerWeightChild(t *testing.T) { func TestNode_ViableForHead(t *testing.T) { tests := []struct { n *Node - justifiedEpoch types.Epoch - finalizedEpoch types.Epoch + justifiedEpoch primitives.Epoch + finalizedEpoch primitives.Epoch want bool }{ {&Node{}, 0, 0, true}, diff --git a/beacon-chain/forkchoice/doubly-linked-tree/on_tick.go b/beacon-chain/forkchoice/doubly-linked-tree/on_tick.go index db2b8efb1d..5a5962014b 100644 --- a/beacon-chain/forkchoice/doubly-linked-tree/on_tick.go +++ b/beacon-chain/forkchoice/doubly-linked-tree/on_tick.go @@ -5,7 +5,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/config/features" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/time/slots" ) @@ -30,7 +30,7 @@ import ( // ancestor_at_finalized_slot = get_ancestor(store, store.best_justified_checkpoint.root, finalized_slot) // if ancestor_at_finalized_slot == store.finalized_checkpoint.root: // store.justified_checkpoint = store.best_justified_checkpoint -func (f *ForkChoice) NewSlot(ctx context.Context, slot types.Slot) error { +func (f *ForkChoice) NewSlot(ctx context.Context, slot primitives.Slot) error { // Reset proposer boost root if err := f.ResetBoostedProposerRoot(ctx); err != nil { return errors.Wrap(err, "could not reset boosted proposer root in fork choice") diff --git a/beacon-chain/forkchoice/doubly-linked-tree/on_tick_test.go b/beacon-chain/forkchoice/doubly-linked-tree/on_tick_test.go index 29ceb47673..a2a2877164 100644 --- a/beacon-chain/forkchoice/doubly-linked-tree/on_tick_test.go +++ b/beacon-chain/forkchoice/doubly-linked-tree/on_tick_test.go @@ -6,7 +6,7 @@ import ( forkchoicetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/types" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -15,7 +15,7 @@ func TestStore_NewSlot(t *testing.T) { bj := [32]byte{'z'} type args struct { - slot types.Slot + slot primitives.Slot finalized *forkchoicetypes.Checkpoint justified *forkchoicetypes.Checkpoint bestJustified *forkchoicetypes.Checkpoint diff --git a/beacon-chain/forkchoice/doubly-linked-tree/proposer_boost_test.go b/beacon-chain/forkchoice/doubly-linked-tree/proposer_boost_test.go index 0629c648ba..82dce138df 100644 --- a/beacon-chain/forkchoice/doubly-linked-tree/proposer_boost_test.go +++ b/beacon-chain/forkchoice/doubly-linked-tree/proposer_boost_test.go @@ -6,14 +6,14 @@ import ( "time" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" ) // Helper function to simulate the block being on time or delayed for proposer // boost. It alters the genesisTime tracked by the store. -func driftGenesisTime(f *ForkChoice, slot types.Slot, delay uint64) { +func driftGenesisTime(f *ForkChoice, slot primitives.Slot, delay uint64) { f.SetGenesisTime(uint64(time.Now().Unix()) - uint64(slot)*params.BeaconConfig().SecondsPerSlot - delay) } @@ -25,7 +25,7 @@ func driftGenesisTime(f *ForkChoice, slot types.Slot, delay uint64) { // If the honest proposal is boosted at slot n+2, it will win against this attacker. func TestForkChoice_BoostProposerRoot_PreventsExAnteAttack(t *testing.T) { ctx := context.Background() - jEpoch, fEpoch := types.Epoch(0), types.Epoch(0) + jEpoch, fEpoch := primitives.Epoch(0), primitives.Epoch(0) zeroHash := params.BeaconConfig().ZeroHash balances := make([]uint64, 64) // 64 active validators. for i := 0; i < len(balances); i++ { @@ -43,7 +43,7 @@ func TestForkChoice_BoostProposerRoot_PreventsExAnteAttack(t *testing.T) { // 0 // | // 1 <- HEAD - slot := types.Slot(1) + slot := primitives.Slot(1) driftGenesisTime(f, slot, 0) newRoot := indexToHash(1) state, blkRoot, err := prepareForkchoiceState( @@ -68,7 +68,7 @@ func TestForkChoice_BoostProposerRoot_PreventsExAnteAttack(t *testing.T) { // 1 // | // 2 <- HEAD - slot = types.Slot(2) + slot = primitives.Slot(2) driftGenesisTime(f, slot, 0) newRoot = indexToHash(2) state, blkRoot, err = prepareForkchoiceState( @@ -95,7 +95,7 @@ func TestForkChoice_BoostProposerRoot_PreventsExAnteAttack(t *testing.T) { // 2 // | // 3 <- HEAD - slot = types.Slot(3) + slot = primitives.Slot(3) driftGenesisTime(f, slot, 0) newRoot = indexToHash(3) state, blkRoot, err = prepareForkchoiceState( @@ -123,7 +123,7 @@ func TestForkChoice_BoostProposerRoot_PreventsExAnteAttack(t *testing.T) { // / \ // 3 | // 4 <- HEAD - slot = types.Slot(4) + slot = primitives.Slot(4) driftGenesisTime(f, slot, 0) newRoot = indexToHash(4) state, blkRoot, err = prepareForkchoiceState( @@ -188,7 +188,7 @@ func TestForkChoice_BoostProposerRoot_PreventsExAnteAttack(t *testing.T) { // (B?) \ // \ // C <- Slot 2 HEAD - honestBlockSlot := types.Slot(2) + honestBlockSlot := primitives.Slot(2) driftGenesisTime(f, honestBlockSlot, 0) honestBlock := indexToHash(2) state, blkRoot, err := prepareForkchoiceState( @@ -206,7 +206,7 @@ func TestForkChoice_BoostProposerRoot_PreventsExAnteAttack(t *testing.T) { require.NoError(t, err) assert.Equal(t, honestBlock, r, "Incorrect head for justified epoch at slot 2") - maliciouslyWithheldBlockSlot := types.Slot(1) + maliciouslyWithheldBlockSlot := primitives.Slot(1) maliciouslyWithheldBlock := indexToHash(1) state, blkRoot, err = prepareForkchoiceState( ctx, @@ -253,7 +253,7 @@ func TestForkChoice_BoostProposerRoot_PreventsExAnteAttack(t *testing.T) { // (B?) \ // \ // C <- Slot 2 HEAD - honestBlockSlot := types.Slot(2) + honestBlockSlot := primitives.Slot(2) driftGenesisTime(f, honestBlockSlot, 0) honestBlock := indexToHash(2) state, blkRoot, err := prepareForkchoiceState( @@ -273,7 +273,7 @@ func TestForkChoice_BoostProposerRoot_PreventsExAnteAttack(t *testing.T) { require.NoError(t, err) assert.Equal(t, honestBlock, r, "Incorrect head for justified epoch at slot 2") - maliciouslyWithheldBlockSlot := types.Slot(1) + maliciouslyWithheldBlockSlot := primitives.Slot(1) maliciouslyWithheldBlock := indexToHash(1) state, blkRoot, err = prepareForkchoiceState( ctx, @@ -324,7 +324,7 @@ func TestForkChoice_BoostProposerRoot_PreventsExAnteAttack(t *testing.T) { require.NoError(t, err) assert.Equal(t, zeroHash, r, "Incorrect head with genesis") - cSlot := types.Slot(2) + cSlot := primitives.Slot(2) driftGenesisTime(f, cSlot, 0) c := indexToHash(2) state, blkRoot, err := prepareForkchoiceState( @@ -344,7 +344,7 @@ func TestForkChoice_BoostProposerRoot_PreventsExAnteAttack(t *testing.T) { require.NoError(t, err) assert.Equal(t, c, r, "Incorrect head for justified epoch at slot 2") - bSlot := types.Slot(1) + bSlot := primitives.Slot(1) b := indexToHash(1) state, blkRoot, err = prepareForkchoiceState( ctx, @@ -368,7 +368,7 @@ func TestForkChoice_BoostProposerRoot_PreventsExAnteAttack(t *testing.T) { f.ProcessAttestation(ctx, votes, c, fEpoch) // A block D, building on B, is received at slot N+3. It should not be able to win without boosting. - dSlot := types.Slot(3) + dSlot := primitives.Slot(3) d := indexToHash(3) state, blkRoot, err = prepareForkchoiceState( ctx, @@ -418,8 +418,8 @@ func TestForkChoice_BoostProposerRoot(t *testing.T) { t.Run("does not boost block from different slot", func(t *testing.T) { f := setup(0, 0) - slot := types.Slot(0) - currentSlot := types.Slot(1) + slot := primitives.Slot(0) + currentSlot := primitives.Slot(1) driftGenesisTime(f, currentSlot, 0) state, blkRoot, err := prepareForkchoiceState(ctx, slot, root, zeroHash, zeroHash, 0, 0) require.NoError(t, err) @@ -428,8 +428,8 @@ func TestForkChoice_BoostProposerRoot(t *testing.T) { }) t.Run("does not boost untimely block from same slot", func(t *testing.T) { f := setup(0, 0) - slot := types.Slot(1) - currentSlot := types.Slot(1) + slot := primitives.Slot(1) + currentSlot := primitives.Slot(1) driftGenesisTime(f, currentSlot, params.BeaconConfig().SecondsPerSlot-1) state, blkRoot, err := prepareForkchoiceState(ctx, slot, root, zeroHash, zeroHash, 0, 0) require.NoError(t, err) @@ -438,8 +438,8 @@ func TestForkChoice_BoostProposerRoot(t *testing.T) { }) t.Run("boosts perfectly timely block from same slot", func(t *testing.T) { f := setup(0, 0) - slot := types.Slot(1) - currentSlot := types.Slot(1) + slot := primitives.Slot(1) + currentSlot := primitives.Slot(1) driftGenesisTime(f, currentSlot, 0) state, blkRoot, err := prepareForkchoiceState(ctx, slot, root, zeroHash, zeroHash, 0, 0) require.NoError(t, err) @@ -448,8 +448,8 @@ func TestForkChoice_BoostProposerRoot(t *testing.T) { }) t.Run("boosts timely block from same slot", func(t *testing.T) { f := setup(0, 0) - slot := types.Slot(1) - currentSlot := types.Slot(1) + slot := primitives.Slot(1) + currentSlot := primitives.Slot(1) driftGenesisTime(f, currentSlot, 1) state, blkRoot, err := prepareForkchoiceState(ctx, slot, root, zeroHash, zeroHash, 0, 0) require.NoError(t, err) diff --git a/beacon-chain/forkchoice/doubly-linked-tree/store.go b/beacon-chain/forkchoice/doubly-linked-tree/store.go index 94ee234925..f89a1673ef 100644 --- a/beacon-chain/forkchoice/doubly-linked-tree/store.go +++ b/beacon-chain/forkchoice/doubly-linked-tree/store.go @@ -8,7 +8,7 @@ import ( "github.com/pkg/errors" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/time/slots" "go.opencensus.io/trace" ) @@ -106,9 +106,9 @@ func (s *Store) head(ctx context.Context) ([32]byte, error) { // insert registers a new block node to the fork choice store's node list. // It then updates the new node's parent with best child and descendant node. func (s *Store) insert(ctx context.Context, - slot types.Slot, + slot primitives.Slot, root, parentRoot, payloadHash [fieldparams.RootLength]byte, - justifiedEpoch, finalizedEpoch types.Epoch) (*Node, error) { + justifiedEpoch, finalizedEpoch primitives.Epoch) (*Node, error) { ctx, span := trace.StartSpan(ctx, "doublyLinkedForkchoice.insert") defer span.End() @@ -242,9 +242,9 @@ func (s *Store) prune(ctx context.Context) error { // tips returns a list of possible heads from fork choice store, it returns the // roots and the slots of the leaf nodes. -func (s *Store) tips() ([][32]byte, []types.Slot) { +func (s *Store) tips() ([][32]byte, []primitives.Slot) { var roots [][32]byte - var slots []types.Slot + var slots []primitives.Slot s.nodesLock.RLock() defer s.nodesLock.RUnlock() @@ -259,7 +259,7 @@ func (s *Store) tips() ([][32]byte, []types.Slot) { } // HighestReceivedBlockSlot returns the highest slot received by the forkchoice -func (f *ForkChoice) HighestReceivedBlockSlot() types.Slot { +func (f *ForkChoice) HighestReceivedBlockSlot() primitives.Slot { f.store.nodesLock.RLock() defer f.store.nodesLock.RUnlock() if f.store.highestReceivedNode == nil { diff --git a/beacon-chain/forkchoice/doubly-linked-tree/store_test.go b/beacon-chain/forkchoice/doubly-linked-tree/store_test.go index 140100b5b7..1e6914f2d9 100644 --- a/beacon-chain/forkchoice/doubly-linked-tree/store_test.go +++ b/beacon-chain/forkchoice/doubly-linked-tree/store_test.go @@ -7,19 +7,19 @@ import ( forkchoicetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/types" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" ) func TestStore_JustifiedEpoch(t *testing.T) { - j := types.Epoch(100) + j := primitives.Epoch(100) f := setup(j, j) require.Equal(t, j, f.JustifiedCheckpoint().Epoch) } func TestStore_FinalizedEpoch(t *testing.T) { - j := types.Epoch(50) + j := primitives.Epoch(50) f := setup(j, j) require.Equal(t, j, f.FinalizedCheckpoint().Epoch) } @@ -140,8 +140,8 @@ func TestStore_Insert(t *testing.T) { assert.Equal(t, 1, len(treeRootNode.children), "Incorrect children number") assert.Equal(t, payloadHash, treeRootNode.children[0].payloadHash, "Incorrect payload hash") child := treeRootNode.children[0] - assert.Equal(t, types.Epoch(1), child.justifiedEpoch, "Incorrect justification") - assert.Equal(t, types.Epoch(1), child.finalizedEpoch, "Incorrect finalization") + assert.Equal(t, primitives.Epoch(1), child.justifiedEpoch, "Incorrect justification") + assert.Equal(t, primitives.Epoch(1), child.finalizedEpoch, "Incorrect finalization") assert.Equal(t, indexToHash(100), child.root, "Incorrect root") } @@ -154,7 +154,7 @@ func TestStore_Prune_MoreThanThreshold(t *testing.T) { require.NoError(t, err) require.NoError(t, f.InsertNode(ctx, state, blkRoot)) for i := uint64(2); i < numOfNodes; i++ { - state, blkRoot, err = prepareForkchoiceState(ctx, types.Slot(i), indexToHash(i), indexToHash(i-1), params.BeaconConfig().ZeroHash, 0, 0) + state, blkRoot, err = prepareForkchoiceState(ctx, primitives.Slot(i), indexToHash(i), indexToHash(i-1), params.BeaconConfig().ZeroHash, 0, 0) require.NoError(t, err) require.NoError(t, f.InsertNode(ctx, state, blkRoot)) } @@ -176,7 +176,7 @@ func TestStore_Prune_MoreThanOnce(t *testing.T) { require.NoError(t, err) require.NoError(t, f.InsertNode(ctx, state, blkRoot)) for i := uint64(2); i < numOfNodes; i++ { - state, blkRoot, err = prepareForkchoiceState(ctx, types.Slot(i), indexToHash(i), indexToHash(i-1), params.BeaconConfig().ZeroHash, 0, 0) + state, blkRoot, err = prepareForkchoiceState(ctx, primitives.Slot(i), indexToHash(i), indexToHash(i-1), params.BeaconConfig().ZeroHash, 0, 0) require.NoError(t, err) require.NoError(t, f.InsertNode(ctx, state, blkRoot)) } @@ -203,7 +203,7 @@ func TestStore_Prune_ReturnEarly(t *testing.T) { require.NoError(t, err) require.NoError(t, f.InsertNode(ctx, state, blkRoot)) for i := uint64(2); i < numOfNodes; i++ { - state, blkRoot, err = prepareForkchoiceState(ctx, types.Slot(i), indexToHash(i), indexToHash(i-1), params.BeaconConfig().ZeroHash, 0, 0) + state, blkRoot, err = prepareForkchoiceState(ctx, primitives.Slot(i), indexToHash(i), indexToHash(i-1), params.BeaconConfig().ZeroHash, 0, 0) require.NoError(t, err) require.NoError(t, f.InsertNode(ctx, state, blkRoot)) } @@ -287,7 +287,7 @@ func TestStore_tips(t *testing.T) { state, blkRoot, err = prepareForkchoiceState(ctx, 106, [32]byte{'l'}, [32]byte{'k'}, params.BeaconConfig().ZeroHash, 1, 1) require.NoError(t, err) require.NoError(t, f.InsertNode(ctx, state, blkRoot)) - expectedMap := map[[32]byte]types.Slot{ + expectedMap := map[[32]byte]primitives.Slot{ {'f'}: 105, {'i'}: 106, {'l'}: 106, @@ -342,18 +342,18 @@ func TestForkChoice_HighestReceivedBlockSlotRoot(t *testing.T) { s := f.store _, err := s.insert(context.Background(), 100, [32]byte{'A'}, [32]byte{}, params.BeaconConfig().ZeroHash, 1, 1) require.NoError(t, err) - require.Equal(t, types.Slot(100), s.highestReceivedNode.slot) - require.Equal(t, types.Slot(100), f.HighestReceivedBlockSlot()) + require.Equal(t, primitives.Slot(100), s.highestReceivedNode.slot) + require.Equal(t, primitives.Slot(100), f.HighestReceivedBlockSlot()) require.Equal(t, [32]byte{'A'}, f.HighestReceivedBlockRoot()) _, err = s.insert(context.Background(), 1000, [32]byte{'B'}, [32]byte{}, params.BeaconConfig().ZeroHash, 1, 1) require.NoError(t, err) - require.Equal(t, types.Slot(1000), s.highestReceivedNode.slot) - require.Equal(t, types.Slot(1000), f.HighestReceivedBlockSlot()) + require.Equal(t, primitives.Slot(1000), s.highestReceivedNode.slot) + require.Equal(t, primitives.Slot(1000), f.HighestReceivedBlockSlot()) require.Equal(t, [32]byte{'B'}, f.HighestReceivedBlockRoot()) _, err = s.insert(context.Background(), 500, [32]byte{'C'}, [32]byte{}, params.BeaconConfig().ZeroHash, 1, 1) require.NoError(t, err) - require.Equal(t, types.Slot(1000), s.highestReceivedNode.slot) - require.Equal(t, types.Slot(1000), f.HighestReceivedBlockSlot()) + require.Equal(t, primitives.Slot(1000), s.highestReceivedNode.slot) + require.Equal(t, primitives.Slot(1000), f.HighestReceivedBlockSlot()) require.Equal(t, [32]byte{'B'}, f.HighestReceivedBlockRoot()) } @@ -369,7 +369,7 @@ func TestForkChoice_ReceivedBlocksLastEpoch(t *testing.T) { count, err := f.ReceivedBlocksLastEpoch() require.NoError(t, err) require.Equal(t, uint64(1), count) - require.Equal(t, types.Slot(1), f.HighestReceivedBlockSlot()) + require.Equal(t, primitives.Slot(1), f.HighestReceivedBlockSlot()) // 64 // Received block last epoch is 1 @@ -379,7 +379,7 @@ func TestForkChoice_ReceivedBlocksLastEpoch(t *testing.T) { count, err = f.ReceivedBlocksLastEpoch() require.NoError(t, err) require.Equal(t, uint64(1), count) - require.Equal(t, types.Slot(64), f.HighestReceivedBlockSlot()) + require.Equal(t, primitives.Slot(64), f.HighestReceivedBlockSlot()) // 64 65 // Received block last epoch is 2 @@ -389,7 +389,7 @@ func TestForkChoice_ReceivedBlocksLastEpoch(t *testing.T) { count, err = f.ReceivedBlocksLastEpoch() require.NoError(t, err) require.Equal(t, uint64(2), count) - require.Equal(t, types.Slot(65), f.HighestReceivedBlockSlot()) + require.Equal(t, primitives.Slot(65), f.HighestReceivedBlockSlot()) // 64 65 66 // Received block last epoch is 3 @@ -399,7 +399,7 @@ func TestForkChoice_ReceivedBlocksLastEpoch(t *testing.T) { count, err = f.ReceivedBlocksLastEpoch() require.NoError(t, err) require.Equal(t, uint64(3), count) - require.Equal(t, types.Slot(66), f.HighestReceivedBlockSlot()) + require.Equal(t, primitives.Slot(66), f.HighestReceivedBlockSlot()) // 64 65 66 // 98 @@ -410,7 +410,7 @@ func TestForkChoice_ReceivedBlocksLastEpoch(t *testing.T) { count, err = f.ReceivedBlocksLastEpoch() require.NoError(t, err) require.Equal(t, uint64(1), count) - require.Equal(t, types.Slot(98), f.HighestReceivedBlockSlot()) + require.Equal(t, primitives.Slot(98), f.HighestReceivedBlockSlot()) // 64 65 66 // 98 @@ -422,7 +422,7 @@ func TestForkChoice_ReceivedBlocksLastEpoch(t *testing.T) { count, err = f.ReceivedBlocksLastEpoch() require.NoError(t, err) require.Equal(t, uint64(1), count) - require.Equal(t, types.Slot(132), f.HighestReceivedBlockSlot()) + require.Equal(t, primitives.Slot(132), f.HighestReceivedBlockSlot()) // 64 65 66 // 98 @@ -435,7 +435,7 @@ func TestForkChoice_ReceivedBlocksLastEpoch(t *testing.T) { count, err = f.ReceivedBlocksLastEpoch() require.NoError(t, err) require.Equal(t, uint64(1), count) - require.Equal(t, types.Slot(132), f.HighestReceivedBlockSlot()) + require.Equal(t, primitives.Slot(132), f.HighestReceivedBlockSlot()) // 64 65 66 // 98 @@ -448,7 +448,7 @@ func TestForkChoice_ReceivedBlocksLastEpoch(t *testing.T) { count, err = f.ReceivedBlocksLastEpoch() require.NoError(t, err) require.Equal(t, uint64(1), count) - require.Equal(t, types.Slot(132), f.HighestReceivedBlockSlot()) + require.Equal(t, primitives.Slot(132), f.HighestReceivedBlockSlot()) // 64 65 66 // 98 @@ -461,7 +461,7 @@ func TestForkChoice_ReceivedBlocksLastEpoch(t *testing.T) { count, err = f.ReceivedBlocksLastEpoch() require.NoError(t, err) require.Equal(t, uint64(2), count) - require.Equal(t, types.Slot(132), f.HighestReceivedBlockSlot()) + require.Equal(t, primitives.Slot(132), f.HighestReceivedBlockSlot()) s.genesisTime = uint64(time.Now().Add(time.Duration(-134*int64(params.BeaconConfig().SecondsPerSlot)) * time.Second).Unix()) count, err = f.ReceivedBlocksLastEpoch() diff --git a/beacon-chain/forkchoice/doubly-linked-tree/types.go b/beacon-chain/forkchoice/doubly-linked-tree/types.go index f6e1a2fe6a..2d19f5ee33 100644 --- a/beacon-chain/forkchoice/doubly-linked-tree/types.go +++ b/beacon-chain/forkchoice/doubly-linked-tree/types.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice" forkchoicetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/types" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // ForkChoice defines the overall fork choice store which includes all block nodes, validator's latest votes and balances. @@ -33,30 +33,30 @@ type Store struct { headNode *Node // last head Node nodeByRoot map[[fieldparams.RootLength]byte]*Node // nodes indexed by roots. nodeByPayload map[[fieldparams.RootLength]byte]*Node // nodes indexed by payload Hash - slashedIndices map[types.ValidatorIndex]bool // the list of equivocating validator indices + slashedIndices map[primitives.ValidatorIndex]bool // the list of equivocating validator indices originRoot [fieldparams.RootLength]byte // The genesis block root nodesLock sync.RWMutex proposerBoostLock sync.RWMutex checkpointsLock sync.RWMutex genesisTime uint64 - highestReceivedNode *Node // The highest slot node. - receivedBlocksLastEpoch [fieldparams.SlotsPerEpoch]types.Slot // Using `highestReceivedSlot`. The slot of blocks received in the last epoch. - allTipsAreInvalid bool // tracks if all tips are not viable for head - committeeBalance uint64 // tracks the total active validator balance divided by slots per epoch. Requires a lock on nodes to read/write + highestReceivedNode *Node // The highest slot node. + receivedBlocksLastEpoch [fieldparams.SlotsPerEpoch]primitives.Slot // Using `highestReceivedSlot`. The slot of blocks received in the last epoch. + allTipsAreInvalid bool // tracks if all tips are not viable for head + committeeBalance uint64 // tracks the total active validator balance divided by slots per epoch. Requires a lock on nodes to read/write } // 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 types.Slot // slot of the block converted to the node. + slot primitives.Slot // slot of the block converted to the node. root [fieldparams.RootLength]byte // root of the block converted to the node. payloadHash [fieldparams.RootLength]byte // payloadHash of the block converted to the node. parent *Node // parent index of this node. children []*Node // the list of direct children of this Node - justifiedEpoch types.Epoch // justifiedEpoch of this node. - unrealizedJustifiedEpoch types.Epoch // the epoch that would be justified if the block would be advanced to the next epoch. - finalizedEpoch types.Epoch // finalizedEpoch of this node. - unrealizedFinalizedEpoch types.Epoch // the epoch that would be finalized if the block would be advanced to the next epoch. + justifiedEpoch primitives.Epoch // justifiedEpoch of this node. + unrealizedJustifiedEpoch primitives.Epoch // the epoch that would be justified if the block would be advanced to the next epoch. + finalizedEpoch primitives.Epoch // finalizedEpoch of this node. + unrealizedFinalizedEpoch primitives.Epoch // the epoch that would be finalized if the block would be advanced to the next epoch. balance uint64 // the balance that voted for this node directly weight uint64 // weight of this node: the total balance including children bestDescendant *Node // bestDescendant node of this node. @@ -68,5 +68,5 @@ type Node struct { type Vote struct { currentRoot [fieldparams.RootLength]byte // current voting root. nextRoot [fieldparams.RootLength]byte // next voting root. - nextEpoch types.Epoch // epoch of next voting period. + nextEpoch primitives.Epoch // epoch of next voting period. } diff --git a/beacon-chain/forkchoice/doubly-linked-tree/unrealized_justification.go b/beacon-chain/forkchoice/doubly-linked-tree/unrealized_justification.go index 867908c65d..aa7e5ad240 100644 --- a/beacon-chain/forkchoice/doubly-linked-tree/unrealized_justification.go +++ b/beacon-chain/forkchoice/doubly-linked-tree/unrealized_justification.go @@ -6,13 +6,13 @@ import ( forkchoicetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" ) -func (s *Store) setUnrealizedJustifiedEpoch(root [32]byte, epoch types.Epoch) error { +func (s *Store) setUnrealizedJustifiedEpoch(root [32]byte, epoch primitives.Epoch) error { s.nodesLock.Lock() defer s.nodesLock.Unlock() @@ -27,7 +27,7 @@ func (s *Store) setUnrealizedJustifiedEpoch(root [32]byte, epoch types.Epoch) er return nil } -func (s *Store) setUnrealizedFinalizedEpoch(root [32]byte, epoch types.Epoch) error { +func (s *Store) setUnrealizedFinalizedEpoch(root [32]byte, epoch primitives.Epoch) error { s.nodesLock.Lock() defer s.nodesLock.Unlock() diff --git a/beacon-chain/forkchoice/doubly-linked-tree/unrealized_justification_test.go b/beacon-chain/forkchoice/doubly-linked-tree/unrealized_justification_test.go index 18c6dacb64..dae60620f8 100644 --- a/beacon-chain/forkchoice/doubly-linked-tree/unrealized_justification_test.go +++ b/beacon-chain/forkchoice/doubly-linked-tree/unrealized_justification_test.go @@ -7,7 +7,7 @@ import ( forkchoicetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/types" "github.com/prysmaticlabs/prysm/v3/config/features" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -24,14 +24,14 @@ func TestStore_SetUnrealizedEpochs(t *testing.T) { require.NoError(t, err) require.NoError(t, f.InsertNode(ctx, state, blkRoot)) f.store.nodesLock.RLock() - require.Equal(t, types.Epoch(1), f.store.nodeByRoot[[32]byte{'b'}].unrealizedJustifiedEpoch) - require.Equal(t, types.Epoch(1), f.store.nodeByRoot[[32]byte{'b'}].unrealizedFinalizedEpoch) + require.Equal(t, primitives.Epoch(1), f.store.nodeByRoot[[32]byte{'b'}].unrealizedJustifiedEpoch) + require.Equal(t, primitives.Epoch(1), f.store.nodeByRoot[[32]byte{'b'}].unrealizedFinalizedEpoch) f.store.nodesLock.RUnlock() require.NoError(t, f.store.setUnrealizedJustifiedEpoch([32]byte{'b'}, 2)) require.NoError(t, f.store.setUnrealizedFinalizedEpoch([32]byte{'b'}, 2)) f.store.nodesLock.RLock() - require.Equal(t, types.Epoch(2), f.store.nodeByRoot[[32]byte{'b'}].unrealizedJustifiedEpoch) - require.Equal(t, types.Epoch(2), f.store.nodeByRoot[[32]byte{'b'}].unrealizedFinalizedEpoch) + require.Equal(t, primitives.Epoch(2), f.store.nodeByRoot[[32]byte{'b'}].unrealizedJustifiedEpoch) + require.Equal(t, primitives.Epoch(2), f.store.nodeByRoot[[32]byte{'b'}].unrealizedFinalizedEpoch) f.store.nodesLock.RUnlock() require.ErrorIs(t, errInvalidUnrealizedJustifiedEpoch, f.store.setUnrealizedJustifiedEpoch([32]byte{'b'}, 0)) @@ -163,7 +163,7 @@ func TestStore_NoDeadLock(t *testing.T) { headRoot, err := f.Head(ctx, []uint64{100}) require.NoError(t, err) require.Equal(t, [32]byte{'h'}, headRoot) - require.Equal(t, types.Epoch(0), f.JustifiedCheckpoint().Epoch) + require.Equal(t, primitives.Epoch(0), f.JustifiedCheckpoint().Epoch) // Insert Block I, it becomes Head hr := [32]byte{'i'} @@ -175,16 +175,16 @@ func TestStore_NoDeadLock(t *testing.T) { headRoot, err = f.Head(ctx, []uint64{100}) require.NoError(t, err) require.Equal(t, [32]byte{'i'}, headRoot) - require.Equal(t, types.Epoch(1), f.JustifiedCheckpoint().Epoch) - require.Equal(t, types.Epoch(0), f.FinalizedCheckpoint().Epoch) + require.Equal(t, primitives.Epoch(1), f.JustifiedCheckpoint().Epoch) + require.Equal(t, primitives.Epoch(0), f.FinalizedCheckpoint().Epoch) // Realized Justified checkpoints, H becomes head f.updateUnrealizedCheckpoints() headRoot, err = f.Head(ctx, []uint64{100}) require.NoError(t, err) require.Equal(t, [32]byte{'h'}, headRoot) - require.Equal(t, types.Epoch(2), f.JustifiedCheckpoint().Epoch) - require.Equal(t, types.Epoch(1), f.FinalizedCheckpoint().Epoch) + require.Equal(t, primitives.Epoch(2), f.JustifiedCheckpoint().Epoch) + require.Equal(t, primitives.Epoch(1), f.FinalizedCheckpoint().Epoch) } // Epoch 1 | Epoch 2 @@ -236,7 +236,7 @@ func TestStore_ForkNextEpoch(t *testing.T) { headRoot, err := f.Head(ctx, []uint64{100}) require.NoError(t, err) require.Equal(t, [32]byte{'h'}, headRoot) - require.Equal(t, types.Epoch(0), f.JustifiedCheckpoint().Epoch) + require.Equal(t, primitives.Epoch(0), f.JustifiedCheckpoint().Epoch) // D arrives late, D is head state, blkRoot, err = prepareForkchoiceState(ctx, 95, [32]byte{'d'}, [32]byte{'c'}, [32]byte{'D'}, 0, 0) @@ -248,7 +248,7 @@ func TestStore_ForkNextEpoch(t *testing.T) { headRoot, err = f.Head(ctx, []uint64{100}) require.NoError(t, err) require.Equal(t, [32]byte{'d'}, headRoot) - require.Equal(t, types.Epoch(2), f.JustifiedCheckpoint().Epoch) + require.Equal(t, primitives.Epoch(2), f.JustifiedCheckpoint().Epoch) require.Equal(t, uint64(0), f.store.nodeByRoot[[32]byte{'d'}].weight) require.Equal(t, uint64(100), f.store.nodeByRoot[[32]byte{'h'}].weight) // Set current epoch to 3, and H's unrealized checkpoint. Check it's head @@ -257,7 +257,7 @@ func TestStore_ForkNextEpoch(t *testing.T) { headRoot, err = f.Head(ctx, []uint64{100}) require.NoError(t, err) require.Equal(t, [32]byte{'h'}, headRoot) - require.Equal(t, types.Epoch(2), f.JustifiedCheckpoint().Epoch) + require.Equal(t, primitives.Epoch(2), f.JustifiedCheckpoint().Epoch) require.Equal(t, uint64(0), f.store.nodeByRoot[[32]byte{'d'}].weight) require.Equal(t, uint64(100), f.store.nodeByRoot[[32]byte{'h'}].weight) } @@ -269,14 +269,14 @@ func TestStore_PullTips_Heuristics(t *testing.T) { st, root, err := prepareForkchoiceState(ctx, 65, [32]byte{'p'}, [32]byte{}, [32]byte{}, 1, 1) require.NoError(tt, err) require.NoError(tt, f.InsertNode(ctx, st, root)) - f.store.nodeByRoot[[32]byte{'p'}].unrealizedJustifiedEpoch = types.Epoch(2) + f.store.nodeByRoot[[32]byte{'p'}].unrealizedJustifiedEpoch = primitives.Epoch(2) driftGenesisTime(f, 66, 0) st, root, err = prepareForkchoiceState(ctx, 66, [32]byte{'h'}, [32]byte{'p'}, [32]byte{}, 1, 1) require.NoError(tt, err) require.NoError(tt, f.InsertNode(ctx, st, root)) - require.Equal(tt, types.Epoch(2), f.store.nodeByRoot[[32]byte{'h'}].unrealizedJustifiedEpoch) - require.Equal(tt, types.Epoch(1), f.store.nodeByRoot[[32]byte{'h'}].unrealizedFinalizedEpoch) + require.Equal(tt, primitives.Epoch(2), f.store.nodeByRoot[[32]byte{'h'}].unrealizedJustifiedEpoch) + require.Equal(tt, primitives.Epoch(1), f.store.nodeByRoot[[32]byte{'h'}].unrealizedFinalizedEpoch) }) t.Run("Previous Epoch is justified and too early for current", func(tt *testing.T) { @@ -284,21 +284,21 @@ func TestStore_PullTips_Heuristics(t *testing.T) { st, root, err := prepareForkchoiceState(ctx, 95, [32]byte{'p'}, [32]byte{}, [32]byte{}, 1, 1) require.NoError(tt, err) require.NoError(tt, f.InsertNode(ctx, st, root)) - f.store.nodeByRoot[[32]byte{'p'}].unrealizedJustifiedEpoch = types.Epoch(2) + f.store.nodeByRoot[[32]byte{'p'}].unrealizedJustifiedEpoch = primitives.Epoch(2) driftGenesisTime(f, 96, 0) st, root, err = prepareForkchoiceState(ctx, 96, [32]byte{'h'}, [32]byte{'p'}, [32]byte{}, 1, 1) require.NoError(tt, err) require.NoError(tt, f.InsertNode(ctx, st, root)) - require.Equal(tt, types.Epoch(2), f.store.nodeByRoot[[32]byte{'h'}].unrealizedJustifiedEpoch) - require.Equal(tt, types.Epoch(1), f.store.nodeByRoot[[32]byte{'h'}].unrealizedFinalizedEpoch) + require.Equal(tt, primitives.Epoch(2), f.store.nodeByRoot[[32]byte{'h'}].unrealizedJustifiedEpoch) + require.Equal(tt, primitives.Epoch(1), f.store.nodeByRoot[[32]byte{'h'}].unrealizedFinalizedEpoch) }) t.Run("Previous Epoch is justified and not too early for current", func(tt *testing.T) { f := setup(1, 1) st, root, err := prepareForkchoiceState(ctx, 95, [32]byte{'p'}, [32]byte{}, [32]byte{}, 1, 1) require.NoError(tt, err) require.NoError(tt, f.InsertNode(ctx, st, root)) - f.store.nodeByRoot[[32]byte{'p'}].unrealizedJustifiedEpoch = types.Epoch(2) + f.store.nodeByRoot[[32]byte{'p'}].unrealizedJustifiedEpoch = primitives.Epoch(2) driftGenesisTime(f, 127, 0) st, root, err = prepareForkchoiceState(ctx, 127, [32]byte{'h'}, [32]byte{'p'}, [32]byte{}, 1, 1) @@ -308,14 +308,14 @@ func TestStore_PullTips_Heuristics(t *testing.T) { // This tests that the heuristics in pullTips did not apply and // the test continues to compute a bogus unrealized // justification - require.Equal(tt, types.Epoch(1), f.store.nodeByRoot[[32]byte{'h'}].unrealizedJustifiedEpoch) + require.Equal(tt, primitives.Epoch(1), f.store.nodeByRoot[[32]byte{'h'}].unrealizedJustifiedEpoch) }) t.Run("Block from previous Epoch", func(tt *testing.T) { f := setup(1, 1) st, root, err := prepareForkchoiceState(ctx, 94, [32]byte{'p'}, [32]byte{}, [32]byte{}, 1, 1) require.NoError(tt, err) require.NoError(tt, f.InsertNode(ctx, st, root)) - f.store.nodeByRoot[[32]byte{'p'}].unrealizedJustifiedEpoch = types.Epoch(2) + f.store.nodeByRoot[[32]byte{'p'}].unrealizedJustifiedEpoch = primitives.Epoch(2) driftGenesisTime(f, 96, 0) st, root, err = prepareForkchoiceState(ctx, 95, [32]byte{'h'}, [32]byte{'p'}, [32]byte{}, 1, 1) @@ -325,7 +325,7 @@ func TestStore_PullTips_Heuristics(t *testing.T) { // This tests that the heuristics in pullTips did not apply and // the test continues to compute a bogus unrealized // justification - require.Equal(tt, types.Epoch(1), f.store.nodeByRoot[[32]byte{'h'}].unrealizedJustifiedEpoch) + require.Equal(tt, primitives.Epoch(1), f.store.nodeByRoot[[32]byte{'h'}].unrealizedJustifiedEpoch) }) t.Run("Previous Epoch is not justified", func(tt *testing.T) { f := setup(1, 1) @@ -341,6 +341,6 @@ func TestStore_PullTips_Heuristics(t *testing.T) { // This tests that the heuristics in pullTips did not apply and // the test continues to compute a bogus unrealized // justification - require.Equal(tt, types.Epoch(2), f.store.nodeByRoot[[32]byte{'h'}].unrealizedJustifiedEpoch) + require.Equal(tt, primitives.Epoch(2), f.store.nodeByRoot[[32]byte{'h'}].unrealizedJustifiedEpoch) }) } diff --git a/beacon-chain/forkchoice/interfaces.go b/beacon-chain/forkchoice/interfaces.go index e177679c40..9fe80ca003 100644 --- a/beacon-chain/forkchoice/interfaces.go +++ b/beacon-chain/forkchoice/interfaces.go @@ -6,11 +6,11 @@ import ( forkchoicetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" v1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ) -// BalanceByRooter is a handler to obtain the effective balances of the state +// BalancesByRooter is a handler to obtain the effective balances of the state // with the given block root type BalancesByRooter func(context.Context, [32]byte) ([]uint64, error) @@ -28,7 +28,7 @@ type ForkChoicer interface { type HeadRetriever interface { Head(context.Context, []uint64) ([32]byte, error) CachedHeadRoot() [32]byte - Tips() ([][32]byte, []types.Slot) + Tips() ([][32]byte, []primitives.Slot) IsOptimistic(root [32]byte) (bool, error) AllTipsAreInvalid() bool } @@ -41,8 +41,8 @@ type BlockProcessor interface { // AttestationProcessor processes the attestation that's used for accounting fork choice. type AttestationProcessor interface { - ProcessAttestation(context.Context, []uint64, [32]byte, types.Epoch) - InsertSlashedIndex(context.Context, types.ValidatorIndex) + ProcessAttestation(context.Context, []uint64, [32]byte, primitives.Epoch) + InsertSlashedIndex(context.Context, primitives.ValidatorIndex) } // ProposerBooster is able to boost the proposer's root score during fork choice. @@ -55,8 +55,8 @@ type Getter interface { HasNode([32]byte) bool ProposerBoost() [fieldparams.RootLength]byte HasParent(root [32]byte) bool - AncestorRoot(ctx context.Context, root [32]byte, slot types.Slot) ([32]byte, error) - CommonAncestor(ctx context.Context, root1 [32]byte, root2 [32]byte) ([32]byte, types.Slot, error) + AncestorRoot(ctx context.Context, root [32]byte, slot primitives.Slot) ([32]byte, error) + CommonAncestor(ctx context.Context, root1 [32]byte, root2 [32]byte) ([32]byte, primitives.Slot, error) IsCanonical(root [32]byte) bool FinalizedCheckpoint() *forkchoicetypes.Checkpoint FinalizedPayloadBlockHash() [32]byte @@ -65,7 +65,7 @@ type Getter interface { JustifiedPayloadBlockHash() [32]byte BestJustifiedCheckpoint() *forkchoicetypes.Checkpoint NodeCount() int - HighestReceivedBlockSlot() types.Slot + HighestReceivedBlockSlot() primitives.Slot HighestReceivedBlockRoot() [32]byte ReceivedBlocksLastEpoch() (uint64, error) ForkChoiceDump(context.Context) (*v1.ForkChoiceDump, error) @@ -81,6 +81,6 @@ type Setter interface { UpdateFinalizedCheckpoint(*forkchoicetypes.Checkpoint) error SetGenesisTime(uint64) SetOriginRoot([32]byte) - NewSlot(context.Context, types.Slot) error + NewSlot(context.Context, primitives.Slot) error SetBalancesByRooter(BalancesByRooter) } diff --git a/beacon-chain/forkchoice/types/types.go b/beacon-chain/forkchoice/types/types.go index 105ad531b3..9cceb1ea1d 100644 --- a/beacon-chain/forkchoice/types/types.go +++ b/beacon-chain/forkchoice/types/types.go @@ -3,15 +3,15 @@ package types import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) // ProposerBoostRootArgs to call the BoostProposerRoot function. type ProposerBoostRootArgs struct { BlockRoot [32]byte - BlockSlot types.Slot - CurrentSlot types.Slot + BlockSlot primitives.Slot + CurrentSlot primitives.Slot SecondsIntoSlot uint64 } @@ -19,7 +19,7 @@ type ProposerBoostRootArgs struct { // forkchoice, while the slice version is used in the interface to legagy code // in other packages type Checkpoint struct { - Epoch types.Epoch + Epoch primitives.Epoch Root [fieldparams.RootLength]byte } diff --git a/beacon-chain/monitor/process_attestation.go b/beacon-chain/monitor/process_attestation.go index d949d041b0..3a40249f99 100644 --- a/beacon-chain/monitor/process_attestation.go +++ b/beacon-chain/monitor/process_attestation.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/attestation" @@ -21,7 +21,7 @@ import ( // canUpdateAttestedValidator returns true if the validator is tracked and if the // given slot is different than the last attested slot from this validator. // It assumes that a read lock is held on the monitor service. -func (s *Service) canUpdateAttestedValidator(idx types.ValidatorIndex, slot types.Slot) bool { +func (s *Service) canUpdateAttestedValidator(idx primitives.ValidatorIndex, slot primitives.Slot) bool { if !s.trackedIndex(idx) { return false } @@ -42,7 +42,7 @@ func attestingIndices(ctx context.Context, state state.BeaconState, att *ethpb.A } // logMessageTimelyFlagsForIndex returns the log message with performance info for the attestation (head, source, target) -func logMessageTimelyFlagsForIndex(idx types.ValidatorIndex, data *ethpb.AttestationData) logrus.Fields { +func logMessageTimelyFlagsForIndex(idx primitives.ValidatorIndex, data *ethpb.AttestationData) logrus.Fields { return logrus.Fields{ "ValidatorIndex": idx, "Slot": data.Slot, @@ -72,19 +72,19 @@ func (s *Service) processIncludedAttestation(ctx context.Context, state state.Be s.Lock() defer s.Unlock() for _, idx := range attestingIndices { - if s.canUpdateAttestedValidator(types.ValidatorIndex(idx), att.Data.Slot) { - logFields := logMessageTimelyFlagsForIndex(types.ValidatorIndex(idx), att.Data) - balance, err := state.BalanceAtIndex(types.ValidatorIndex(idx)) + if s.canUpdateAttestedValidator(primitives.ValidatorIndex(idx), att.Data.Slot) { + logFields := logMessageTimelyFlagsForIndex(primitives.ValidatorIndex(idx), att.Data) + balance, err := state.BalanceAtIndex(primitives.ValidatorIndex(idx)) if err != nil { log.WithError(err).Error("Could not get balance") return } - aggregatedPerf := s.aggregatedPerformance[types.ValidatorIndex(idx)] + aggregatedPerf := s.aggregatedPerformance[primitives.ValidatorIndex(idx)] aggregatedPerf.totalAttestedCount++ aggregatedPerf.totalRequestedCount++ - latestPerf := s.latestPerformance[types.ValidatorIndex(idx)] + latestPerf := s.latestPerformance[primitives.ValidatorIndex(idx)] balanceChg := int64(balance - latestPerf.balance) latestPerf.balanceChange = balanceChg latestPerf.balance = balance @@ -153,8 +153,8 @@ func (s *Service) processIncludedAttestation(ctx context.Context, state state.Be logFields["NewBalance"] = balance logFields["BalanceChange"] = balanceChg - s.latestPerformance[types.ValidatorIndex(idx)] = latestPerf - s.aggregatedPerformance[types.ValidatorIndex(idx)] = aggregatedPerf + s.latestPerformance[primitives.ValidatorIndex(idx)] = latestPerf + s.aggregatedPerformance[primitives.ValidatorIndex(idx)] = aggregatedPerf log.WithFields(logFields).Info("Attestation included") } } @@ -177,8 +177,8 @@ func (s *Service) processUnaggregatedAttestation(ctx context.Context, att *ethpb return } for _, idx := range attestingIndices { - if s.canUpdateAttestedValidator(types.ValidatorIndex(idx), att.Data.Slot) { - logFields := logMessageTimelyFlagsForIndex(types.ValidatorIndex(idx), att.Data) + if s.canUpdateAttestedValidator(primitives.ValidatorIndex(idx), att.Data.Slot) { + logFields := logMessageTimelyFlagsForIndex(primitives.ValidatorIndex(idx), att.Data) log.WithFields(logFields).Info("Processed unaggregated attestation") } } @@ -219,8 +219,8 @@ func (s *Service) processAggregatedAttestation(ctx context.Context, att *ethpb.A return } for _, idx := range attestingIndices { - if s.canUpdateAttestedValidator(types.ValidatorIndex(idx), att.Aggregate.Data.Slot) { - logFields := logMessageTimelyFlagsForIndex(types.ValidatorIndex(idx), att.Aggregate.Data) + if s.canUpdateAttestedValidator(primitives.ValidatorIndex(idx), att.Aggregate.Data.Slot) { + logFields := logMessageTimelyFlagsForIndex(primitives.ValidatorIndex(idx), att.Aggregate.Data) log.WithFields(logFields).Info("Processed aggregated attestation") } } diff --git a/beacon-chain/monitor/process_block.go b/beacon-chain/monitor/process_block.go index e15dd50321..4502e088cc 100644 --- a/beacon-chain/monitor/process_block.go +++ b/beacon-chain/monitor/process_block.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/time/slots" "github.com/sirupsen/logrus" @@ -120,7 +120,7 @@ func (s *Service) processSlashings(blk interfaces.BeaconBlock) { for _, slashing := range blk.Body().AttesterSlashings() { for _, idx := range blocks.SlashableAttesterIndices(slashing) { - if s.trackedIndex(types.ValidatorIndex(idx)) { + if s.trackedIndex(primitives.ValidatorIndex(idx)) { log.WithFields(logrus.Fields{ "AttesterIndex": idx, "BlockInclusionSlot": blk.Slot(), diff --git a/beacon-chain/monitor/process_block_test.go b/beacon-chain/monitor/process_block_test.go index 46eaa9f3ec..996f8ef68e 100644 --- a/beacon-chain/monitor/process_block_test.go +++ b/beacon-chain/monitor/process_block_test.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/altair" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -119,7 +119,7 @@ func TestProcessSlashings(t *testing.T) { t.Run(tt.name, func(t *testing.T) { hook := logTest.NewGlobal() s := &Service{ - TrackedValidators: map[types.ValidatorIndex]bool{ + TrackedValidators: map[primitives.ValidatorIndex]bool{ 1: true, 2: true, }, diff --git a/beacon-chain/monitor/process_exit_test.go b/beacon-chain/monitor/process_exit_test.go index 49d5a13af0..fde746071a 100644 --- a/beacon-chain/monitor/process_exit_test.go +++ b/beacon-chain/monitor/process_exit_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" logTest "github.com/sirupsen/logrus/hooks/test" @@ -13,7 +13,7 @@ import ( func TestProcessExitsFromBlockTrackedIndices(t *testing.T) { hook := logTest.NewGlobal() s := &Service{ - TrackedValidators: map[types.ValidatorIndex]bool{ + TrackedValidators: map[primitives.ValidatorIndex]bool{ 1: true, 2: true, }, @@ -49,7 +49,7 @@ func TestProcessExitsFromBlockTrackedIndices(t *testing.T) { func TestProcessExitsFromBlockUntrackedIndices(t *testing.T) { hook := logTest.NewGlobal() s := &Service{ - TrackedValidators: map[types.ValidatorIndex]bool{ + TrackedValidators: map[primitives.ValidatorIndex]bool{ 1: true, 2: true, }, @@ -85,7 +85,7 @@ func TestProcessExitsFromBlockUntrackedIndices(t *testing.T) { func TestProcessExitP2PTrackedIndices(t *testing.T) { hook := logTest.NewGlobal() s := &Service{ - TrackedValidators: map[types.ValidatorIndex]bool{ + TrackedValidators: map[primitives.ValidatorIndex]bool{ 1: true, 2: true, }, @@ -105,7 +105,7 @@ func TestProcessExitP2PTrackedIndices(t *testing.T) { func TestProcessExitP2PUntrackedIndices(t *testing.T) { hook := logTest.NewGlobal() s := &Service{ - TrackedValidators: map[types.ValidatorIndex]bool{ + TrackedValidators: map[primitives.ValidatorIndex]bool{ 1: true, 2: true, }, diff --git a/beacon-chain/monitor/service.go b/beacon-chain/monitor/service.go index b41187abec..71631d4086 100644 --- a/beacon-chain/monitor/service.go +++ b/beacon-chain/monitor/service.go @@ -14,7 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/time/slots" "github.com/sirupsen/logrus" ) @@ -29,8 +29,8 @@ var ( // ValidatorLatestPerformance keeps track of the latest participation of the validator type ValidatorLatestPerformance struct { - attestedSlot types.Slot - inclusionSlot types.Slot + attestedSlot primitives.Slot + inclusionSlot primitives.Slot timelySource bool timelyTarget bool timelyHead bool @@ -41,7 +41,7 @@ type ValidatorLatestPerformance struct { // ValidatorAggregatedPerformance keeps track of the accumulated performance of // the tracked validator since start of monitor service. type ValidatorAggregatedPerformance struct { - startEpoch types.Epoch + startEpoch primitives.Epoch startBalance uint64 totalAttestedCount uint64 totalRequestedCount uint64 @@ -77,24 +77,24 @@ type Service struct { // trackedSyncedCommitteeIndices and lastSyncedEpoch sync.RWMutex - TrackedValidators map[types.ValidatorIndex]bool - latestPerformance map[types.ValidatorIndex]ValidatorLatestPerformance - aggregatedPerformance map[types.ValidatorIndex]ValidatorAggregatedPerformance - trackedSyncCommitteeIndices map[types.ValidatorIndex][]types.CommitteeIndex - lastSyncedEpoch types.Epoch + TrackedValidators map[primitives.ValidatorIndex]bool + latestPerformance map[primitives.ValidatorIndex]ValidatorLatestPerformance + aggregatedPerformance map[primitives.ValidatorIndex]ValidatorAggregatedPerformance + trackedSyncCommitteeIndices map[primitives.ValidatorIndex][]primitives.CommitteeIndex + lastSyncedEpoch primitives.Epoch } // NewService sets up a new validator monitor service instance when given a list of validator indices to track. -func NewService(ctx context.Context, config *ValidatorMonitorConfig, tracked []types.ValidatorIndex) (*Service, error) { +func NewService(ctx context.Context, config *ValidatorMonitorConfig, tracked []primitives.ValidatorIndex) (*Service, error) { ctx, cancel := context.WithCancel(ctx) r := &Service{ config: config, ctx: ctx, cancel: cancel, - TrackedValidators: make(map[types.ValidatorIndex]bool, len(tracked)), - latestPerformance: make(map[types.ValidatorIndex]ValidatorLatestPerformance), - aggregatedPerformance: make(map[types.ValidatorIndex]ValidatorAggregatedPerformance), - trackedSyncCommitteeIndices: make(map[types.ValidatorIndex][]types.CommitteeIndex), + TrackedValidators: make(map[primitives.ValidatorIndex]bool, len(tracked)), + latestPerformance: make(map[primitives.ValidatorIndex]ValidatorLatestPerformance), + aggregatedPerformance: make(map[primitives.ValidatorIndex]ValidatorAggregatedPerformance), + trackedSyncCommitteeIndices: make(map[primitives.ValidatorIndex][]primitives.CommitteeIndex), isLogging: false, } for _, idx := range tracked { @@ -108,7 +108,7 @@ func (s *Service) Start() { s.Lock() defer s.Unlock() - tracked := make([]types.ValidatorIndex, 0, len(s.TrackedValidators)) + tracked := make([]primitives.ValidatorIndex, 0, len(s.TrackedValidators)) for idx := range s.TrackedValidators { tracked = append(tracked, idx) } @@ -163,7 +163,7 @@ func (s *Service) run(stateChannel chan *feed.Event, stateSub event.Subscription // initializePerformanceStructures initializes the validatorLatestPerformance // and validatorAggregatedPerformance for each tracked validator. -func (s *Service) initializePerformanceStructures(state state.BeaconState, epoch types.Epoch) { +func (s *Service) initializePerformanceStructures(state state.BeaconState, epoch primitives.Epoch) { for idx := range s.TrackedValidators { balance, err := state.BalanceAtIndex(idx) if err != nil { @@ -284,7 +284,7 @@ func (s *Service) monitorRoutine(stateChannel chan *feed.Event, stateSub event.S // TrackedIndex returns true if input validator index exists in tracked validator list. // It assumes the caller holds the service Lock -func (s *Service) trackedIndex(idx types.ValidatorIndex) bool { +func (s *Service) trackedIndex(idx primitives.ValidatorIndex) bool { _, ok := s.TrackedValidators[idx] return ok } diff --git a/beacon-chain/monitor/service_test.go b/beacon-chain/monitor/service_test.go index f07b6d20db..ca49bce08b 100644 --- a/beacon-chain/monitor/service_test.go +++ b/beacon-chain/monitor/service_test.go @@ -15,7 +15,7 @@ import ( doublylinkedtree "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/doubly-linked-tree" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -45,13 +45,13 @@ func setupService(t *testing.T) *Service { ValidatorsRoot: [32]byte{}, } - trackedVals := map[types.ValidatorIndex]bool{ + trackedVals := map[primitives.ValidatorIndex]bool{ 1: true, 2: true, 12: true, 15: true, } - latestPerformance := map[types.ValidatorIndex]ValidatorLatestPerformance{ + latestPerformance := map[primitives.ValidatorIndex]ValidatorLatestPerformance{ 1: { balance: 32000000000, }, @@ -65,7 +65,7 @@ func setupService(t *testing.T) *Service { balance: 31900000000, }, } - aggregatedPerformance := map[types.ValidatorIndex]ValidatorAggregatedPerformance{ + aggregatedPerformance := map[primitives.ValidatorIndex]ValidatorAggregatedPerformance{ 1: { startEpoch: 0, startBalance: 31700000000, @@ -83,7 +83,7 @@ func setupService(t *testing.T) *Service { 12: {}, 15: {}, } - trackedSyncCommitteeIndices := map[types.ValidatorIndex][]types.CommitteeIndex{ + trackedSyncCommitteeIndices := map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 1: {0, 1, 2, 3}, 12: {4, 5}, } @@ -106,13 +106,13 @@ func setupService(t *testing.T) *Service { func TestTrackedIndex(t *testing.T) { s := &Service{ - TrackedValidators: map[types.ValidatorIndex]bool{ + TrackedValidators: map[primitives.ValidatorIndex]bool{ 1: true, 2: true, }, } - require.Equal(t, s.trackedIndex(types.ValidatorIndex(1)), true) - require.Equal(t, s.trackedIndex(types.ValidatorIndex(3)), false) + require.Equal(t, s.trackedIndex(primitives.ValidatorIndex(1)), true) + require.Equal(t, s.trackedIndex(primitives.ValidatorIndex(3)), false) } func TestUpdateSyncCommitteeTrackedVals(t *testing.T) { @@ -122,7 +122,7 @@ func TestUpdateSyncCommitteeTrackedVals(t *testing.T) { s.updateSyncCommitteeTrackedVals(state) require.LogsDoNotContain(t, hook, "Sync committee assignments will not be reported") - newTrackedSyncIndices := map[types.ValidatorIndex][]types.CommitteeIndex{ + newTrackedSyncIndices := map[primitives.ValidatorIndex][]primitives.CommitteeIndex{ 1: {1, 3, 4}, 2: {2}, } @@ -131,7 +131,7 @@ func TestUpdateSyncCommitteeTrackedVals(t *testing.T) { func TestNewService(t *testing.T) { config := &ValidatorMonitorConfig{} - var tracked []types.ValidatorIndex + var tracked []primitives.ValidatorIndex ctx := context.Background() _, err := NewService(ctx, config, tracked) require.NoError(t, err) @@ -187,7 +187,7 @@ func TestInitializePerformanceStructures(t *testing.T) { epoch := slots.ToEpoch(state.Slot()) s.initializePerformanceStructures(state, epoch) require.LogsDoNotContain(t, hook, "Could not fetch starting balance") - latestPerformance := map[types.ValidatorIndex]ValidatorLatestPerformance{ + latestPerformance := map[primitives.ValidatorIndex]ValidatorLatestPerformance{ 1: { balance: 32000000000, }, @@ -201,7 +201,7 @@ func TestInitializePerformanceStructures(t *testing.T) { balance: 32000000000, }, } - aggregatedPerformance := map[types.ValidatorIndex]ValidatorAggregatedPerformance{ + aggregatedPerformance := map[primitives.ValidatorIndex]ValidatorAggregatedPerformance{ 1: { startBalance: 32000000000, }, diff --git a/beacon-chain/node/config.go b/beacon-chain/node/config.go index 751700336d..5f9954f1dc 100644 --- a/beacon-chain/node/config.go +++ b/beacon-chain/node/config.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/v3/config/features" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" tracing2 "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" "github.com/urfave/cli/v2" ) @@ -56,14 +56,14 @@ func configureHistoricalSlasher(cliCtx *cli.Context) error { func configureBuilderCircuitBreaker(cliCtx *cli.Context) error { if cliCtx.IsSet(flags.MaxBuilderConsecutiveMissedSlots.Name) { c := params.BeaconConfig().Copy() - c.MaxBuilderConsecutiveMissedSlots = types.Slot(cliCtx.Int(flags.MaxBuilderConsecutiveMissedSlots.Name)) + c.MaxBuilderConsecutiveMissedSlots = primitives.Slot(cliCtx.Int(flags.MaxBuilderConsecutiveMissedSlots.Name)) if err := params.SetActive(c); err != nil { return err } } if cliCtx.IsSet(flags.MaxBuilderEpochMissedSlots.Name) { c := params.BeaconConfig().Copy() - c.MaxBuilderEpochMissedSlots = types.Slot(cliCtx.Int(flags.MaxBuilderEpochMissedSlots.Name)) + c.MaxBuilderEpochMissedSlots = primitives.Slot(cliCtx.Int(flags.MaxBuilderEpochMissedSlots.Name)) if err := params.SetActive(c); err != nil { return err } @@ -74,7 +74,7 @@ func configureBuilderCircuitBreaker(cliCtx *cli.Context) error { func configureSlotsPerArchivedPoint(cliCtx *cli.Context) error { if cliCtx.IsSet(flags.SlotsPerArchivedPoint.Name) { c := params.BeaconConfig().Copy() - c.SlotsPerArchivedPoint = types.Slot(cliCtx.Int(flags.SlotsPerArchivedPoint.Name)) + c.SlotsPerArchivedPoint = primitives.Slot(cliCtx.Int(flags.SlotsPerArchivedPoint.Name)) if err := params.SetActive(c); err != nil { return err } @@ -157,7 +157,7 @@ func configureExecutionSetting(cliCtx *cli.Context) error { } if cliCtx.IsSet(flags.TerminalBlockHashActivationEpochOverride.Name) { c := params.BeaconConfig() - c.TerminalBlockHashActivationEpoch = types.Epoch(cliCtx.Uint64(flags.TerminalBlockHashActivationEpochOverride.Name)) + c.TerminalBlockHashActivationEpoch = primitives.Epoch(cliCtx.Uint64(flags.TerminalBlockHashActivationEpochOverride.Name)) log.WithField("terminal block hash activation epoch", c.TerminalBlockHashActivationEpoch).Warn("Terminal block hash activation epoch overridden") params.OverrideBeaconConfig(c) } diff --git a/beacon-chain/node/config_test.go b/beacon-chain/node/config_test.go index 37a3086df2..abf874ae68 100644 --- a/beacon-chain/node/config_test.go +++ b/beacon-chain/node/config_test.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/cmd" "github.com/prysmaticlabs/prysm/v3/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" logTest "github.com/sirupsen/logrus/hooks/test" @@ -50,7 +50,7 @@ func TestConfigureSlotsPerArchivedPoint(t *testing.T) { require.NoError(t, configureSlotsPerArchivedPoint(cliCtx)) - assert.Equal(t, types.Slot(100), params.BeaconConfig().SlotsPerArchivedPoint) + assert.Equal(t, primitives.Slot(100), params.BeaconConfig().SlotsPerArchivedPoint) } func TestConfigureProofOfWork(t *testing.T) { @@ -110,7 +110,7 @@ func TestConfigureExecutionSetting(t *testing.T) { assert.Equal(t, "100", params.BeaconConfig().TerminalTotalDifficulty) assert.Equal(t, common.HexToHash("0xA"), params.BeaconConfig().TerminalBlockHash) - assert.Equal(t, types.Epoch(200), params.BeaconConfig().TerminalBlockHashActivationEpoch) + assert.Equal(t, primitives.Epoch(200), params.BeaconConfig().TerminalBlockHashActivationEpoch) } diff --git a/beacon-chain/node/node.go b/beacon-chain/node/node.go index e08a8c7c74..d58c931c87 100644 --- a/beacon-chain/node/node.go +++ b/beacon-chain/node/node.go @@ -53,7 +53,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/v3/config/features" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/monitoring/prometheus" @@ -947,9 +947,9 @@ func (b *BeaconNode) registerValidatorMonitorService() error { if cliSlice == nil { return nil } - tracked := make([]types.ValidatorIndex, len(cliSlice)) + tracked := make([]primitives.ValidatorIndex, len(cliSlice)) for i := range tracked { - tracked[i] = types.ValidatorIndex(cliSlice[i]) + tracked[i] = primitives.ValidatorIndex(cliSlice[i]) } var chainService *blockchain.Service diff --git a/beacon-chain/operations/attestations/kv/aggregated.go b/beacon-chain/operations/attestations/kv/aggregated.go index d1522df0f2..6a4e25322a 100644 --- a/beacon-chain/operations/attestations/kv/aggregated.go +++ b/beacon-chain/operations/attestations/kv/aggregated.go @@ -5,7 +5,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" attaggregation "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/attestation/aggregation/attestations" log "github.com/sirupsen/logrus" @@ -29,7 +29,7 @@ func (c *AttCaches) AggregateUnaggregatedAttestations(ctx context.Context) error // AggregateUnaggregatedAttestationsBySlotIndex aggregates the unaggregated attestations and saves // newly aggregated attestations in the pool. Unaggregated attestations are filtered by slot and // committee index. -func (c *AttCaches) AggregateUnaggregatedAttestationsBySlotIndex(ctx context.Context, slot types.Slot, committeeIndex types.CommitteeIndex) error { +func (c *AttCaches) AggregateUnaggregatedAttestationsBySlotIndex(ctx context.Context, slot primitives.Slot, committeeIndex primitives.CommitteeIndex) error { ctx, span := trace.StartSpan(ctx, "operations.attestations.kv.AggregateUnaggregatedAttestationsBySlotIndex") defer span.End() unaggregatedAtts := c.UnaggregatedAttestationsBySlotIndex(ctx, slot, committeeIndex) @@ -167,7 +167,7 @@ func (c *AttCaches) AggregatedAttestations() []*ethpb.Attestation { // AggregatedAttestationsBySlotIndex returns the aggregated attestations in cache, // filtered by committee index and slot. -func (c *AttCaches) AggregatedAttestationsBySlotIndex(ctx context.Context, slot types.Slot, committeeIndex types.CommitteeIndex) []*ethpb.Attestation { +func (c *AttCaches) AggregatedAttestationsBySlotIndex(ctx context.Context, slot primitives.Slot, committeeIndex primitives.CommitteeIndex) []*ethpb.Attestation { ctx, span := trace.StartSpan(ctx, "operations.attestations.kv.AggregatedAttestationsBySlotIndex") defer span.End() diff --git a/beacon-chain/operations/attestations/kv/aggregated_test.go b/beacon-chain/operations/attestations/kv/aggregated_test.go index c622364841..5aab95c532 100644 --- a/beacon-chain/operations/attestations/kv/aggregated_test.go +++ b/beacon-chain/operations/attestations/kv/aggregated_test.go @@ -9,7 +9,7 @@ import ( "github.com/pkg/errors" fssz "github.com/prysmaticlabs/fastssz" "github.com/prysmaticlabs/go-bitfield" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -41,7 +41,7 @@ func TestKV_Aggregated_AggregateUnaggregatedAttestations(t *testing.T) { func TestKV_Aggregated_AggregateUnaggregatedAttestationsBySlotIndex(t *testing.T) { cache := NewAttCaches() - genData := func(slot types.Slot, committeeIndex types.CommitteeIndex) *ethpb.AttestationData { + genData := func(slot primitives.Slot, committeeIndex primitives.CommitteeIndex) *ethpb.AttestationData { return util.HydrateAttestationData(ðpb.AttestationData{ Slot: slot, CommitteeIndex: committeeIndex, diff --git a/beacon-chain/operations/attestations/kv/unaggregated.go b/beacon-chain/operations/attestations/kv/unaggregated.go index e328a05abf..8ab5feda7c 100644 --- a/beacon-chain/operations/attestations/kv/unaggregated.go +++ b/beacon-chain/operations/attestations/kv/unaggregated.go @@ -5,7 +5,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "go.opencensus.io/trace" ) @@ -70,7 +70,7 @@ func (c *AttCaches) UnaggregatedAttestations() ([]*ethpb.Attestation, error) { // UnaggregatedAttestationsBySlotIndex returns the unaggregated attestations in cache, // filtered by committee index and slot. -func (c *AttCaches) UnaggregatedAttestationsBySlotIndex(ctx context.Context, slot types.Slot, committeeIndex types.CommitteeIndex) []*ethpb.Attestation { +func (c *AttCaches) UnaggregatedAttestationsBySlotIndex(ctx context.Context, slot primitives.Slot, committeeIndex primitives.CommitteeIndex) []*ethpb.Attestation { ctx, span := trace.StartSpan(ctx, "operations.attestations.kv.UnaggregatedAttestationsBySlotIndex") defer span.End() diff --git a/beacon-chain/operations/attestations/mock/mock.go b/beacon-chain/operations/attestations/mock/mock.go index 8091a3193b..487ca589f2 100644 --- a/beacon-chain/operations/attestations/mock/mock.go +++ b/beacon-chain/operations/attestations/mock/mock.go @@ -3,7 +3,7 @@ package mock import ( "context" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -18,7 +18,7 @@ func (*PoolMock) AggregateUnaggregatedAttestations(_ context.Context) error { } // AggregateUnaggregatedAttestationsBySlotIndex -- -func (*PoolMock) AggregateUnaggregatedAttestationsBySlotIndex(_ context.Context, _ types.Slot, _ types.CommitteeIndex) error { +func (*PoolMock) AggregateUnaggregatedAttestationsBySlotIndex(_ context.Context, _ primitives.Slot, _ primitives.CommitteeIndex) error { panic("implement me") } @@ -39,7 +39,7 @@ func (m *PoolMock) AggregatedAttestations() []*ethpb.Attestation { } // AggregatedAttestationsBySlotIndex -- -func (*PoolMock) AggregatedAttestationsBySlotIndex(_ context.Context, _ types.Slot, _ types.CommitteeIndex) []*ethpb.Attestation { +func (*PoolMock) AggregatedAttestationsBySlotIndex(_ context.Context, _ primitives.Slot, _ primitives.CommitteeIndex) []*ethpb.Attestation { panic("implement me") } @@ -74,7 +74,7 @@ func (*PoolMock) UnaggregatedAttestations() ([]*ethpb.Attestation, error) { } // UnaggregatedAttestationsBySlotIndex -- -func (*PoolMock) UnaggregatedAttestationsBySlotIndex(_ context.Context, _ types.Slot, _ types.CommitteeIndex) []*ethpb.Attestation { +func (*PoolMock) UnaggregatedAttestationsBySlotIndex(_ context.Context, _ primitives.Slot, _ primitives.CommitteeIndex) []*ethpb.Attestation { panic("implement me") } diff --git a/beacon-chain/operations/attestations/pool.go b/beacon-chain/operations/attestations/pool.go index bac255a5d9..c639e2b263 100644 --- a/beacon-chain/operations/attestations/pool.go +++ b/beacon-chain/operations/attestations/pool.go @@ -4,7 +4,7 @@ import ( "context" "github.com/prysmaticlabs/prysm/v3/beacon-chain/operations/attestations/kv" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -15,11 +15,11 @@ import ( type Pool interface { // For Aggregated attestations AggregateUnaggregatedAttestations(ctx context.Context) error - AggregateUnaggregatedAttestationsBySlotIndex(ctx context.Context, slot types.Slot, committeeIndex types.CommitteeIndex) error + AggregateUnaggregatedAttestationsBySlotIndex(ctx context.Context, slot primitives.Slot, committeeIndex primitives.CommitteeIndex) error SaveAggregatedAttestation(att *ethpb.Attestation) error SaveAggregatedAttestations(atts []*ethpb.Attestation) error AggregatedAttestations() []*ethpb.Attestation - AggregatedAttestationsBySlotIndex(ctx context.Context, slot types.Slot, committeeIndex types.CommitteeIndex) []*ethpb.Attestation + AggregatedAttestationsBySlotIndex(ctx context.Context, slot primitives.Slot, committeeIndex primitives.CommitteeIndex) []*ethpb.Attestation DeleteAggregatedAttestation(att *ethpb.Attestation) error HasAggregatedAttestation(att *ethpb.Attestation) (bool, error) AggregatedAttestationCount() int @@ -27,7 +27,7 @@ type Pool interface { SaveUnaggregatedAttestation(att *ethpb.Attestation) error SaveUnaggregatedAttestations(atts []*ethpb.Attestation) error UnaggregatedAttestations() ([]*ethpb.Attestation, error) - UnaggregatedAttestationsBySlotIndex(ctx context.Context, slot types.Slot, committeeIndex types.CommitteeIndex) []*ethpb.Attestation + UnaggregatedAttestationsBySlotIndex(ctx context.Context, slot primitives.Slot, committeeIndex primitives.CommitteeIndex) []*ethpb.Attestation DeleteUnaggregatedAttestation(att *ethpb.Attestation) error DeleteSeenUnaggregatedAttestations() (int, error) UnaggregatedAttestationCount() int diff --git a/beacon-chain/operations/attestations/prune_expired.go b/beacon-chain/operations/attestations/prune_expired.go index f77239cc62..ec2767ab41 100644 --- a/beacon-chain/operations/attestations/prune_expired.go +++ b/beacon-chain/operations/attestations/prune_expired.go @@ -4,7 +4,7 @@ import ( "time" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" prysmTime "github.com/prysmaticlabs/prysm/v3/time" ) @@ -66,7 +66,7 @@ func (s *Service) pruneExpiredAtts() { // Return true if the input slot has been expired. // Expired is defined as one epoch behind than current time. -func (s *Service) expired(slot types.Slot) bool { +func (s *Service) expired(slot primitives.Slot) bool { expirationSlot := slot + params.BeaconConfig().SlotsPerEpoch expirationTime := s.genesisTime + uint64(expirationSlot.Mul(params.BeaconConfig().SecondsPerSlot)) currentTime := uint64(prysmTime.Now().Unix()) diff --git a/beacon-chain/operations/blstoexec/mock/mock.go b/beacon-chain/operations/blstoexec/mock/mock.go index 0a45c7c48a..85e82d995c 100644 --- a/beacon-chain/operations/blstoexec/mock/mock.go +++ b/beacon-chain/operations/blstoexec/mock/mock.go @@ -2,7 +2,7 @@ package mock import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -32,6 +32,6 @@ func (*PoolMock) MarkIncluded(_ *eth.SignedBLSToExecutionChange) { } // ValidatorExists -- -func (*PoolMock) ValidatorExists(_ types.ValidatorIndex) bool { +func (*PoolMock) ValidatorExists(_ primitives.ValidatorIndex) bool { panic("implement me") } diff --git a/beacon-chain/operations/blstoexec/pool.go b/beacon-chain/operations/blstoexec/pool.go index 75f723da98..be3a7df373 100644 --- a/beacon-chain/operations/blstoexec/pool.go +++ b/beacon-chain/operations/blstoexec/pool.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" doublylinkedlist "github.com/prysmaticlabs/prysm/v3/container/doubly-linked-list" "github.com/prysmaticlabs/prysm/v3/crypto/bls/blst" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -21,21 +21,21 @@ type PoolManager interface { BLSToExecChangesForInclusion(beaconState state.ReadOnlyBeaconState) ([]*ethpb.SignedBLSToExecutionChange, error) InsertBLSToExecChange(change *ethpb.SignedBLSToExecutionChange) MarkIncluded(change *ethpb.SignedBLSToExecutionChange) - ValidatorExists(idx types.ValidatorIndex) bool + ValidatorExists(idx primitives.ValidatorIndex) bool } // Pool is a concrete implementation of PoolManager. type Pool struct { lock sync.RWMutex pending doublylinkedlist.List[*ethpb.SignedBLSToExecutionChange] - m map[types.ValidatorIndex]*doublylinkedlist.Node[*ethpb.SignedBLSToExecutionChange] + m map[primitives.ValidatorIndex]*doublylinkedlist.Node[*ethpb.SignedBLSToExecutionChange] } // NewPool returns an initialized pool. func NewPool() *Pool { return &Pool{ pending: doublylinkedlist.List[*ethpb.SignedBLSToExecutionChange]{}, - m: make(map[types.ValidatorIndex]*doublylinkedlist.Node[*ethpb.SignedBLSToExecutionChange]), + m: make(map[primitives.ValidatorIndex]*doublylinkedlist.Node[*ethpb.SignedBLSToExecutionChange]), } } @@ -154,7 +154,7 @@ func (p *Pool) MarkIncluded(change *ethpb.SignedBLSToExecutionChange) { // ValidatorExists checks if the bls to execution change object exists // for that particular validator. -func (p *Pool) ValidatorExists(idx types.ValidatorIndex) bool { +func (p *Pool) ValidatorExists(idx primitives.ValidatorIndex) bool { p.lock.RLock() defer p.lock.RUnlock() diff --git a/beacon-chain/operations/blstoexec/pool_test.go b/beacon-chain/operations/blstoexec/pool_test.go index 8205b47594..e6d249df74 100644 --- a/beacon-chain/operations/blstoexec/pool_test.go +++ b/beacon-chain/operations/blstoexec/pool_test.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/bls/common" "github.com/prysmaticlabs/prysm/v3/crypto/hash" @@ -69,7 +69,7 @@ func TestBLSToExecChangesForInclusion(t *testing.T) { message := ð.BLSToExecutionChange{ ToExecutionAddress: executionAddress, - ValidatorIndex: types.ValidatorIndex(i), + ValidatorIndex: primitives.ValidatorIndex(i), FromBlsPubkey: pubkey, } @@ -130,7 +130,7 @@ func TestBLSToExecChangesForInclusion(t *testing.T) { // We want FIFO semantics, which means validator with index 16 shouldn't be returned assert.Equal(t, int(params.BeaconConfig().MaxBlsToExecutionChanges), len(changes)) for _, ch := range changes { - assert.NotEqual(t, types.ValidatorIndex(15), ch.Message.ValidatorIndex) + assert.NotEqual(t, primitives.ValidatorIndex(15), ch.Message.ValidatorIndex) } }) t.Run("One Bad change", func(t *testing.T) { @@ -143,7 +143,7 @@ func TestBLSToExecChangesForInclusion(t *testing.T) { changes, err := pool.BLSToExecChangesForInclusion(st) require.NoError(t, err) assert.Equal(t, int(params.BeaconConfig().MaxBlsToExecutionChanges), len(changes)) - assert.Equal(t, types.ValidatorIndex(30), changes[1].Message.ValidatorIndex) + assert.Equal(t, primitives.ValidatorIndex(30), changes[1].Message.ValidatorIndex) signedChanges[1].Message.FromBlsPubkey[5] = saveByte }) t.Run("One Bad Signature", func(t *testing.T) { @@ -155,7 +155,7 @@ func TestBLSToExecChangesForInclusion(t *testing.T) { changes, err := pool.BLSToExecChangesForInclusion(st) require.NoError(t, err) assert.Equal(t, int(params.BeaconConfig().MaxBlsToExecutionChanges)-1, len(changes)) - assert.Equal(t, types.ValidatorIndex(29), changes[1].Message.ValidatorIndex) + assert.Equal(t, primitives.ValidatorIndex(29), changes[1].Message.ValidatorIndex) }) } @@ -164,7 +164,7 @@ func TestInsertBLSToExecChange(t *testing.T) { pool := NewPool() change := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(0), + ValidatorIndex: primitives.ValidatorIndex(0), }, } pool.InsertBLSToExecChange(change) @@ -180,12 +180,12 @@ func TestInsertBLSToExecChange(t *testing.T) { pool := NewPool() old := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(0), + ValidatorIndex: primitives.ValidatorIndex(0), }, } change := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(1), + ValidatorIndex: primitives.ValidatorIndex(1), }, } pool.InsertBLSToExecChange(old) @@ -207,13 +207,13 @@ func TestInsertBLSToExecChange(t *testing.T) { pool := NewPool() old := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(0), + ValidatorIndex: primitives.ValidatorIndex(0), }, Signature: []byte("old"), } change := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(0), + ValidatorIndex: primitives.ValidatorIndex(0), }, Signature: []byte("change"), } @@ -234,7 +234,7 @@ func TestMarkIncluded(t *testing.T) { pool := NewPool() change := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(0), + ValidatorIndex: primitives.ValidatorIndex(0), }} pool.InsertBLSToExecChange(change) pool.MarkIncluded(change) @@ -246,15 +246,15 @@ func TestMarkIncluded(t *testing.T) { pool := NewPool() first := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(0), + ValidatorIndex: primitives.ValidatorIndex(0), }} second := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(1), + ValidatorIndex: primitives.ValidatorIndex(1), }} third := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(2), + ValidatorIndex: primitives.ValidatorIndex(2), }} pool.InsertBLSToExecChange(first) pool.InsertBLSToExecChange(second) @@ -268,15 +268,15 @@ func TestMarkIncluded(t *testing.T) { pool := NewPool() first := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(0), + ValidatorIndex: primitives.ValidatorIndex(0), }} second := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(1), + ValidatorIndex: primitives.ValidatorIndex(1), }} third := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(2), + ValidatorIndex: primitives.ValidatorIndex(2), }} pool.InsertBLSToExecChange(first) pool.InsertBLSToExecChange(second) @@ -290,15 +290,15 @@ func TestMarkIncluded(t *testing.T) { pool := NewPool() first := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(0), + ValidatorIndex: primitives.ValidatorIndex(0), }} second := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(1), + ValidatorIndex: primitives.ValidatorIndex(1), }} third := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(2), + ValidatorIndex: primitives.ValidatorIndex(2), }} pool.InsertBLSToExecChange(first) pool.InsertBLSToExecChange(second) @@ -312,15 +312,15 @@ func TestMarkIncluded(t *testing.T) { pool := NewPool() first := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(0), + ValidatorIndex: primitives.ValidatorIndex(0), }} second := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(1), + ValidatorIndex: primitives.ValidatorIndex(1), }} change := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(2), + ValidatorIndex: primitives.ValidatorIndex(2), }} pool.InsertBLSToExecChange(first) pool.InsertBLSToExecChange(second) @@ -344,7 +344,7 @@ func TestValidatorExists(t *testing.T) { pool := NewPool() change := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(0), + ValidatorIndex: primitives.ValidatorIndex(0), }} pool.InsertBLSToExecChange(change) assert.Equal(t, true, pool.ValidatorExists(0)) @@ -353,17 +353,17 @@ func TestValidatorExists(t *testing.T) { pool := NewPool() change := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(0), + ValidatorIndex: primitives.ValidatorIndex(0), }} pool.InsertBLSToExecChange(change) change = ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(10), + ValidatorIndex: primitives.ValidatorIndex(10), }} pool.InsertBLSToExecChange(change) change = ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(30), + ValidatorIndex: primitives.ValidatorIndex(30), }} pool.InsertBLSToExecChange(change) @@ -375,7 +375,7 @@ func TestValidatorExists(t *testing.T) { pool := NewPool() change := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(0), + ValidatorIndex: primitives.ValidatorIndex(0), }} pool.InsertBLSToExecChange(change) pool.MarkIncluded(change) @@ -385,17 +385,17 @@ func TestValidatorExists(t *testing.T) { pool := NewPool() firstChange := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(0), + ValidatorIndex: primitives.ValidatorIndex(0), }} pool.InsertBLSToExecChange(firstChange) secondChange := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(10), + ValidatorIndex: primitives.ValidatorIndex(10), }} pool.InsertBLSToExecChange(secondChange) thirdChange := ð.SignedBLSToExecutionChange{ Message: ð.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(30), + ValidatorIndex: primitives.ValidatorIndex(30), }} pool.InsertBLSToExecChange(thirdChange) diff --git a/beacon-chain/operations/slashings/service.go b/beacon-chain/operations/slashings/service.go index 61fc8f7657..c7a7d31b89 100644 --- a/beacon-chain/operations/slashings/service.go +++ b/beacon-chain/operations/slashings/service.go @@ -11,7 +11,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/trailofbits/go-mutexasserts" @@ -23,7 +23,7 @@ func NewPool() *Pool { return &Pool{ pendingProposerSlashing: make([]*ethpb.ProposerSlashing, 0), pendingAttesterSlashing: make([]*PendingAttesterSlashing, 0), - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), } } @@ -39,7 +39,7 @@ func (p *Pool) PendingAttesterSlashings(ctx context.Context, state state.ReadOnl // Update prom metric. numPendingAttesterSlashings.Set(float64(len(p.pendingAttesterSlashing))) - included := make(map[types.ValidatorIndex]bool) + included := make(map[primitives.ValidatorIndex]bool) // Allocate pending slice with a capacity of maxAttesterSlashings or len(p.pendingAttesterSlashing)) depending on the request. maxSlashings := params.BeaconConfig().MaxAttesterSlashings @@ -65,7 +65,7 @@ func (p *Pool) PendingAttesterSlashings(ctx context.Context, state state.ReadOnl attSlashing := slashing.attesterSlashing slashedVal := slice.IntersectionUint64(attSlashing.Attestation_1.AttestingIndices, attSlashing.Attestation_2.AttestingIndices) for _, idx := range slashedVal { - included[types.ValidatorIndex(idx)] = true + included[primitives.ValidatorIndex(idx)] = true } pending = append(pending, attSlashing) @@ -134,7 +134,7 @@ func (p *Pool) InsertAttesterSlashing( slashingReason := "" for _, val := range slashedVal { // Has this validator index been included recently? - ok, err := p.validatorSlashingPreconditionCheck(state, types.ValidatorIndex(val)) + ok, err := p.validatorSlashingPreconditionCheck(state, primitives.ValidatorIndex(val)) if err != nil { return err } @@ -159,7 +159,7 @@ func (p *Pool) InsertAttesterSlashing( pendingSlashing := &PendingAttesterSlashing{ attesterSlashing: slashing, - validatorToSlash: types.ValidatorIndex(val), + validatorToSlash: primitives.ValidatorIndex(val), } // Insert into pending list and sort again. p.pendingAttesterSlashing = append(p.pendingAttesterSlashing, pendingSlashing) @@ -240,7 +240,7 @@ func (p *Pool) MarkIncludedAttesterSlashing(as *ethpb.AttesterSlashing) { if i != len(p.pendingAttesterSlashing) && uint64(p.pendingAttesterSlashing[i].validatorToSlash) == val { p.pendingAttesterSlashing = append(p.pendingAttesterSlashing[:i], p.pendingAttesterSlashing[i+1:]...) } - p.included[types.ValidatorIndex(val)] = true + p.included[primitives.ValidatorIndex(val)] = true numAttesterSlashingsIncluded.Inc() } } @@ -267,7 +267,7 @@ func (p *Pool) MarkIncludedProposerSlashing(ps *ethpb.ProposerSlashing) { // Note: this method requires caller to hold the lock. func (p *Pool) validatorSlashingPreconditionCheck( state state.ReadOnlyBeaconState, - valIdx types.ValidatorIndex, + valIdx primitives.ValidatorIndex, ) (bool, error) { if !mutexasserts.RWMutexLocked(&p.lock) && !mutexasserts.RWMutexRLocked(&p.lock) { return false, errors.New("pool.validatorSlashingPreconditionCheck: caller must hold read/write lock") diff --git a/beacon-chain/operations/slashings/service_attester_test.go b/beacon-chain/operations/slashings/service_attester_test.go index 24d7c1f512..4d94de1f75 100644 --- a/beacon-chain/operations/slashings/service_attester_test.go +++ b/beacon-chain/operations/slashings/service_attester_test.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -17,7 +17,7 @@ import ( func validAttesterSlashingForValIdx(t *testing.T, beaconState state.BeaconState, privs []bls.SecretKey, valIdx ...uint64) *ethpb.AttesterSlashing { var slashings []*ethpb.AttesterSlashing for _, idx := range valIdx { - slashing, err := util.GenerateAttesterSlashingForValidator(beaconState, privs[idx], types.ValidatorIndex(idx)) + slashing, err := util.GenerateAttesterSlashingForValidator(beaconState, privs[idx], primitives.ValidatorIndex(idx)) require.NoError(t, err) slashings = append(slashings, slashing) } @@ -60,14 +60,14 @@ func attesterSlashingForValIdx(valIdx ...uint64) *ethpb.AttesterSlashing { func pendingSlashingForValIdx(valIdx ...uint64) *PendingAttesterSlashing { return &PendingAttesterSlashing{ attesterSlashing: attesterSlashingForValIdx(valIdx...), - validatorToSlash: types.ValidatorIndex(valIdx[0]), + validatorToSlash: primitives.ValidatorIndex(valIdx[0]), } } func TestPool_InsertAttesterSlashing(t *testing.T) { type fields struct { pending []*PendingAttesterSlashing - included map[types.ValidatorIndex]bool + included map[primitives.ValidatorIndex]bool wantErr []bool } type args struct { @@ -78,33 +78,33 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { pendingSlashings := make([]*PendingAttesterSlashing, 20) slashings := make([]*ethpb.AttesterSlashing, 20) for i := 0; i < len(pendingSlashings); i++ { - sl, err := util.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i)) + sl, err := util.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], primitives.ValidatorIndex(i)) require.NoError(t, err) pendingSlashings[i] = &PendingAttesterSlashing{ attesterSlashing: sl, - validatorToSlash: types.ValidatorIndex(i), + validatorToSlash: primitives.ValidatorIndex(i), } slashings[i] = sl } require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch)) // We mark the following validators with some preconditions. - exitedVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(2)) + exitedVal, err := beaconState.ValidatorAtIndex(primitives.ValidatorIndex(2)) require.NoError(t, err) exitedVal.WithdrawableEpoch = 0 - require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(2), exitedVal)) - futureWithdrawVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(4)) + require.NoError(t, beaconState.UpdateValidatorAtIndex(primitives.ValidatorIndex(2), exitedVal)) + futureWithdrawVal, err := beaconState.ValidatorAtIndex(primitives.ValidatorIndex(4)) require.NoError(t, err) futureWithdrawVal.WithdrawableEpoch = 17 - require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(4), futureWithdrawVal)) - slashedVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(5)) + require.NoError(t, beaconState.UpdateValidatorAtIndex(primitives.ValidatorIndex(4), futureWithdrawVal)) + slashedVal, err := beaconState.ValidatorAtIndex(primitives.ValidatorIndex(5)) require.NoError(t, err) slashedVal.Slashed = true - require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(5), slashedVal)) - slashedVal2, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(21)) + require.NoError(t, beaconState.UpdateValidatorAtIndex(primitives.ValidatorIndex(5), slashedVal)) + slashedVal2, err := beaconState.ValidatorAtIndex(primitives.ValidatorIndex(21)) require.NoError(t, err) slashedVal2.Slashed = true - require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(21), slashedVal2)) + require.NoError(t, beaconState.UpdateValidatorAtIndex(primitives.ValidatorIndex(21), slashedVal2)) aggSlashing1 := validAttesterSlashingForValIdx(t, beaconState, privKeys, 0, 1, 2) aggSlashing2 := validAttesterSlashingForValIdx(t, beaconState, privKeys, 5, 9, 13) @@ -122,7 +122,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Empty list", fields: fields{ pending: make([]*PendingAttesterSlashing, 0), - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), wantErr: []bool{false}, }, args: args{ @@ -139,7 +139,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Empty list two validators slashed", fields: fields{ pending: make([]*PendingAttesterSlashing, 0), - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), wantErr: []bool{false, false}, }, args: args{ @@ -153,7 +153,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { pending: []*PendingAttesterSlashing{ pendingSlashings[1], }, - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), wantErr: []bool{true}, }, args: args{ @@ -165,7 +165,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Slashing for already exit validator", fields: fields{ pending: []*PendingAttesterSlashing{}, - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), wantErr: []bool{true}, }, args: args{ @@ -177,7 +177,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Slashing for withdrawable validator", fields: fields{ pending: []*PendingAttesterSlashing{}, - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), wantErr: []bool{true}, }, args: args{ @@ -189,7 +189,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Slashing for slashed validator", fields: fields{ pending: []*PendingAttesterSlashing{}, - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), wantErr: []bool{false}, }, args: args{ @@ -201,7 +201,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Already included", fields: fields{ pending: []*PendingAttesterSlashing{}, - included: map[types.ValidatorIndex]bool{ + included: map[primitives.ValidatorIndex]bool{ 1: true, }, wantErr: []bool{true}, @@ -218,7 +218,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { pendingSlashings[0], pendingSlashings[2], }, - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), wantErr: []bool{false}, }, args: args{ @@ -230,7 +230,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) { name: "Doesn't reject partially slashed slashings", fields: fields{ pending: []*PendingAttesterSlashing{}, - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), wantErr: []bool{false, false, false, true}, }, args: args{ @@ -303,11 +303,11 @@ func TestPool_InsertAttesterSlashing_SigFailsVerify_ClearPool(t *testing.T) { pendingSlashings := make([]*PendingAttesterSlashing, 2) slashings := make([]*ethpb.AttesterSlashing, 2) for i := 0; i < 2; i++ { - sl, err := util.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i)) + sl, err := util.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], primitives.ValidatorIndex(i)) require.NoError(t, err) pendingSlashings[i] = &PendingAttesterSlashing{ attesterSlashing: sl, - validatorToSlash: types.ValidatorIndex(i), + validatorToSlash: primitives.ValidatorIndex(i), } slashings[i] = sl } @@ -328,7 +328,7 @@ func TestPool_InsertAttesterSlashing_SigFailsVerify_ClearPool(t *testing.T) { func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { type fields struct { pending []*PendingAttesterSlashing - included map[types.ValidatorIndex]bool + included map[primitives.ValidatorIndex]bool } type args struct { slashing *ethpb.AttesterSlashing @@ -348,7 +348,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { validatorToSlash: 1, }, }, - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), }, args: args{ slashing: attesterSlashingForValIdx(3), @@ -357,7 +357,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { pending: []*PendingAttesterSlashing{ pendingSlashingForValIdx(1), }, - included: map[types.ValidatorIndex]bool{ + included: map[primitives.ValidatorIndex]bool{ 3: true, }, }, @@ -370,7 +370,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { pendingSlashingForValIdx(2), pendingSlashingForValIdx(3), }, - included: map[types.ValidatorIndex]bool{ + included: map[primitives.ValidatorIndex]bool{ 0: true, }, }, @@ -382,7 +382,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { pendingSlashingForValIdx(1), pendingSlashingForValIdx(3), }, - included: map[types.ValidatorIndex]bool{ + included: map[primitives.ValidatorIndex]bool{ 0: true, 2: true, }, @@ -404,7 +404,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { pendingSlashingForValIdx(10), pendingSlashingForValIdx(11), }, - included: map[types.ValidatorIndex]bool{ + included: map[primitives.ValidatorIndex]bool{ 0: true, }, }, @@ -424,7 +424,7 @@ func TestPool_MarkIncludedAttesterSlashing(t *testing.T) { pendingSlashingForValIdx(10), pendingSlashingForValIdx(11), }, - included: map[types.ValidatorIndex]bool{ + included: map[primitives.ValidatorIndex]bool{ 0: true, 6: true, }, @@ -457,11 +457,11 @@ func TestPool_PendingAttesterSlashings(t *testing.T) { pendingSlashings := make([]*PendingAttesterSlashing, 20) slashings := make([]*ethpb.AttesterSlashing, 20) for i := 0; i < len(pendingSlashings); i++ { - sl, err := util.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i)) + sl, err := util.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], primitives.ValidatorIndex(i)) require.NoError(t, err) pendingSlashings[i] = &PendingAttesterSlashing{ attesterSlashing: sl, - validatorToSlash: types.ValidatorIndex(i), + validatorToSlash: primitives.ValidatorIndex(i), } slashings[i] = sl } @@ -532,15 +532,15 @@ func TestPool_PendingAttesterSlashings_Slashed(t *testing.T) { pendingSlashings2 := make([]*PendingAttesterSlashing, 20) slashings := make([]*ethpb.AttesterSlashing, 20) for i := 0; i < len(pendingSlashings); i++ { - sl, err := util.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i)) + sl, err := util.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], primitives.ValidatorIndex(i)) require.NoError(t, err) pendingSlashings[i] = &PendingAttesterSlashing{ attesterSlashing: sl, - validatorToSlash: types.ValidatorIndex(i), + validatorToSlash: primitives.ValidatorIndex(i), } pendingSlashings2[i] = &PendingAttesterSlashing{ attesterSlashing: sl, - validatorToSlash: types.ValidatorIndex(i), + validatorToSlash: primitives.ValidatorIndex(i), } slashings[i] = sl } @@ -590,11 +590,11 @@ func TestPool_PendingAttesterSlashings_NoDuplicates(t *testing.T) { pendingSlashings := make([]*PendingAttesterSlashing, 3) slashings := make([]*ethpb.AttesterSlashing, 3) for i := 0; i < 2; i++ { - sl, err := util.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i)) + sl, err := util.GenerateAttesterSlashingForValidator(beaconState, privKeys[i], primitives.ValidatorIndex(i)) require.NoError(t, err) pendingSlashings[i] = &PendingAttesterSlashing{ attesterSlashing: sl, - validatorToSlash: types.ValidatorIndex(i), + validatorToSlash: primitives.ValidatorIndex(i), } slashings[i] = sl } diff --git a/beacon-chain/operations/slashings/service_proposer_test.go b/beacon-chain/operations/slashings/service_proposer_test.go index 58c9d7ba96..35d4ff2afb 100644 --- a/beacon-chain/operations/slashings/service_proposer_test.go +++ b/beacon-chain/operations/slashings/service_proposer_test.go @@ -6,14 +6,14 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" ) -func proposerSlashingForValIdx(valIdx types.ValidatorIndex) *ethpb.ProposerSlashing { +func proposerSlashingForValIdx(valIdx primitives.ValidatorIndex) *ethpb.ProposerSlashing { return ðpb.ProposerSlashing{ Header_1: ðpb.SignedBeaconBlockHeader{ Header: ðpb.BeaconBlockHeader{ProposerIndex: valIdx}, @@ -28,7 +28,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { type fields struct { wantedErr string pending []*ethpb.ProposerSlashing - included map[types.ValidatorIndex]bool + included map[primitives.ValidatorIndex]bool } type args struct { slashings []*ethpb.ProposerSlashing @@ -37,7 +37,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { beaconState, privKeys := util.DeterministicGenesisState(t, 64) slashings := make([]*ethpb.ProposerSlashing, 20) for i := 0; i < len(slashings); i++ { - sl, err := util.GenerateProposerSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i)) + sl, err := util.GenerateProposerSlashingForValidator(beaconState, privKeys[i], primitives.ValidatorIndex(i)) require.NoError(t, err) slashings[i] = sl } @@ -45,18 +45,18 @@ func TestPool_InsertProposerSlashing(t *testing.T) { require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch)) // We mark the following validators with some preconditions. - exitedVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(2)) + exitedVal, err := beaconState.ValidatorAtIndex(primitives.ValidatorIndex(2)) require.NoError(t, err) exitedVal.WithdrawableEpoch = 0 - futureExitedVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(4)) + futureExitedVal, err := beaconState.ValidatorAtIndex(primitives.ValidatorIndex(4)) require.NoError(t, err) futureExitedVal.WithdrawableEpoch = 17 - slashedVal, err := beaconState.ValidatorAtIndex(types.ValidatorIndex(5)) + slashedVal, err := beaconState.ValidatorAtIndex(primitives.ValidatorIndex(5)) require.NoError(t, err) slashedVal.Slashed = true - require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(2), exitedVal)) - require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(4), futureExitedVal)) - require.NoError(t, beaconState.UpdateValidatorAtIndex(types.ValidatorIndex(5), slashedVal)) + require.NoError(t, beaconState.UpdateValidatorAtIndex(primitives.ValidatorIndex(2), exitedVal)) + require.NoError(t, beaconState.UpdateValidatorAtIndex(primitives.ValidatorIndex(4), futureExitedVal)) + require.NoError(t, beaconState.UpdateValidatorAtIndex(primitives.ValidatorIndex(5), slashedVal)) tests := []struct { name string @@ -68,7 +68,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { name: "Empty list", fields: fields{ pending: make([]*ethpb.ProposerSlashing, 0), - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), }, args: args{ slashings: slashings[0:1], @@ -79,7 +79,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { name: "Duplicate identical slashing", fields: fields{ pending: slashings[0:1], - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), wantedErr: "slashing object already exists in pending proposer slashings", }, args: args{ @@ -91,7 +91,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { name: "Slashing for exited validator", fields: fields{ pending: []*ethpb.ProposerSlashing{}, - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), wantedErr: "is not slashable", }, args: args{ @@ -103,7 +103,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { name: "Slashing for exiting validator", fields: fields{ pending: []*ethpb.ProposerSlashing{}, - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), }, args: args{ slashings: slashings[4:5], @@ -114,7 +114,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { name: "Slashing for slashed validator", fields: fields{ pending: []*ethpb.ProposerSlashing{}, - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), wantedErr: "not slashable", }, args: args{ @@ -126,7 +126,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { name: "Already included", fields: fields{ pending: []*ethpb.ProposerSlashing{}, - included: map[types.ValidatorIndex]bool{ + included: map[primitives.ValidatorIndex]bool{ 1: true, }, wantedErr: "cannot be slashed", @@ -143,7 +143,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) { slashings[0], slashings[2], }, - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), }, args: args{ slashings: slashings[1:2], @@ -187,7 +187,7 @@ func TestPool_InsertProposerSlashing_SigFailsVerify_ClearPool(t *testing.T) { beaconState, privKeys := util.DeterministicGenesisState(t, 64) slashings := make([]*ethpb.ProposerSlashing, 2) for i := 0; i < 2; i++ { - sl, err := util.GenerateProposerSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i)) + sl, err := util.GenerateProposerSlashingForValidator(beaconState, privKeys[i], primitives.ValidatorIndex(i)) require.NoError(t, err) slashings[i] = sl } @@ -208,7 +208,7 @@ func TestPool_InsertProposerSlashing_SigFailsVerify_ClearPool(t *testing.T) { func TestPool_MarkIncludedProposerSlashing(t *testing.T) { type fields struct { pending []*ethpb.ProposerSlashing - included map[types.ValidatorIndex]bool + included map[primitives.ValidatorIndex]bool } type args struct { slashing *ethpb.ProposerSlashing @@ -225,7 +225,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) { pending: []*ethpb.ProposerSlashing{ proposerSlashingForValIdx(1), }, - included: make(map[types.ValidatorIndex]bool), + included: make(map[primitives.ValidatorIndex]bool), }, args: args{ slashing: proposerSlashingForValIdx(3), @@ -234,7 +234,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) { pending: []*ethpb.ProposerSlashing{ proposerSlashingForValIdx(1), }, - included: map[types.ValidatorIndex]bool{ + included: map[primitives.ValidatorIndex]bool{ 3: true, }, }, @@ -247,7 +247,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) { proposerSlashingForValIdx(2), proposerSlashingForValIdx(3), }, - included: map[types.ValidatorIndex]bool{ + included: map[primitives.ValidatorIndex]bool{ 0: true, }, }, @@ -259,7 +259,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) { proposerSlashingForValIdx(1), proposerSlashingForValIdx(3), }, - included: map[types.ValidatorIndex]bool{ + included: map[primitives.ValidatorIndex]bool{ 0: true, 2: true, }, @@ -280,7 +280,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) { proposerSlashingForValIdx(9), proposerSlashingForValIdx(10), }, - included: map[types.ValidatorIndex]bool{ + included: map[primitives.ValidatorIndex]bool{ 0: true, }, }, @@ -299,7 +299,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) { proposerSlashingForValIdx(9), proposerSlashingForValIdx(10), }, - included: map[types.ValidatorIndex]bool{ + included: map[primitives.ValidatorIndex]bool{ 0: true, 7: true, }, @@ -330,7 +330,7 @@ func TestPool_PendingProposerSlashings(t *testing.T) { beaconState, privKeys := util.DeterministicGenesisState(t, 64) slashings := make([]*ethpb.ProposerSlashing, 20) for i := 0; i < len(slashings); i++ { - sl, err := util.GenerateProposerSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i)) + sl, err := util.GenerateProposerSlashingForValidator(beaconState, privKeys[i], primitives.ValidatorIndex(i)) require.NoError(t, err) slashings[i] = sl } @@ -397,7 +397,7 @@ func TestPool_PendingProposerSlashings_Slashed(t *testing.T) { slashings2 := make([]*ethpb.ProposerSlashing, 32) result := make([]*ethpb.ProposerSlashing, 32) for i := 0; i < len(slashings); i++ { - sl, err := util.GenerateProposerSlashingForValidator(beaconState, privKeys[i], types.ValidatorIndex(i)) + sl, err := util.GenerateProposerSlashingForValidator(beaconState, privKeys[i], primitives.ValidatorIndex(i)) require.NoError(t, err) slashings[i] = sl slashings2[i] = sl diff --git a/beacon-chain/operations/slashings/types.go b/beacon-chain/operations/slashings/types.go index 032943c846..3c0d89816d 100644 --- a/beacon-chain/operations/slashings/types.go +++ b/beacon-chain/operations/slashings/types.go @@ -5,7 +5,7 @@ import ( "sync" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -38,12 +38,12 @@ type Pool struct { lock sync.RWMutex pendingProposerSlashing []*ethpb.ProposerSlashing pendingAttesterSlashing []*PendingAttesterSlashing - included map[types.ValidatorIndex]bool + included map[primitives.ValidatorIndex]bool } // PendingAttesterSlashing represents an attester slashing in the operation pool. // Allows for easy binary searching of included validator indexes. type PendingAttesterSlashing struct { attesterSlashing *ethpb.AttesterSlashing - validatorToSlash types.ValidatorIndex + validatorToSlash primitives.ValidatorIndex } diff --git a/beacon-chain/operations/synccommittee/contribution.go b/beacon-chain/operations/synccommittee/contribution.go index 16f3ce6a37..74ec0b18c8 100644 --- a/beacon-chain/operations/synccommittee/contribution.go +++ b/beacon-chain/operations/synccommittee/contribution.go @@ -4,7 +4,7 @@ import ( "strconv" "github.com/pkg/errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/queue" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -68,7 +68,7 @@ func (s *Store) SaveSyncCommitteeContribution(cont *ethpb.SyncCommitteeContribut // SyncCommitteeContributions returns sync committee contributions by slot from the priority queue. // Upon retrieval, the contribution is removed from the queue. -func (s *Store) SyncCommitteeContributions(slot types.Slot) ([]*ethpb.SyncCommitteeContribution, error) { +func (s *Store) SyncCommitteeContributions(slot primitives.Slot) ([]*ethpb.SyncCommitteeContribution, error) { s.contributionLock.RLock() defer s.contributionLock.RUnlock() @@ -85,6 +85,6 @@ func (s *Store) SyncCommitteeContributions(slot types.Slot) ([]*ethpb.SyncCommit return contributions, nil } -func syncCommitteeKey(slot types.Slot) string { +func syncCommitteeKey(slot primitives.Slot) string { return strconv.FormatUint(uint64(slot), 10) } diff --git a/beacon-chain/operations/synccommittee/message.go b/beacon-chain/operations/synccommittee/message.go index 96c3facea5..6f468a0e41 100644 --- a/beacon-chain/operations/synccommittee/message.go +++ b/beacon-chain/operations/synccommittee/message.go @@ -2,7 +2,7 @@ package synccommittee import ( "github.com/pkg/errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/queue" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -61,7 +61,7 @@ func (s *Store) SaveSyncCommitteeMessage(msg *ethpb.SyncCommitteeMessage) error // SyncCommitteeMessages returns sync committee messages by slot from the priority queue. // Upon retrieval, the message is removed from the queue. -func (s *Store) SyncCommitteeMessages(slot types.Slot) ([]*ethpb.SyncCommitteeMessage, error) { +func (s *Store) SyncCommitteeMessages(slot primitives.Slot) ([]*ethpb.SyncCommitteeMessage, error) { s.messageLock.RLock() defer s.messageLock.RUnlock() diff --git a/beacon-chain/operations/synccommittee/pool.go b/beacon-chain/operations/synccommittee/pool.go index 3f265b9d0c..6681b121a3 100644 --- a/beacon-chain/operations/synccommittee/pool.go +++ b/beacon-chain/operations/synccommittee/pool.go @@ -1,7 +1,7 @@ package synccommittee import ( - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -14,11 +14,11 @@ var _ = Pool(&Store{}) type Pool interface { // Methods for Sync Contributions. SaveSyncCommitteeContribution(contr *ethpb.SyncCommitteeContribution) error - SyncCommitteeContributions(slot types.Slot) ([]*ethpb.SyncCommitteeContribution, error) + SyncCommitteeContributions(slot primitives.Slot) ([]*ethpb.SyncCommitteeContribution, error) // Methods for Sync Committee Messages. SaveSyncCommitteeMessage(sig *ethpb.SyncCommitteeMessage) error - SyncCommitteeMessages(slot types.Slot) ([]*ethpb.SyncCommitteeMessage, error) + SyncCommitteeMessages(slot primitives.Slot) ([]*ethpb.SyncCommitteeMessage, error) } // NewPool returns the sync committee store fulfilling the pool interface. diff --git a/beacon-chain/operations/voluntaryexits/mock/mock.go b/beacon-chain/operations/voluntaryexits/mock/mock.go index f1a98b97f9..a073fbb162 100644 --- a/beacon-chain/operations/voluntaryexits/mock/mock.go +++ b/beacon-chain/operations/voluntaryexits/mock/mock.go @@ -4,7 +4,7 @@ import ( "context" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -14,7 +14,7 @@ type PoolMock struct { } // PendingExits -- -func (m *PoolMock) PendingExits(_ state.ReadOnlyBeaconState, _ types.Slot, _ bool) []*eth.SignedVoluntaryExit { +func (m *PoolMock) PendingExits(_ state.ReadOnlyBeaconState, _ primitives.Slot, _ bool) []*eth.SignedVoluntaryExit { return m.Exits } diff --git a/beacon-chain/operations/voluntaryexits/service.go b/beacon-chain/operations/voluntaryexits/service.go index 916edfecd2..5b063d380a 100644 --- a/beacon-chain/operations/voluntaryexits/service.go +++ b/beacon-chain/operations/voluntaryexits/service.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" "go.opencensus.io/trace" @@ -16,7 +16,7 @@ import ( // PoolManager maintains pending and seen voluntary exits. // This pool is used by proposers to insert voluntary exits into new blocks. type PoolManager interface { - PendingExits(state state.ReadOnlyBeaconState, slot types.Slot, noLimit bool) []*ethpb.SignedVoluntaryExit + PendingExits(state state.ReadOnlyBeaconState, slot primitives.Slot, noLimit bool) []*ethpb.SignedVoluntaryExit InsertVoluntaryExit(ctx context.Context, state state.ReadOnlyBeaconState, exit *ethpb.SignedVoluntaryExit) MarkIncluded(exit *ethpb.SignedVoluntaryExit) } @@ -37,7 +37,7 @@ func NewPool() *Pool { // PendingExits returns exits that are ready for inclusion at the given slot. This method will not // return more than the block enforced MaxVoluntaryExits. -func (p *Pool) PendingExits(state state.ReadOnlyBeaconState, slot types.Slot, noLimit bool) []*ethpb.SignedVoluntaryExit { +func (p *Pool) PendingExits(state state.ReadOnlyBeaconState, slot primitives.Slot, noLimit bool) []*ethpb.SignedVoluntaryExit { p.lock.RLock() defer p.lock.RUnlock() @@ -114,7 +114,7 @@ func (p *Pool) MarkIncluded(exit *ethpb.SignedVoluntaryExit) { } // Binary search to check if the index exists in the list of pending exits. -func existsInList(pending []*ethpb.SignedVoluntaryExit, searchingFor types.ValidatorIndex) (bool, int) { +func existsInList(pending []*ethpb.SignedVoluntaryExit, searchingFor primitives.ValidatorIndex) (bool, int) { i := sort.Search(len(pending), func(j int) bool { return pending[j].Exit.ValidatorIndex >= searchingFor }) diff --git a/beacon-chain/operations/voluntaryexits/service_test.go b/beacon-chain/operations/voluntaryexits/service_test.go index 19acdb8632..a4e79a3346 100644 --- a/beacon-chain/operations/voluntaryexits/service_test.go +++ b/beacon-chain/operations/voluntaryexits/service_test.go @@ -7,7 +7,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" "google.golang.org/protobuf/proto" @@ -353,7 +353,7 @@ func TestPool_PendingExits(t *testing.T) { noLimit bool } type args struct { - slot types.Slot + slot primitives.Slot } tests := []struct { name string diff --git a/beacon-chain/p2p/fork_test.go b/beacon-chain/p2p/fork_test.go index 0676f9db59..4d28cf63e6 100644 --- a/beacon-chain/p2p/fork_test.go +++ b/beacon-chain/p2p/fork_test.go @@ -17,7 +17,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/network/forks" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -144,7 +144,7 @@ func TestStartDiscv5_SameForkDigests_DifferentNextForkData(t *testing.T) { ipAddr, pkey := createAddrAndPrivKey(t) c := params.BeaconConfig().Copy() - nextForkEpoch := types.Epoch(i) + nextForkEpoch := primitives.Epoch(i) c.ForkVersionSchedule[[4]byte{'A', 'B', 'C', 'D'}] = nextForkEpoch params.OverrideBeaconConfig(c) @@ -210,11 +210,11 @@ func TestStartDiscv5_SameForkDigests_DifferentNextForkData(t *testing.T) { func TestDiscv5_AddRetrieveForkEntryENR(t *testing.T) { params.SetupTestConfigCleanup(t) c := params.BeaconConfig().Copy() - c.ForkVersionSchedule = map[[4]byte]types.Epoch{ + c.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ bytesutil.ToBytes4(params.BeaconConfig().GenesisForkVersion): 0, {0, 0, 0, 1}: 1, } - nextForkEpoch := types.Epoch(1) + nextForkEpoch := primitives.Epoch(1) nextForkVersion := []byte{0, 0, 0, 1} params.OverrideBeaconConfig(c) @@ -265,7 +265,7 @@ func TestAddForkEntry_Genesis(t *testing.T) { require.NoError(t, err) bCfg := params.MainnetConfig().Copy() - bCfg.ForkVersionSchedule = map[[4]byte]types.Epoch{} + bCfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{} bCfg.ForkVersionSchedule[bytesutil.ToBytes4(params.BeaconConfig().GenesisForkVersion)] = bCfg.GenesisEpoch params.OverrideBeaconConfig(bCfg) diff --git a/beacon-chain/p2p/gossip_topic_mappings.go b/beacon-chain/p2p/gossip_topic_mappings.go index 113f0207b6..8d3d69b865 100644 --- a/beacon-chain/p2p/gossip_topic_mappings.go +++ b/beacon-chain/p2p/gossip_topic_mappings.go @@ -4,7 +4,7 @@ import ( "reflect" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "google.golang.org/protobuf/proto" ) @@ -25,7 +25,7 @@ var gossipTopicMappings = map[string]proto.Message{ // GossipTopicMappings is a function to return the assigned data type // versioned by epoch. -func GossipTopicMappings(topic string, epoch types.Epoch) proto.Message { +func GossipTopicMappings(topic string, epoch primitives.Epoch) proto.Message { if topic == BlockSubnetTopicFormat { if epoch >= params.BeaconConfig().CapellaForkEpoch { return ðpb.SignedBeaconBlockCapella{} diff --git a/beacon-chain/p2p/gossip_topic_mappings_test.go b/beacon-chain/p2p/gossip_topic_mappings_test.go index 9b8dd271c4..530271cd53 100644 --- a/beacon-chain/p2p/gossip_topic_mappings_test.go +++ b/beacon-chain/p2p/gossip_topic_mappings_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/config/params" - eth2types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -25,16 +25,16 @@ func TestMappingHasNoDuplicates(t *testing.T) { func TestGossipTopicMappings_CorrectBlockType(t *testing.T) { params.SetupTestConfigCleanup(t) bCfg := params.BeaconConfig().Copy() - altairForkEpoch := eth2types.Epoch(100) - BellatrixForkEpoch := eth2types.Epoch(200) - CapellaForkEpoch := eth2types.Epoch(300) + altairForkEpoch := primitives.Epoch(100) + BellatrixForkEpoch := primitives.Epoch(200) + CapellaForkEpoch := primitives.Epoch(300) bCfg.AltairForkEpoch = altairForkEpoch bCfg.BellatrixForkEpoch = BellatrixForkEpoch bCfg.CapellaForkEpoch = CapellaForkEpoch - bCfg.ForkVersionSchedule[bytesutil.ToBytes4(bCfg.AltairForkVersion)] = eth2types.Epoch(100) - bCfg.ForkVersionSchedule[bytesutil.ToBytes4(bCfg.BellatrixForkVersion)] = eth2types.Epoch(200) - bCfg.ForkVersionSchedule[bytesutil.ToBytes4(bCfg.CapellaForkVersion)] = eth2types.Epoch(300) + bCfg.ForkVersionSchedule[bytesutil.ToBytes4(bCfg.AltairForkVersion)] = primitives.Epoch(100) + bCfg.ForkVersionSchedule[bytesutil.ToBytes4(bCfg.BellatrixForkVersion)] = primitives.Epoch(200) + bCfg.ForkVersionSchedule[bytesutil.ToBytes4(bCfg.CapellaForkVersion)] = primitives.Epoch(300) params.OverrideBeaconConfig(bCfg) // Phase 0 diff --git a/beacon-chain/p2p/message_id.go b/beacon-chain/p2p/message_id.go index 0a92f00f56..f23e6990e4 100644 --- a/beacon-chain/p2p/message_id.go +++ b/beacon-chain/p2p/message_id.go @@ -4,7 +4,7 @@ import ( pubsubpb "github.com/libp2p/go-libp2p-pubsub/pb" "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/encoder" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/math" @@ -72,7 +72,7 @@ func MsgID(genesisValidatorsRoot []byte, pmsg *pubsubpb.Message) string { // + message.topic + snappy_decompress(message.data))[:20]. Otherwise, set message-id to the first 20 bytes of the SHA256 hash of the concatenation // of the following data: MESSAGE_DOMAIN_INVALID_SNAPPY, the length of the topic byte string (encoded as little-endian uint64), // the topic byte string, and the raw message data: i.e. SHA256(MESSAGE_DOMAIN_INVALID_SNAPPY + uint_to_bytes(uint64(len(message.topic))) + message.topic + message.data)[:20]. -func postAltairMsgID(pmsg *pubsubpb.Message, fEpoch types.Epoch) string { +func postAltairMsgID(pmsg *pubsubpb.Message, fEpoch primitives.Epoch) string { topic := *pmsg.Topic topicLen := len(topic) topicLenBytes := bytesutil.Uint64ToBytesLittleEndian(uint64(topicLen)) // topicLen cannot be negative diff --git a/beacon-chain/p2p/peers/scorers/peer_status.go b/beacon-chain/p2p/peers/scorers/peer_status.go index d1119c2baa..522385025a 100644 --- a/beacon-chain/p2p/peers/scorers/peer_status.go +++ b/beacon-chain/p2p/peers/scorers/peer_status.go @@ -7,7 +7,7 @@ import ( "github.com/libp2p/go-libp2p/core/peer" "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/peers/peerdata" p2ptypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time" ) @@ -19,8 +19,8 @@ var _ Scorer = (*PeerStatusScorer)(nil) type PeerStatusScorer struct { config *PeerStatusScorerConfig store *peerdata.Store - ourHeadSlot types.Slot - highestPeerHeadSlot types.Slot + ourHeadSlot primitives.Slot + highestPeerHeadSlot primitives.Slot } // PeerStatusScorerConfig holds configuration parameters for peer status scoring service. @@ -144,7 +144,7 @@ func (s *PeerStatusScorer) peerStatus(pid peer.ID) (*pb.Status, error) { } // SetHeadSlot updates known head slot. -func (s *PeerStatusScorer) SetHeadSlot(slot types.Slot) { +func (s *PeerStatusScorer) SetHeadSlot(slot primitives.Slot) { s.store.Lock() defer s.store.Unlock() s.ourHeadSlot = slot diff --git a/beacon-chain/p2p/peers/scorers/peer_status_test.go b/beacon-chain/p2p/peers/scorers/peer_status_test.go index 0cee08923a..2ab1d5b024 100644 --- a/beacon-chain/p2p/peers/scorers/peer_status_test.go +++ b/beacon-chain/p2p/peers/scorers/peer_status_test.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/peers/peerdata" "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/peers/scorers" p2ptypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -75,7 +75,7 @@ func TestScorers_PeerStatus_Score(t *testing.T) { { name: "existent peer partial score", update: func(scorer *scorers.PeerStatusScorer) { - headSlot := types.Slot(128) + headSlot := primitives.Slot(128) scorer.SetHeadSlot(headSlot) scorer.SetPeerStatus("peer1", &pb.Status{ HeadRoot: make([]byte, 32), @@ -95,7 +95,7 @@ func TestScorers_PeerStatus_Score(t *testing.T) { { name: "existent peer full score", update: func(scorer *scorers.PeerStatusScorer) { - headSlot := types.Slot(128) + headSlot := primitives.Slot(128) scorer.SetHeadSlot(headSlot) scorer.SetPeerStatus("peer1", &pb.Status{ HeadRoot: make([]byte, 32), @@ -191,7 +191,7 @@ func TestScorers_PeerStatus_PeerStatus(t *testing.T) { }, p2ptypes.ErrInvalidEpoch) status, err = peerStatuses.Scorers().PeerStatusScorer().PeerStatus("peer1") require.NoError(t, err) - assert.Equal(t, types.Slot(128), status.HeadSlot) + assert.Equal(t, primitives.Slot(128), status.HeadSlot) assert.Equal(t, nil, peerStatuses.Scorers().ValidationError("peer1")) assert.ErrorContains(t, p2ptypes.ErrInvalidEpoch.Error(), peerStatuses.Scorers().ValidationError("peer2")) assert.Equal(t, nil, peerStatuses.Scorers().ValidationError("peer3")) diff --git a/beacon-chain/p2p/peers/status.go b/beacon-chain/p2p/peers/status.go index a78e6a7b3a..eed767c330 100644 --- a/beacon-chain/p2p/peers/status.go +++ b/beacon-chain/p2p/peers/status.go @@ -38,7 +38,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/peers/scorers" "github.com/prysmaticlabs/prysm/v3/config/features" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/rand" pmath "github.com/prysmaticlabs/prysm/v3/math" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -645,11 +645,11 @@ func (p *Status) deprecatedPrune() { // 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 types.Epoch) (types.Epoch, []peer.ID) { +func (p *Status) BestFinalized(maxPeers int, ourFinalizedEpoch primitives.Epoch) (primitives.Epoch, []peer.ID) { connected := p.Connected() - finalizedEpochVotes := make(map[types.Epoch]uint64) - pidEpoch := make(map[peer.ID]types.Epoch, len(connected)) - pidHead := make(map[peer.ID]types.Slot, len(connected)) + finalizedEpochVotes := make(map[primitives.Epoch]uint64) + pidEpoch := make(map[peer.ID]primitives.Epoch, len(connected)) + pidHead := make(map[peer.ID]primitives.Slot, len(connected)) potentialPIDs := make([]peer.ID, 0, len(connected)) for _, pid := range connected { peerChainState, err := p.ChainState(pid) @@ -662,7 +662,7 @@ func (p *Status) BestFinalized(maxPeers int, ourFinalizedEpoch types.Epoch) (typ } // Select the target epoch, which is the epoch most peers agree upon. - var targetEpoch types.Epoch + var targetEpoch primitives.Epoch var mostVotes uint64 for epoch, count := range finalizedEpochVotes { if count > mostVotes || (count == mostVotes && epoch > targetEpoch) { @@ -697,11 +697,11 @@ func (p *Status) BestFinalized(maxPeers int, ourFinalizedEpoch types.Epoch) (typ // BestNonFinalized returns the highest known epoch, higher than ours, // and is shared by at least minPeers. -func (p *Status) BestNonFinalized(minPeers int, ourHeadEpoch types.Epoch) (types.Epoch, []peer.ID) { +func (p *Status) BestNonFinalized(minPeers int, ourHeadEpoch primitives.Epoch) (primitives.Epoch, []peer.ID) { connected := p.Connected() - epochVotes := make(map[types.Epoch]uint64) - pidEpoch := make(map[peer.ID]types.Epoch, len(connected)) - pidHead := make(map[peer.ID]types.Slot, len(connected)) + epochVotes := make(map[primitives.Epoch]uint64) + pidEpoch := make(map[peer.ID]primitives.Epoch, len(connected)) + pidHead := make(map[peer.ID]primitives.Slot, len(connected)) potentialPIDs := make([]peer.ID, 0, len(connected)) ourHeadSlot := params.BeaconConfig().SlotsPerEpoch.Mul(uint64(ourHeadEpoch)) @@ -717,7 +717,7 @@ func (p *Status) BestNonFinalized(minPeers int, ourHeadEpoch types.Epoch) (types } // Select the target epoch, which has enough peers' votes (>= minPeers). - var targetEpoch types.Epoch + var targetEpoch primitives.Epoch for epoch, votes := range epochVotes { if votes >= uint64(minPeers) && targetEpoch < epoch { targetEpoch = epoch @@ -878,10 +878,10 @@ func (p *Status) deprecatedPeersToPrune() []peer.ID { } // HighestEpoch returns the highest epoch reported epoch amongst peers. -func (p *Status) HighestEpoch() types.Epoch { +func (p *Status) HighestEpoch() primitives.Epoch { p.store.RLock() defer p.store.RUnlock() - var highestSlot types.Slot + var highestSlot primitives.Slot for _, peerData := range p.store.Peers() { if peerData != nil && peerData.ChainState != nil && peerData.ChainState.HeadSlot > highestSlot { highestSlot = peerData.ChainState.HeadSlot diff --git a/beacon-chain/p2p/peers/status_test.go b/beacon-chain/p2p/peers/status_test.go index 5e494833a5..7aa910fedb 100644 --- a/beacon-chain/p2p/peers/status_test.go +++ b/beacon-chain/p2p/peers/status_test.go @@ -17,7 +17,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/peers/scorers" "github.com/prysmaticlabs/prysm/v3/config/features" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/consensus-types/wrapper" ethpb "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -289,7 +289,7 @@ func TestPeerChainState(t *testing.T) { oldChainStartLastUpdated, err := p.ChainStateLastUpdated(id) require.NoError(t, err) - finalizedEpoch := types.Epoch(123) + finalizedEpoch := primitives.Epoch(123) p.SetChainState(id, &pb.Status{FinalizedEpoch: finalizedEpoch}) resChainState, err := p.ChainState(id) @@ -601,7 +601,7 @@ func TestTrimmedOrderedPeers(t *testing.T) { }, }) - expectedTarget := types.Epoch(2) + expectedTarget := primitives.Epoch(2) maxPeers := 3 var mockroot2 [32]byte var mockroot3 [32]byte @@ -757,15 +757,15 @@ func TestPrunePeers(t *testing.T) { func TestStatus_BestPeer(t *testing.T) { type peerConfig struct { - headSlot types.Slot - finalizedEpoch types.Epoch + headSlot primitives.Slot + finalizedEpoch primitives.Epoch } tests := []struct { name string peers []*peerConfig limitPeers int - ourFinalizedEpoch types.Epoch - targetEpoch types.Epoch + ourFinalizedEpoch primitives.Epoch + targetEpoch primitives.Epoch // targetEpochSupport denotes how many peers support returned epoch. targetEpochSupport int }{ @@ -943,7 +943,7 @@ func TestStatus_BestNonFinalized(t *testing.T) { }, }) - peerSlots := []types.Slot{32, 32, 32, 32, 235, 233, 258, 268, 270} + peerSlots := []primitives.Slot{32, 32, 32, 32, 235, 233, 258, 268, 270} for i, headSlot := range peerSlots { p.Add(new(enr.Record), peer.ID(rune(i)), nil, network.DirOutbound) p.SetConnectionState(peer.ID(rune(i)), peers.PeerConnected) @@ -952,7 +952,7 @@ func TestStatus_BestNonFinalized(t *testing.T) { }) } - expectedEpoch := types.Epoch(8) + expectedEpoch := primitives.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") @@ -984,7 +984,7 @@ func TestStatus_CurrentEpoch(t *testing.T) { HeadSlot: params.BeaconConfig().SlotsPerEpoch * 4, }) - assert.Equal(t, types.Epoch(5), p.HighestEpoch(), "Expected current epoch to be 5") + assert.Equal(t, primitives.Epoch(5), p.HighestEpoch(), "Expected current epoch to be 5") } func TestInbound(t *testing.T) { diff --git a/beacon-chain/p2p/rpc_topic_mappings.go b/beacon-chain/p2p/rpc_topic_mappings.go index 020a8c2c8d..15849b5289 100644 --- a/beacon-chain/p2p/rpc_topic_mappings.go +++ b/beacon-chain/p2p/rpc_topic_mappings.go @@ -6,7 +6,7 @@ import ( "github.com/pkg/errors" p2ptypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -71,7 +71,7 @@ var RPCTopicMappings = map[string]interface{}{ // RPC Status Message RPCStatusTopicV1: new(pb.Status), // RPC Goodbye Message - RPCGoodByeTopicV1: new(types.SSZUint64), + RPCGoodByeTopicV1: new(primitives.SSZUint64), // RPC Block By Range Message RPCBlocksByRangeTopicV1: new(pb.BeaconBlocksByRangeRequest), RPCBlocksByRangeTopicV2: new(pb.BeaconBlocksByRangeRequest), @@ -79,7 +79,7 @@ var RPCTopicMappings = map[string]interface{}{ RPCBlocksByRootTopicV1: new(p2ptypes.BeaconBlockByRootsReq), RPCBlocksByRootTopicV2: new(p2ptypes.BeaconBlockByRootsReq), // RPC Ping Message - RPCPingTopicV1: new(types.SSZUint64), + RPCPingTopicV1: new(primitives.SSZUint64), // RPC Metadata Message RPCMetaDataTopicV1: new(interface{}), RPCMetaDataTopicV2: new(interface{}), @@ -224,7 +224,7 @@ func (r RPCTopic) Version() string { // TopicFromMessage constructs the rpc topic from the provided message // type and epoch. -func TopicFromMessage(msg string, epoch types.Epoch) (string, error) { +func TopicFromMessage(msg string, epoch primitives.Epoch) (string, error) { if !messageMapping[msg] { return "", errors.Errorf("%s: %s", invalidRPCMessageType, msg) } diff --git a/beacon-chain/p2p/rpc_topic_mappings_test.go b/beacon-chain/p2p/rpc_topic_mappings_test.go index b96be543be..ef15d370fe 100644 --- a/beacon-chain/p2p/rpc_topic_mappings_test.go +++ b/beacon-chain/p2p/rpc_topic_mappings_test.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/v3/config/params" - eth2types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -84,9 +84,9 @@ func TestTopicDeconstructor(t *testing.T) { func TestTopicFromMessage_CorrectType(t *testing.T) { params.SetupTestConfigCleanup(t) bCfg := params.BeaconConfig().Copy() - forkEpoch := eth2types.Epoch(100) + forkEpoch := primitives.Epoch(100) bCfg.AltairForkEpoch = forkEpoch - bCfg.ForkVersionSchedule[bytesutil.ToBytes4(bCfg.AltairForkVersion)] = eth2types.Epoch(100) + bCfg.ForkVersionSchedule[bytesutil.ToBytes4(bCfg.AltairForkVersion)] = primitives.Epoch(100) params.OverrideBeaconConfig(bCfg) // Garbage Message diff --git a/beacon-chain/p2p/types/rpc_goodbye_codes.go b/beacon-chain/p2p/types/rpc_goodbye_codes.go index 602af491ae..9ca25a0a76 100644 --- a/beacon-chain/p2p/types/rpc_goodbye_codes.go +++ b/beacon-chain/p2p/types/rpc_goodbye_codes.go @@ -1,11 +1,11 @@ package types import ( - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // RPCGoodbyeCode represents goodbye code, used in sync package. -type RPCGoodbyeCode = types.SSZUint64 +type RPCGoodbyeCode = primitives.SSZUint64 const ( // Spec defined codes. diff --git a/beacon-chain/p2p/types/types_test.go b/beacon-chain/p2p/types/types_test.go index 2429c9b652..13037f971a 100644 --- a/beacon-chain/p2p/types/types_test.go +++ b/beacon-chain/p2p/types/types_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -109,13 +109,13 @@ func TestSSZBytes_HashTreeRoot(t *testing.T) { } func TestGoodbyeCodes(t *testing.T) { - assert.Equal(t, types.SSZUint64(1), GoodbyeCodeClientShutdown) - assert.Equal(t, types.SSZUint64(2), GoodbyeCodeWrongNetwork) - assert.Equal(t, types.SSZUint64(3), GoodbyeCodeGenericError) - assert.Equal(t, types.SSZUint64(128), GoodbyeCodeUnableToVerifyNetwork) - assert.Equal(t, types.SSZUint64(129), GoodbyeCodeTooManyPeers) - assert.Equal(t, types.SSZUint64(250), GoodbyeCodeBadScore) - assert.Equal(t, types.SSZUint64(251), GoodbyeCodeBanned) + assert.Equal(t, primitives.SSZUint64(1), GoodbyeCodeClientShutdown) + assert.Equal(t, primitives.SSZUint64(2), GoodbyeCodeWrongNetwork) + assert.Equal(t, primitives.SSZUint64(3), GoodbyeCodeGenericError) + assert.Equal(t, primitives.SSZUint64(128), GoodbyeCodeUnableToVerifyNetwork) + assert.Equal(t, primitives.SSZUint64(129), GoodbyeCodeTooManyPeers) + assert.Equal(t, primitives.SSZUint64(250), GoodbyeCodeBadScore) + assert.Equal(t, primitives.SSZUint64(251), GoodbyeCodeBanned) } diff --git a/beacon-chain/rpc/apimiddleware/custom_hooks.go b/beacon-chain/rpc/apimiddleware/custom_hooks.go index 383abbac45..032b61b92e 100644 --- a/beacon-chain/rpc/apimiddleware/custom_hooks.go +++ b/beacon-chain/rpc/apimiddleware/custom_hooks.go @@ -12,7 +12,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/api/gateway/apimiddleware" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpbv2 "github.com/prysmaticlabs/prysm/v3/proto/eth/v2" "github.com/prysmaticlabs/prysm/v3/time/slots" ) @@ -296,7 +296,7 @@ func setInitialPublishBlockPostRequest(endpoint *apimiddleware.Endpoint, if err != nil { return false, apimiddleware.InternalServerErrorWithMessage(err, "slot is not an unsigned integer") } - currentEpoch := slots.ToEpoch(types.Slot(slot)) + currentEpoch := slots.ToEpoch(primitives.Slot(slot)) if currentEpoch < params.BeaconConfig().AltairForkEpoch { endpoint.PostRequest = &SignedBeaconBlockContainerJson{} } else if currentEpoch < params.BeaconConfig().BellatrixForkEpoch { @@ -380,7 +380,7 @@ func setInitialPublishBlindedBlockPostRequest(endpoint *apimiddleware.Endpoint, if err != nil { return false, apimiddleware.InternalServerErrorWithMessage(err, "slot is not an unsigned integer") } - currentEpoch := slots.ToEpoch(types.Slot(slot)) + currentEpoch := slots.ToEpoch(primitives.Slot(slot)) if currentEpoch < params.BeaconConfig().AltairForkEpoch { endpoint.PostRequest = &SignedBeaconBlockContainerJson{} } else if currentEpoch < params.BeaconConfig().BellatrixForkEpoch { diff --git a/beacon-chain/rpc/eth/beacon/blocks.go b/beacon-chain/rpc/eth/beacon/blocks.go index f208a80401..310dc93502 100644 --- a/beacon-chain/rpc/eth/beacon/blocks.go +++ b/beacon-chain/rpc/eth/beacon/blocks.go @@ -16,7 +16,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/encoding/ssz/detect" "github.com/prysmaticlabs/prysm/v3/network/forks" @@ -484,7 +484,7 @@ func (bs *Server) GetBlockRoot(ctx context.Context, req *ethpbv1.BlockRequest) ( if err != nil { return nil, status.Errorf(codes.InvalidArgument, "Could not parse block ID: %v", err) } - hasRoots, roots, err := bs.BeaconDB.BlockRootsBySlot(ctx, types.Slot(slot)) + hasRoots, roots, err := bs.BeaconDB.BlockRootsBySlot(ctx, primitives.Slot(slot)) if err != nil { return nil, status.Errorf(codes.Internal, "Could not retrieve blocks for slot %d: %v", slot, err) } @@ -589,11 +589,11 @@ func (bs *Server) blockFromBlockID(ctx context.Context, blockId []byte) (interfa e := newBlockIdParseError(err) return nil, &e } - blks, err := bs.BeaconDB.BlocksBySlot(ctx, types.Slot(slot)) + blks, err := bs.BeaconDB.BlocksBySlot(ctx, primitives.Slot(slot)) if err != nil { return nil, errors.Wrapf(err, "could not retrieve blocks for slot %d", slot) } - _, roots, err := bs.BeaconDB.BlockRootsBySlot(ctx, types.Slot(slot)) + _, roots, err := bs.BeaconDB.BlockRootsBySlot(ctx, primitives.Slot(slot)) if err != nil { return nil, errors.Wrapf(err, "could not retrieve block roots for slot %d", slot) } diff --git a/beacon-chain/rpc/eth/beacon/blocks_test.go b/beacon-chain/rpc/eth/beacon/blocks_test.go index d0f16139bb..7f545517d3 100644 --- a/beacon-chain/rpc/eth/beacon/blocks_test.go +++ b/beacon-chain/rpc/eth/beacon/blocks_test.go @@ -15,7 +15,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpbv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" @@ -37,10 +37,10 @@ func fillDBTestBlocks(ctx context.Context, t *testing.T, beaconDB db.Database) ( util.SaveBlock(t, ctx, beaconDB, genBlk) require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - count := types.Slot(100) + count := primitives.Slot(100) blks := make([]interfaces.SignedBeaconBlock, count) blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { b := util.NewBeaconBlock() b.Block.Slot = i b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) @@ -73,10 +73,10 @@ func fillDBTestBlocksAltair(ctx context.Context, t *testing.T, beaconDB db.Datab util.SaveBlock(t, ctx, beaconDB, genBlk) require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - count := types.Slot(100) + count := primitives.Slot(100) blks := make([]interfaces.SignedBeaconBlock, count) blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { b := util.NewBeaconBlockAltair() b.Block.Slot = i b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) @@ -114,10 +114,10 @@ func fillDBTestBlocksBellatrix(ctx context.Context, t *testing.T, beaconDB db.Da util.SaveBlock(t, ctx, beaconDB, genBlk) require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - count := types.Slot(100) + count := primitives.Slot(100) blks := make([]interfaces.SignedBeaconBlock, count) blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { b := util.NewBeaconBlockBellatrix() b.Block.Slot = i b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) @@ -171,10 +171,10 @@ func fillDBTestBlocksCapella(ctx context.Context, t *testing.T, beaconDB db.Data util.SaveBlock(t, ctx, beaconDB, genBlk) require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - count := types.Slot(100) + count := primitives.Slot(100) blks := make([]interfaces.SignedBeaconBlock, count) blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { b := util.NewBeaconBlockCapella() b.Block.Slot = i b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) @@ -242,10 +242,10 @@ func fillDBTestBlocksBellatrixBlinded(ctx context.Context, t *testing.T, beaconD util.SaveBlock(t, ctx, beaconDB, genBlk) require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - count := types.Slot(100) + count := primitives.Slot(100) blks := make([]interfaces.SignedBeaconBlock, count) blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { b := util.NewBlindedBeaconBlockBellatrix() b.Block.Slot = i b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) @@ -299,10 +299,10 @@ func fillDBTestBlocksCapellaBlinded(ctx context.Context, t *testing.T, beaconDB util.SaveBlock(t, ctx, beaconDB, genBlk) require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - count := types.Slot(100) + count := primitives.Slot(100) blks := make([]interfaces.SignedBeaconBlock, count) blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { b := util.NewBlindedBeaconBlockCapella() b.Block.Slot = i b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) @@ -561,14 +561,14 @@ func TestServer_ListBlockHeaders(t *testing.T) { tests := []struct { name string - slot types.Slot + slot primitives.Slot parentRoot []byte want []*ethpbalpha.SignedBeaconBlock wantErr bool }{ { name: "slot", - slot: types.Slot(30), + slot: primitives.Slot(30), want: []*ethpbalpha.SignedBeaconBlock{ blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, b1, @@ -641,7 +641,7 @@ func TestServer_ListBlockHeaders(t *testing.T) { OptimisticModeFetcher: mockChainFetcher, FinalizationFetcher: mockChainFetcher, } - slot := types.Slot(30) + slot := primitives.Slot(30) headers, err := bs.ListBlockHeaders(ctx, ðpbv1.BlockHeadersRequest{ Slot: &slot, }) @@ -680,7 +680,7 @@ func TestServer_ListBlockHeaders(t *testing.T) { } t.Run("true", func(t *testing.T) { - slot := types.Slot(999) + slot := primitives.Slot(999) headers, err := bs.ListBlockHeaders(ctx, ðpbv1.BlockHeadersRequest{ Slot: &slot, }) @@ -688,7 +688,7 @@ func TestServer_ListBlockHeaders(t *testing.T) { assert.Equal(t, true, headers.Finalized) }) t.Run("false", func(t *testing.T) { - slot := types.Slot(1000) + slot := primitives.Slot(1000) headers, err := bs.ListBlockHeaders(ctx, ðpbv1.BlockHeadersRequest{ Slot: &slot, }) diff --git a/beacon-chain/rpc/eth/beacon/config_test.go b/beacon-chain/rpc/eth/beacon/config_test.go index 2d88c69842..a00b76d2a6 100644 --- a/beacon-chain/rpc/eth/beacon/config_test.go +++ b/beacon-chain/rpc/eth/beacon/config_test.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/network/forks" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -383,15 +383,15 @@ func TestGetDepositContract(t *testing.T) { func TestForkSchedule_Ok(t *testing.T) { genesisForkVersion := []byte("Genesis") - firstForkVersion, firstForkEpoch := []byte("Firs"), types.Epoch(100) - secondForkVersion, secondForkEpoch := []byte("Seco"), types.Epoch(200) - thirdForkVersion, thirdForkEpoch := []byte("Thir"), types.Epoch(300) + firstForkVersion, firstForkEpoch := []byte("Firs"), primitives.Epoch(100) + secondForkVersion, secondForkEpoch := []byte("Seco"), primitives.Epoch(200) + thirdForkVersion, thirdForkEpoch := []byte("Thir"), primitives.Epoch(300) params.SetupTestConfigCleanup(t) config := params.BeaconConfig().Copy() config.GenesisForkVersion = genesisForkVersion // Create fork schedule adding keys in non-sorted order. - schedule := make(map[[4]byte]types.Epoch, 3) + schedule := make(map[[4]byte]primitives.Epoch, 3) schedule[bytesutil.ToBytes4(secondForkVersion)] = secondForkEpoch schedule[bytesutil.ToBytes4(firstForkVersion)] = firstForkEpoch schedule[bytesutil.ToBytes4(thirdForkVersion)] = thirdForkEpoch diff --git a/beacon-chain/rpc/eth/beacon/pool_test.go b/beacon-chain/rpc/eth/beacon/pool_test.go index f60f239d22..522e8a0f51 100644 --- a/beacon-chain/rpc/eth/beacon/pool_test.go +++ b/beacon-chain/rpc/eth/beacon/pool_test.go @@ -21,7 +21,7 @@ import ( p2pMock "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/testing" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - eth2types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/bls/common" "github.com/prysmaticlabs/prysm/v3/crypto/hash" @@ -159,7 +159,7 @@ func TestListPoolAttestations(t *testing.T) { }) t.Run("slot request", func(t *testing.T) { - slot := eth2types.Slot(2) + slot := primitives.Slot(2) req := ðpbv1.AttestationsPoolRequest{ Slot: &slot, } @@ -172,7 +172,7 @@ func TestListPoolAttestations(t *testing.T) { }) t.Run("index request", func(t *testing.T) { - index := eth2types.CommitteeIndex(4) + index := primitives.CommitteeIndex(4) req := ðpbv1.AttestationsPoolRequest{ CommitteeIndex: &index, } @@ -185,8 +185,8 @@ func TestListPoolAttestations(t *testing.T) { }) t.Run("both slot + index request", func(t *testing.T) { - slot := eth2types.Slot(2) - index := eth2types.CommitteeIndex(4) + slot := primitives.Slot(2) + index := primitives.CommitteeIndex(4) req := ðpbv1.AttestationsPoolRequest{ Slot: &slot, CommitteeIndex: &index, @@ -574,7 +574,7 @@ func TestSubmitProposerSlashing_Ok(t *testing.T) { require.NoError(t, err) validator := ðpbv1alpha1.Validator{ PublicKey: keys[0].PublicKey().Marshal(), - WithdrawableEpoch: eth2types.Epoch(1), + WithdrawableEpoch: primitives.Epoch(1), } bs, err := util.NewBeaconState(func(state *ethpbv1alpha1.BeaconState) error { state.Validators = []*ethpbv1alpha1.Validator{validator} @@ -1230,7 +1230,7 @@ func TestSubmitSignedBLSToExecutionChanges_Ok(t *testing.T) { message := ðpbv2.BLSToExecutionChange{ ToExecutionAddress: executionAddress, - ValidatorIndex: eth2types.ValidatorIndex(i), + ValidatorIndex: primitives.ValidatorIndex(i), FromBlsPubkey: pubkey, } @@ -1322,7 +1322,7 @@ func TestSubmitSignedBLSToExecutionChanges_Bellatrix(t *testing.T) { message := ðpbv2.BLSToExecutionChange{ ToExecutionAddress: executionAddress, - ValidatorIndex: eth2types.ValidatorIndex(i), + ValidatorIndex: primitives.ValidatorIndex(i), FromBlsPubkey: pubkey, } @@ -1430,7 +1430,7 @@ func TestSubmitSignedBLSToExecutionChanges_Failures(t *testing.T) { message := ðpbv2.BLSToExecutionChange{ ToExecutionAddress: executionAddress, - ValidatorIndex: eth2types.ValidatorIndex(i), + ValidatorIndex: primitives.ValidatorIndex(i), FromBlsPubkey: pubkey, } diff --git a/beacon-chain/rpc/eth/beacon/state.go b/beacon-chain/rpc/eth/beacon/state.go index e0dbbc9a3f..df06f40cd7 100644 --- a/beacon-chain/rpc/eth/beacon/state.go +++ b/beacon-chain/rpc/eth/beacon/state.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/statefetcher" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" eth2 "github.com/prysmaticlabs/prysm/v3/proto/eth/v2" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -22,7 +22,7 @@ import ( ) type stateRequest struct { - epoch *types.Epoch + epoch *primitives.Epoch stateId []byte } diff --git a/beacon-chain/rpc/eth/beacon/state_test.go b/beacon-chain/rpc/eth/beacon/state_test.go index 8e36a51d90..091a1a0eb0 100644 --- a/beacon-chain/rpc/eth/beacon/state_test.go +++ b/beacon-chain/rpc/eth/beacon/state_test.go @@ -9,7 +9,7 @@ import ( dbTest "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/testutil" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" eth "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" eth2 "github.com/prysmaticlabs/prysm/v3/proto/eth/v2" @@ -261,7 +261,7 @@ func TestGetFinalityCheckpoints(t *testing.T) { func TestGetRandao(t *testing.T) { mixCurrent := bytesutil.PadTo([]byte("current"), 32) mixOld := bytesutil.PadTo([]byte("old"), 32) - epochCurrent := types.Epoch(100000) + epochCurrent := primitives.Epoch(100000) epochOld := 100000 - params.BeaconConfig().EpochsPerHistoricalVector + 1 ctx := context.Background() @@ -272,7 +272,7 @@ func TestGetRandao(t *testing.T) { require.NoError(t, st.UpdateRandaoMixesAtIndex(uint64(epochCurrent%params.BeaconConfig().EpochsPerHistoricalVector), mixCurrent)) require.NoError(t, st.UpdateRandaoMixesAtIndex(uint64(epochOld%params.BeaconConfig().EpochsPerHistoricalVector), mixOld)) - headEpoch := types.Epoch(1) + headEpoch := primitives.Epoch(1) headSt, err := util.NewBeaconState() require.NoError(t, err) require.NoError(t, headSt.SetSlot(params.BeaconConfig().SlotsPerEpoch)) @@ -314,12 +314,12 @@ func TestGetRandao(t *testing.T) { assert.DeepEqual(t, headRandao, resp.Data.Randao) }) t.Run("epoch too old", func(t *testing.T) { - epochTooOld := types.Epoch(100000 - st.RandaoMixesLength()) + epochTooOld := primitives.Epoch(100000 - st.RandaoMixesLength()) _, err := server.GetRandao(ctx, ð2.RandaoRequest{StateId: make([]byte, 0), Epoch: &epochTooOld}) require.ErrorContains(t, "Epoch is out of range for the randao mixes of the state", err) }) t.Run("epoch in the future", func(t *testing.T) { - futureEpoch := types.Epoch(100000 + 1) + futureEpoch := primitives.Epoch(100000 + 1) _, err := server.GetRandao(ctx, ð2.RandaoRequest{StateId: make([]byte, 0), Epoch: &futureEpoch}) require.ErrorContains(t, "Epoch is out of range for the randao mixes of the state", err) }) diff --git a/beacon-chain/rpc/eth/beacon/sync_committee.go b/beacon-chain/rpc/eth/beacon/sync_committee.go index b82e9032a7..d812cd5cf0 100644 --- a/beacon-chain/rpc/eth/beacon/sync_committee.go +++ b/beacon-chain/rpc/eth/beacon/sync_committee.go @@ -11,7 +11,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/helpers" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpbv2 "github.com/prysmaticlabs/prysm/v3/proto/eth/v2" ethpbalpha "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -71,7 +71,7 @@ func (bs *Server) ListSyncCommittees(ctx context.Context, req *ethpbv2.StateSync return nil, status.Errorf(codes.Internal, "Could not fetch beacon state using request: %v", err) } - var committeeIndices []types.ValidatorIndex + var committeeIndices []primitives.ValidatorIndex var committee *ethpbalpha.SyncCommittee if requestNextCommittee { // Get the next sync committee and sync committee indices from the state. @@ -105,8 +105,8 @@ func (bs *Server) ListSyncCommittees(ctx context.Context, req *ethpbv2.StateSync }, nil } -func committeeIndicesFromState(st state.BeaconState, committee *ethpbalpha.SyncCommittee) ([]types.ValidatorIndex, *ethpbalpha.SyncCommittee, error) { - committeeIndices := make([]types.ValidatorIndex, len(committee.Pubkeys)) +func committeeIndicesFromState(st state.BeaconState, committee *ethpbalpha.SyncCommittee) ([]primitives.ValidatorIndex, *ethpbalpha.SyncCommittee, error) { + committeeIndices := make([]primitives.ValidatorIndex, len(committee.Pubkeys)) for i, key := range committee.Pubkeys { index, ok := st.ValidatorIndexByPubkey(bytesutil.ToBytes48(key)) if !ok { @@ -120,7 +120,7 @@ func committeeIndicesFromState(st state.BeaconState, committee *ethpbalpha.SyncC return committeeIndices, committee, nil } -func currentCommitteeIndicesFromState(st state.BeaconState) ([]types.ValidatorIndex, *ethpbalpha.SyncCommittee, error) { +func currentCommitteeIndicesFromState(st state.BeaconState) ([]primitives.ValidatorIndex, *ethpbalpha.SyncCommittee, error) { committee, err := st.CurrentSyncCommittee() if err != nil { return nil, nil, fmt.Errorf( @@ -131,7 +131,7 @@ func currentCommitteeIndicesFromState(st state.BeaconState) ([]types.ValidatorIn return committeeIndicesFromState(st, committee) } -func nextCommitteeIndicesFromState(st state.BeaconState) ([]types.ValidatorIndex, *ethpbalpha.SyncCommittee, error) { +func nextCommitteeIndicesFromState(st state.BeaconState) ([]primitives.ValidatorIndex, *ethpbalpha.SyncCommittee, error) { committee, err := st.NextSyncCommittee() if err != nil { return nil, nil, fmt.Errorf( @@ -146,13 +146,13 @@ func extractSyncSubcommittees(st state.BeaconState, committee *ethpbalpha.SyncCo subcommitteeCount := params.BeaconConfig().SyncCommitteeSubnetCount subcommittees := make([]*ethpbv2.SyncSubcommitteeValidators, subcommitteeCount) for i := uint64(0); i < subcommitteeCount; i++ { - pubkeys, err := altair.SyncSubCommitteePubkeys(committee, types.CommitteeIndex(i)) + pubkeys, err := altair.SyncSubCommitteePubkeys(committee, primitives.CommitteeIndex(i)) if err != nil { return nil, fmt.Errorf( "failed to get subcommittee pubkeys: %v", err, ) } - subcommittee := ðpbv2.SyncSubcommitteeValidators{Validators: make([]types.ValidatorIndex, len(pubkeys))} + subcommittee := ðpbv2.SyncSubcommitteeValidators{Validators: make([]primitives.ValidatorIndex, len(pubkeys))} for j, key := range pubkeys { index, ok := st.ValidatorIndexByPubkey(bytesutil.ToBytes48(key)) if !ok { diff --git a/beacon-chain/rpc/eth/beacon/sync_committee_test.go b/beacon-chain/rpc/eth/beacon/sync_committee_test.go index c1cbb9d63c..ae95f933e6 100644 --- a/beacon-chain/rpc/eth/beacon/sync_committee_test.go +++ b/beacon-chain/rpc/eth/beacon/sync_committee_test.go @@ -18,7 +18,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/testutil" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpbv2 "github.com/prysmaticlabs/prysm/v3/proto/eth/v2" ethpbalpha "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -35,9 +35,9 @@ func Test_currentCommitteeIndicesFromState(t *testing.T) { st, _ := util.DeterministicGenesisStateAltair(t, params.BeaconConfig().SyncCommitteeSize) vals := st.Validators() wantedCommittee := make([][]byte, params.BeaconConfig().SyncCommitteeSize) - wantedIndices := make([]types.ValidatorIndex, len(wantedCommittee)) + wantedIndices := make([]primitives.ValidatorIndex, len(wantedCommittee)) for i := 0; i < len(wantedCommittee); i++ { - wantedIndices[i] = types.ValidatorIndex(i) + wantedIndices[i] = primitives.ValidatorIndex(i) wantedCommittee[i] = vals[i].PublicKey } require.NoError(t, st.SetCurrentSyncCommittee(ðpbalpha.SyncCommittee{ @@ -66,9 +66,9 @@ func Test_nextCommitteeIndicesFromState(t *testing.T) { st, _ := util.DeterministicGenesisStateAltair(t, params.BeaconConfig().SyncCommitteeSize) vals := st.Validators() wantedCommittee := make([][]byte, params.BeaconConfig().SyncCommitteeSize) - wantedIndices := make([]types.ValidatorIndex, len(wantedCommittee)) + wantedIndices := make([]primitives.ValidatorIndex, len(wantedCommittee)) for i := 0; i < len(wantedCommittee); i++ { - wantedIndices[i] = types.ValidatorIndex(i) + wantedIndices[i] = primitives.ValidatorIndex(i) wantedCommittee[i] = vals[i].PublicKey } require.NoError(t, st.SetNextSyncCommittee(ðpbalpha.SyncCommittee{ @@ -107,17 +107,17 @@ func Test_extractSyncSubcommittees(t *testing.T) { commSize := params.BeaconConfig().SyncCommitteeSize subCommSize := params.BeaconConfig().SyncCommitteeSize / params.BeaconConfig().SyncCommitteeSubnetCount - wantedSubcommitteeValidators := make([][]types.ValidatorIndex, 0) + wantedSubcommitteeValidators := make([][]primitives.ValidatorIndex, 0) for i := uint64(0); i < commSize; i += subCommSize { - sub := make([]types.ValidatorIndex, 0) + sub := make([]primitives.ValidatorIndex, 0) start := i end := i + subCommSize if end > commSize { end = commSize } for j := start; j < end; j++ { - sub = append(sub, types.ValidatorIndex(j)) + sub = append(sub, primitives.ValidatorIndex(j)) } wantedSubcommitteeValidators = append(wantedSubcommitteeValidators, sub) } @@ -181,13 +181,13 @@ func TestListSyncCommittees(t *testing.T) { require.NotNil(t, committeeVals) require.Equal(t, params.BeaconConfig().SyncCommitteeSize, uint64(len(committeeVals)), "incorrect committee size") for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSize; i++ { - assert.Equal(t, types.ValidatorIndex(i), committeeVals[i]) + assert.Equal(t, primitives.ValidatorIndex(i), committeeVals[i]) } require.NotNil(t, resp.Data.ValidatorAggregates) assert.Equal(t, params.BeaconConfig().SyncCommitteeSubnetCount, uint64(len(resp.Data.ValidatorAggregates))) for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSubnetCount; i++ { - vStartIndex := types.ValidatorIndex(params.BeaconConfig().SyncCommitteeSize / params.BeaconConfig().SyncCommitteeSubnetCount * i) - vEndIndex := types.ValidatorIndex(params.BeaconConfig().SyncCommitteeSize/params.BeaconConfig().SyncCommitteeSubnetCount*(i+1) - 1) + vStartIndex := primitives.ValidatorIndex(params.BeaconConfig().SyncCommitteeSize / params.BeaconConfig().SyncCommitteeSubnetCount * i) + vEndIndex := primitives.ValidatorIndex(params.BeaconConfig().SyncCommitteeSize/params.BeaconConfig().SyncCommitteeSubnetCount*(i+1) - 1) j := 0 for vIndex := vStartIndex; vIndex <= vEndIndex; vIndex++ { assert.Equal(t, vIndex, resp.Data.ValidatorAggregates[i].Validators[j]) @@ -244,7 +244,7 @@ func (m *futureSyncMockFetcher) StateRoot(context.Context, []byte) ([]byte, erro return m.BeaconStateRoot, nil } -func (m *futureSyncMockFetcher) StateBySlot(context.Context, types.Slot) (state.BeaconState, error) { +func (m *futureSyncMockFetcher) StateBySlot(context.Context, primitives.Slot) (state.BeaconState, error) { return m.BeaconState, nil } @@ -289,13 +289,13 @@ func TestListSyncCommitteesFuture(t *testing.T) { require.NotNil(t, committeeVals) require.Equal(t, params.BeaconConfig().SyncCommitteeSize, uint64(len(committeeVals)), "incorrect committee size") for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSize; i++ { - assert.Equal(t, types.ValidatorIndex(i), committeeVals[i]) + assert.Equal(t, primitives.ValidatorIndex(i), committeeVals[i]) } require.NotNil(t, resp.Data.ValidatorAggregates) assert.Equal(t, params.BeaconConfig().SyncCommitteeSubnetCount, uint64(len(resp.Data.ValidatorAggregates))) for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSubnetCount; i++ { - vStartIndex := types.ValidatorIndex(params.BeaconConfig().SyncCommitteeSize / params.BeaconConfig().SyncCommitteeSubnetCount * i) - vEndIndex := types.ValidatorIndex(params.BeaconConfig().SyncCommitteeSize/params.BeaconConfig().SyncCommitteeSubnetCount*(i+1) - 1) + vStartIndex := primitives.ValidatorIndex(params.BeaconConfig().SyncCommitteeSize / params.BeaconConfig().SyncCommitteeSubnetCount * i) + vEndIndex := primitives.ValidatorIndex(params.BeaconConfig().SyncCommitteeSize/params.BeaconConfig().SyncCommitteeSubnetCount*(i+1) - 1) j := 0 for vIndex := vStartIndex; vIndex <= vEndIndex; vIndex++ { assert.Equal(t, vIndex, resp.Data.ValidatorAggregates[i].Validators[j]) diff --git a/beacon-chain/rpc/eth/beacon/validator.go b/beacon-chain/rpc/eth/beacon/validator.go index de90417df4..a096c892a2 100644 --- a/beacon-chain/rpc/eth/beacon/validator.go +++ b/beacon-chain/rpc/eth/beacon/validator.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" statenative "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" "github.com/prysmaticlabs/prysm/v3/proto/migration" @@ -185,7 +185,7 @@ func (bs *Server) ListCommittees(ctx context.Context, req *ethpb.StateCommittees if req.Slot != nil && slot != *req.Slot { continue } - for index := types.CommitteeIndex(0); index < types.CommitteeIndex(committeesPerSlot); index++ { + for index := primitives.CommitteeIndex(0); index < primitives.CommitteeIndex(committeesPerSlot); index++ { if req.Index != nil && index != *req.Index { continue } @@ -229,7 +229,7 @@ func valContainersByRequestIds(state state.BeaconState, validatorIds [][]byte) ( return nil, errors.Wrap(err, "could not get validator sub status") } valContainers[i] = ðpb.ValidatorContainer{ - Index: types.ValidatorIndex(i), + Index: primitives.ValidatorIndex(i), Balance: allBalances[i], Status: subStatus, Validator: migration.V1Alpha1ValidatorToV1(validator), @@ -238,7 +238,7 @@ func valContainersByRequestIds(state state.BeaconState, validatorIds [][]byte) ( } else { valContainers = make([]*ethpb.ValidatorContainer, 0, len(validatorIds)) for _, validatorId := range validatorIds { - var valIndex types.ValidatorIndex + var valIndex primitives.ValidatorIndex if len(validatorId) == params.BeaconConfig().BLSPubkeyLength { var ok bool valIndex, ok = state.ValidatorIndexByPubkey(bytesutil.ToBytes48(validatorId)) @@ -252,7 +252,7 @@ func valContainersByRequestIds(state state.BeaconState, validatorIds [][]byte) ( e := newInvalidValidatorIdError(validatorId, err) return nil, &e } - valIndex = types.ValidatorIndex(index) + valIndex = primitives.ValidatorIndex(index) } validator, err := state.ValidatorAtIndex(valIndex) if _, ok := err.(*statenative.ValidatorIndexOutOfRangeError); ok { diff --git a/beacon-chain/rpc/eth/beacon/validator_test.go b/beacon-chain/rpc/eth/beacon/validator_test.go index 7c84fed663..18eaf7cc29 100644 --- a/beacon-chain/rpc/eth/beacon/validator_test.go +++ b/beacon-chain/rpc/eth/beacon/validator_test.go @@ -14,7 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" "github.com/prysmaticlabs/prysm/v3/proto/migration" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -47,7 +47,7 @@ func TestGetValidator(t *testing.T) { ValidatorId: []byte("15"), }) require.NoError(t, err) - assert.Equal(t, types.ValidatorIndex(15), resp.Data.Index) + assert.Equal(t, primitives.ValidatorIndex(15), resp.Data.Index) }) t.Run("Head Get Validator by pubkey", func(t *testing.T) { @@ -61,13 +61,13 @@ func TestGetValidator(t *testing.T) { BeaconDB: db, } - pubKey := st.PubkeyAtIndex(types.ValidatorIndex(20)) + pubKey := st.PubkeyAtIndex(primitives.ValidatorIndex(20)) resp, err := s.GetValidator(ctx, ðpb.StateValidatorRequest{ StateId: []byte("head"), ValidatorId: pubKey[:], }) require.NoError(t, err) - assert.Equal(t, types.ValidatorIndex(20), resp.Data.Index) + assert.Equal(t, primitives.ValidatorIndex(20), resp.Data.Index) assert.Equal(t, true, bytes.Equal(pubKey[:], resp.Data.Validator.Pubkey)) }) @@ -151,7 +151,7 @@ func TestListValidators(t *testing.T) { } ids := [][]byte{[]byte("15"), []byte("26"), []byte("400")} - idNums := []types.ValidatorIndex{15, 26, 400} + idNums := []primitives.ValidatorIndex{15, 26, 400} resp, err := s.ListValidators(ctx, ðpb.StateValidatorsRequest{ StateId: []byte("head"), Id: ids, @@ -173,11 +173,11 @@ func TestListValidators(t *testing.T) { OptimisticModeFetcher: chainService, BeaconDB: db, } - idNums := []types.ValidatorIndex{20, 66, 90, 100} - pubkey1 := st.PubkeyAtIndex(types.ValidatorIndex(20)) - pubkey2 := st.PubkeyAtIndex(types.ValidatorIndex(66)) - pubkey3 := st.PubkeyAtIndex(types.ValidatorIndex(90)) - pubkey4 := st.PubkeyAtIndex(types.ValidatorIndex(100)) + idNums := []primitives.ValidatorIndex{20, 66, 90, 100} + pubkey1 := st.PubkeyAtIndex(primitives.ValidatorIndex(20)) + pubkey2 := st.PubkeyAtIndex(primitives.ValidatorIndex(66)) + pubkey3 := st.PubkeyAtIndex(primitives.ValidatorIndex(90)) + pubkey4 := st.PubkeyAtIndex(primitives.ValidatorIndex(100)) pubKeys := [][]byte{pubkey1[:], pubkey2[:], pubkey3[:], pubkey4[:]} resp, err := s.ListValidators(ctx, ðpb.StateValidatorsRequest{ StateId: []byte("head"), @@ -202,11 +202,11 @@ func TestListValidators(t *testing.T) { BeaconDB: db, } - idNums := []types.ValidatorIndex{20, 90, 170, 129} - pubkey1 := st.PubkeyAtIndex(types.ValidatorIndex(20)) - pubkey2 := st.PubkeyAtIndex(types.ValidatorIndex(90)) - pubkey3 := st.PubkeyAtIndex(types.ValidatorIndex(170)) - pubkey4 := st.PubkeyAtIndex(types.ValidatorIndex(129)) + idNums := []primitives.ValidatorIndex{20, 90, 170, 129} + pubkey1 := st.PubkeyAtIndex(primitives.ValidatorIndex(20)) + pubkey2 := st.PubkeyAtIndex(primitives.ValidatorIndex(90)) + pubkey3 := st.PubkeyAtIndex(primitives.ValidatorIndex(170)) + pubkey4 := st.PubkeyAtIndex(primitives.ValidatorIndex(129)) pubkeys := [][]byte{pubkey1[:], pubkey2[:], pubkey3[:], pubkey4[:]} ids := [][]byte{pubkey1[:], []byte("90"), pubkey3[:], []byte("129")} resp, err := s.ListValidators(ctx, ðpb.StateValidatorsRequest{ @@ -232,7 +232,7 @@ func TestListValidators(t *testing.T) { BeaconDB: db, } - existingKey := st.PubkeyAtIndex(types.ValidatorIndex(1)) + existingKey := st.PubkeyAtIndex(primitives.ValidatorIndex(1)) pubkeys := [][]byte{existingKey[:], []byte(strings.Repeat("f", 48))} resp, err := s.ListValidators(ctx, ðpb.StateValidatorsRequest{ StateId: []byte("head"), @@ -240,7 +240,7 @@ func TestListValidators(t *testing.T) { }) require.NoError(t, err) require.Equal(t, 1, len(resp.Data)) - assert.Equal(t, types.ValidatorIndex(1), resp.Data[0].Index) + assert.Equal(t, primitives.ValidatorIndex(1), resp.Data[0].Index) }) t.Run("Unknown index is ignored", func(t *testing.T) { @@ -261,7 +261,7 @@ func TestListValidators(t *testing.T) { }) require.NoError(t, err) require.Equal(t, 1, len(resp.Data)) - assert.Equal(t, types.ValidatorIndex(1), resp.Data[0].Index) + assert.Equal(t, primitives.ValidatorIndex(1), resp.Data[0].Index) }) t.Run("execution optimistic", func(t *testing.T) { @@ -567,7 +567,7 @@ func TestListValidatorBalances(t *testing.T) { } ids := [][]byte{[]byte("15"), []byte("26"), []byte("400")} - idNums := []types.ValidatorIndex{15, 26, 400} + idNums := []primitives.ValidatorIndex{15, 26, 400} resp, err := s.ListValidatorBalances(ctx, ðpb.ValidatorBalancesRequest{ StateId: []byte("head"), Id: ids, @@ -589,11 +589,11 @@ func TestListValidatorBalances(t *testing.T) { OptimisticModeFetcher: chainService, BeaconDB: db, } - idNums := []types.ValidatorIndex{20, 66, 90, 100} - pubkey1 := st.PubkeyAtIndex(types.ValidatorIndex(20)) - pubkey2 := st.PubkeyAtIndex(types.ValidatorIndex(66)) - pubkey3 := st.PubkeyAtIndex(types.ValidatorIndex(90)) - pubkey4 := st.PubkeyAtIndex(types.ValidatorIndex(100)) + idNums := []primitives.ValidatorIndex{20, 66, 90, 100} + pubkey1 := st.PubkeyAtIndex(primitives.ValidatorIndex(20)) + pubkey2 := st.PubkeyAtIndex(primitives.ValidatorIndex(66)) + pubkey3 := st.PubkeyAtIndex(primitives.ValidatorIndex(90)) + pubkey4 := st.PubkeyAtIndex(primitives.ValidatorIndex(100)) pubKeys := [][]byte{pubkey1[:], pubkey2[:], pubkey3[:], pubkey4[:]} resp, err := s.ListValidatorBalances(ctx, ðpb.ValidatorBalancesRequest{ StateId: []byte("head"), @@ -617,9 +617,9 @@ func TestListValidatorBalances(t *testing.T) { BeaconDB: db, } - idNums := []types.ValidatorIndex{20, 90, 170, 129} - pubkey1 := st.PubkeyAtIndex(types.ValidatorIndex(20)) - pubkey3 := st.PubkeyAtIndex(types.ValidatorIndex(170)) + idNums := []primitives.ValidatorIndex{20, 90, 170, 129} + pubkey1 := st.PubkeyAtIndex(primitives.ValidatorIndex(20)) + pubkey3 := st.PubkeyAtIndex(primitives.ValidatorIndex(170)) ids := [][]byte{pubkey1[:], []byte("90"), pubkey3[:], []byte("129")} resp, err := s.ListValidatorBalances(ctx, ðpb.ValidatorBalancesRequest{ StateId: []byte("head"), @@ -686,7 +686,7 @@ func TestListCommittees(t *testing.T) { require.NoError(t, err) assert.Equal(t, int(params.BeaconConfig().SlotsPerEpoch)*2, len(resp.Data)) for _, datum := range resp.Data { - assert.Equal(t, true, datum.Index == types.CommitteeIndex(0) || datum.Index == types.CommitteeIndex(1)) + assert.Equal(t, true, datum.Index == primitives.CommitteeIndex(0) || datum.Index == primitives.CommitteeIndex(1)) assert.Equal(t, epoch, slots.ToEpoch(datum.Slot)) } }) @@ -701,7 +701,7 @@ func TestListCommittees(t *testing.T) { OptimisticModeFetcher: chainService, BeaconDB: db, } - epoch := types.Epoch(10) + epoch := primitives.Epoch(10) resp, err := s.ListCommittees(ctx, ðpb.StateCommitteesRequest{ StateId: []byte("head"), Epoch: &epoch, @@ -723,14 +723,14 @@ func TestListCommittees(t *testing.T) { BeaconDB: db, } - slot := types.Slot(4) + slot := primitives.Slot(4) resp, err := s.ListCommittees(ctx, ðpb.StateCommitteesRequest{ StateId: []byte("head"), Slot: &slot, }) require.NoError(t, err) assert.Equal(t, 2, len(resp.Data)) - index := types.CommitteeIndex(0) + index := primitives.CommitteeIndex(0) for _, datum := range resp.Data { assert.Equal(t, epoch, slots.ToEpoch(datum.Slot)) assert.Equal(t, slot, datum.Slot) @@ -750,14 +750,14 @@ func TestListCommittees(t *testing.T) { BeaconDB: db, } - index := types.CommitteeIndex(1) + index := primitives.CommitteeIndex(1) resp, err := s.ListCommittees(ctx, ðpb.StateCommitteesRequest{ StateId: []byte("head"), Index: &index, }) require.NoError(t, err) assert.Equal(t, int(params.BeaconConfig().SlotsPerEpoch), len(resp.Data)) - slot := types.Slot(0) + slot := primitives.Slot(0) for _, datum := range resp.Data { assert.Equal(t, epoch, slots.ToEpoch(datum.Slot)) assert.Equal(t, slot, datum.Slot) @@ -777,8 +777,8 @@ func TestListCommittees(t *testing.T) { BeaconDB: db, } - index := types.CommitteeIndex(1) - slot := types.Slot(2) + index := primitives.CommitteeIndex(1) + slot := primitives.Slot(2) resp, err := s.ListCommittees(ctx, ðpb.StateCommitteesRequest{ StateId: []byte("head"), Slot: &slot, diff --git a/beacon-chain/rpc/eth/debug/debug_test.go b/beacon-chain/rpc/eth/debug/debug_test.go index 9e900b351f..3fc442adbb 100644 --- a/beacon-chain/rpc/eth/debug/debug_test.go +++ b/beacon-chain/rpc/eth/debug/debug_test.go @@ -10,7 +10,7 @@ import ( doublylinkedtree "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/doubly-linked-tree" forkchoicetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/testutil" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpbv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ethpbv2 "github.com/prysmaticlabs/prysm/v3/proto/eth/v2" @@ -224,7 +224,7 @@ func TestListForkChoiceHeadsV2(t *testing.T) { ctx := context.Background() expectedSlotsAndRoots := []struct { - Slot types.Slot + Slot primitives.Slot Root [32]byte }{{ Slot: 0, @@ -288,6 +288,6 @@ func TestServer_GetForkChoice(t *testing.T) { bs := &Server{ForkFetcher: &blockchainmock.ChainService{ForkChoiceStore: store}} res, err := bs.GetForkChoice(context.Background(), &empty.Empty{}) require.NoError(t, err) - require.Equal(t, types.Epoch(3), res.JustifiedCheckpoint.Epoch, "Did not get wanted justified epoch") - require.Equal(t, types.Epoch(2), res.FinalizedCheckpoint.Epoch, "Did not get wanted finalized epoch") + require.Equal(t, primitives.Epoch(3), res.JustifiedCheckpoint.Epoch, "Did not get wanted justified epoch") + require.Equal(t, primitives.Epoch(2), res.FinalizedCheckpoint.Epoch, "Did not get wanted finalized epoch") } diff --git a/beacon-chain/rpc/eth/helpers/sync_test.go b/beacon-chain/rpc/eth/helpers/sync_test.go index b0da861561..9afcbe0807 100644 --- a/beacon-chain/rpc/eth/helpers/sync_test.go +++ b/beacon-chain/rpc/eth/helpers/sync_test.go @@ -9,7 +9,7 @@ import ( grpcutil "github.com/prysmaticlabs/prysm/v3/api/grpc" chainmock "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain/testing" syncmock "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -22,7 +22,7 @@ func TestValidateSync(t *testing.T) { syncChecker := &syncmock.Sync{ IsSyncing: true, } - headSlot := types.Slot(100) + headSlot := primitives.Slot(100) st, err := util.NewBeaconState() require.NoError(t, err) require.NoError(t, st.SetSlot(50)) @@ -47,7 +47,7 @@ func TestValidateSync(t *testing.T) { syncChecker := &syncmock.Sync{ IsSyncing: false, } - headSlot := types.Slot(100) + headSlot := primitives.Slot(100) st, err := util.NewBeaconState() require.NoError(t, err) require.NoError(t, st.SetSlot(50)) diff --git a/beacon-chain/rpc/eth/helpers/validator_status.go b/beacon-chain/rpc/eth/helpers/validator_status.go index fdd7bec218..8b525a2ae8 100644 --- a/beacon-chain/rpc/eth/helpers/validator_status.go +++ b/beacon-chain/rpc/eth/helpers/validator_status.go @@ -4,12 +4,12 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ) // ValidatorStatus returns a validator's status at the given epoch. -func ValidatorStatus(validator state.ReadOnlyValidator, epoch types.Epoch) (ethpb.ValidatorStatus, error) { +func ValidatorStatus(validator state.ReadOnlyValidator, epoch primitives.Epoch) (ethpb.ValidatorStatus, error) { valStatus, err := ValidatorSubStatus(validator, epoch) if err != nil { return 0, errors.Wrap(err, "could not get sub status") @@ -28,7 +28,7 @@ func ValidatorStatus(validator state.ReadOnlyValidator, epoch types.Epoch) (ethp } // ValidatorSubStatus returns a validator's sub-status at the given epoch. -func ValidatorSubStatus(validator state.ReadOnlyValidator, epoch types.Epoch) (ethpb.ValidatorStatus, error) { +func ValidatorSubStatus(validator state.ReadOnlyValidator, epoch primitives.Epoch) (ethpb.ValidatorStatus, error) { farFutureEpoch := params.BeaconConfig().FarFutureEpoch // Pending. diff --git a/beacon-chain/rpc/eth/helpers/validator_status_test.go b/beacon-chain/rpc/eth/helpers/validator_status_test.go index a53fa5efc8..1f35f2dc0d 100644 --- a/beacon-chain/rpc/eth/helpers/validator_status_test.go +++ b/beacon-chain/rpc/eth/helpers/validator_status_test.go @@ -6,7 +6,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" "github.com/prysmaticlabs/prysm/v3/proto/migration" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -18,7 +18,7 @@ func Test_ValidatorStatus(t *testing.T) { type args struct { validator *ethpb.Validator - epoch types.Epoch + epoch primitives.Epoch } tests := []struct { name string @@ -33,7 +33,7 @@ func Test_ValidatorStatus(t *testing.T) { ActivationEpoch: farFutureEpoch, ActivationEligibilityEpoch: farFutureEpoch, }, - epoch: types.Epoch(5), + epoch: primitives.Epoch(5), }, want: ethpb.ValidatorStatus_PENDING, }, @@ -44,7 +44,7 @@ func Test_ValidatorStatus(t *testing.T) { ActivationEpoch: 10, ActivationEligibilityEpoch: 2, }, - epoch: types.Epoch(5), + epoch: primitives.Epoch(5), }, want: ethpb.ValidatorStatus_PENDING, }, @@ -55,7 +55,7 @@ func Test_ValidatorStatus(t *testing.T) { ActivationEpoch: 3, ExitEpoch: farFutureEpoch, }, - epoch: types.Epoch(5), + epoch: primitives.Epoch(5), }, want: ethpb.ValidatorStatus_ACTIVE, }, @@ -67,7 +67,7 @@ func Test_ValidatorStatus(t *testing.T) { ExitEpoch: 30, Slashed: true, }, - epoch: types.Epoch(5), + epoch: primitives.Epoch(5), }, want: ethpb.ValidatorStatus_ACTIVE, }, @@ -79,7 +79,7 @@ func Test_ValidatorStatus(t *testing.T) { ExitEpoch: 30, Slashed: false, }, - epoch: types.Epoch(5), + epoch: primitives.Epoch(5), }, want: ethpb.ValidatorStatus_ACTIVE, }, @@ -92,7 +92,7 @@ func Test_ValidatorStatus(t *testing.T) { WithdrawableEpoch: 40, Slashed: true, }, - epoch: types.Epoch(35), + epoch: primitives.Epoch(35), }, want: ethpb.ValidatorStatus_EXITED, }, @@ -105,7 +105,7 @@ func Test_ValidatorStatus(t *testing.T) { WithdrawableEpoch: 40, Slashed: false, }, - epoch: types.Epoch(35), + epoch: primitives.Epoch(35), }, want: ethpb.ValidatorStatus_EXITED, }, @@ -119,7 +119,7 @@ func Test_ValidatorStatus(t *testing.T) { EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, Slashed: false, }, - epoch: types.Epoch(45), + epoch: primitives.Epoch(45), }, want: ethpb.ValidatorStatus_WITHDRAWAL, }, @@ -133,7 +133,7 @@ func Test_ValidatorStatus(t *testing.T) { EffectiveBalance: 0, Slashed: false, }, - epoch: types.Epoch(45), + epoch: primitives.Epoch(45), }, want: ethpb.ValidatorStatus_WITHDRAWAL, }, @@ -156,7 +156,7 @@ func Test_ValidatorSubStatus(t *testing.T) { type args struct { validator *ethpb.Validator - epoch types.Epoch + epoch primitives.Epoch } tests := []struct { name string @@ -171,7 +171,7 @@ func Test_ValidatorSubStatus(t *testing.T) { ActivationEpoch: farFutureEpoch, ActivationEligibilityEpoch: farFutureEpoch, }, - epoch: types.Epoch(5), + epoch: primitives.Epoch(5), }, want: ethpb.ValidatorStatus_PENDING_INITIALIZED, }, @@ -182,7 +182,7 @@ func Test_ValidatorSubStatus(t *testing.T) { ActivationEpoch: 10, ActivationEligibilityEpoch: 2, }, - epoch: types.Epoch(5), + epoch: primitives.Epoch(5), }, want: ethpb.ValidatorStatus_PENDING_QUEUED, }, @@ -193,7 +193,7 @@ func Test_ValidatorSubStatus(t *testing.T) { ActivationEpoch: 3, ExitEpoch: farFutureEpoch, }, - epoch: types.Epoch(5), + epoch: primitives.Epoch(5), }, want: ethpb.ValidatorStatus_ACTIVE_ONGOING, }, @@ -205,7 +205,7 @@ func Test_ValidatorSubStatus(t *testing.T) { ExitEpoch: 30, Slashed: true, }, - epoch: types.Epoch(5), + epoch: primitives.Epoch(5), }, want: ethpb.ValidatorStatus_ACTIVE_SLASHED, }, @@ -217,7 +217,7 @@ func Test_ValidatorSubStatus(t *testing.T) { ExitEpoch: 30, Slashed: false, }, - epoch: types.Epoch(5), + epoch: primitives.Epoch(5), }, want: ethpb.ValidatorStatus_ACTIVE_EXITING, }, @@ -230,7 +230,7 @@ func Test_ValidatorSubStatus(t *testing.T) { WithdrawableEpoch: 40, Slashed: true, }, - epoch: types.Epoch(35), + epoch: primitives.Epoch(35), }, want: ethpb.ValidatorStatus_EXITED_SLASHED, }, @@ -243,7 +243,7 @@ func Test_ValidatorSubStatus(t *testing.T) { WithdrawableEpoch: 40, Slashed: false, }, - epoch: types.Epoch(35), + epoch: primitives.Epoch(35), }, want: ethpb.ValidatorStatus_EXITED_UNSLASHED, }, @@ -257,7 +257,7 @@ func Test_ValidatorSubStatus(t *testing.T) { EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, Slashed: false, }, - epoch: types.Epoch(45), + epoch: primitives.Epoch(45), }, want: ethpb.ValidatorStatus_WITHDRAWAL_POSSIBLE, }, @@ -271,7 +271,7 @@ func Test_ValidatorSubStatus(t *testing.T) { EffectiveBalance: 0, Slashed: false, }, - epoch: types.Epoch(45), + epoch: primitives.Epoch(45), }, want: ethpb.ValidatorStatus_WITHDRAWAL_DONE, }, diff --git a/beacon-chain/rpc/eth/node/node_test.go b/beacon-chain/rpc/eth/node/node_test.go index 50f2ba9482..267d8ffa02 100644 --- a/beacon-chain/rpc/eth/node/node_test.go +++ b/beacon-chain/rpc/eth/node/node_test.go @@ -23,7 +23,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/peers" mockp2p "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/testing" syncmock "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/consensus-types/wrapper" ethpb "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -161,7 +161,7 @@ func TestGetIdentity(t *testing.T) { } func TestSyncStatus(t *testing.T) { - currentSlot := new(types.Slot) + currentSlot := new(primitives.Slot) *currentSlot = 110 state, err := util.NewBeaconState() require.NoError(t, err) @@ -179,8 +179,8 @@ func TestSyncStatus(t *testing.T) { } resp, err := s.GetSyncStatus(context.Background(), &emptypb.Empty{}) require.NoError(t, err) - assert.Equal(t, types.Slot(100), resp.Data.HeadSlot) - assert.Equal(t, types.Slot(10), resp.Data.SyncDistance) + assert.Equal(t, primitives.Slot(100), resp.Data.HeadSlot) + assert.Equal(t, primitives.Slot(10), resp.Data.SyncDistance) assert.Equal(t, true, resp.Data.IsSyncing) assert.Equal(t, true, resp.Data.IsOptimistic) } diff --git a/beacon-chain/rpc/eth/validator/validator.go b/beacon-chain/rpc/eth/validator/validator.go index b5fe3c68f5..fced59bab0 100644 --- a/beacon-chain/rpc/eth/validator/validator.go +++ b/beacon-chain/rpc/eth/validator/validator.go @@ -21,7 +21,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpbv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ethpbv2 "github.com/prysmaticlabs/prysm/v3/proto/eth/v2" @@ -60,7 +60,7 @@ func (vs *Server) GetAttesterDuties(ctx context.Context, req *ethpbv1.AttesterDu return nil, status.Errorf(codes.Internal, "Could not check optimistic status: %v", err) } - var startSlot types.Slot + var startSlot primitives.Slot if req.Epoch == currentEpoch+1 { startSlot, err = slots.EpochStart(currentEpoch) } else { @@ -96,12 +96,12 @@ func (vs *Server) GetAttesterDuties(ctx context.Context, req *ethpbv1.AttesterDu if committee == nil { continue } - var valIndexInCommittee types.CommitteeIndex + var valIndexInCommittee primitives.CommitteeIndex // valIndexInCommittee will be 0 in case we don't get a match. This is a potential false positive, // however it's an impossible condition because every validator must be assigned to a committee. for cIndex, vIndex := range committee.Committee { if vIndex == index { - valIndexInCommittee = types.CommitteeIndex(uint64(cIndex)) + valIndexInCommittee = primitives.CommitteeIndex(uint64(cIndex)) break } } @@ -164,7 +164,7 @@ func (vs *Server) GetProposerDuties(ctx context.Context, req *ethpbv1.ProposerDu return nil, status.Errorf(codes.Internal, "Could not get state: %v", err) } - var proposals map[types.ValidatorIndex][]types.Slot + var proposals map[primitives.ValidatorIndex][]primitives.Slot if nextEpochLookahead { _, proposals, err = helpers.CommitteeAssignments(ctx, s, nextEpoch) } else { @@ -458,7 +458,7 @@ func (vs *Server) ProduceBlindedBlock(ctx context.Context, req *ethpbv1.ProduceB } // Before Bellatrix, return normal block. - if req.Slot < types.Slot(params.BeaconConfig().BellatrixForkEpoch)*params.BeaconConfig().SlotsPerEpoch { + if req.Slot < primitives.Slot(params.BeaconConfig().BellatrixForkEpoch)*params.BeaconConfig().SlotsPerEpoch { v1alpha1resp, err := vs.V1Alpha1Server.GetBeaconBlock(ctx, v1alpha1req) if err != nil { // We simply return err because it's already of a gRPC error type. @@ -596,7 +596,7 @@ func (vs *Server) PrepareBeaconProposer( ctx, span := trace.StartSpan(ctx, "validator.PrepareBeaconProposer") defer span.End() var feeRecipients []common.Address - var validatorIndices []types.ValidatorIndex + var validatorIndices []primitives.ValidatorIndex newRecipients := make([]*ethpbv1.PrepareBeaconProposerRequest_FeeRecipientContainer, 0, len(request.Recipients)) for _, r := range request.Recipients { f, err := vs.V1Alpha1Server.BeaconDB.FeeRecipientByValidatorID(ctx, r.ValidatorIndex) @@ -795,7 +795,7 @@ func (vs *Server) SubmitBeaconCommitteeSubscription(ctx context.Context, req *et validators[i] = val } - fetchValsLen := func(slot types.Slot) (uint64, error) { + fetchValsLen := func(slot primitives.Slot) (uint64, error) { wantedEpoch := slots.ToEpoch(slot) vals, err := vs.HeadFetcher.HeadValidatorsIndices(ctx, wantedEpoch) if err != nil { @@ -1034,7 +1034,7 @@ func (vs *Server) GetLiveness(ctx context.Context, req *ethpbv2.GetLivenessReque Data: make([]*ethpbv2.GetLivenessResponse_Liveness, len(req.Index)), } for i, vi := range req.Index { - if vi >= types.ValidatorIndex(len(participation)) { + if vi >= primitives.ValidatorIndex(len(participation)) { return nil, status.Errorf(codes.InvalidArgument, "Validator index %d is invalid", vi) } resp.Data[i] = ðpbv2.GetLivenessResponse_Liveness{ @@ -1048,8 +1048,8 @@ func (vs *Server) GetLiveness(ctx context.Context, req *ethpbv2.GetLivenessReque // attestationDependentRoot is get_block_root_at_slot(state, compute_start_slot_at_epoch(epoch - 1) - 1) // or the genesis block root in the case of underflow. -func attestationDependentRoot(s state.BeaconState, epoch types.Epoch) ([]byte, error) { - var dependentRootSlot types.Slot +func attestationDependentRoot(s state.BeaconState, epoch primitives.Epoch) ([]byte, error) { + var dependentRootSlot primitives.Slot if epoch <= 1 { dependentRootSlot = 0 } else { @@ -1068,8 +1068,8 @@ func attestationDependentRoot(s state.BeaconState, epoch types.Epoch) ([]byte, e // proposalDependentRoot is get_block_root_at_slot(state, compute_start_slot_at_epoch(epoch) - 1) // or the genesis block root in the case of underflow. -func proposalDependentRoot(s state.BeaconState, epoch types.Epoch) ([]byte, error) { - var dependentRootSlot types.Slot +func proposalDependentRoot(s state.BeaconState, epoch primitives.Epoch) ([]byte, error) { + var dependentRootSlot primitives.Slot if epoch == 0 { dependentRootSlot = 0 } else { @@ -1100,7 +1100,7 @@ func v1ValidatorStatusToV1Alpha1(valStatus ethpbv1.ValidatorStatus) ethpbalpha.V } } -func syncCommitteeDutiesLastValidEpoch(currentEpoch types.Epoch) types.Epoch { +func syncCommitteeDutiesLastValidEpoch(currentEpoch primitives.Epoch) primitives.Epoch { currentSyncPeriodIndex := currentEpoch / params.BeaconConfig().EpochsPerSyncCommitteePeriod // Return the last epoch of the next sync committee. // To do this we go two periods ahead to find the first invalid epoch, and then subtract 1. @@ -1108,7 +1108,7 @@ func syncCommitteeDutiesLastValidEpoch(currentEpoch types.Epoch) types.Epoch { } func syncCommitteeDuties( - valIndices []types.ValidatorIndex, + valIndices []primitives.ValidatorIndex, st state.BeaconState, committeePubkeys map[[fieldparams.BLSPubkeyLength]byte][]uint64, ) ([]*ethpbv2.SyncCommitteeDuty, error) { diff --git a/beacon-chain/rpc/eth/validator/validator_test.go b/beacon-chain/rpc/eth/validator/validator_test.go index 2aeba59b64..d84beb70ea 100644 --- a/beacon-chain/rpc/eth/validator/validator_test.go +++ b/beacon-chain/rpc/eth/validator/validator_test.go @@ -34,7 +34,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" @@ -84,13 +84,13 @@ func TestGetAttesterDuties(t *testing.T) { require.NoError(t, nextEpochState.SetSlot(params.BeaconConfig().SlotsPerEpoch)) require.NoError(t, nextEpochState.SetValidators(vals[:512])) - chainSlot := types.Slot(0) + chainSlot := primitives.Slot(0) chain := &mockChain.ChainService{ State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ StateFetcher: &testutil.MockFetcher{ - StatesBySlot: map[types.Slot]state.BeaconState{ + StatesBySlot: map[primitives.Slot]state.BeaconState{ 0: bs, params.BeaconConfig().SlotsPerEpoch: nextEpochState, }, @@ -103,26 +103,26 @@ func TestGetAttesterDuties(t *testing.T) { t.Run("Single validator", func(t *testing.T) { req := ðpbv1.AttesterDutiesRequest{ Epoch: 0, - Index: []types.ValidatorIndex{0}, + Index: []primitives.ValidatorIndex{0}, } resp, err := vs.GetAttesterDuties(ctx, req) require.NoError(t, err) assert.DeepEqual(t, genesisRoot[:], resp.DependentRoot) require.Equal(t, 1, len(resp.Data)) duty := resp.Data[0] - assert.Equal(t, types.CommitteeIndex(1), duty.CommitteeIndex) - assert.Equal(t, types.Slot(0), duty.Slot) - assert.Equal(t, types.ValidatorIndex(0), duty.ValidatorIndex) + assert.Equal(t, primitives.CommitteeIndex(1), duty.CommitteeIndex) + assert.Equal(t, primitives.Slot(0), duty.Slot) + assert.Equal(t, primitives.ValidatorIndex(0), duty.ValidatorIndex) assert.DeepEqual(t, pubKeys[0], duty.Pubkey) assert.Equal(t, uint64(171), duty.CommitteeLength) assert.Equal(t, uint64(3), duty.CommitteesAtSlot) - assert.Equal(t, types.CommitteeIndex(80), duty.ValidatorCommitteeIndex) + assert.Equal(t, primitives.CommitteeIndex(80), duty.ValidatorCommitteeIndex) }) t.Run("Multiple validators", func(t *testing.T) { req := ðpbv1.AttesterDutiesRequest{ Epoch: 0, - Index: []types.ValidatorIndex{0, 1}, + Index: []primitives.ValidatorIndex{0, 1}, } resp, err := vs.GetAttesterDuties(ctx, req) require.NoError(t, err) @@ -132,27 +132,27 @@ func TestGetAttesterDuties(t *testing.T) { t.Run("Next epoch", func(t *testing.T) { req := ðpbv1.AttesterDutiesRequest{ Epoch: slots.ToEpoch(bs.Slot()) + 1, - Index: []types.ValidatorIndex{0}, + Index: []primitives.ValidatorIndex{0}, } resp, err := vs.GetAttesterDuties(ctx, req) require.NoError(t, err) assert.DeepEqual(t, genesisRoot[:], resp.DependentRoot) require.Equal(t, 1, len(resp.Data)) duty := resp.Data[0] - assert.Equal(t, types.CommitteeIndex(0), duty.CommitteeIndex) - assert.Equal(t, types.Slot(62), duty.Slot) - assert.Equal(t, types.ValidatorIndex(0), duty.ValidatorIndex) + assert.Equal(t, primitives.CommitteeIndex(0), duty.CommitteeIndex) + assert.Equal(t, primitives.Slot(62), duty.Slot) + assert.Equal(t, primitives.ValidatorIndex(0), duty.ValidatorIndex) assert.DeepEqual(t, pubKeys[0], duty.Pubkey) assert.Equal(t, uint64(170), duty.CommitteeLength) assert.Equal(t, uint64(3), duty.CommitteesAtSlot) - assert.Equal(t, types.CommitteeIndex(110), duty.ValidatorCommitteeIndex) + assert.Equal(t, primitives.CommitteeIndex(110), duty.ValidatorCommitteeIndex) }) t.Run("Epoch out of bound", func(t *testing.T) { currentEpoch := slots.ToEpoch(bs.Slot()) req := ðpbv1.AttesterDutiesRequest{ Epoch: currentEpoch + 2, - Index: []types.ValidatorIndex{0}, + Index: []primitives.ValidatorIndex{0}, } _, err := vs.GetAttesterDuties(ctx, req) require.NotNil(t, err) @@ -162,7 +162,7 @@ func TestGetAttesterDuties(t *testing.T) { t.Run("Validator index out of bound", func(t *testing.T) { req := ðpbv1.AttesterDutiesRequest{ Epoch: 0, - Index: []types.ValidatorIndex{types.ValidatorIndex(len(pubKeys))}, + Index: []primitives.ValidatorIndex{primitives.ValidatorIndex(len(pubKeys))}, } _, err := vs.GetAttesterDuties(ctx, req) require.NotNil(t, err) @@ -172,7 +172,7 @@ func TestGetAttesterDuties(t *testing.T) { t.Run("Inactive validator - no duties", func(t *testing.T) { req := ðpbv1.AttesterDutiesRequest{ Epoch: 0, - Index: []types.ValidatorIndex{types.ValidatorIndex(len(pubKeys) - 1)}, + Index: []primitives.ValidatorIndex{primitives.ValidatorIndex(len(pubKeys) - 1)}, } resp, err := vs.GetAttesterDuties(ctx, req) require.NoError(t, err) @@ -189,19 +189,19 @@ func TestGetAttesterDuties(t *testing.T) { util.SaveBlock(t, ctx, db, blk) require.NoError(t, db.SaveGenesisBlockRoot(ctx, root)) - chainSlot := types.Slot(0) + chainSlot := primitives.Slot(0) chain := &mockChain.ChainService{ State: bs, Root: genesisRoot[:], Slot: &chainSlot, Optimistic: true, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{StatesBySlot: map[types.Slot]state.BeaconState{0: bs}}, + StateFetcher: &testutil.MockFetcher{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, TimeFetcher: chain, OptimisticModeFetcher: chain, SyncChecker: &mockSync.Sync{IsSyncing: false}, } req := ðpbv1.AttesterDutiesRequest{ Epoch: 0, - Index: []types.ValidatorIndex{0}, + Index: []primitives.ValidatorIndex{0}, } resp, err := vs.GetAttesterDuties(ctx, req) require.NoError(t, err) @@ -249,12 +249,12 @@ func TestGetProposerDuties(t *testing.T) { require.NoError(t, err, "Could not set up genesis state") require.NoError(t, bs.SetSlot(params.BeaconConfig().SlotsPerEpoch)) require.NoError(t, bs.SetBlockRoots(roots)) - chainSlot := types.Slot(0) + chainSlot := primitives.Slot(0) chain := &mockChain.ChainService{ State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{StatesBySlot: map[types.Slot]state.BeaconState{0: bs}}, + StateFetcher: &testutil.MockFetcher{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -278,9 +278,9 @@ func TestGetProposerDuties(t *testing.T) { } vid, _, has := vs.ProposerSlotIndexCache.GetProposerPayloadIDs(11, [32]byte{}) require.Equal(t, true, has) - require.Equal(t, types.ValidatorIndex(9982), vid) + require.Equal(t, primitives.ValidatorIndex(9982), vid) require.NotNil(t, expectedDuty, "Expected duty for slot 11 not found") - assert.Equal(t, types.ValidatorIndex(9982), expectedDuty.ValidatorIndex) + assert.Equal(t, primitives.ValidatorIndex(9982), expectedDuty.ValidatorIndex) assert.DeepEqual(t, pubKeys[9982], expectedDuty.Pubkey) }) @@ -288,12 +288,12 @@ func TestGetProposerDuties(t *testing.T) { bs, err := transition.GenesisBeaconState(context.Background(), deposits, 0, eth1Data) require.NoError(t, err, "Could not set up genesis state") require.NoError(t, bs.SetBlockRoots(roots)) - chainSlot := types.Slot(0) + chainSlot := primitives.Slot(0) chain := &mockChain.ChainService{ State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{StatesBySlot: map[types.Slot]state.BeaconState{0: bs}}, + StateFetcher: &testutil.MockFetcher{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -317,9 +317,9 @@ func TestGetProposerDuties(t *testing.T) { } vid, _, has := vs.ProposerSlotIndexCache.GetProposerPayloadIDs(43, [32]byte{}) require.Equal(t, true, has) - require.Equal(t, types.ValidatorIndex(4863), vid) + require.Equal(t, primitives.ValidatorIndex(4863), vid) require.NotNil(t, expectedDuty, "Expected duty for slot 43 not found") - assert.Equal(t, types.ValidatorIndex(4863), expectedDuty.ValidatorIndex) + assert.Equal(t, primitives.ValidatorIndex(4863), expectedDuty.ValidatorIndex) assert.DeepEqual(t, pubKeys[4863], expectedDuty.Pubkey) }) @@ -333,7 +333,7 @@ func TestGetProposerDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{StatesBySlot: map[types.Slot]state.BeaconState{params.BeaconConfig().SlotsPerEpoch: bs}}, + StateFetcher: &testutil.MockFetcher{StatesBySlot: map[primitives.Slot]state.BeaconState{params.BeaconConfig().SlotsPerEpoch: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -353,13 +353,13 @@ func TestGetProposerDuties(t *testing.T) { vid, _, has := vs.ProposerSlotIndexCache.GetProposerPayloadIDs(1, [32]byte{}) require.Equal(t, false, has) - require.Equal(t, types.ValidatorIndex(0), vid) + require.Equal(t, primitives.ValidatorIndex(0), vid) vid, _, has = vs.ProposerSlotIndexCache.GetProposerPayloadIDs(2, [32]byte{}) require.Equal(t, false, has) - require.Equal(t, types.ValidatorIndex(0), vid) + require.Equal(t, primitives.ValidatorIndex(0), vid) vid, _, has = vs.ProposerSlotIndexCache.GetProposerPayloadIDs(32, [32]byte{}) require.Equal(t, true, has) - require.Equal(t, types.ValidatorIndex(4309), vid) + require.Equal(t, primitives.ValidatorIndex(4309), vid) }) t.Run("Epoch out of bound", func(t *testing.T) { @@ -368,12 +368,12 @@ func TestGetProposerDuties(t *testing.T) { // Set state to non-epoch start slot. require.NoError(t, bs.SetSlot(5)) require.NoError(t, bs.SetBlockRoots(roots)) - chainSlot := types.Slot(0) + chainSlot := primitives.Slot(0) chain := &mockChain.ChainService{ State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{StatesBySlot: map[types.Slot]state.BeaconState{0: bs}}, + StateFetcher: &testutil.MockFetcher{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -405,12 +405,12 @@ func TestGetProposerDuties(t *testing.T) { util.SaveBlock(t, ctx, db, blk) require.NoError(t, db.SaveGenesisBlockRoot(ctx, root)) - chainSlot := types.Slot(0) + chainSlot := primitives.Slot(0) chain := &mockChain.ChainService{ State: bs, Root: genesisRoot[:], Slot: &chainSlot, Optimistic: true, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{StatesBySlot: map[types.Slot]state.BeaconState{0: bs}}, + StateFetcher: &testutil.MockFetcher{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -473,7 +473,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { t.Run("Single validator", func(t *testing.T) { req := ðpbv2.SyncCommitteeDutiesRequest{ Epoch: 0, - Index: []types.ValidatorIndex{1}, + Index: []primitives.ValidatorIndex{1}, } resp, err := vs.GetSyncCommitteeDuties(ctx, req) require.NoError(t, err) @@ -482,7 +482,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { require.Equal(t, 1, len(resp.Data)) duty := resp.Data[0] assert.DeepEqual(t, vals[1].PublicKey, duty.Pubkey) - assert.Equal(t, types.ValidatorIndex(1), duty.ValidatorIndex) + assert.Equal(t, primitives.ValidatorIndex(1), duty.ValidatorIndex) require.Equal(t, 1, len(duty.ValidatorSyncCommitteeIndices)) assert.Equal(t, uint64(1), duty.ValidatorSyncCommitteeIndices[0]) }) @@ -490,7 +490,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { t.Run("Epoch not at period start", func(t *testing.T) { req := ðpbv2.SyncCommitteeDutiesRequest{ Epoch: 1, - Index: []types.ValidatorIndex{1}, + Index: []primitives.ValidatorIndex{1}, } resp, err := vs.GetSyncCommitteeDuties(ctx, req) require.NoError(t, err) @@ -499,7 +499,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { require.Equal(t, 1, len(resp.Data)) duty := resp.Data[0] assert.DeepEqual(t, vals[1].PublicKey, duty.Pubkey) - assert.Equal(t, types.ValidatorIndex(1), duty.ValidatorIndex) + assert.Equal(t, primitives.ValidatorIndex(1), duty.ValidatorIndex) require.Equal(t, 1, len(duty.ValidatorSyncCommitteeIndices)) assert.Equal(t, uint64(1), duty.ValidatorSyncCommitteeIndices[0]) }) @@ -507,7 +507,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { t.Run("Multiple validators", func(t *testing.T) { req := ðpbv2.SyncCommitteeDutiesRequest{ Epoch: 0, - Index: []types.ValidatorIndex{1, 2}, + Index: []primitives.ValidatorIndex{1, 2}, } resp, err := vs.GetSyncCommitteeDuties(ctx, req) require.NoError(t, err) @@ -517,18 +517,18 @@ func TestGetSyncCommitteeDuties(t *testing.T) { t.Run("Validator without duty not returned", func(t *testing.T) { req := ðpbv2.SyncCommitteeDutiesRequest{ Epoch: 0, - Index: []types.ValidatorIndex{1, 10}, + Index: []primitives.ValidatorIndex{1, 10}, } resp, err := vs.GetSyncCommitteeDuties(ctx, req) require.NoError(t, err) require.Equal(t, 1, len(resp.Data)) - assert.Equal(t, types.ValidatorIndex(1), resp.Data[0].ValidatorIndex) + assert.Equal(t, primitives.ValidatorIndex(1), resp.Data[0].ValidatorIndex) }) t.Run("Multiple indices for validator", func(t *testing.T) { req := ðpbv2.SyncCommitteeDutiesRequest{ Epoch: 0, - Index: []types.ValidatorIndex{0}, + Index: []primitives.ValidatorIndex{0}, } resp, err := vs.GetSyncCommitteeDuties(ctx, req) require.NoError(t, err) @@ -540,7 +540,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { t.Run("Validator index out of bound", func(t *testing.T) { req := ðpbv2.SyncCommitteeDutiesRequest{ Epoch: 0, - Index: []types.ValidatorIndex{types.ValidatorIndex(numVals)}, + Index: []primitives.ValidatorIndex{primitives.ValidatorIndex(numVals)}, } _, err := vs.GetSyncCommitteeDuties(ctx, req) require.NotNil(t, err) @@ -550,7 +550,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { t.Run("next sync committee period", func(t *testing.T) { req := ðpbv2.SyncCommitteeDutiesRequest{ Epoch: params.BeaconConfig().EpochsPerSyncCommitteePeriod, - Index: []types.ValidatorIndex{5}, + Index: []primitives.ValidatorIndex{5}, } resp, err := vs.GetSyncCommitteeDuties(ctx, req) require.NoError(t, err) @@ -559,7 +559,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { require.Equal(t, 1, len(resp.Data)) duty := resp.Data[0] assert.DeepEqual(t, vals[5].PublicKey, duty.Pubkey) - assert.Equal(t, types.ValidatorIndex(5), duty.ValidatorIndex) + assert.Equal(t, primitives.ValidatorIndex(5), duty.ValidatorIndex) require.Equal(t, 1, len(duty.ValidatorSyncCommitteeIndices)) assert.Equal(t, uint64(0), duty.ValidatorSyncCommitteeIndices[0]) }) @@ -567,7 +567,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { t.Run("epoch too far in the future", func(t *testing.T) { req := ðpbv2.SyncCommitteeDutiesRequest{ Epoch: params.BeaconConfig().EpochsPerSyncCommitteePeriod * 2, - Index: []types.ValidatorIndex{5}, + Index: []primitives.ValidatorIndex{5}, } _, err := vs.GetSyncCommitteeDuties(ctx, req) require.NotNil(t, err) @@ -577,7 +577,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { t.Run("correct sync committee is fetched", func(t *testing.T) { // in this test we swap validators in the current and next sync committee inside the new state - newSyncPeriodStartSlot := types.Slot(uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod) * uint64(params.BeaconConfig().SlotsPerEpoch)) + newSyncPeriodStartSlot := primitives.Slot(uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod) * uint64(params.BeaconConfig().SlotsPerEpoch)) newSyncPeriodSt, _ := util.DeterministicGenesisStateAltair(t, numVals) require.NoError(t, newSyncPeriodSt.SetSlot(newSyncPeriodStartSlot)) require.NoError(t, newSyncPeriodSt.SetGenesisTime(uint64(genesisTime.Unix()))) @@ -593,7 +593,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { } require.NoError(t, newSyncPeriodSt.SetNextSyncCommittee(nextCommittee)) - stateFetchFn := func(slot types.Slot) state.BeaconState { + stateFetchFn := func(slot primitives.Slot) state.BeaconState { if slot < newSyncPeriodStartSlot { return st } else { @@ -611,7 +611,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { req := ðpbv2.SyncCommitteeDutiesRequest{ Epoch: params.BeaconConfig().EpochsPerSyncCommitteePeriod, - Index: []types.ValidatorIndex{8}, + Index: []primitives.ValidatorIndex{8}, } resp, err := vs.GetSyncCommitteeDuties(ctx, req) require.NoError(t, err) @@ -620,7 +620,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { require.Equal(t, 1, len(resp.Data)) duty := resp.Data[0] assert.DeepEqual(t, vals[8].PublicKey, duty.Pubkey) - assert.Equal(t, types.ValidatorIndex(8), duty.ValidatorIndex) + assert.Equal(t, primitives.ValidatorIndex(8), duty.ValidatorIndex) require.Equal(t, 1, len(duty.ValidatorSyncCommitteeIndices)) assert.Equal(t, uint64(3), duty.ValidatorSyncCommitteeIndices[0]) }) @@ -644,7 +644,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { } req := ðpbv2.SyncCommitteeDutiesRequest{ Epoch: 0, - Index: []types.ValidatorIndex{1}, + Index: []primitives.ValidatorIndex{1}, } resp, err := vs.GetSyncCommitteeDuties(ctx, req) require.NoError(t, err) @@ -706,7 +706,7 @@ func TestProduceBlockV2(t *testing.T) { } proposerSlashings := make([]*ethpbalpha.ProposerSlashing, params.BeaconConfig().MaxProposerSlashings) - for i := types.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { proposerSlashing, err := util.GenerateProposerSlashingForValidator( beaconState, privKeys[i], @@ -723,7 +723,7 @@ func TestProduceBlockV2(t *testing.T) { attesterSlashing, err := util.GenerateAttesterSlashingForValidator( beaconState, privKeys[i+params.BeaconConfig().MaxProposerSlashings], - types.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */ + primitives.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */ ) require.NoError(t, err) attSlashings[i] = attesterSlashing @@ -776,7 +776,7 @@ func TestProduceBlockV2(t *testing.T) { params.SetupTestConfigCleanup(t) bc := params.BeaconConfig().Copy() - bc.AltairForkEpoch = types.Epoch(0) + bc.AltairForkEpoch = primitives.Epoch(0) params.OverrideBeaconConfig(bc) beaconState, privKeys := util.DeterministicGenesisStateAltair(t, params.BeaconConfig().SyncCommitteeSize) @@ -817,7 +817,7 @@ func TestProduceBlockV2(t *testing.T) { } proposerSlashings := make([]*ethpbalpha.ProposerSlashing, params.BeaconConfig().MaxProposerSlashings) - for i := types.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { proposerSlashing, err := util.GenerateProposerSlashingForValidator( beaconState, privKeys[i], @@ -834,7 +834,7 @@ func TestProduceBlockV2(t *testing.T) { attesterSlashing, err := util.GenerateAttesterSlashingForValidator( beaconState, privKeys[i+params.BeaconConfig().MaxProposerSlashings], - types.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */ + primitives.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */ ) require.NoError(t, err) attSlashings[i] = attesterSlashing @@ -923,8 +923,8 @@ func TestProduceBlockV2(t *testing.T) { params.SetupTestConfigCleanup(t) bc := params.BeaconConfig().Copy() - bc.AltairForkEpoch = types.Epoch(0) - bc.BellatrixForkEpoch = types.Epoch(1) + bc.AltairForkEpoch = primitives.Epoch(0) + bc.BellatrixForkEpoch = primitives.Epoch(1) params.OverrideBeaconConfig(bc) beaconState, privKeys := util.DeterministicGenesisStateBellatrix(t, params.BeaconConfig().SyncCommitteeSize) @@ -1018,7 +1018,7 @@ func TestProduceBlockV2(t *testing.T) { } proposerSlashings := make([]*ethpbalpha.ProposerSlashing, params.BeaconConfig().MaxProposerSlashings) - for i := types.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { proposerSlashing, err := util.GenerateProposerSlashingForValidator( beaconState, privKeys[i], @@ -1035,7 +1035,7 @@ func TestProduceBlockV2(t *testing.T) { attesterSlashing, err := util.GenerateAttesterSlashingForValidator( beaconState, privKeys[i+params.BeaconConfig().MaxProposerSlashings], - types.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */ + primitives.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */ ) require.NoError(t, err) attSlashings[i] = attesterSlashing @@ -1084,7 +1084,7 @@ func TestProduceBlockV2(t *testing.T) { Graffiti: graffiti[:], } v1Server.V1Alpha1Server.BeaconDB = db - require.NoError(t, v1Alpha1Server.BeaconDB.SaveRegistrationsByValidatorIDs(ctx, []types.ValidatorIndex{348}, + require.NoError(t, v1Alpha1Server.BeaconDB.SaveRegistrationsByValidatorIDs(ctx, []primitives.ValidatorIndex{348}, []*ethpbalpha.ValidatorRegistrationV1{{FeeRecipient: bytesutil.PadTo([]byte{}, fieldparams.FeeRecipientLength), Pubkey: bytesutil.PadTo([]byte{}, fieldparams.BLSPubkeyLength)}})) resp, err := v1Server.ProduceBlockV2(ctx, req) @@ -1273,7 +1273,7 @@ func TestProduceBlockV2SSZ(t *testing.T) { params.SetupTestConfigCleanup(t) bc := params.BeaconConfig() - bc.AltairForkEpoch = types.Epoch(0) + bc.AltairForkEpoch = primitives.Epoch(0) params.OverrideBeaconConfig(bc) bs, privKeys := util.DeterministicGenesisStateAltair(t, params.BeaconConfig().SyncCommitteeSize) @@ -1468,8 +1468,8 @@ func TestProduceBlockV2SSZ(t *testing.T) { params.SetupTestConfigCleanup(t) bc := params.BeaconConfig() - bc.AltairForkEpoch = types.Epoch(0) - bc.BellatrixForkEpoch = types.Epoch(1) + bc.AltairForkEpoch = primitives.Epoch(0) + bc.BellatrixForkEpoch = primitives.Epoch(1) params.OverrideBeaconConfig(bc) bs, privKeys := util.DeterministicGenesisStateBellatrix(t, params.BeaconConfig().SyncCommitteeSize) @@ -1581,7 +1581,7 @@ func TestProduceBlockV2SSZ(t *testing.T) { Graffiti: graffiti[:], } v1Server.V1Alpha1Server.BeaconDB = db - require.NoError(t, v1Alpha1Server.BeaconDB.SaveRegistrationsByValidatorIDs(ctx, []types.ValidatorIndex{348}, + require.NoError(t, v1Alpha1Server.BeaconDB.SaveRegistrationsByValidatorIDs(ctx, []primitives.ValidatorIndex{348}, []*ethpbalpha.ValidatorRegistrationV1{{FeeRecipient: bytesutil.PadTo([]byte{}, fieldparams.FeeRecipientLength), Pubkey: bytesutil.PadTo([]byte{}, fieldparams.BLSPubkeyLength)}})) resp, err := v1Server.ProduceBlockV2SSZ(ctx, req) @@ -1738,7 +1738,7 @@ func TestProduceBlindedBlock(t *testing.T) { } proposerSlashings := make([]*ethpbalpha.ProposerSlashing, params.BeaconConfig().MaxProposerSlashings) - for i := types.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { proposerSlashing, err := util.GenerateProposerSlashingForValidator( beaconState, privKeys[i], @@ -1755,7 +1755,7 @@ func TestProduceBlindedBlock(t *testing.T) { attesterSlashing, err := util.GenerateAttesterSlashingForValidator( beaconState, privKeys[i+params.BeaconConfig().MaxProposerSlashings], - types.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */ + primitives.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */ ) require.NoError(t, err) attSlashings[i] = attesterSlashing @@ -1806,7 +1806,7 @@ func TestProduceBlindedBlock(t *testing.T) { params.SetupTestConfigCleanup(t) bc := params.BeaconConfig().Copy() - bc.AltairForkEpoch = types.Epoch(0) + bc.AltairForkEpoch = primitives.Epoch(0) params.OverrideBeaconConfig(bc) beaconState, privKeys := util.DeterministicGenesisStateAltair(t, params.BeaconConfig().SyncCommitteeSize) @@ -1843,7 +1843,7 @@ func TestProduceBlindedBlock(t *testing.T) { } proposerSlashings := make([]*ethpbalpha.ProposerSlashing, params.BeaconConfig().MaxProposerSlashings) - for i := types.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { proposerSlashing, err := util.GenerateProposerSlashingForValidator( beaconState, privKeys[i], @@ -1860,7 +1860,7 @@ func TestProduceBlindedBlock(t *testing.T) { attesterSlashing, err := util.GenerateAttesterSlashingForValidator( beaconState, privKeys[i+params.BeaconConfig().MaxProposerSlashings], - types.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */ + primitives.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */ ) require.NoError(t, err) attSlashings[i] = attesterSlashing @@ -1946,8 +1946,8 @@ func TestProduceBlindedBlock(t *testing.T) { params.SetupTestConfigCleanup(t) bc := params.BeaconConfig().Copy() - bc.AltairForkEpoch = types.Epoch(0) - bc.BellatrixForkEpoch = types.Epoch(1) + bc.AltairForkEpoch = primitives.Epoch(0) + bc.BellatrixForkEpoch = primitives.Epoch(1) bc.MaxBuilderConsecutiveMissedSlots = params.BeaconConfig().SlotsPerEpoch + 1 bc.MaxBuilderEpochMissedSlots = params.BeaconConfig().SlotsPerEpoch params.OverrideBeaconConfig(bc) @@ -2046,7 +2046,7 @@ func TestProduceBlindedBlock(t *testing.T) { } proposerSlashings := make([]*ethpbalpha.ProposerSlashing, params.BeaconConfig().MaxProposerSlashings) - for i := types.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { proposerSlashing, err := util.GenerateProposerSlashingForValidator( beaconState, privKeys[i], @@ -2063,7 +2063,7 @@ func TestProduceBlindedBlock(t *testing.T) { attesterSlashing, err := util.GenerateAttesterSlashingForValidator( beaconState, privKeys[i+params.BeaconConfig().MaxProposerSlashings], - types.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */ + primitives.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), /* validator index */ ) require.NoError(t, err) attSlashings[i] = attesterSlashing @@ -2114,7 +2114,7 @@ func TestProduceBlindedBlock(t *testing.T) { idx, err := helpers.BeaconProposerIndex(ctx, copied) require.NoError(t, err) require.NoError(t, - db.SaveRegistrationsByValidatorIDs(ctx, []types.ValidatorIndex{idx}, + db.SaveRegistrationsByValidatorIDs(ctx, []primitives.ValidatorIndex{idx}, []*ethpbalpha.ValidatorRegistrationV1{{FeeRecipient: make([]byte, 20), Pubkey: make([]byte, 48)}})) req := ðpbv1.ProduceBlockRequest{ @@ -2303,7 +2303,7 @@ func TestProduceBlindedBlockSSZ(t *testing.T) { params.SetupTestConfigCleanup(t) bc := params.BeaconConfig() - bc.AltairForkEpoch = types.Epoch(0) + bc.AltairForkEpoch = primitives.Epoch(0) params.OverrideBeaconConfig(bc) bs, privKeys := util.DeterministicGenesisStateAltair(t, params.BeaconConfig().SyncCommitteeSize) @@ -2498,8 +2498,8 @@ func TestProduceBlindedBlockSSZ(t *testing.T) { params.SetupTestConfigCleanup(t) bc := params.BeaconConfig() - bc.AltairForkEpoch = types.Epoch(0) - bc.BellatrixForkEpoch = types.Epoch(1) + bc.AltairForkEpoch = primitives.Epoch(0) + bc.BellatrixForkEpoch = primitives.Epoch(1) params.OverrideBeaconConfig(bc) bs, privKeys := util.DeterministicGenesisStateBellatrix(t, params.BeaconConfig().SyncCommitteeSize) @@ -2914,14 +2914,14 @@ func TestGetAggregateAttestation(t *testing.T) { require.NotNil(t, att.Data) assert.DeepEqual(t, bitfield.Bitlist{0, 1, 1, 1}, att.Data.AggregationBits) assert.DeepEqual(t, sig22, att.Data.Signature) - assert.Equal(t, types.Slot(2), att.Data.Data.Slot) - assert.Equal(t, types.CommitteeIndex(3), att.Data.Data.Index) + assert.Equal(t, primitives.Slot(2), att.Data.Data.Slot) + assert.Equal(t, primitives.CommitteeIndex(3), att.Data.Data.Index) assert.DeepEqual(t, root22, att.Data.Data.BeaconBlockRoot) require.NotNil(t, att.Data.Data.Source) - assert.Equal(t, types.Epoch(1), att.Data.Data.Source.Epoch) + assert.Equal(t, primitives.Epoch(1), att.Data.Data.Source.Epoch) assert.DeepEqual(t, root22, att.Data.Data.Source.Root) require.NotNil(t, att.Data.Data.Target) - assert.Equal(t, types.Epoch(1), att.Data.Data.Target.Epoch) + assert.Equal(t, primitives.Epoch(1), att.Data.Data.Target.Epoch) assert.DeepEqual(t, root22, att.Data.Data.Target.Root) }) @@ -3032,7 +3032,7 @@ func TestSubmitBeaconCommitteeSubscription(t *testing.T) { pubKeys[i] = deposits[i].Data.PublicKey } - chainSlot := types.Slot(0) + chainSlot := primitives.Slot(0) chain := &mockChain.ChainService{ State: bs, Root: genesisRoot[:], Slot: &chainSlot, } @@ -3100,7 +3100,7 @@ func TestSubmitBeaconCommitteeSubscription(t *testing.T) { } _, err = vs.SubmitBeaconCommitteeSubscription(ctx, req) require.NoError(t, err) - ids := cache.SubnetIDs.GetAggregatorSubnetIDs(types.Slot(1)) + ids := cache.SubnetIDs.GetAggregatorSubnetIDs(primitives.Slot(1)) assert.Equal(t, 1, len(ids)) }) @@ -3176,7 +3176,7 @@ func TestSubmitSyncCommitteeSubscription(t *testing.T) { pubkeys[i] = deposits[i].Data.PublicKey } - chainSlot := types.Slot(0) + chainSlot := primitives.Slot(0) chain := &mockChain.ChainService{ State: bs, Root: genesisRoot[:], Slot: &chainSlot, } @@ -3343,7 +3343,7 @@ func TestSubmitAggregateAndProofs(t *testing.T) { } t.Run("OK", func(t *testing.T) { - chainSlot := types.Slot(0) + chainSlot := primitives.Slot(0) chain := &mockChain.ChainService{ Genesis: time.Now(), Slot: &chainSlot, } @@ -3565,7 +3565,7 @@ func TestSubmitAggregateAndProofs(t *testing.T) { }) t.Run("invalid attestation time", func(t *testing.T) { - chainSlot := types.Slot(0) + chainSlot := primitives.Slot(0) chain := &mockChain.ChainService{ Genesis: time.Now().Add(time.Hour * 2), Slot: &chainSlot, } @@ -3610,7 +3610,7 @@ func TestProduceSyncCommitteeContribution(t *testing.T) { v1Server := &v1alpha1validator.Server{ SyncCommitteePool: syncCommitteePool, HeadFetcher: &mockChain.ChainService{ - SyncCommitteeIndices: []types.CommitteeIndex{0}, + SyncCommitteeIndices: []primitives.CommitteeIndex{0}, }, } server := Server{ @@ -3625,7 +3625,7 @@ func TestProduceSyncCommitteeContribution(t *testing.T) { } resp, err := server.ProduceSyncCommitteeContribution(ctx, req) require.NoError(t, err) - assert.Equal(t, types.Slot(0), resp.Data.Slot) + assert.Equal(t, primitives.Slot(0), resp.Data.Slot) assert.Equal(t, uint64(0), resp.Data.SubcommitteeIndex) assert.DeepEqual(t, root, resp.Data.BeaconBlockRoot) aggregationBits := resp.Data.AggregationBits @@ -3636,7 +3636,7 @@ func TestProduceSyncCommitteeContribution(t *testing.T) { v1Server = &v1alpha1validator.Server{ SyncCommitteePool: syncCommitteePool, HeadFetcher: &mockChain.ChainService{ - SyncCommitteeIndices: []types.CommitteeIndex{0}, + SyncCommitteeIndices: []primitives.CommitteeIndex{0}, }, } server = Server{ @@ -3824,7 +3824,7 @@ func TestPrepareBeaconProposer(t *testing.T) { address, err := server.V1Alpha1Server.BeaconDB.FeeRecipientByValidatorID(ctx, 1) require.NoError(t, err) require.Equal(t, common.BytesToAddress(tt.args.request.Recipients[0].FeeRecipient), address) - indexs := make([]types.ValidatorIndex, len(tt.args.request.Recipients)) + indexs := make([]primitives.ValidatorIndex, len(tt.args.request.Recipients)) for i, recipient := range tt.args.request.Recipients { indexs[i] = recipient.ValidatorIndex } @@ -3901,7 +3901,7 @@ func BenchmarkServer_PrepareBeaconProposer(b *testing.B) { f := bytesutil.PadTo([]byte{0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF}, fieldparams.FeeRecipientLength) recipients := make([]*ethpbv1.PrepareBeaconProposerRequest_FeeRecipientContainer, 0) for i := 0; i < 10000; i++ { - recipients = append(recipients, ðpbv1.PrepareBeaconProposerRequest_FeeRecipientContainer{FeeRecipient: f, ValidatorIndex: types.ValidatorIndex(i)}) + recipients = append(recipients, ðpbv1.PrepareBeaconProposerRequest_FeeRecipientContainer{FeeRecipient: f, ValidatorIndex: primitives.ValidatorIndex(i)}) } req := ðpbv1.PrepareBeaconProposerRequest{ @@ -4000,7 +4000,7 @@ func TestGetLiveness(t *testing.T) { HeadFetcher: &mockChain.ChainService{State: headSt}, StateFetcher: &testutil.MockFetcher{ // We configure states for last slots of an epoch - StatesBySlot: map[types.Slot]state.BeaconState{ + StatesBySlot: map[primitives.Slot]state.BeaconState{ params.BeaconConfig().SlotsPerEpoch - 1: oldSt, params.BeaconConfig().SlotsPerEpoch*3 - 1: headSt, }, @@ -4010,7 +4010,7 @@ func TestGetLiveness(t *testing.T) { t.Run("old epoch", func(t *testing.T) { resp, err := server.GetLiveness(ctx, ðpbv2.GetLivenessRequest{ Epoch: 0, - Index: []types.ValidatorIndex{0, 1}, + Index: []primitives.ValidatorIndex{0, 1}, }) require.NoError(t, err) data0 := resp.Data[0] @@ -4021,7 +4021,7 @@ func TestGetLiveness(t *testing.T) { t.Run("previous epoch", func(t *testing.T) { resp, err := server.GetLiveness(ctx, ðpbv2.GetLivenessRequest{ Epoch: 1, - Index: []types.ValidatorIndex{0, 1}, + Index: []primitives.ValidatorIndex{0, 1}, }) require.NoError(t, err) data0 := resp.Data[0] @@ -4032,7 +4032,7 @@ func TestGetLiveness(t *testing.T) { t.Run("current epoch", func(t *testing.T) { resp, err := server.GetLiveness(ctx, ðpbv2.GetLivenessRequest{ Epoch: 2, - Index: []types.ValidatorIndex{0, 1}, + Index: []primitives.ValidatorIndex{0, 1}, }) require.NoError(t, err) data0 := resp.Data[0] @@ -4043,14 +4043,14 @@ func TestGetLiveness(t *testing.T) { t.Run("future epoch", func(t *testing.T) { _, err := server.GetLiveness(ctx, ðpbv2.GetLivenessRequest{ Epoch: 3, - Index: []types.ValidatorIndex{0, 1}, + Index: []primitives.ValidatorIndex{0, 1}, }) require.ErrorContains(t, "Requested epoch cannot be in the future", err) }) t.Run("unknown validator index", func(t *testing.T) { _, err := server.GetLiveness(ctx, ðpbv2.GetLivenessRequest{ Epoch: 0, - Index: []types.ValidatorIndex{0, 1, 2}, + Index: []primitives.ValidatorIndex{0, 1, 2}, }) require.ErrorContains(t, "Validator index 2 is invalid", err) }) diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments.go index a4574e9778..bf370f5d4e 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/api/pagination" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/v3/cmd" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -33,9 +33,9 @@ func (bs *Server) ListValidatorAssignments( } var res []*ethpb.ValidatorAssignments_CommitteeAssignment - filtered := map[types.ValidatorIndex]bool{} // track filtered validators to prevent duplication in the response. - filteredIndices := make([]types.ValidatorIndex, 0) - var requestedEpoch types.Epoch + filtered := map[primitives.ValidatorIndex]bool{} // track filtered validators to prevent duplication in the response. + filteredIndices := make([]primitives.ValidatorIndex, 0) + var requestedEpoch primitives.Epoch switch q := req.QueryFilter.(type) { case *ethpb.ListValidatorAssignmentsRequest_Genesis: if q.Genesis { diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments_test.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments_test.go index 8748c7462c..f132091d53 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/assignments_test.go @@ -15,7 +15,7 @@ import ( mockstategen "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen/mock" "github.com/prysmaticlabs/prysm/v3/cmd" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -274,7 +274,7 @@ func TestServer_ListAssignments_FilterPubkeysIndices_NoPagination(t *testing.T) binary.LittleEndian.PutUint64(pubKey1, 1) pubKey2 := make([]byte, params.BeaconConfig().BLSPubkeyLength) binary.LittleEndian.PutUint64(pubKey2, 2) - req := ðpb.ListValidatorAssignmentsRequest{PublicKeys: [][]byte{pubKey1, pubKey2}, Indices: []types.ValidatorIndex{2, 3}} + req := ðpb.ListValidatorAssignmentsRequest{PublicKeys: [][]byte{pubKey1, pubKey2}, Indices: []primitives.ValidatorIndex{2, 3}} res, err := bs.ListValidatorAssignments(context.Background(), req) require.NoError(t, err) @@ -342,7 +342,7 @@ func TestServer_ListAssignments_CanFilterPubkeysIndices_WithPagination(t *testin addDefaultReplayerBuilder(bs, db) - req := ðpb.ListValidatorAssignmentsRequest{Indices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}, PageSize: 2, PageToken: "1"} + req := ðpb.ListValidatorAssignmentsRequest{Indices: []primitives.ValidatorIndex{1, 2, 3, 4, 5, 6}, PageSize: 2, PageToken: "1"} res, err := bs.ListValidatorAssignments(context.Background(), req) require.NoError(t, err) @@ -376,7 +376,7 @@ func TestServer_ListAssignments_CanFilterPubkeysIndices_WithPagination(t *testin // Test the wrap around scenario. assignments = nil - req = ðpb.ListValidatorAssignmentsRequest{Indices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}, PageSize: 5, PageToken: "1"} + req = ðpb.ListValidatorAssignmentsRequest{Indices: []primitives.ValidatorIndex{1, 2, 3, 4, 5, 6}, PageSize: 5, PageToken: "1"} res, err = bs.ListValidatorAssignments(context.Background(), req) require.NoError(t, err) cAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(context.Background(), s, 0) diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/attestations_test.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/attestations_test.go index b4fc67ea95..80d6c36cf6 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/attestations_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/attestations_test.go @@ -25,7 +25,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/attestation" @@ -117,9 +117,9 @@ func TestServer_ListAttestations_NoPagination(t *testing.T) { db := dbTest.SetupDB(t) ctx := context.Background() - count := types.Slot(8) + count := primitives.Slot(8) atts := make([]*ethpb.Attestation, 0, count) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { blockExample := util.NewBeaconBlock() blockExample.Block.Body.Attestations = []*ethpb.Attestation{ { @@ -156,9 +156,9 @@ func TestServer_ListAttestations_FiltersCorrectly(t *testing.T) { someRoot := [32]byte{1, 2, 3} sourceRoot := [32]byte{4, 5, 6} - sourceEpoch := types.Epoch(5) + sourceEpoch := primitives.Epoch(5) targetRoot := [32]byte{7, 8, 9} - targetEpoch := types.Epoch(7) + targetEpoch := primitives.Epoch(7) unwrappedBlocks := []*ethpb.SignedBeaconBlock{ util.HydrateSignedBeaconBlock( @@ -271,8 +271,8 @@ func TestServer_ListAttestations_Pagination_CustomPageParameters(t *testing.T) { count := params.BeaconConfig().SlotsPerEpoch * 4 atts := make([]*ethpb.Attestation, 0, count) - for i := types.Slot(0); i < params.BeaconConfig().SlotsPerEpoch; i++ { - for s := types.CommitteeIndex(0); s < 4; s++ { + for i := primitives.Slot(0); i < params.BeaconConfig().SlotsPerEpoch; i++ { + for s := primitives.CommitteeIndex(0); s < 4; s++ { blockExample := util.NewBeaconBlock() blockExample.Block.Slot = i blockExample.Block.Body.Attestations = []*ethpb.Attestation{ @@ -372,9 +372,9 @@ func TestServer_ListAttestations_Pagination_OutOfRange(t *testing.T) { db := dbTest.SetupDB(t) ctx := context.Background() util.NewBeaconBlock() - count := types.Slot(1) + count := primitives.Slot(1) atts := make([]*ethpb.Attestation, 0, count) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { blockExample := util.HydrateSignedBeaconBlock(ðpb.SignedBeaconBlock{ Block: ðpb.BeaconBlock{ Body: ðpb.BeaconBlockBody{ @@ -428,9 +428,9 @@ func TestServer_ListAttestations_Pagination_DefaultPageSize(t *testing.T) { db := dbTest.SetupDB(t) ctx := context.Background() - count := types.Slot(params.BeaconConfig().DefaultPageSize) + count := primitives.Slot(params.BeaconConfig().DefaultPageSize) atts := make([]*ethpb.Attestation, 0, count) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { blockExample := util.NewBeaconBlock() blockExample.Block.Body.Attestations = []*ethpb.Attestation{ { @@ -466,12 +466,12 @@ func TestServer_ListAttestations_Pagination_DefaultPageSize(t *testing.T) { } func TestServer_mapAttestationToTargetRoot(t *testing.T) { - count := types.Slot(100) + count := primitives.Slot(100) atts := make([]*ethpb.Attestation, count) targetRoot1 := bytesutil.ToBytes32([]byte("root1")) targetRoot2 := bytesutil.ToBytes32([]byte("root2")) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { var targetRoot [32]byte if i%2 == 0 { targetRoot = targetRoot1 @@ -509,7 +509,7 @@ func TestServer_ListIndexedAttestations_GenesisEpoch(t *testing.T) { atts := make([]*ethpb.Attestation, 0, count) atts2 := make([]*ethpb.Attestation, 0, count) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { var targetRoot [32]byte if i%2 == 0 { targetRoot = targetRoot1 @@ -614,7 +614,7 @@ func TestServer_ListIndexedAttestations_OldEpoch(t *testing.T) { blockRoot := bytesutil.ToBytes32([]byte("root")) count := params.BeaconConfig().SlotsPerEpoch atts := make([]*ethpb.Attestation, 0, count) - epoch := types.Epoch(50) + epoch := primitives.Epoch(50) startSlot, err := slots.EpochStart(epoch) require.NoError(t, err) @@ -756,7 +756,7 @@ func TestServer_AttestationPool_Pagination_DefaultPageSize(t *testing.T) { atts := make([]*ethpb.Attestation, params.BeaconConfig().DefaultPageSize+1) for i := 0; i < len(atts); i++ { att := util.NewAttestation() - att.Data.Slot = types.Slot(i) + att.Data.Slot = primitives.Slot(i) atts[i] = att } require.NoError(t, bs.AttestationsPool.SaveAggregatedAttestations(atts)) @@ -778,7 +778,7 @@ func TestServer_AttestationPool_Pagination_CustomPageSize(t *testing.T) { atts := make([]*ethpb.Attestation, numAtts) for i := 0; i < len(atts); i++ { att := util.NewAttestation() - att.Data.Slot = types.Slot(i) + att.Data.Slot = primitives.Slot(i) atts[i] = att } require.NoError(t, bs.AttestationsPool.SaveAggregatedAttestations(atts)) @@ -871,7 +871,7 @@ func TestServer_StreamIndexedAttestations_OK(t *testing.T) { activeIndices, err := helpers.ActiveValidatorIndices(ctx, headState, 0) require.NoError(t, err) - epoch := types.Epoch(0) + epoch := primitives.Epoch(0) attesterSeed, err := helpers.Seed(headState, epoch, params.BeaconConfig().DomainBeaconAttester) require.NoError(t, err) committees, err := computeCommittees(context.Background(), params.BeaconConfig().SlotsPerEpoch.Mul(uint64(epoch)), activeIndices, attesterSeed) @@ -880,18 +880,18 @@ func TestServer_StreamIndexedAttestations_OK(t *testing.T) { count := params.BeaconConfig().SlotsPerEpoch // We generate attestations for each validator per slot per epoch. atts := make(map[[32]byte][]*ethpb.Attestation) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { comms := committees[i].Committees for j := 0; j < numValidators; j++ { var indexInCommittee uint64 - var committeeIndex types.CommitteeIndex + var committeeIndex primitives.CommitteeIndex var committeeLength int var found bool for comIndex, item := range comms { for n, idx := range item.ValidatorIndices { - if types.ValidatorIndex(j) == idx { + if primitives.ValidatorIndex(j) == idx { indexInCommittee = uint64(n) - committeeIndex = types.CommitteeIndex(comIndex) + committeeIndex = primitives.CommitteeIndex(comIndex) committeeLength = len(item.ValidatorIndices) found = true break diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/blocks_test.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/blocks_test.go index be29de70bc..3d5c893066 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/blocks_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/blocks_test.go @@ -18,7 +18,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -189,12 +189,12 @@ func TestServer_GetChainHead(t *testing.T) { head, err := bs.GetChainHead(context.Background(), nil) require.NoError(t, err) - 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, types.Slot(24), head.PreviousJustifiedSlot, "Unexpected PreviousJustifiedSlot") - assert.Equal(t, types.Slot(16), head.JustifiedSlot, "Unexpected JustifiedSlot") - assert.Equal(t, types.Slot(8), head.FinalizedSlot, "Unexpected FinalizedSlot") + assert.Equal(t, primitives.Epoch(3), head.PreviousJustifiedEpoch, "Unexpected PreviousJustifiedEpoch") + assert.Equal(t, primitives.Epoch(2), head.JustifiedEpoch, "Unexpected JustifiedEpoch") + assert.Equal(t, primitives.Epoch(1), head.FinalizedEpoch, "Unexpected FinalizedEpoch") + assert.Equal(t, primitives.Slot(24), head.PreviousJustifiedSlot, "Unexpected PreviousJustifiedSlot") + assert.Equal(t, primitives.Slot(16), head.JustifiedSlot, "Unexpected JustifiedSlot") + assert.Equal(t, primitives.Slot(8), head.FinalizedSlot, "Unexpected FinalizedSlot") assert.DeepEqual(t, pjRoot[:], head.PreviousJustifiedBlockRoot, "Unexpected PreviousJustifiedBlockRoot") assert.DeepEqual(t, jRoot[:], head.JustifiedBlockRoot, "Unexpected JustifiedBlockRoot") assert.DeepEqual(t, fRoot[:], head.FinalizedBlockRoot, "Unexpected FinalizedBlockRoot") @@ -605,7 +605,7 @@ func TestServer_ListBeaconBlocks_Genesis_MultiBlocks(t *testing.T) { parentRoot := [32]byte{1, 2, 3} blk := util.NewBeaconBlock() blk.Block.ParentRoot = parentRoot[:] - blockCreator := func(i types.Slot) interfaces.SignedBeaconBlock { + blockCreator := func(i primitives.Slot) interfaces.SignedBeaconBlock { b := util.NewBeaconBlock() b.Block.Slot = i wrappedB, err := blocks.NewSignedBeaconBlock(b) @@ -620,7 +620,7 @@ func TestServer_ListBeaconBlocks_Genesis_MultiBlocks(t *testing.T) { parentRoot := [32]byte{1, 2, 3} blk := util.NewBeaconBlockAltair() blk.Block.ParentRoot = parentRoot[:] - blockCreator := func(i types.Slot) interfaces.SignedBeaconBlock { + blockCreator := func(i primitives.Slot) interfaces.SignedBeaconBlock { b := util.NewBeaconBlockAltair() b.Block.Slot = i wrappedB, err := blocks.NewSignedBeaconBlock(b) @@ -635,7 +635,7 @@ func TestServer_ListBeaconBlocks_Genesis_MultiBlocks(t *testing.T) { parentRoot := [32]byte{1, 2, 3} blk := util.NewBeaconBlockBellatrix() blk.Block.ParentRoot = parentRoot[:] - blockCreator := func(i types.Slot) interfaces.SignedBeaconBlock { + blockCreator := func(i primitives.Slot) interfaces.SignedBeaconBlock { b := util.NewBeaconBlockBellatrix() b.Block.Slot = i wrappedB, err := blocks.NewSignedBeaconBlock(b) @@ -650,7 +650,7 @@ func TestServer_ListBeaconBlocks_Genesis_MultiBlocks(t *testing.T) { parentRoot := [32]byte{1, 2, 3} blk := util.NewBeaconBlockCapella() blk.Block.ParentRoot = parentRoot[:] - blockCreator := func(i types.Slot) interfaces.SignedBeaconBlock { + blockCreator := func(i primitives.Slot) interfaces.SignedBeaconBlock { b := util.NewBeaconBlockCapella() b.Block.Slot = i wrappedB, err := blocks.NewSignedBeaconBlock(b) @@ -664,7 +664,7 @@ func TestServer_ListBeaconBlocks_Genesis_MultiBlocks(t *testing.T) { } func runListBeaconBlocksGenesisMultiBlocks(t *testing.T, genBlock interfaces.SignedBeaconBlock, - blockCreator func(i types.Slot) interfaces.SignedBeaconBlock) { + blockCreator func(i primitives.Slot) interfaces.SignedBeaconBlock) { db := dbTest.SetupDB(t) ctx := context.Background() @@ -677,9 +677,9 @@ func runListBeaconBlocksGenesisMultiBlocks(t *testing.T, genBlock interfaces.Sig require.NoError(t, db.SaveBlock(ctx, genBlock)) require.NoError(t, db.SaveGenesisBlockRoot(ctx, root)) - count := types.Slot(100) + count := primitives.Slot(100) blks := make([]interfaces.SignedBeaconBlock, count) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { blks[i] = blockCreator(i) } require.NoError(t, db.SaveBlocks(ctx, blks)) @@ -699,14 +699,14 @@ func TestServer_ListBeaconBlocks_Pagination(t *testing.T) { t.Run("phase 0 block", func(t *testing.T) { blk := util.NewBeaconBlock() blk.Block.Slot = 300 - blockCreator := func(i types.Slot) interfaces.SignedBeaconBlock { + blockCreator := func(i primitives.Slot) interfaces.SignedBeaconBlock { b := util.NewBeaconBlock() b.Block.Slot = i wrappedB, err := blocks.NewSignedBeaconBlock(b) assert.NoError(t, err) return wrappedB } - containerCreator := func(i types.Slot, root []byte, canonical bool) *ethpb.BeaconBlockContainer { + containerCreator := func(i primitives.Slot, root []byte, canonical bool) *ethpb.BeaconBlockContainer { b := util.NewBeaconBlock() b.Block.Slot = i ctr := ðpb.BeaconBlockContainer{ @@ -723,14 +723,14 @@ func TestServer_ListBeaconBlocks_Pagination(t *testing.T) { t.Run("altair block", func(t *testing.T) { blk := util.NewBeaconBlockAltair() blk.Block.Slot = 300 - blockCreator := func(i types.Slot) interfaces.SignedBeaconBlock { + blockCreator := func(i primitives.Slot) interfaces.SignedBeaconBlock { b := util.NewBeaconBlockAltair() b.Block.Slot = i wrappedB, err := blocks.NewSignedBeaconBlock(b) assert.NoError(t, err) return wrappedB } - containerCreator := func(i types.Slot, root []byte, canonical bool) *ethpb.BeaconBlockContainer { + containerCreator := func(i primitives.Slot, root []byte, canonical bool) *ethpb.BeaconBlockContainer { b := util.NewBeaconBlockAltair() b.Block.Slot = i ctr := ðpb.BeaconBlockContainer{ @@ -747,14 +747,14 @@ func TestServer_ListBeaconBlocks_Pagination(t *testing.T) { t.Run("bellatrix block", func(t *testing.T) { blk := util.NewBeaconBlockBellatrix() blk.Block.Slot = 300 - blockCreator := func(i types.Slot) interfaces.SignedBeaconBlock { + blockCreator := func(i primitives.Slot) interfaces.SignedBeaconBlock { b := util.NewBeaconBlockBellatrix() b.Block.Slot = i wrappedB, err := blocks.NewSignedBeaconBlock(b) assert.NoError(t, err) return wrappedB } - containerCreator := func(i types.Slot, root []byte, canonical bool) *ethpb.BeaconBlockContainer { + containerCreator := func(i primitives.Slot, root []byte, canonical bool) *ethpb.BeaconBlockContainer { b := util.NewBeaconBlockBellatrix() b.Block.Slot = i ctr := ðpb.BeaconBlockContainer{ @@ -771,14 +771,14 @@ func TestServer_ListBeaconBlocks_Pagination(t *testing.T) { t.Run("capella block", func(t *testing.T) { blk := util.NewBeaconBlockCapella() blk.Block.Slot = 300 - blockCreator := func(i types.Slot) interfaces.SignedBeaconBlock { + blockCreator := func(i primitives.Slot) interfaces.SignedBeaconBlock { b := util.NewBeaconBlockCapella() b.Block.Slot = i wrappedB, err := blocks.NewSignedBeaconBlock(b) assert.NoError(t, err) return wrappedB } - containerCreator := func(i types.Slot, root []byte, canonical bool) *ethpb.BeaconBlockContainer { + containerCreator := func(i primitives.Slot, root []byte, canonical bool) *ethpb.BeaconBlockContainer { b := util.NewBeaconBlockCapella() b.Block.Slot = i ctr := ðpb.BeaconBlockContainer{ @@ -795,7 +795,7 @@ func TestServer_ListBeaconBlocks_Pagination(t *testing.T) { } func runListBeaconBlocksPagination(t *testing.T, orphanedBlk interfaces.SignedBeaconBlock, - blockCreator func(i types.Slot) interfaces.SignedBeaconBlock, containerCreator func(i types.Slot, root []byte, canonical bool) *ethpb.BeaconBlockContainer) { + blockCreator func(i primitives.Slot) interfaces.SignedBeaconBlock, containerCreator func(i primitives.Slot, root []byte, canonical bool) *ethpb.BeaconBlockContainer) { db := dbTest.SetupDB(t) chain := &chainMock.ChainService{ @@ -803,10 +803,10 @@ func runListBeaconBlocksPagination(t *testing.T, orphanedBlk interfaces.SignedBe } ctx := context.Background() - count := types.Slot(100) + count := primitives.Slot(100) blks := make([]interfaces.SignedBeaconBlock, count) blkContainers := make([]*ethpb.BeaconBlockContainer, count) - for i := types.Slot(0); i < count; i++ { + for i := primitives.Slot(0); i < count; i++ { b := blockCreator(i) root, err := b.Block().HashTreeRoot() require.NoError(t, err) diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/committees.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/committees.go index ea3f584060..239606ee59 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/committees.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/committees.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -24,7 +24,7 @@ func (bs *Server) ListBeaconCommittees( req *ethpb.ListCommitteesRequest, ) (*ethpb.BeaconCommittees, error) { currentSlot := bs.GenesisTimeFetcher.CurrentSlot() - var requestedSlot types.Slot + var requestedSlot primitives.Slot switch q := req.QueryFilter.(type) { case *ethpb.ListCommitteesRequest_Epoch: startSlot, err := slots.EpochStart(q.Epoch) @@ -68,8 +68,8 @@ func (bs *Server) ListBeaconCommittees( func (bs *Server) retrieveCommitteesForEpoch( ctx context.Context, - epoch types.Epoch, -) (SlotToCommiteesMap, []types.ValidatorIndex, error) { + epoch primitives.Epoch, +) (SlotToCommiteesMap, []primitives.ValidatorIndex, error) { startSlot, err := slots.EpochStart(epoch) if err != nil { return nil, nil, err @@ -105,7 +105,7 @@ func (bs *Server) retrieveCommitteesForEpoch( func (bs *Server) retrieveCommitteesForRoot( ctx context.Context, root []byte, -) (SlotToCommiteesMap, []types.ValidatorIndex, error) { +) (SlotToCommiteesMap, []primitives.ValidatorIndex, error) { requestedState, err := bs.StateGen.StateByRoot(ctx, bytesutil.ToBytes32(root)) if err != nil { return nil, nil, status.Error(codes.Internal, fmt.Sprintf("Could not get state: %v", err)) @@ -140,8 +140,8 @@ func (bs *Server) retrieveCommitteesForRoot( // the attester seeds value. func computeCommittees( ctx context.Context, - startSlot types.Slot, - activeIndices []types.ValidatorIndex, + startSlot primitives.Slot, + activeIndices []primitives.ValidatorIndex, attesterSeed [32]byte, ) (SlotToCommiteesMap, error) { committeesListsBySlot := make(SlotToCommiteesMap, params.BeaconConfig().SlotsPerEpoch) @@ -155,7 +155,7 @@ func computeCommittees( } committeeItems := make([]*ethpb.BeaconCommittees_CommitteeItem, countAtSlot) for committeeIndex := uint64(0); committeeIndex < countAtSlot; committeeIndex++ { - committee, err := helpers.BeaconCommittee(ctx, activeIndices, attesterSeed, slot, types.CommitteeIndex(committeeIndex)) + committee, err := helpers.BeaconCommittee(ctx, activeIndices, attesterSeed, slot, primitives.CommitteeIndex(committeeIndex)) if err != nil { return nil, status.Errorf( codes.Internal, @@ -176,7 +176,7 @@ func computeCommittees( } // SlotToCommiteesMap represents map. -type SlotToCommiteesMap map[types.Slot]*ethpb.BeaconCommittees_CommitteesList +type SlotToCommiteesMap map[primitives.Slot]*ethpb.BeaconCommittees_CommitteesList // SlotToUint64 updates map keys to slots (workaround which will be unnecessary if we can cast // map correctly in beacon_chain.proto) diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/slashings.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/slashings.go index c69d85aae7..573750723f 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/slashings.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/slashings.go @@ -4,7 +4,7 @@ import ( "context" "github.com/prysmaticlabs/prysm/v3/config/features" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "google.golang.org/grpc/codes" @@ -32,7 +32,7 @@ func (bs *Server) SubmitProposerSlashing( } return ðpb.SubmitSlashingResponse{ - SlashedIndices: []types.ValidatorIndex{req.Header_1.Header.ProposerIndex}, + SlashedIndices: []primitives.ValidatorIndex{req.Header_1.Header.ProposerIndex}, }, nil } @@ -56,9 +56,9 @@ func (bs *Server) SubmitAttesterSlashing( } } indices := slice.IntersectionUint64(req.Attestation_1.AttestingIndices, req.Attestation_2.AttestingIndices) - slashedIndices := make([]types.ValidatorIndex, len(indices)) + slashedIndices := make([]primitives.ValidatorIndex, len(indices)) for i, index := range indices { - slashedIndices[i] = types.ValidatorIndex(index) + slashedIndices[i] = primitives.ValidatorIndex(index) } return ðpb.SubmitSlashingResponse{ SlashedIndices: slashedIndices, diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/slashings_test.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/slashings_test.go index 6a41c5cf5a..0e3ae1cbdd 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/slashings_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/slashings_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/config/features" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/util" "google.golang.org/protobuf/proto" @@ -38,7 +38,7 @@ func TestServer_SubmitProposerSlashing(t *testing.T) { // We want a proposer slashing for validator with index 2 to // be included in the pool. - slashing, err := util.GenerateProposerSlashingForValidator(st, privs[2], types.ValidatorIndex(2)) + slashing, err := util.GenerateProposerSlashingForValidator(st, privs[2], primitives.ValidatorIndex(2)) require.NoError(t, err) _, err = bs.SubmitProposerSlashing(ctx, slashing) @@ -66,7 +66,7 @@ func TestServer_SubmitAttesterSlashing(t *testing.T) { Broadcaster: mb, } - slashing, err := util.GenerateAttesterSlashingForValidator(st, privs[2], types.ValidatorIndex(2)) + slashing, err := util.GenerateAttesterSlashingForValidator(st, privs[2], primitives.ValidatorIndex(2)) require.NoError(t, err) // We want the intersection of the slashing attesting indices @@ -100,9 +100,9 @@ func TestServer_SubmitProposerSlashing_DontBroadcast(t *testing.T) { // We want a proposer slashing for validator with index 2 to // be included in the pool. wanted := ðpb.SubmitSlashingResponse{ - SlashedIndices: []types.ValidatorIndex{2}, + SlashedIndices: []primitives.ValidatorIndex{2}, } - slashing, err := util.GenerateProposerSlashingForValidator(st, privs[2], types.ValidatorIndex(2)) + slashing, err := util.GenerateProposerSlashingForValidator(st, privs[2], primitives.ValidatorIndex(2)) require.NoError(t, err) res, err := bs.SubmitProposerSlashing(ctx, slashing) @@ -113,7 +113,7 @@ func TestServer_SubmitProposerSlashing_DontBroadcast(t *testing.T) { assert.Equal(t, false, mb.BroadcastCalled, "Expected broadcast not to be called by default") - slashing, err = util.GenerateProposerSlashingForValidator(st, privs[5], types.ValidatorIndex(5)) + slashing, err = util.GenerateProposerSlashingForValidator(st, privs[5], primitives.ValidatorIndex(5)) require.NoError(t, err) // We do not want a proposer slashing for an already slashed validator @@ -144,14 +144,14 @@ func TestServer_SubmitAttesterSlashing_DontBroadcast(t *testing.T) { Broadcaster: mb, } - slashing, err := util.GenerateAttesterSlashingForValidator(st, privs[2], types.ValidatorIndex(2)) + slashing, err := util.GenerateAttesterSlashingForValidator(st, privs[2], primitives.ValidatorIndex(2)) require.NoError(t, err) // We want the intersection of the slashing attesting indices // to be slashed, so we expect validators 2 and 3 to be in the response // slashed indices. wanted := ðpb.SubmitSlashingResponse{ - SlashedIndices: []types.ValidatorIndex{2}, + SlashedIndices: []primitives.ValidatorIndex{2}, } res, err := bs.SubmitAttesterSlashing(ctx, slashing) require.NoError(t, err) @@ -160,7 +160,7 @@ func TestServer_SubmitAttesterSlashing_DontBroadcast(t *testing.T) { } assert.Equal(t, false, mb.BroadcastCalled, "Expected broadcast not to be called by default") - slashing, err = util.GenerateAttesterSlashingForValidator(st, privs[5], types.ValidatorIndex(5)) + slashing, err = util.GenerateAttesterSlashingForValidator(st, privs[5], primitives.ValidatorIndex(5)) require.NoError(t, err) // If any of the attesting indices in the slashing object have already // been slashed, we should fail to insert properly into the attester slashing pool. diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/validators.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/validators.go index 6ca9791e61..32e99a2f2e 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/validators.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/validators.go @@ -16,7 +16,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/cmd" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -59,7 +59,7 @@ func (bs *Server) ListValidatorBalances( ) } res := make([]*ethpb.ValidatorBalances_Balance, 0) - filtered := map[types.ValidatorIndex]bool{} // Track filtered validators to prevent duplication in the response. + filtered := map[primitives.ValidatorIndex]bool{} // Track filtered validators to prevent duplication in the response. startSlot, err := slots.EpochStart(requestedEpoch) if err != nil { @@ -152,12 +152,12 @@ func (bs *Server) ListValidatorBalances( if len(req.Indices) == 0 && len(req.PublicKeys) == 0 { // Return everything. for i := start; i < end; i++ { - pubkey := requestedState.PubkeyAtIndex(types.ValidatorIndex(i)) + pubkey := requestedState.PubkeyAtIndex(primitives.ValidatorIndex(i)) val := vals[i] st := validatorStatus(val, requestedEpoch) res = append(res, ðpb.ValidatorBalances_Balance{ PublicKey: pubkey[:], - Index: types.ValidatorIndex(i), + Index: primitives.ValidatorIndex(i), Balance: balances[i], Status: st.String(), }) @@ -215,7 +215,7 @@ func (bs *Server) ListValidators( var reqState state.BeaconState var err error if requestedEpoch != currentEpoch { - var s types.Slot + var s primitives.Slot s, err = slots.EpochStart(requestedEpoch) if err != nil { return nil, err @@ -289,7 +289,7 @@ func (bs *Server) ListValidators( }) if len(req.PublicKeys) == 0 && len(req.Indices) == 0 { - for i := types.ValidatorIndex(0); uint64(i) < uint64(reqState.NumValidators()); i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < uint64(reqState.NumValidators()); i++ { val, err := reqState.ValidatorAtIndex(i) if err != nil { return nil, status.Errorf(codes.Internal, "Could not get validator: %v", err) @@ -345,7 +345,7 @@ func (bs *Server) GetValidator( ctx context.Context, req *ethpb.GetValidatorRequest, ) (*ethpb.Validator, error) { var requestingIndex bool - var index types.ValidatorIndex + var index primitives.ValidatorIndex var pubKey []byte switch q := req.QueryFilter.(type) { case *ethpb.GetValidatorRequest_Index: @@ -375,7 +375,7 @@ func (bs *Server) GetValidator( return headState.ValidatorAtIndex(index) } pk48 := bytesutil.ToBytes48(pubKey) - for i := types.ValidatorIndex(0); uint64(i) < uint64(headState.NumValidators()); i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < uint64(headState.NumValidators()); i++ { keyFromState := headState.PubkeyAtIndex(i) if keyFromState == pk48 { return headState.ValidatorAtIndex(i) @@ -393,7 +393,7 @@ func (bs *Server) GetValidatorActiveSetChanges( ) (*ethpb.ActiveSetChanges, error) { currentEpoch := slots.ToEpoch(bs.GenesisTimeFetcher.CurrentSlot()) - var requestedEpoch types.Epoch + var requestedEpoch primitives.Epoch switch q := req.QueryFilter.(type) { case *ethpb.GetValidatorActiveSetChangesRequest_Genesis: requestedEpoch = 0 @@ -479,7 +479,7 @@ func (bs *Server) GetValidatorParticipation( currentSlot := bs.GenesisTimeFetcher.CurrentSlot() currentEpoch := slots.ToEpoch(currentSlot) - var requestedEpoch types.Epoch + var requestedEpoch primitives.Epoch switch q := req.QueryFilter.(type) { case *ethpb.GetValidatorParticipationRequest_Genesis: requestedEpoch = 0 @@ -573,19 +573,19 @@ func (bs *Server) GetValidatorQueue( } // Queue the validators whose eligible to activate and sort them by activation eligibility epoch number. // Additionally, determine those validators queued to exit - awaitingExit := make([]types.ValidatorIndex, 0) - exitEpochs := make([]types.Epoch, 0) - activationQ := make([]types.ValidatorIndex, 0) + awaitingExit := make([]primitives.ValidatorIndex, 0) + exitEpochs := make([]primitives.Epoch, 0) + activationQ := make([]primitives.ValidatorIndex, 0) vals := headState.Validators() for idx, validator := range vals { eligibleActivated := validator.ActivationEligibilityEpoch != params.BeaconConfig().FarFutureEpoch canBeActive := validator.ActivationEpoch >= helpers.ActivationExitEpoch(headState.FinalizedCheckpointEpoch()) if eligibleActivated && canBeActive { - activationQ = append(activationQ, types.ValidatorIndex(idx)) + activationQ = append(activationQ, primitives.ValidatorIndex(idx)) } if validator.ExitEpoch != params.BeaconConfig().FarFutureEpoch { exitEpochs = append(exitEpochs, validator.ExitEpoch) - awaitingExit = append(awaitingExit, types.ValidatorIndex(idx)) + awaitingExit = append(awaitingExit, primitives.ValidatorIndex(idx)) } } sort.Slice(activationQ, func(i, j int) bool { @@ -605,7 +605,7 @@ func (bs *Server) GetValidatorQueue( return nil, status.Errorf(codes.Internal, "Could not compute churn limit: %v", err) } - exitQueueEpoch := types.Epoch(0) + exitQueueEpoch := primitives.Epoch(0) for _, i := range exitEpochs { if exitQueueEpoch < i { exitQueueEpoch = i @@ -625,7 +625,7 @@ func (bs *Server) GetValidatorQueue( // We use the exit queue churn to determine if we have passed a churn limit. minEpoch := exitQueueEpoch + params.BeaconConfig().MinValidatorWithdrawabilityDelay - exitQueueIndices := make([]types.ValidatorIndex, 0) + exitQueueIndices := make([]primitives.ValidatorIndex, 0) for _, valIdx := range awaitingExit { val := vals[valIdx] // Ensure the validator has not yet exited before adding its index to the exit queue. @@ -716,10 +716,10 @@ func (bs *Server) GetValidatorPerformance( } responseCap := len(req.Indices) + len(req.PublicKeys) - validatorIndices := make([]types.ValidatorIndex, 0, responseCap) + validatorIndices := make([]primitives.ValidatorIndex, 0, responseCap) missingValidators := make([][]byte, 0, responseCap) - filtered := map[types.ValidatorIndex]bool{} // Track filtered validators to prevent duplication in the response. + filtered := map[primitives.ValidatorIndex]bool{} // Track filtered validators to prevent duplication in the response. // Convert the list of validator public keys to validator indices and add to the indices set. for _, pubKey := range req.PublicKeys { // Skip empty public key. @@ -832,14 +832,14 @@ func (bs *Server) GetIndividualVotes( return nil, status.Errorf(codes.Internal, "failed to replay blocks for state at epoch %d: %v", req.Epoch, err) } // Track filtered validators to prevent duplication in the response. - filtered := map[types.ValidatorIndex]bool{} - filteredIndices := make([]types.ValidatorIndex, 0) + filtered := map[primitives.ValidatorIndex]bool{} + filteredIndices := make([]primitives.ValidatorIndex, 0) votes := make([]*ethpb.IndividualVotesRespond_IndividualVote, 0, len(req.Indices)+len(req.PublicKeys)) // Filter out assignments by public keys. for _, pubKey := range req.PublicKeys { index, ok := st.ValidatorIndexByPubkey(bytesutil.ToBytes48(pubKey)) if !ok { - votes = append(votes, ðpb.IndividualVotesRespond_IndividualVote{PublicKey: pubKey, ValidatorIndex: types.ValidatorIndex(^uint64(0))}) + votes = append(votes, ðpb.IndividualVotesRespond_IndividualVote{PublicKey: pubKey, ValidatorIndex: primitives.ValidatorIndex(^uint64(0))}) continue } filtered[index] = true @@ -916,7 +916,7 @@ func (bs *Server) GetIndividualVotes( } // Determines whether a validator has already exited. -func validatorHasExited(validator *ethpb.Validator, currentEpoch types.Epoch) bool { +func validatorHasExited(validator *ethpb.Validator, currentEpoch primitives.Epoch) bool { farFutureEpoch := params.BeaconConfig().FarFutureEpoch if currentEpoch < validator.ActivationEligibilityEpoch { return false @@ -936,7 +936,7 @@ func validatorHasExited(validator *ethpb.Validator, currentEpoch types.Epoch) bo return true } -func validatorStatus(validator *ethpb.Validator, epoch types.Epoch) ethpb.ValidatorStatus { +func validatorStatus(validator *ethpb.Validator, epoch primitives.Epoch) ethpb.ValidatorStatus { farFutureEpoch := params.BeaconConfig().FarFutureEpoch if validator == nil { return ethpb.ValidatorStatus_UNKNOWN_STATUS diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_stream.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_stream.go index b994dce813..22b28d582e 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_stream.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_stream.go @@ -25,7 +25,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "google.golang.org/grpc/codes" @@ -47,7 +47,7 @@ type infostream struct { eth1DepositsMutex *sync.RWMutex eth1Blocktimes *cache.Cache eth1BlocktimesMutex *sync.RWMutex - currentEpoch types.Epoch + currentEpoch primitives.Epoch stream ethpb.BeaconChain_StreamValidatorsInfoServer genesisTime uint64 } @@ -120,7 +120,7 @@ func (bs *Server) StreamValidatorsInfo(stream ethpb.BeaconChain_StreamValidators eth1DepositsMutex: &sync.RWMutex{}, eth1Blocktimes: cache.New(epochDuration*12, epochDuration*24), eth1BlocktimesMutex: &sync.RWMutex{}, - currentEpoch: types.Epoch(headState.Slot() / params.BeaconConfig().SlotsPerEpoch), + currentEpoch: primitives.Epoch(headState.Slot() / params.BeaconConfig().SlotsPerEpoch), stream: stream, genesisTime: headState.GenesisTime(), } @@ -265,7 +265,7 @@ func (is *infostream) generateValidatorsInfo(pubKeys [][]byte) ([]*ethpb.Validat if headState == nil || headState.IsNil() { return nil, status.Error(codes.Internal, "Not ready to serve information") } - epoch := types.Epoch(headState.Slot() / params.BeaconConfig().SlotsPerEpoch) + epoch := primitives.Epoch(headState.Slot() / params.BeaconConfig().SlotsPerEpoch) if epoch == 0 { // Not reporting, but no error. return nil, nil @@ -304,7 +304,7 @@ func (is *infostream) generateValidatorInfo( pubKey []byte, validator state.ReadOnlyValidator, headState state.ReadOnlyBeaconState, - epoch types.Epoch, + epoch primitives.Epoch, ) (*ethpb.ValidatorInfo, error) { info := ðpb.ValidatorInfo{ PublicKey: pubKey, @@ -375,7 +375,7 @@ func (is *infostream) generatePendingValidatorInfo(info *ethpb.ValidatorInfo) (* return info, nil } -func (is *infostream) calculateActivationTimeForPendingValidators(res []*ethpb.ValidatorInfo, headState state.ReadOnlyBeaconState, epoch types.Epoch) error { +func (is *infostream) calculateActivationTimeForPendingValidators(res []*ethpb.ValidatorInfo, headState state.ReadOnlyBeaconState, epoch primitives.Epoch) error { // pendingValidatorsMap is map from the validator pubkey to the index in our return array pendingValidatorsMap := make(map[[fieldparams.BLSPubkeyLength]byte]int) for i, info := range res { @@ -390,7 +390,7 @@ func (is *infostream) calculateActivationTimeForPendingValidators(res []*ethpb.V // Fetch the list of pending validators; count the number of attesting validators. numAttestingValidators := uint64(0) - pendingValidators := make([]types.ValidatorIndex, 0, headState.NumValidators()) + pendingValidators := make([]primitives.ValidatorIndex, 0, headState.NumValidators()) err := headState.ReadFromEveryValidator(func(idx int, val state.ReadOnlyValidator) error { if val.IsNil() { @@ -456,7 +456,7 @@ func (is *infostream) handleBlockProcessed() { // We aren't ready to serve information return } - blockEpoch := types.Epoch(headState.Slot() / params.BeaconConfig().SlotsPerEpoch) + blockEpoch := primitives.Epoch(headState.Slot() / params.BeaconConfig().SlotsPerEpoch) if blockEpoch == is.currentEpoch { // Epoch hasn't changed, nothing to report yet. return @@ -469,7 +469,7 @@ func (is *infostream) handleBlockProcessed() { } type indicesSorter struct { - indices []types.ValidatorIndex + indices []primitives.ValidatorIndex } // Len is the number of elements in the collection. @@ -483,7 +483,7 @@ func (s indicesSorter) Less(i, j int) bool { return s.indices[i] < s.indices[j] } -func (is *infostream) calculateStatusAndTransition(validator state.ReadOnlyValidator, currentEpoch types.Epoch) (ethpb.ValidatorStatus, uint64) { +func (is *infostream) calculateStatusAndTransition(validator state.ReadOnlyValidator, currentEpoch primitives.Epoch) (ethpb.ValidatorStatus, uint64) { farFutureEpoch := params.BeaconConfig().FarFutureEpoch if validator.IsNil() { @@ -515,7 +515,7 @@ func (is *infostream) calculateStatusAndTransition(validator state.ReadOnlyValid } // epochToTimestamp converts an epoch number to a timestamp. -func (is *infostream) epochToTimestamp(epoch types.Epoch) uint64 { +func (is *infostream) epochToTimestamp(epoch primitives.Epoch) uint64 { return is.genesisTime + params.BeaconConfig().SecondsPerSlot*uint64(params.BeaconConfig().SlotsPerEpoch.Mul(uint64(epoch))) } diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_stream_test.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_stream_test.go index ebdcdd1a10..614bffcd80 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_stream_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_stream_test.go @@ -6,7 +6,7 @@ import ( mock "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -17,7 +17,7 @@ func TestInfostream_EpochToTimestamp(t *testing.T) { params.OverrideBeaconConfig(params.MainnetConfig()) tests := []struct { name string - epoch types.Epoch + epoch primitives.Epoch timestamp uint64 }{ { diff --git a/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_test.go b/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_test.go index c88b585b68..4bd36876dd 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/beacon/validators_test.go @@ -30,7 +30,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" blocktest "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks/testing" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -157,7 +157,7 @@ func TestServer_ListValidatorBalances_DefaultResponse_NoArchive(t *testing.T) { balances[i] = params.BeaconConfig().MaxEffectiveBalance balancesResponse[i] = ðpb.ValidatorBalances_Balance{ PublicKey: pubKey(uint64(i)), - Index: types.ValidatorIndex(i), + Index: primitives.ValidatorIndex(i), Balance: params.BeaconConfig().MaxEffectiveBalance, Status: "EXITED", } @@ -273,7 +273,7 @@ func TestServer_ListValidatorBalances_Pagination_Default(t *testing.T) { TotalSize: 1, }, }, - {req: ðpb.ListValidatorBalancesRequest{Indices: []types.ValidatorIndex{1, 2, 3}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, + {req: ðpb.ListValidatorBalancesRequest{Indices: []primitives.ValidatorIndex{1, 2, 3}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, res: ðpb.ValidatorBalances{ Balances: []*ethpb.ValidatorBalances_Balance{ {Index: 1, PublicKey: pubKey(1), Balance: 1, Status: "EXITED"}, @@ -294,7 +294,7 @@ func TestServer_ListValidatorBalances_Pagination_Default(t *testing.T) { NextPageToken: "", TotalSize: 3, }}, - {req: ðpb.ListValidatorBalancesRequest{PublicKeys: [][]byte{pubKey(2), pubKey(3)}, Indices: []types.ValidatorIndex{3, 4}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, // Duplication + {req: ðpb.ListValidatorBalancesRequest{PublicKeys: [][]byte{pubKey(2), pubKey(3)}, Indices: []primitives.ValidatorIndex{3, 4}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, // Duplication res: ðpb.ValidatorBalances{ Balances: []*ethpb.ValidatorBalances_Balance{ {Index: 2, PublicKey: pubKey(2), Balance: 2, Status: "EXITED"}, @@ -304,7 +304,7 @@ func TestServer_ListValidatorBalances_Pagination_Default(t *testing.T) { NextPageToken: "", TotalSize: 3, }}, - {req: ðpb.ListValidatorBalancesRequest{PublicKeys: [][]byte{{}}, Indices: []types.ValidatorIndex{3, 4}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, // Public key has a blank value + {req: ðpb.ListValidatorBalancesRequest{PublicKeys: [][]byte{{}}, Indices: []primitives.ValidatorIndex{3, 4}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}, // Public key has a blank value res: ðpb.ValidatorBalances{ Balances: []*ethpb.ValidatorBalances_Balance{ {Index: 3, PublicKey: pubKey(3), Balance: 3, Status: "EXITED"}, @@ -412,7 +412,7 @@ func TestServer_ListValidatorBalances_OutOfRange(t *testing.T) { ReplayerBuilder: mockstategen.NewMockReplayerBuilder(mockstategen.WithMockState(headState)), } - req := ðpb.ListValidatorBalancesRequest{Indices: []types.ValidatorIndex{types.ValidatorIndex(1)}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}} + req := ðpb.ListValidatorBalancesRequest{Indices: []primitives.ValidatorIndex{primitives.ValidatorIndex(1)}, QueryFilter: ðpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}} wanted := "Validator index 1 >= balance list 1" _, err = bs.ListValidatorBalances(context.Background(), req) assert.ErrorContains(t, wanted, err) @@ -461,7 +461,7 @@ func TestServer_ListValidators_reqStateIsNil(t *testing.T) { State: nil, }, StateGen: &mockstategen.MockStateManager{ - StatesBySlot: map[types.Slot]state.BeaconState{ + StatesBySlot: map[primitives.Slot]state.BeaconState{ 0: nil, }, }, @@ -543,7 +543,7 @@ func TestServer_ListValidators_OnlyActiveValidators(t *testing.T) { } validators[i] = val activeValidators = append(activeValidators, ðpb.Validators_ValidatorContainer{ - Index: types.ValidatorIndex(i), + Index: primitives.ValidatorIndex(i), Validator: val, }) } else { @@ -606,7 +606,7 @@ func TestServer_ListValidators_InactiveInTheMiddle(t *testing.T) { } validators[i] = val activeValidators = append(activeValidators, ðpb.Validators_ValidatorContainer{ - Index: types.ValidatorIndex(i), + Index: primitives.ValidatorIndex(i), Validator: val, }) } else { @@ -708,7 +708,7 @@ func TestServer_ListValidators_NoPagination(t *testing.T) { want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) for i := 0; i < len(validators); i++ { want[i] = ðpb.Validators_ValidatorContainer{ - Index: types.ValidatorIndex(i), + Index: primitives.ValidatorIndex(i), Validator: validators[i], } } @@ -741,7 +741,7 @@ func TestServer_ListValidators_StategenNotUsed(t *testing.T) { want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) for i := 0; i < len(validators); i++ { want[i] = ðpb.Validators_ValidatorContainer{ - Index: types.ValidatorIndex(i), + Index: primitives.ValidatorIndex(i), Validator: validators[i], } } @@ -765,8 +765,8 @@ func TestServer_ListValidators_IndicesPubKeys(t *testing.T) { beaconDB := dbTest.SetupDB(t) validators, _, headState := setupValidators(t, beaconDB, 100) - indicesWanted := []types.ValidatorIndex{2, 7, 11, 17} - pubkeyIndicesWanted := []types.ValidatorIndex{3, 5, 9, 15} + indicesWanted := []primitives.ValidatorIndex{2, 7, 11, 17} + pubkeyIndicesWanted := []primitives.ValidatorIndex{3, 5, 9, 15} allIndicesWanted := append(indicesWanted, pubkeyIndicesWanted...) want := make([]*ethpb.Validators_ValidatorContainer, len(allIndicesWanted)) for i, idx := range allIndicesWanted { @@ -991,7 +991,7 @@ func TestServer_ListValidators_DefaultPageSize(t *testing.T) { want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) for i := 0; i < len(validators); i++ { want[i] = ðpb.Validators_ValidatorContainer{ - Index: types.ValidatorIndex(i), + Index: primitives.ValidatorIndex(i), Validator: validators[i], } } @@ -1027,7 +1027,7 @@ func TestServer_ListValidators_FromOldEpoch(t *testing.T) { transition.SkipSlotCache.Disable() ctx := context.Background() - slot := types.Slot(0) + slot := primitives.Slot(0) epochs := 10 numVals := uint64(10) @@ -1070,7 +1070,7 @@ func TestServer_ListValidators_FromOldEpoch(t *testing.T) { want := make([]*ethpb.Validators_ValidatorContainer, 0) for i, v := range vals { want = append(want, ðpb.Validators_ValidatorContainer{ - Index: types.ValidatorIndex(i), + Index: primitives.ValidatorIndex(i), Validator: v, }) } @@ -1093,7 +1093,7 @@ func TestServer_ListValidators_ProcessHeadStateSlots(t *testing.T) { beaconDB := dbTest.SetupDB(t) ctx := context.Background() - headSlot := types.Slot(32) + headSlot := primitives.Slot(32) numValidators := params.BeaconConfig().MinGenesisActiveValidatorCount validators := make([]*ethpb.Validator, numValidators) balances := make([]uint64, numValidators) @@ -1109,7 +1109,7 @@ func TestServer_ListValidators_ProcessHeadStateSlots(t *testing.T) { want := make([]*ethpb.Validators_ValidatorContainer, len(validators)) for i := 0; i < len(validators); i++ { want[i] = ðpb.Validators_ValidatorContainer{ - Index: types.ValidatorIndex(i), + Index: primitives.ValidatorIndex(i), Validator: validators[i], } } @@ -1150,9 +1150,9 @@ func TestServer_ListValidators_ProcessHeadStateSlots(t *testing.T) { } func TestServer_GetValidator(t *testing.T) { - count := types.Epoch(30) + count := primitives.Epoch(30) validators := make([]*ethpb.Validator, count) - for i := types.Epoch(0); i < count; i++ { + for i := primitives.Epoch(0); i < count; i++ { validators[i] = ðpb.Validator{ ActivationEpoch: i, PublicKey: pubKey(uint64(i)), @@ -1186,7 +1186,7 @@ func TestServer_GetValidator(t *testing.T) { { req: ðpb.GetValidatorRequest{ QueryFilter: ðpb.GetValidatorRequest_Index{ - Index: types.ValidatorIndex(count - 1), + Index: primitives.ValidatorIndex(count - 1), }, }, res: validators[count-1], @@ -1211,7 +1211,7 @@ func TestServer_GetValidator(t *testing.T) { { req: ðpb.GetValidatorRequest{ QueryFilter: ðpb.GetValidatorRequest_Index{ - Index: types.ValidatorIndex(len(validators)), + Index: primitives.ValidatorIndex(len(validators)), }, }, res: nil, @@ -1262,7 +1262,7 @@ func TestServer_GetValidatorActiveSetChanges(t *testing.T) { withdrawableEpoch = params.BeaconConfig().MinValidatorWithdrawabilityDelay balance = params.BeaconConfig().EjectionBalance } - err := headState.UpdateValidatorAtIndex(types.ValidatorIndex(i), ðpb.Validator{ + err := headState.UpdateValidatorAtIndex(primitives.ValidatorIndex(i), ðpb.Validator{ ActivationEpoch: activationEpoch, PublicKey: pubKey(uint64(i)), EffectiveBalance: balance, @@ -1298,19 +1298,19 @@ func TestServer_GetValidatorActiveSetChanges(t *testing.T) { pubKey(4), pubKey(6), } - wantedActiveIndices := []types.ValidatorIndex{0, 2, 4, 6} + wantedActiveIndices := []primitives.ValidatorIndex{0, 2, 4, 6} wantedExited := [][]byte{ pubKey(5), } - wantedExitedIndices := []types.ValidatorIndex{5} + wantedExitedIndices := []primitives.ValidatorIndex{5} wantedSlashed := [][]byte{ pubKey(3), } - wantedSlashedIndices := []types.ValidatorIndex{3} + wantedSlashedIndices := []primitives.ValidatorIndex{3} wantedEjected := [][]byte{ pubKey(7), } - wantedEjectedIndices := []types.ValidatorIndex{7} + wantedEjectedIndices := []primitives.ValidatorIndex{7} wanted := ðpb.ActiveSetChanges{ Epoch: 0, ActivatedPublicKeys: wantedActive, @@ -1373,7 +1373,7 @@ func TestServer_GetValidatorQueue_PendingActivation(t *testing.T) { require.NoError(t, err) assert.Equal(t, wantChurn, res.ChurnLimit) assert.DeepEqual(t, wanted, res.ActivationPublicKeys) - wantedActiveIndices := []types.ValidatorIndex{2, 1, 0} + wantedActiveIndices := []primitives.ValidatorIndex{2, 1, 0} assert.DeepEqual(t, wantedActiveIndices, res.ActivationValidatorIndices) } @@ -1415,7 +1415,7 @@ func TestServer_GetValidatorQueue_ExitedValidatorLeavesQueue(t *testing.T) { require.NoError(t, err) assert.Equal(t, wantChurn, res.ChurnLimit) assert.DeepEqual(t, wanted, res.ExitPublicKeys) - wantedExitIndices := []types.ValidatorIndex{1} + wantedExitIndices := []primitives.ValidatorIndex{1} assert.DeepEqual(t, wantedExitIndices, res.ExitValidatorIndices) // Now, we move the state.slot past the exit epoch of the validator, and now @@ -1811,7 +1811,7 @@ func TestGetValidatorPerformance_OK(t *testing.T) { params.OverrideBeaconConfig(params.MinimalSpecConfig()) ctx := context.Background() - epoch := types.Epoch(1) + epoch := primitives.Epoch(1) headState, err := util.NewBeaconState() require.NoError(t, err) require.NoError(t, headState.SetSlot(params.BeaconConfig().SlotsPerEpoch.Mul(uint64(epoch+1)))) @@ -1885,7 +1885,7 @@ func TestGetValidatorPerformance_OK(t *testing.T) { func TestGetValidatorPerformance_Indices(t *testing.T) { ctx := context.Background() - epoch := types.Epoch(1) + epoch := primitives.Epoch(1) defaultBal := params.BeaconConfig().MaxEffectiveBalance extraBal := params.BeaconConfig().MaxEffectiveBalance + params.BeaconConfig().GweiPerEth headState, err := util.NewBeaconState() @@ -1944,7 +1944,7 @@ func TestGetValidatorPerformance_Indices(t *testing.T) { } res, err := bs.GetValidatorPerformance(ctx, ðpb.ValidatorPerformanceRequest{ - Indices: []types.ValidatorIndex{2, 1, 0}, + Indices: []primitives.ValidatorIndex{2, 1, 0}, }) require.NoError(t, err) if !proto.Equal(want, res) { @@ -1954,7 +1954,7 @@ func TestGetValidatorPerformance_Indices(t *testing.T) { func TestGetValidatorPerformance_IndicesPubkeys(t *testing.T) { ctx := context.Background() - epoch := types.Epoch(1) + epoch := primitives.Epoch(1) defaultBal := params.BeaconConfig().MaxEffectiveBalance extraBal := params.BeaconConfig().MaxEffectiveBalance + params.BeaconConfig().GweiPerEth headState, err := util.NewBeaconState() @@ -2015,7 +2015,7 @@ func TestGetValidatorPerformance_IndicesPubkeys(t *testing.T) { // Index 2 and publicKey3 points to the same validator. // Should not return duplicates. res, err := bs.GetValidatorPerformance(ctx, ðpb.ValidatorPerformanceRequest{ - PublicKeys: [][]byte{publicKey1[:], publicKey3[:]}, Indices: []types.ValidatorIndex{1, 2}, + PublicKeys: [][]byte{publicKey1[:], publicKey3[:]}, Indices: []primitives.ValidatorIndex{1, 2}, }) require.NoError(t, err) if !proto.Equal(want, res) { @@ -2029,7 +2029,7 @@ func TestGetValidatorPerformanceAltair_OK(t *testing.T) { params.OverrideBeaconConfig(params.MinimalSpecConfig()) ctx := context.Background() - epoch := types.Epoch(1) + epoch := primitives.Epoch(1) headState, _ := util.DeterministicGenesisStateAltair(t, 32) require.NoError(t, headState.SetSlot(params.BeaconConfig().SlotsPerEpoch.Mul(uint64(epoch+1)))) @@ -2097,7 +2097,7 @@ func TestGetValidatorPerformanceBellatrix_OK(t *testing.T) { params.OverrideBeaconConfig(params.MinimalSpecConfig()) ctx := context.Background() - epoch := types.Epoch(1) + epoch := primitives.Epoch(1) headState, _ := util.DeterministicGenesisStateBellatrix(t, 32) require.NoError(t, headState.SetSlot(params.BeaconConfig().SlotsPerEpoch.Mul(uint64(epoch+1)))) @@ -2165,7 +2165,7 @@ func TestGetValidatorPerformanceCapella_OK(t *testing.T) { params.OverrideBeaconConfig(params.MinimalSpecConfig()) ctx := context.Background() - epoch := types.Epoch(1) + epoch := primitives.Epoch(1) headState, _ := util.DeterministicGenesisStateCapella(t, 32) require.NoError(t, headState.SetSlot(params.BeaconConfig().SlotsPerEpoch.Mul(uint64(epoch+1)))) @@ -2284,7 +2284,7 @@ func TestServer_GetIndividualVotes_ValidatorsDontExist(t *testing.T) { beaconDB := dbTest.SetupDB(t) ctx := context.Background() - var slot types.Slot = 0 + var slot primitives.Slot = 0 validators := uint64(64) stateWithValidators, _ := util.DeterministicGenesisState(t, validators) beaconState, err := util.NewBeaconState() @@ -2315,14 +2315,14 @@ func TestServer_GetIndividualVotes_ValidatorsDontExist(t *testing.T) { require.NoError(t, err) wanted := ðpb.IndividualVotesRespond{ IndividualVotes: []*ethpb.IndividualVotesRespond_IndividualVote{ - {PublicKey: []byte{'a'}, ValidatorIndex: types.ValidatorIndex(^uint64(0))}, + {PublicKey: []byte{'a'}, ValidatorIndex: primitives.ValidatorIndex(^uint64(0))}, }, } assert.DeepEqual(t, wanted, res, "Unexpected response") // Test non-existent validator index. res, err = bs.GetIndividualVotes(ctx, ðpb.IndividualVotesRequest{ - Indices: []types.ValidatorIndex{100}, + Indices: []primitives.ValidatorIndex{100}, Epoch: 0, }) require.NoError(t, err) @@ -2336,14 +2336,14 @@ func TestServer_GetIndividualVotes_ValidatorsDontExist(t *testing.T) { // Test both. res, err = bs.GetIndividualVotes(ctx, ðpb.IndividualVotesRequest{ PublicKeys: [][]byte{{'a'}, {'b'}}, - Indices: []types.ValidatorIndex{100, 101}, + Indices: []primitives.ValidatorIndex{100, 101}, Epoch: 0, }) require.NoError(t, err) wanted = ðpb.IndividualVotesRespond{ IndividualVotes: []*ethpb.IndividualVotesRespond_IndividualVote{ - {PublicKey: []byte{'a'}, ValidatorIndex: types.ValidatorIndex(^uint64(0))}, - {PublicKey: []byte{'b'}, ValidatorIndex: types.ValidatorIndex(^uint64(0))}, + {PublicKey: []byte{'a'}, ValidatorIndex: primitives.ValidatorIndex(^uint64(0))}, + {PublicKey: []byte{'b'}, ValidatorIndex: primitives.ValidatorIndex(^uint64(0))}, {ValidatorIndex: 100}, {ValidatorIndex: 101}, }, @@ -2404,7 +2404,7 @@ func TestServer_GetIndividualVotes_Working(t *testing.T) { addDefaultReplayerBuilder(bs, beaconDB) res, err := bs.GetIndividualVotes(ctx, ðpb.IndividualVotesRequest{ - Indices: []types.ValidatorIndex{0, 1}, + Indices: []primitives.ValidatorIndex{0, 1}, Epoch: 0, }) require.NoError(t, err) @@ -2438,7 +2438,7 @@ func TestServer_GetIndividualVotes_WorkingAltair(t *testing.T) { beaconDB := dbTest.SetupDB(t) ctx := context.Background() - var slot types.Slot = 0 + var slot primitives.Slot = 0 validators := uint64(32) beaconState, _ := util.DeterministicGenesisStateAltair(t, validators) require.NoError(t, beaconState.SetSlot(slot)) @@ -2467,7 +2467,7 @@ func TestServer_GetIndividualVotes_WorkingAltair(t *testing.T) { addDefaultReplayerBuilder(bs, beaconDB) res, err := bs.GetIndividualVotes(ctx, ðpb.IndividualVotesRequest{ - Indices: []types.ValidatorIndex{0, 1}, + Indices: []primitives.ValidatorIndex{0, 1}, Epoch: 0, }) require.NoError(t, err) @@ -2553,7 +2553,7 @@ func TestServer_GetIndividualVotes_AltairEndOfEpoch(t *testing.T) { addDefaultReplayerBuilder(bs, beaconDB) res, err := bs.GetIndividualVotes(ctx, ðpb.IndividualVotesRequest{ - Indices: []types.ValidatorIndex{0, 1}, + Indices: []primitives.ValidatorIndex{0, 1}, Epoch: 1, }) require.NoError(t, err) @@ -2641,7 +2641,7 @@ func TestServer_GetIndividualVotes_BellatrixEndOfEpoch(t *testing.T) { addDefaultReplayerBuilder(bs, beaconDB) res, err := bs.GetIndividualVotes(ctx, ðpb.IndividualVotesRequest{ - Indices: []types.ValidatorIndex{0, 1}, + Indices: []primitives.ValidatorIndex{0, 1}, Epoch: 1, }) require.NoError(t, err) @@ -2729,7 +2729,7 @@ func TestServer_GetIndividualVotes_CapellaEndOfEpoch(t *testing.T) { addDefaultReplayerBuilder(bs, beaconDB) res, err := bs.GetIndividualVotes(ctx, ðpb.IndividualVotesRequest{ - Indices: []types.ValidatorIndex{0, 1}, + Indices: []primitives.ValidatorIndex{0, 1}, Epoch: 1, }) require.NoError(t, err) @@ -2770,7 +2770,7 @@ func Test_validatorStatus(t *testing.T) { tests := []struct { name string validator *ethpb.Validator - epoch types.Epoch + epoch primitives.Epoch want ethpb.ValidatorStatus }{ { diff --git a/beacon-chain/rpc/prysm/v1alpha1/debug/block.go b/beacon-chain/rpc/prysm/v1alpha1/debug/block.go index 098b73ffa4..28468c4114 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/debug/block.go +++ b/beacon-chain/rpc/prysm/v1alpha1/debug/block.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/filters" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" pbrpc "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/attestation" @@ -44,7 +44,7 @@ func (ds *Server) GetInclusionSlot(ctx context.Context, req *pbrpc.InclusionSlot ds.GenesisTimeFetcher.CurrentSlot() // Attestation has one epoch to get included in the chain. This blocks users from requesting too soon. - epochBack := types.Slot(0) + epochBack := primitives.Slot(0) if ds.GenesisTimeFetcher.CurrentSlot() > params.BeaconConfig().SlotsPerEpoch { epochBack = ds.GenesisTimeFetcher.CurrentSlot() - params.BeaconConfig().SlotsPerEpoch } @@ -62,7 +62,7 @@ func (ds *Server) GetInclusionSlot(ctx context.Context, req *pbrpc.InclusionSlot return nil, status.Errorf(codes.Internal, "Could not retrieve blocks: %v", err) } - inclusionSlot := types.Slot(math.MaxUint64) + inclusionSlot := primitives.Slot(math.MaxUint64) targetStates := make(map[[32]byte]state.ReadOnlyBeaconState) for _, blk := range blks { for _, a := range blk.Block().Body().Attestations() { diff --git a/beacon-chain/rpc/prysm/v1alpha1/debug/state_test.go b/beacon-chain/rpc/prysm/v1alpha1/debug/state_test.go index 15caf4149f..4facf516e3 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/debug/state_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/debug/state_test.go @@ -10,7 +10,7 @@ import ( doublylinkedtree "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/doubly-linked-tree" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" mockstategen "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen/mock" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" pbrpc "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -28,7 +28,7 @@ func TestServer_GetBeaconState(t *testing.T) { ctx := context.Background() st, err := util.NewBeaconState() require.NoError(t, err) - slot := types.Slot(100) + slot := primitives.Slot(100) require.NoError(t, st.SetSlot(slot)) b := util.NewBeaconBlock() b.Block.Slot = slot diff --git a/beacon-chain/rpc/prysm/v1alpha1/slasher/attestations.go b/beacon-chain/rpc/prysm/v1alpha1/slasher/attestations.go index 9b4c5db667..1a64c850bf 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/slasher/attestations.go +++ b/beacon-chain/rpc/prysm/v1alpha1/slasher/attestations.go @@ -3,7 +3,7 @@ package slasher import ( "context" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -31,9 +31,9 @@ func (s *Server) IsSlashableAttestation( func (s *Server) HighestAttestations( ctx context.Context, req *ethpb.HighestAttestationRequest, ) (*ethpb.HighestAttestationResponse, error) { - valIndices := make([]types.ValidatorIndex, len(req.ValidatorIndices)) + valIndices := make([]primitives.ValidatorIndex, len(req.ValidatorIndices)) for i, valIdx := range req.ValidatorIndices { - valIndices[i] = types.ValidatorIndex(valIdx) + valIndices[i] = primitives.ValidatorIndex(valIdx) } atts, err := s.SlashingChecker.HighestAttestations(ctx, valIndices) if err != nil { diff --git a/beacon-chain/rpc/prysm/v1alpha1/slasher/attestations_test.go b/beacon-chain/rpc/prysm/v1alpha1/slasher/attestations_test.go index 5ed8b2e2f8..dc22f4c1ee 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/slasher/attestations_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/slasher/attestations_test.go @@ -5,13 +5,13 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/mock" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" ) func TestServer_HighestAttestations(t *testing.T) { - highestAtts := map[types.ValidatorIndex]*ethpb.HighestAttestation{ + highestAtts := map[primitives.ValidatorIndex]*ethpb.HighestAttestation{ 0: { ValidatorIndex: 0, HighestSourceEpoch: 1, diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/assignments.go b/beacon-chain/rpc/prysm/v1alpha1/validator/assignments.go index a89c485187..2f88397d0e 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/assignments.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/assignments.go @@ -13,7 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/transition" beaconState "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/rand" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpbv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" @@ -47,7 +47,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 types.Epoch + var currentEpoch primitives.Epoch if genesisTime.Before(prysmTime.Now()) { currentEpoch = slots.EpochsSinceGenesis(vs.TimeFetcher.GenesisTime()) } @@ -71,7 +71,7 @@ func (vs *Server) StreamDuties(req *ethpb.DutiesRequest, stream ethpb.BeaconNode select { // Ticks every epoch to submit assignments to connected validator clients. case slot := <-epochTicker.C(): - req.Epoch = types.Epoch(slot) + req.Epoch = primitives.Epoch(slot) res, err := vs.duties(stream.Context(), req) if err != nil { return status.Errorf(codes.Internal, "Could not compute validator duties: %v", err) @@ -268,7 +268,7 @@ func (vs *Server) AssignValidatorToSubnet(pubkey []byte, status ethpb.ValidatorS cache.SubnetIDs.AddPersistentCommittee(pubkey, assignedIdxs, totalDuration*time.Second) } -func registerSyncSubnetCurrentPeriod(s beaconState.BeaconState, epoch types.Epoch, pubKey []byte, status ethpb.ValidatorStatus) error { +func registerSyncSubnetCurrentPeriod(s beaconState.BeaconState, epoch primitives.Epoch, pubKey []byte, status ethpb.ValidatorStatus) error { committee, err := s.CurrentSyncCommittee() if err != nil { return err @@ -278,7 +278,7 @@ func registerSyncSubnetCurrentPeriod(s beaconState.BeaconState, epoch types.Epoc return nil } -func registerSyncSubnetNextPeriod(s beaconState.BeaconState, epoch types.Epoch, pubKey []byte, status ethpb.ValidatorStatus) error { +func registerSyncSubnetNextPeriod(s beaconState.BeaconState, epoch primitives.Epoch, pubKey []byte, status ethpb.ValidatorStatus) error { committee, err := s.NextSyncCommittee() if err != nil { return err @@ -290,12 +290,12 @@ func registerSyncSubnetNextPeriod(s beaconState.BeaconState, epoch types.Epoch, // registerSyncSubnet checks the status and pubkey of a particular validator // to discern whether persistent subnets need to be registered for them. -func registerSyncSubnet(currEpoch types.Epoch, syncPeriod uint64, pubkey []byte, +func registerSyncSubnet(currEpoch primitives.Epoch, syncPeriod uint64, pubkey []byte, syncCommittee *ethpb.SyncCommittee, status ethpb.ValidatorStatus) { if status != ethpb.ValidatorStatus_ACTIVE && status != ethpb.ValidatorStatus_EXITING { return } - startEpoch := types.Epoch(syncPeriod * uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod)) + startEpoch := primitives.Epoch(syncPeriod * uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod)) currPeriod := slots.SyncCommitteePeriod(currEpoch) endEpoch := startEpoch + params.BeaconConfig().EpochsPerSyncCommitteePeriod _, _, ok, expTime := cache.SyncSubnetIDs.GetSyncCommitteeSubnets(pubkey, startEpoch) diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/assignments_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/assignments_test.go index 70f618bc04..e2e8a01a55 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/assignments_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/assignments_test.go @@ -20,7 +20,7 @@ import ( mockSync "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpbv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -97,14 +97,14 @@ func TestGetDuties_OK(t *testing.T) { res, err = vs.GetDuties(context.Background(), req) require.NoError(t, err, "Could not call epoch committee assignment") for i := 0; i < len(res.CurrentEpochDuties); i++ { - assert.Equal(t, types.ValidatorIndex(i), res.CurrentEpochDuties[i].ValidatorIndex) + assert.Equal(t, primitives.ValidatorIndex(i), res.CurrentEpochDuties[i].ValidatorIndex) } } func TestGetAltairDuties_SyncCommitteeOK(t *testing.T) { params.SetupTestConfigCleanup(t) cfg := params.BeaconConfig().Copy() - cfg.AltairForkEpoch = types.Epoch(0) + cfg.AltairForkEpoch = primitives.Epoch(0) params.OverrideBeaconConfig(cfg) genesis := util.NewBeaconBlock() @@ -132,7 +132,7 @@ func TestGetAltairDuties_SyncCommitteeOK(t *testing.T) { pubKeys[i] = deposits[i].Data.PublicKey indices[i] = uint64(i) } - require.NoError(t, bs.SetSlot(params.BeaconConfig().SlotsPerEpoch*types.Slot(params.BeaconConfig().EpochsPerSyncCommitteePeriod)-1)) + require.NoError(t, bs.SetSlot(params.BeaconConfig().SlotsPerEpoch*primitives.Slot(params.BeaconConfig().EpochsPerSyncCommitteePeriod)-1)) require.NoError(t, helpers.UpdateSyncCommitteeCache(bs)) pubkeysAs48ByteType := make([][fieldparams.BLSPubkeyLength]byte, len(pubKeys)) @@ -183,7 +183,7 @@ func TestGetAltairDuties_SyncCommitteeOK(t *testing.T) { res, err = vs.GetDuties(context.Background(), req) require.NoError(t, err, "Could not call epoch committee assignment") for i := 0; i < len(res.CurrentEpochDuties); i++ { - require.Equal(t, types.ValidatorIndex(i), res.CurrentEpochDuties[i].ValidatorIndex) + require.Equal(t, primitives.ValidatorIndex(i), res.CurrentEpochDuties[i].ValidatorIndex) } for i := 0; i < len(res.CurrentEpochDuties); i++ { require.Equal(t, true, res.CurrentEpochDuties[i].IsSyncCommittee) @@ -206,8 +206,8 @@ func TestGetAltairDuties_SyncCommitteeOK(t *testing.T) { func TestGetBellatrixDuties_SyncCommitteeOK(t *testing.T) { params.SetupTestConfigCleanup(t) cfg := params.BeaconConfig().Copy() - cfg.AltairForkEpoch = types.Epoch(0) - cfg.BellatrixForkEpoch = types.Epoch(1) + cfg.AltairForkEpoch = primitives.Epoch(0) + cfg.BellatrixForkEpoch = primitives.Epoch(1) params.OverrideBeaconConfig(cfg) genesis := util.NewBeaconBlock() @@ -235,7 +235,7 @@ func TestGetBellatrixDuties_SyncCommitteeOK(t *testing.T) { pubKeys[i] = deposits[i].Data.PublicKey indices[i] = uint64(i) } - require.NoError(t, bs.SetSlot(params.BeaconConfig().SlotsPerEpoch*types.Slot(params.BeaconConfig().EpochsPerSyncCommitteePeriod)-1)) + require.NoError(t, bs.SetSlot(params.BeaconConfig().SlotsPerEpoch*primitives.Slot(params.BeaconConfig().EpochsPerSyncCommitteePeriod)-1)) require.NoError(t, helpers.UpdateSyncCommitteeCache(bs)) bs, err = execution.UpgradeToBellatrix(bs) @@ -289,7 +289,7 @@ func TestGetBellatrixDuties_SyncCommitteeOK(t *testing.T) { res, err = vs.GetDuties(context.Background(), req) require.NoError(t, err, "Could not call epoch committee assignment") for i := 0; i < len(res.CurrentEpochDuties); i++ { - assert.Equal(t, types.ValidatorIndex(i), res.CurrentEpochDuties[i].ValidatorIndex) + assert.Equal(t, primitives.ValidatorIndex(i), res.CurrentEpochDuties[i].ValidatorIndex) } for i := 0; i < len(res.CurrentEpochDuties); i++ { assert.Equal(t, true, res.CurrentEpochDuties[i].IsSyncCommittee) @@ -312,7 +312,7 @@ func TestGetBellatrixDuties_SyncCommitteeOK(t *testing.T) { func TestGetAltairDuties_UnknownPubkey(t *testing.T) { params.SetupTestConfigCleanup(t) cfg := params.BeaconConfig().Copy() - cfg.AltairForkEpoch = types.Epoch(0) + cfg.AltairForkEpoch = primitives.Epoch(0) params.OverrideBeaconConfig(cfg) genesis := util.NewBeaconBlock() @@ -332,7 +332,7 @@ func TestGetAltairDuties_UnknownPubkey(t *testing.T) { genesisRoot, err := genesis.Block.HashTreeRoot() require.NoError(t, err, "Could not get signing root") - require.NoError(t, bs.SetSlot(params.BeaconConfig().SlotsPerEpoch*types.Slot(params.BeaconConfig().EpochsPerSyncCommitteePeriod)-1)) + require.NoError(t, bs.SetSlot(params.BeaconConfig().SlotsPerEpoch*primitives.Slot(params.BeaconConfig().EpochsPerSyncCommitteePeriod)-1)) require.NoError(t, helpers.UpdateSyncCommitteeCache(bs)) slot := uint64(params.BeaconConfig().SlotsPerEpoch) * uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod) * params.BeaconConfig().SecondsPerSlot @@ -369,7 +369,7 @@ func TestGetDuties_SlotOutOfUpperBound(t *testing.T) { TimeFetcher: chain, } req := ðpb.DutiesRequest{ - Epoch: types.Epoch(chain.CurrentSlot()/params.BeaconConfig().SlotsPerEpoch + 2), + Epoch: primitives.Epoch(chain.CurrentSlot()/params.BeaconConfig().SlotsPerEpoch + 2), } _, err := vs.duties(context.Background(), req) require.ErrorContains(t, "can not be greater than next epoch", err) @@ -456,8 +456,8 @@ func TestGetDuties_MultipleKeys_OK(t *testing.T) { res, err := vs.GetDuties(context.Background(), req) require.NoError(t, err, "Could not call epoch committee assignment") assert.Equal(t, 2, len(res.CurrentEpochDuties)) - assert.Equal(t, types.Slot(4), res.CurrentEpochDuties[0].AttesterSlot) - assert.Equal(t, types.Slot(4), res.CurrentEpochDuties[1].AttesterSlot) + assert.Equal(t, primitives.Slot(4), res.CurrentEpochDuties[0].AttesterSlot) + assert.Equal(t, primitives.Slot(4), res.CurrentEpochDuties[1].AttesterSlot) } func TestGetDuties_SyncNotReady(t *testing.T) { diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/attester.go b/beacon-chain/rpc/prysm/v1alpha1/validator/attester.go index 709484ff5d..27807fa8e5 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/attester.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/attester.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -205,7 +205,7 @@ func (vs *Server) SubscribeCommitteeSubnets(ctx context.Context, req *ethpb.Comm return nil, status.Error(codes.InvalidArgument, "no attester slots provided") } - fetchValsLen := func(slot types.Slot) (uint64, error) { + fetchValsLen := func(slot primitives.Slot) (uint64, error) { wantedEpoch := slots.ToEpoch(slot) vals, err := vs.HeadFetcher.HeadValidatorsIndices(ctx, wantedEpoch) if err != nil { diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/attester_mainnet_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/attester_mainnet_test.go index 0ac7073c9f..5c417fde36 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/attester_mainnet_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/attester_mainnet_test.go @@ -10,7 +10,7 @@ import ( mockp2p "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/testing" mockSync "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -50,7 +50,7 @@ func TestAttestationDataAtSlot_HandlesFarAwayJustifiedEpoch(t *testing.T) { require.NoError(t, err, "Could not hash justified block") epochBoundaryRoot, err := epochBoundaryBlock.Block.HashTreeRoot() require.NoError(t, err, "Could not hash justified block") - slot := types.Slot(10000) + slot := primitives.Slot(10000) beaconState, err := util.NewBeaconState() require.NoError(t, err) diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/attester_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/attester_test.go index 8d7fd4e460..d80a7e8219 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/attester_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/attester_test.go @@ -17,7 +17,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" mockSync "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -209,7 +209,7 @@ func TestAttestationDataSlot_handlesInProgressRequest(t *testing.T) { chainService := &mock.ChainService{ Genesis: time.Now(), } - slot := types.Slot(2) + slot := primitives.Slot(2) offset := int64(slot.Mul(params.BeaconConfig().SecondsPerSlot)) server := &Server{ HeadFetcher: &mock.ChainService{State: state}, @@ -367,7 +367,7 @@ func TestServer_GetAttestationData_HeadStateSlotGreaterThanRequestSlot(t *testin } func TestGetAttestationData_SucceedsInFirstEpoch(t *testing.T) { - slot := types.Slot(5) + slot := primitives.Slot(5) block := util.NewBeaconBlock() block.Block.Slot = slot targetBlock := util.NewBeaconBlock() @@ -467,13 +467,13 @@ func TestServer_SubscribeCommitteeSubnets_DifferentLengthSlots(t *testing.T) { OperationNotifier: (&mock.ChainService{}).OperationNotifier(), } - var ss []types.Slot - var comIdxs []types.CommitteeIndex + var ss []primitives.Slot + var comIdxs []primitives.CommitteeIndex var isAggregator []bool - for i := types.Slot(100); i < 200; i++ { + for i := primitives.Slot(100); i < 200; i++ { ss = append(ss, i) - comIdxs = append(comIdxs, types.CommitteeIndex(randGen.Int63n(64))) + comIdxs = append(comIdxs, primitives.CommitteeIndex(randGen.Int63n(64))) boolVal := randGen.Uint64()%2 == 0 isAggregator = append(isAggregator, boolVal) } @@ -513,13 +513,13 @@ func TestServer_SubscribeCommitteeSubnets_MultipleSlots(t *testing.T) { OperationNotifier: (&mock.ChainService{}).OperationNotifier(), } - var ss []types.Slot - var comIdxs []types.CommitteeIndex + var ss []primitives.Slot + var comIdxs []primitives.CommitteeIndex var isAggregator []bool - for i := types.Slot(100); i < 200; i++ { + for i := primitives.Slot(100); i < 200; i++ { ss = append(ss, i) - comIdxs = append(comIdxs, types.CommitteeIndex(randGen.Int63n(64))) + comIdxs = append(comIdxs, primitives.CommitteeIndex(randGen.Int63n(64))) boolVal := randGen.Uint64()%2 == 0 isAggregator = append(isAggregator, boolVal) } @@ -530,7 +530,7 @@ func TestServer_SubscribeCommitteeSubnets_MultipleSlots(t *testing.T) { IsAggregator: isAggregator, }) require.NoError(t, err) - for i := types.Slot(100); i < 200; i++ { + for i := primitives.Slot(100); i < 200; i++ { subnets := cache.SubnetIDs.GetAttesterSubnetIDs(i) assert.Equal(t, 1, len(subnets)) if isAggregator[i-100] { diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/exit_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/exit_test.go index c2cedb12e5..693ab638fd 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/exit_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/exit_test.go @@ -15,7 +15,7 @@ import ( mockSync "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -30,7 +30,7 @@ func TestProposeExit_Notification(t *testing.T) { require.NoError(t, err) beaconState, err := transition.GenesisBeaconState(ctx, deposits, 0, ðpb.Eth1Data{BlockHash: make([]byte, 32)}) require.NoError(t, err) - epoch := types.Epoch(2048) + epoch := primitives.Epoch(2048) require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch.Mul(uint64(epoch)))) block := util.NewBeaconBlock() genesisRoot, err := block.Block.HashTreeRoot() @@ -56,7 +56,7 @@ func TestProposeExit_Notification(t *testing.T) { defer opSub.Unsubscribe() // Send the request, expect a result on the state feed. - validatorIndex := types.ValidatorIndex(0) + validatorIndex := primitives.ValidatorIndex(0) req := ðpb.SignedVoluntaryExit{ Exit: ðpb.VoluntaryExit{ Epoch: epoch, @@ -97,7 +97,7 @@ func TestProposeExit_NoPanic(t *testing.T) { require.NoError(t, err) beaconState, err := transition.GenesisBeaconState(ctx, deposits, 0, ðpb.Eth1Data{BlockHash: make([]byte, 32)}) require.NoError(t, err) - epoch := types.Epoch(2048) + epoch := primitives.Epoch(2048) require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch.Mul(uint64(epoch)))) block := util.NewBeaconBlock() genesisRoot, err := block.Block.HashTreeRoot() @@ -127,7 +127,7 @@ func TestProposeExit_NoPanic(t *testing.T) { require.ErrorContains(t, "voluntary exit does not exist", err, "Expected error for no exit existing") // Send the request, expect a result on the state feed. - validatorIndex := types.ValidatorIndex(0) + validatorIndex := primitives.ValidatorIndex(0) req = ðpb.SignedVoluntaryExit{ Exit: ðpb.VoluntaryExit{ Epoch: epoch, diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer.go index a6abb35316..8ae8ad1581 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer.go @@ -20,7 +20,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -167,7 +167,7 @@ func (vs *Server) PrepareBeaconProposer( ctx, span := trace.StartSpan(ctx, "validator.PrepareBeaconProposer") defer span.End() var feeRecipients []common.Address - var validatorIndices []types.ValidatorIndex + var validatorIndices []primitives.ValidatorIndex newRecipients := make([]*ethpb.PrepareBeaconProposerRequest_FeeRecipientContainer, 0, len(request.Recipients)) for _, r := range request.Recipients { diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_altair.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_altair.go index ca0ee72ce2..a622329fbd 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_altair.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_altair.go @@ -6,7 +6,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -42,7 +42,7 @@ func (vs *Server) setSyncAggregate(ctx context.Context, blk interfaces.BeaconBlo // getSyncAggregate retrieves the sync contributions from the pool to construct the sync aggregate object. // The contributions are filtered based on matching of the input root and slot then profitability. -func (vs *Server) getSyncAggregate(ctx context.Context, slot types.Slot, root [32]byte) (*ethpb.SyncAggregate, error) { +func (vs *Server) getSyncAggregate(ctx context.Context, slot primitives.Slot, root [32]byte) (*ethpb.SyncAggregate, error) { ctx, span := trace.StartSpan(ctx, "ProposerServer.getSyncAggregate") defer span.End() diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_attestations.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_attestations.go index 24ab54cdf1..8d4cf46d1b 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_attestations.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_attestations.go @@ -11,7 +11,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/attestation/aggregation" attaggregation "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/attestation/aggregation/attestations" @@ -123,8 +123,8 @@ func (a proposerAtts) sortByProfitability() (proposerAtts, error) { // Duplicate bits are counted only once, using max-cover algorithm. func (a proposerAtts) sortByProfitabilityUsingMaxCover() (proposerAtts, error) { // Separate attestations by slot, as slot number takes higher precedence when sorting. - var slots []types.Slot - attsBySlot := map[types.Slot]proposerAtts{} + var slots []primitives.Slot + attsBySlot := map[primitives.Slot]proposerAtts{} for _, att := range a { if _, ok := attsBySlot[att.Data.Slot]; !ok { slots = append(slots, att.Data.Slot) diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_attestations_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_attestations_test.go index 58a219fb45..04b2902e0b 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_attestations_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_attestations_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/prysmaticlabs/go-bitfield" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -39,7 +39,7 @@ func TestProposer_ProposerAtts_sortByProfitability(t *testing.T) { func TestProposer_ProposerAtts_sortByProfitabilityUsingMaxCover(t *testing.T) { type testData struct { - slot types.Slot + slot primitives.Slot bits bitfield.Bitlist } getAtts := func(data []testData) proposerAtts { diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_bellatrix.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_bellatrix.go index 3388741822..671c1d31c1 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_bellatrix.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_bellatrix.go @@ -16,7 +16,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/encoding/ssz" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" @@ -70,7 +70,7 @@ func (vs *Server) setExecutionData(ctx context.Context, blk interfaces.BeaconBlo // This function retrieves the payload header given the slot number and the validator index. // It's a no-op if the latest head block is not versioned bellatrix. -func (vs *Server) getPayloadHeaderFromBuilder(ctx context.Context, slot types.Slot, idx types.ValidatorIndex) (interfaces.ExecutionData, error) { +func (vs *Server) getPayloadHeaderFromBuilder(ctx context.Context, slot primitives.Slot, idx primitives.ValidatorIndex) (interfaces.ExecutionData, error) { b, err := vs.HeadFetcher.HeadBlock(ctx) if err != nil { return nil, err diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_builder.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_builder.go index f4fa5ef4d4..dc44108e11 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_builder.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_builder.go @@ -6,14 +6,14 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/kv" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/sirupsen/logrus" ) // Returns true if builder (ie outsourcing block construction) can be used. Both conditions have to meet: // - Validator has registered to use builder (ie called registerBuilder API end point) // - Circuit breaker has not been activated (ie the liveness of the chain is healthy) -func (vs *Server) canUseBuilder(ctx context.Context, slot types.Slot, idx types.ValidatorIndex) (bool, error) { +func (vs *Server) canUseBuilder(ctx context.Context, slot primitives.Slot, idx primitives.ValidatorIndex) (bool, error) { activated, err := vs.circuitBreakBuilder(slot) if err != nil { return false, err @@ -25,7 +25,7 @@ func (vs *Server) canUseBuilder(ctx context.Context, slot types.Slot, idx types. } // validatorRegistered returns true if validator with index `id` was previously registered in the database. -func (vs *Server) validatorRegistered(ctx context.Context, id types.ValidatorIndex) (bool, error) { +func (vs *Server) validatorRegistered(ctx context.Context, id primitives.ValidatorIndex) (bool, error) { if vs.BeaconDB == nil { return false, errors.New("nil beacon db") } @@ -40,7 +40,7 @@ func (vs *Server) validatorRegistered(ctx context.Context, id types.ValidatorInd } // circuitBreakBuilder returns true if the builder is not allowed to be used due to circuit breaker conditions. -func (vs *Server) circuitBreakBuilder(s types.Slot) (bool, error) { +func (vs *Server) circuitBreakBuilder(s primitives.Slot) (bool, error) { if vs.ForkFetcher == nil || vs.ForkFetcher.ForkChoicer() == nil { return true, errors.New("no fork choicer configured") } diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_builder_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_builder_test.go index 9b967e083c..96a0d7d2bc 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_builder_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_builder_test.go @@ -12,7 +12,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" v1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -59,7 +59,7 @@ func TestServer_circuitBreakBuilder(t *testing.T) { require.LogsContain(t, hook, "Circuit breaker activated due to missing enough slots last epoch. Ignore if mev-boost is not used") want := params.BeaconConfig().SlotsPerEpoch - params.BeaconConfig().MaxBuilderEpochMissedSlots - for i := types.Slot(2); i <= want+2; i++ { + for i := primitives.Slot(2); i <= want+2; i++ { st, blkRoot, err = createState(i, [32]byte{byte(i)}, [32]byte{'a'}, params.BeaconConfig().ZeroHash, ojc, ofc) require.NoError(t, err) require.NoError(t, s.ForkFetcher.ForkChoicer().InsertNode(ctx, st, blkRoot)) @@ -84,7 +84,7 @@ func TestServer_validatorRegistered(t *testing.T) { f := bytesutil.PadTo([]byte{}, fieldparams.FeeRecipientLength) p := bytesutil.PadTo([]byte{}, fieldparams.BLSPubkeyLength) - require.NoError(t, proposerServer.BeaconDB.SaveRegistrationsByValidatorIDs(ctx, []types.ValidatorIndex{0, 1}, + require.NoError(t, proposerServer.BeaconDB.SaveRegistrationsByValidatorIDs(ctx, []primitives.ValidatorIndex{0, 1}, []*ethpb.ValidatorRegistrationV1{{FeeRecipient: f, Pubkey: p}, {FeeRecipient: f, Pubkey: p}})) reg, err = proposerServer.validatorRegistered(ctx, 0) @@ -116,7 +116,7 @@ func TestServer_canUseBuilder(t *testing.T) { f := bytesutil.PadTo([]byte{}, fieldparams.FeeRecipientLength) p := bytesutil.PadTo([]byte{}, fieldparams.BLSPubkeyLength) - require.NoError(t, proposerServer.BeaconDB.SaveRegistrationsByValidatorIDs(ctx, []types.ValidatorIndex{0}, + require.NoError(t, proposerServer.BeaconDB.SaveRegistrationsByValidatorIDs(ctx, []primitives.ValidatorIndex{0}, []*ethpb.ValidatorRegistrationV1{{FeeRecipient: f, Pubkey: p}})) reg, err = proposerServer.canUseBuilder(ctx, params.BeaconConfig().MaxBuilderConsecutiveMissedSlots, 0) @@ -125,7 +125,7 @@ func TestServer_canUseBuilder(t *testing.T) { } func createState( - slot types.Slot, + slot primitives.Slot, blockRoot [32]byte, parentRoot [32]byte, payloadHash [32]byte, diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_empty_block.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_empty_block.go index 762419c392..1629302317 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_empty_block.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_empty_block.go @@ -4,14 +4,14 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) -func getEmptyBlock(slot types.Slot) (interfaces.SignedBeaconBlock, error) { +func getEmptyBlock(slot primitives.Slot) (interfaces.SignedBeaconBlock, error) { var sBlk interfaces.SignedBeaconBlock var err error switch { diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_empty_block_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_empty_block_test.go index 372a3082fa..c37499d008 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_empty_block_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_empty_block_test.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -21,12 +21,12 @@ func Test_getEmptyBlock(t *testing.T) { tests := []struct { name string - slot types.Slot + slot primitives.Slot want func() interfaces.SignedBeaconBlock }{ { name: "altair", - slot: types.Slot(params.BeaconConfig().AltairForkEpoch) * params.BeaconConfig().SlotsPerEpoch, + slot: primitives.Slot(params.BeaconConfig().AltairForkEpoch) * params.BeaconConfig().SlotsPerEpoch, want: func() interfaces.SignedBeaconBlock { b, err := blocks.NewSignedBeaconBlock(ðpb.SignedBeaconBlockAltair{Block: ðpb.BeaconBlockAltair{Body: ðpb.BeaconBlockBodyAltair{}}}) require.NoError(t, err) @@ -35,7 +35,7 @@ func Test_getEmptyBlock(t *testing.T) { }, { name: "bellatrix", - slot: types.Slot(params.BeaconConfig().BellatrixForkEpoch) * params.BeaconConfig().SlotsPerEpoch, + slot: primitives.Slot(params.BeaconConfig().BellatrixForkEpoch) * params.BeaconConfig().SlotsPerEpoch, want: func() interfaces.SignedBeaconBlock { b, err := blocks.NewSignedBeaconBlock(ðpb.SignedBeaconBlockBellatrix{Block: ðpb.BeaconBlockBellatrix{Body: ðpb.BeaconBlockBodyBellatrix{}}}) require.NoError(t, err) @@ -44,7 +44,7 @@ func Test_getEmptyBlock(t *testing.T) { }, { name: "capella", - slot: types.Slot(params.BeaconConfig().CapellaForkEpoch) * params.BeaconConfig().SlotsPerEpoch, + slot: primitives.Slot(params.BeaconConfig().CapellaForkEpoch) * params.BeaconConfig().SlotsPerEpoch, want: func() interfaces.SignedBeaconBlock { b, err := blocks.NewSignedBeaconBlock(ðpb.SignedBeaconBlockCapella{Block: ðpb.BeaconBlockCapella{Body: ðpb.BeaconBlockBodyCapella{}}}) require.NoError(t, err) diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_eth1data.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_eth1data.go index 993fa8c80a..2f78c0f409 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_eth1data.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_eth1data.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/features" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/crypto/rand" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -87,7 +87,7 @@ func (vs *Server) eth1DataMajorityVote(ctx context.Context, beaconState state.Be return vs.HeadFetcher.HeadETH1Data(), nil } -func (vs *Server) slotStartTime(slot types.Slot) uint64 { +func (vs *Server) slotStartTime(slot primitives.Slot) uint64 { startTime, _ := vs.Eth1InfoFetcher.GenesisExecutionChainInfo() return slots.VotingPeriodStartTime(startTime, slot) } @@ -126,7 +126,7 @@ func (vs *Server) canonicalEth1Data( return canonicalEth1Data, canonicalEth1DataHeight, nil } -func (vs *Server) mockETH1DataVote(ctx context.Context, slot types.Slot) (*ethpb.Eth1Data, error) { +func (vs *Server) mockETH1DataVote(ctx context.Context, slot primitives.Slot) (*ethpb.Eth1Data, error) { if !eth1DataNotification { log.Warn("Beacon Node is no longer connected to an ETH1 chain, so ETH1 data votes are now mocked.") eth1DataNotification = true diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_execution_payload.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_execution_payload.go index 89951e59cf..a660333429 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_execution_payload.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_execution_payload.go @@ -19,7 +19,7 @@ import ( consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" payloadattribute "github.com/prysmaticlabs/prysm/v3/consensus-types/payload-attribute" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -42,7 +42,7 @@ var ( // This returns the execution payload of a given slot. The function has full awareness of pre and post merge. // The payload is computed given the respected time of merge. -func (vs *Server) getExecutionPayload(ctx context.Context, slot types.Slot, vIdx types.ValidatorIndex, headRoot [32]byte, st state.BeaconState) (interfaces.ExecutionData, error) { +func (vs *Server) getExecutionPayload(ctx context.Context, slot primitives.Slot, vIdx primitives.ValidatorIndex, headRoot [32]byte, st state.BeaconState) (interfaces.ExecutionData, error) { proposerID, payloadId, ok := vs.ProposerSlotIndexCache.GetProposerPayloadIDs(slot, headRoot) feeRecipient := params.BeaconConfig().DefaultFeeRecipient recipient, err := vs.BeaconDB.FeeRecipientByValidatorID(ctx, vIdx) @@ -219,7 +219,7 @@ func (vs *Server) getTerminalBlockHashIfExists(ctx context.Context, transitionTi // is_activation_epoch_reached = get_current_epoch(state) >= TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH // if is_terminal_block_hash_set and not is_activation_epoch_reached: // return True -func activationEpochNotReached(slot types.Slot) bool { +func activationEpochNotReached(slot primitives.Slot) bool { terminalBlockHashSet := bytesutil.ToBytes32(params.BeaconConfig().TerminalBlockHash.Bytes()) != [32]byte{} if terminalBlockHashSet { return params.BeaconConfig().TerminalBlockHashActivationEpoch > slots.ToEpoch(slot) diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_execution_payload_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_execution_payload_test.go index 074bb3c5eb..edec45a44b 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_execution_payload_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_execution_payload_test.go @@ -14,7 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" pb "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -59,7 +59,7 @@ func TestServer_getExecutionPayload(t *testing.T) { Root: b2r[:], })) - require.NoError(t, beaconDB.SaveFeeRecipientsByValidatorIDs(context.Background(), []types.ValidatorIndex{0}, []common.Address{{}})) + require.NoError(t, beaconDB.SaveFeeRecipientsByValidatorIDs(context.Background(), []primitives.ValidatorIndex{0}, []common.Address{{}})) tests := []struct { name string @@ -68,8 +68,8 @@ func TestServer_getExecutionPayload(t *testing.T) { forkchoiceErr error payloadID *pb.PayloadIDBytes terminalBlockHash common.Hash - activationEpoch types.Epoch - validatorIndx types.ValidatorIndex + activationEpoch primitives.Epoch + validatorIndx primitives.ValidatorIndex }{ { name: "transition completed, nil payload id", @@ -145,7 +145,7 @@ func TestServer_getExecutionPayloadContextTimeout(t *testing.T) { Root: b1r[:], })) - require.NoError(t, beaconDB.SaveFeeRecipientsByValidatorIDs(context.Background(), []types.ValidatorIndex{0}, []common.Address{{}})) + require.NoError(t, beaconDB.SaveFeeRecipientsByValidatorIDs(context.Background(), []primitives.ValidatorIndex{0}, []common.Address{{}})) cfg := params.BeaconConfig().Copy() cfg.TerminalBlockHash = common.Hash{'a'} @@ -189,7 +189,7 @@ func TestServer_getExecutionPayload_UnexpectedFeeRecipient(t *testing.T) { })) feeRecipient := common.BytesToAddress([]byte("a")) - require.NoError(t, beaconDB.SaveFeeRecipientsByValidatorIDs(context.Background(), []types.ValidatorIndex{0}, []common.Address{ + require.NoError(t, beaconDB.SaveFeeRecipientsByValidatorIDs(context.Background(), []primitives.ValidatorIndex{0}, []common.Address{ feeRecipient, })) diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_exits.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_exits.go index e4930efb5f..763bc2e83b 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_exits.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_exits.go @@ -3,11 +3,11 @@ package validator import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) -func (vs *Server) getExits(head state.BeaconState, slot types.Slot) []*ethpb.SignedVoluntaryExit { +func (vs *Server) getExits(head state.BeaconState, slot primitives.Slot) []*ethpb.SignedVoluntaryExit { exits := vs.ExitPool.PendingExits(head, slot, false /*noLimit*/) validExits := make([]*ethpb.SignedVoluntaryExit, 0, len(exits)) diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_exits_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_exits_test.go index d4932108ac..22fb145d69 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_exits_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_exits_test.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/operations/voluntaryexits" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -25,7 +25,7 @@ func TestServer_getExits(t *testing.T) { } exits := make([]*eth.SignedVoluntaryExit, params.BeaconConfig().MaxVoluntaryExits) - for i := types.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxVoluntaryExits; i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxVoluntaryExits; i++ { exit, err := util.GenerateVoluntaryExits(beaconState, privKeys[i], i) require.NoError(t, err) proposerServer.ExitPool.InsertVoluntaryExit(context.Background(), beaconState, exit) diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_slashings_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_slashings_test.go index bfdec36c9f..c5c43486ad 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_slashings_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_slashings_test.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/operations/slashings" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -20,7 +20,7 @@ func TestServer_getSlashings(t *testing.T) { } proposerSlashings := make([]*ethpb.ProposerSlashing, params.BeaconConfig().MaxProposerSlashings) - for i := types.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { proposerSlashing, err := util.GenerateProposerSlashingForValidator(beaconState, privKeys[i], i) require.NoError(t, err) proposerSlashings[i] = proposerSlashing @@ -33,7 +33,7 @@ func TestServer_getSlashings(t *testing.T) { attesterSlashing, err := util.GenerateAttesterSlashingForValidator( beaconState, privKeys[i+params.BeaconConfig().MaxProposerSlashings], - types.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), + primitives.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings), ) require.NoError(t, err) attSlashings[i] = attesterSlashing diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_test.go index f82e46bab8..e8f277cf19 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/proposer_test.go @@ -38,7 +38,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/trie" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -480,7 +480,7 @@ func getProposerServer(db db.HeadAccessDatabase, headState state.BeaconState, he func injectSlashings(t *testing.T, st state.BeaconState, keys []bls.SecretKey, server *Server) ([]*ethpb.ProposerSlashing, []*ethpb.AttesterSlashing) { proposerSlashings := make([]*ethpb.ProposerSlashing, params.BeaconConfig().MaxProposerSlashings) - for i := types.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { + for i := primitives.ValidatorIndex(0); uint64(i) < params.BeaconConfig().MaxProposerSlashings; i++ { proposerSlashing, err := util.GenerateProposerSlashingForValidator(st, keys[i], i /* validator index */) require.NoError(t, err) proposerSlashings[i] = proposerSlashing @@ -490,7 +490,7 @@ func injectSlashings(t *testing.T, st state.BeaconState, keys []bls.SecretKey, s attSlashings := make([]*ethpb.AttesterSlashing, params.BeaconConfig().MaxAttesterSlashings) for i := uint64(0); i < params.BeaconConfig().MaxAttesterSlashings; i++ { - attesterSlashing, err := util.GenerateAttesterSlashingForValidator(st, keys[i+params.BeaconConfig().MaxProposerSlashings], types.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings) /* validator index */) + attesterSlashing, err := util.GenerateAttesterSlashingForValidator(st, keys[i+params.BeaconConfig().MaxProposerSlashings], primitives.ValidatorIndex(i+params.BeaconConfig().MaxProposerSlashings) /* validator index */) require.NoError(t, err) attSlashings[i] = attesterSlashing err = server.SlashingsPool.InsertAttesterSlashing(context.Background(), st, attesterSlashing) @@ -1556,7 +1556,7 @@ func TestProposer_Eth1Data_MajorityVote_SpansGenesis(t *testing.T) { // Voting period will span genesis, causing the special case for pre-mined genesis to kick in. // In other words some part of the valid time range is before genesis, so querying the block cache would fail // without the special case added to allow this for testnets. - slot := types.Slot(0) + slot := primitives.Slot(0) earliestValidTime, latestValidTime := majorityVoteBoundaryTime(slot) p := mockExecution.New(). @@ -1590,7 +1590,7 @@ func TestProposer_Eth1Data_MajorityVote_SpansGenesis(t *testing.T) { func TestProposer_Eth1Data_MajorityVote(t *testing.T) { followDistanceSecs := params.BeaconConfig().Eth1FollowDistance * params.BeaconConfig().SecondsPerETH1Block followSlots := followDistanceSecs / params.BeaconConfig().SecondsPerSlot - slot := types.Slot(64 + followSlots) + slot := primitives.Slot(64 + followSlots) earliestValidTime, latestValidTime := majorityVoteBoundaryTime(slot) dc := ethpb.DepositContainer{ @@ -2169,7 +2169,7 @@ func TestProposer_FilterAttestation(t *testing.T) { for i := 0; i < len(atts); i++ { atts[i] = util.HydrateAttestation(ðpb.Attestation{ Data: ðpb.AttestationData{ - CommitteeIndex: types.CommitteeIndex(i), + CommitteeIndex: primitives.CommitteeIndex(i), }, }) } @@ -2186,7 +2186,7 @@ func TestProposer_FilterAttestation(t *testing.T) { for i := 0; i < len(atts); i++ { atts[i] = util.HydrateAttestation(ðpb.Attestation{ Data: ðpb.AttestationData{ - CommitteeIndex: types.CommitteeIndex(i), + CommitteeIndex: primitives.CommitteeIndex(i), Source: ðpb.Checkpoint{Root: params.BeaconConfig().ZeroHash[:]}, }, AggregationBits: bitfield.Bitlist{0b00010010}, @@ -2525,7 +2525,7 @@ func BenchmarkServer_PrepareBeaconProposer(b *testing.B) { f := bytesutil.PadTo([]byte{0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF}, fieldparams.FeeRecipientLength) recipients := make([]*ethpb.PrepareBeaconProposerRequest_FeeRecipientContainer, 0) for i := 0; i < 10000; i++ { - recipients = append(recipients, ðpb.PrepareBeaconProposerRequest_FeeRecipientContainer{FeeRecipient: f, ValidatorIndex: types.ValidatorIndex(i)}) + recipients = append(recipients, ðpb.PrepareBeaconProposerRequest_FeeRecipientContainer{FeeRecipient: f, ValidatorIndex: primitives.ValidatorIndex(i)}) } req := ðpb.PrepareBeaconProposerRequest{ @@ -2557,7 +2557,7 @@ func TestProposer_SubmitValidatorRegistrations(t *testing.T) { require.ErrorContains(t, "bad", err) } -func majorityVoteBoundaryTime(slot types.Slot) (uint64, uint64) { +func majorityVoteBoundaryTime(slot primitives.Slot) (uint64, uint64) { s := params.BeaconConfig().SlotsPerEpoch.Mul(uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod)) slotStartTime := uint64(mockExecution.GenesisTime) + uint64((slot - (slot % (s))).Mul(params.BeaconConfig().SecondsPerSlot)) earliestValidTime := slotStartTime - 2*params.BeaconConfig().SecondsPerETH1Block*params.BeaconConfig().Eth1FollowDistance @@ -2596,7 +2596,7 @@ func TestProposer_GetFeeRecipientByPubKey(t *testing.T) { PublicKey: beaconState.Validators()[0].PublicKey, }) require.NoError(t, err) - err = proposerServer.BeaconDB.SaveFeeRecipientsByValidatorIDs(ctx, []types.ValidatorIndex{index.Index}, []common.Address{common.HexToAddress("0x055Fb65722E7b2455012BFEBf6177F1D2e9728D8")}) + err = proposerServer.BeaconDB.SaveFeeRecipientsByValidatorIDs(ctx, []primitives.ValidatorIndex{index.Index}, []common.Address{common.HexToAddress("0x055Fb65722E7b2455012BFEBf6177F1D2e9728D8")}) require.NoError(t, err) resp, err = proposerServer.GetFeeRecipientByPubKey(ctx, ðpb.FeeRecipientByPubKeyRequest{ PublicKey: beaconState.Validators()[0].PublicKey, diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/status.go b/beacon-chain/rpc/prysm/v1alpha1/validator/status.go index 798708aac7..23ed80613b 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/status.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/status.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/contracts/deposit" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" @@ -24,7 +24,7 @@ import ( var errPubkeyDoesNotExist = errors.New("pubkey does not exist") var errOptimisticMode = errors.New("the node is currently optimistic and cannot serve validators") -var nonExistentIndex = types.ValidatorIndex(^uint64(0)) +var nonExistentIndex = primitives.ValidatorIndex(^uint64(0)) var errParticipation = status.Errorf(codes.Internal, "Failed to obtain epoch participation") @@ -77,7 +77,7 @@ func (vs *Server) MultipleValidatorStatus( } // Convert indices to public keys. for _, idx := range req.Indices { - pubkeyBytes := headState.PubkeyAtIndex(types.ValidatorIndex(idx)) + pubkeyBytes := headState.PubkeyAtIndex(primitives.ValidatorIndex(idx)) if !filtered[pubkeyBytes] { pubKeys = append(pubKeys, pubkeyBytes[:]) filtered[pubkeyBytes] = true @@ -85,7 +85,7 @@ func (vs *Server) MultipleValidatorStatus( } // Fetch statuses from beacon state. statuses := make([]*ethpb.ValidatorStatusResponse, len(pubKeys)) - indices := make([]types.ValidatorIndex, len(pubKeys)) + indices := make([]primitives.ValidatorIndex, len(pubKeys)) for i, pubKey := range pubKeys { statuses[i], indices[i] = vs.validatorStatus(ctx, headState, pubKey) } @@ -273,7 +273,7 @@ func (vs *Server) validatorStatus( ctx context.Context, headState state.ReadOnlyBeaconState, pubKey []byte, -) (*ethpb.ValidatorStatusResponse, types.ValidatorIndex) { +) (*ethpb.ValidatorStatusResponse, primitives.ValidatorIndex) { ctx, span := trace.StartSpan(ctx, "ValidatorServer.validatorStatus") defer span.End() @@ -343,14 +343,14 @@ func (vs *Server) validatorStatus( } } - var lastActivatedvalidatorIndex types.ValidatorIndex + var lastActivatedvalidatorIndex primitives.ValidatorIndex for j := headState.NumValidators() - 1; j >= 0; j-- { - val, err := headState.ValidatorAtIndexReadOnly(types.ValidatorIndex(j)) + val, err := headState.ValidatorAtIndexReadOnly(primitives.ValidatorIndex(j)) if err != nil { return resp, idx } if helpers.IsActiveValidatorUsingTrie(val, time.CurrentEpoch(headState)) { - lastActivatedvalidatorIndex = types.ValidatorIndex(j) + lastActivatedvalidatorIndex = primitives.ValidatorIndex(j) break } } @@ -364,7 +364,7 @@ func (vs *Server) validatorStatus( } } -func checkValidatorsAreRecent(headEpoch types.Epoch, req *ethpb.DoppelGangerRequest) (bool, *ethpb.DoppelGangerResponse) { +func checkValidatorsAreRecent(headEpoch primitives.Epoch, req *ethpb.DoppelGangerRequest) (bool, *ethpb.DoppelGangerResponse) { validatorsAreRecent := true resp := ðpb.DoppelGangerResponse{ Responses: []*ethpb.DoppelGangerResponse_ValidatorResponse{}, @@ -390,7 +390,7 @@ func checkValidatorsAreRecent(headEpoch types.Epoch, req *ethpb.DoppelGangerRequ return validatorsAreRecent, resp } -func statusForPubKey(headState state.ReadOnlyBeaconState, pubKey []byte) (ethpb.ValidatorStatus, types.ValidatorIndex, error) { +func statusForPubKey(headState state.ReadOnlyBeaconState, pubKey []byte) (ethpb.ValidatorStatus, primitives.ValidatorIndex, error) { if headState == nil || headState.IsNil() { return ethpb.ValidatorStatus_UNKNOWN_STATUS, 0, errors.New("head state does not exist") } @@ -401,7 +401,7 @@ func statusForPubKey(headState state.ReadOnlyBeaconState, pubKey []byte) (ethpb. return assignmentStatus(headState, idx), idx, nil } -func assignmentStatus(beaconState state.ReadOnlyBeaconState, validatorIndex types.ValidatorIndex) ethpb.ValidatorStatus { +func assignmentStatus(beaconState state.ReadOnlyBeaconState, validatorIndex primitives.ValidatorIndex) ethpb.ValidatorStatus { validator, err := beaconState.ValidatorAtIndexReadOnly(validatorIndex) if err != nil { return ethpb.ValidatorStatus_UNKNOWN_STATUS diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/status_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/status_test.go index 30b6a4c61e..a8aa443b05 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/status_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/status_test.go @@ -16,7 +16,7 @@ import ( mockstategen "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen/mock" mockSync "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/trie" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -239,7 +239,7 @@ func TestValidatorStatus_Exiting(t *testing.T) { pubKey := pubKey(1) // Initiated exit because validator exit epoch and withdrawable epoch are not FAR_FUTURE_EPOCH - slot := types.Slot(10000) + slot := primitives.Slot(10000) epoch := slots.ToEpoch(slot) exitEpoch := helpers.ActivationExitEpoch(epoch) withdrawableEpoch := exitEpoch + params.BeaconConfig().MinValidatorWithdrawabilityDelay @@ -301,7 +301,7 @@ func TestValidatorStatus_Slashing(t *testing.T) { pubKey := pubKey(1) // Exit slashed because slashed is true, exit epoch is =< current epoch and withdrawable epoch > epoch . - slot := types.Slot(10000) + slot := primitives.Slot(10000) epoch := slots.ToEpoch(slot) block := util.NewBeaconBlock() genesisRoot, err := block.Block.HashTreeRoot() @@ -360,7 +360,7 @@ func TestValidatorStatus_Exited(t *testing.T) { pubKey := pubKey(1) // Exit because only exit epoch is =< current epoch. - slot := types.Slot(10000) + slot := primitives.Slot(10000) epoch := slots.ToEpoch(slot) block := util.NewBeaconBlock() genesisRoot, err := block.Block.HashTreeRoot() @@ -556,7 +556,7 @@ func TestValidatorStatus_CorrectActivationQueue(t *testing.T) { block := util.NewBeaconBlock() genesisRoot, err := block.Block.HashTreeRoot() require.NoError(t, err, "Could not get signing root") - currentSlot := types.Slot(5000) + currentSlot := primitives.Slot(5000) // Pending active because activation epoch is still defaulted at far future slot. validators := []*ethpb.Validator{ { @@ -588,14 +588,14 @@ func TestValidatorStatus_CorrectActivationQueue(t *testing.T) { WithdrawableEpoch: params.BeaconConfig().FarFutureEpoch, }, { - ActivationEpoch: types.Epoch(currentSlot/params.BeaconConfig().SlotsPerEpoch + 1), + ActivationEpoch: primitives.Epoch(currentSlot/params.BeaconConfig().SlotsPerEpoch + 1), PublicKey: pbKey, WithdrawalCredentials: make([]byte, 32), ExitEpoch: params.BeaconConfig().FarFutureEpoch, WithdrawableEpoch: params.BeaconConfig().FarFutureEpoch, }, { - ActivationEpoch: types.Epoch(currentSlot/params.BeaconConfig().SlotsPerEpoch + 4), + ActivationEpoch: primitives.Epoch(currentSlot/params.BeaconConfig().SlotsPerEpoch + 4), PublicKey: pubKey(5), WithdrawalCredentials: make([]byte, 32), ExitEpoch: params.BeaconConfig().FarFutureEpoch, @@ -763,7 +763,7 @@ func TestMultipleValidatorStatus_Pubkeys(t *testing.T) { } func TestMultipleValidatorStatus_Indices(t *testing.T) { - slot := types.Slot(10000) + slot := primitives.Slot(10000) epoch := slots.ToEpoch(slot) pubKeys := [][]byte{pubKey(1), pubKey(2), pubKey(3), pubKey(4), pubKey(5), pubKey(6), pubKey(7)} beaconState := ðpb.BeaconState{ @@ -1214,13 +1214,13 @@ func TestServer_CheckDoppelGanger(t *testing.T) { } } -func createStateSetupPhase0(t *testing.T, head types.Epoch) (state.BeaconState, +func createStateSetupPhase0(t *testing.T, head primitives.Epoch) (state.BeaconState, state.BeaconState, []bls.SecretKey) { gs, keys := util.DeterministicGenesisState(t, 64) hs := gs.Copy() // Head State - headSlot := types.Slot(head)*params.BeaconConfig().SlotsPerEpoch + params.BeaconConfig().SlotsPerEpoch/2 + headSlot := primitives.Slot(head)*params.BeaconConfig().SlotsPerEpoch + params.BeaconConfig().SlotsPerEpoch/2 assert.NoError(t, hs.SetSlot(headSlot)) // Previous Epoch State @@ -1231,13 +1231,13 @@ func createStateSetupPhase0(t *testing.T, head types.Epoch) (state.BeaconState, return hs, ps, keys } -func createStateSetupAltair(t *testing.T, head types.Epoch) (state.BeaconState, +func createStateSetupAltair(t *testing.T, head primitives.Epoch) (state.BeaconState, state.BeaconState, []bls.SecretKey) { gs, keys := util.DeterministicGenesisStateAltair(t, 64) hs := gs.Copy() // Head State - headSlot := types.Slot(head)*params.BeaconConfig().SlotsPerEpoch + params.BeaconConfig().SlotsPerEpoch/2 + headSlot := primitives.Slot(head)*params.BeaconConfig().SlotsPerEpoch + params.BeaconConfig().SlotsPerEpoch/2 assert.NoError(t, hs.SetSlot(headSlot)) // Previous Epoch State diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/sync_committee.go b/beacon-chain/rpc/prysm/v1alpha1/validator/sync_committee.go index 6a263fe8ac..7250e295ea 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/sync_committee.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/sync_committee.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/feed" opfeed "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/feed/operation" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -152,7 +152,7 @@ func (vs *Server) SubmitSignedContributionAndProof( func (vs *Server) AggregatedSigAndAggregationBits( ctx context.Context, msgs []*ethpb.SyncCommitteeMessage, - slot types.Slot, + slot primitives.Slot, subnetId uint64, blockRoot []byte, ) ([]byte, []byte, error) { diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/sync_committee_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/sync_committee_test.go index d7e43a9007..a7964e6bd8 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/sync_committee_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/sync_committee_test.go @@ -13,7 +13,7 @@ import ( mockp2p "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/testing" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -87,16 +87,16 @@ func TestGetSyncSubcommitteeIndex_Ok(t *testing.T) { server := &Server{ HeadFetcher: &mock.ChainService{ - SyncCommitteeIndices: []types.CommitteeIndex{0}, + SyncCommitteeIndices: []primitives.CommitteeIndex{0}, }, } var pubKey [fieldparams.BLSPubkeyLength]byte // Request slot 0, should get the index 0 for validator 0. res, err := server.GetSyncSubcommitteeIndex(context.Background(), ðpb.SyncSubcommitteeIndexRequest{ - PublicKey: pubKey[:], Slot: types.Slot(0), + PublicKey: pubKey[:], Slot: primitives.Slot(0), }) require.NoError(t, err) - require.DeepEqual(t, []types.CommitteeIndex{0}, res.Indices) + require.DeepEqual(t, []primitives.CommitteeIndex{0}, res.Indices) } func TestGetSyncCommitteeContribution_FiltersDuplicates(t *testing.T) { @@ -106,7 +106,7 @@ func TestGetSyncCommitteeContribution_FiltersDuplicates(t *testing.T) { P2P: &mockp2p.MockBroadcaster{}, HeadFetcher: &mock.ChainService{ State: st, - SyncCommitteeIndices: []types.CommitteeIndex{10}, + SyncCommitteeIndices: []primitives.CommitteeIndex{10}, }, TimeFetcher: &mock.ChainService{Genesis: time.Now()}, } diff --git a/beacon-chain/rpc/statefetcher/fetcher.go b/beacon-chain/rpc/statefetcher/fetcher.go index 1d0d58f20a..d252651670 100644 --- a/beacon-chain/rpc/statefetcher/fetcher.go +++ b/beacon-chain/rpc/statefetcher/fetcher.go @@ -14,7 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/time/slots" "go.opencensus.io/trace" @@ -75,7 +75,7 @@ func (e *StateRootNotFoundError) Error() string { type Fetcher interface { State(ctx context.Context, stateId []byte) (state.BeaconState, error) StateRoot(ctx context.Context, stateId []byte) ([]byte, error) - StateBySlot(ctx context.Context, slot types.Slot) (state.BeaconState, error) + StateBySlot(ctx context.Context, slot primitives.Slot) (state.BeaconState, error) } // StateProvider is a real implementation of Fetcher. @@ -150,7 +150,7 @@ func (p *StateProvider) State(ctx context.Context, stateId []byte) (state.Beacon e := NewStateIdParseError(parseErr) return nil, &e } - s, err = p.StateBySlot(ctx, types.Slot(slotNumber)) + s, err = p.StateBySlot(ctx, primitives.Slot(slotNumber)) } } @@ -185,7 +185,7 @@ func (p *StateProvider) StateRoot(ctx context.Context, stateId []byte) (root []b // ID format does not match any valid options. return nil, &e } - root, err = p.stateRootBySlot(ctx, types.Slot(slotNumber)) + root, err = p.stateRootBySlot(ctx, primitives.Slot(slotNumber)) } } @@ -213,7 +213,7 @@ func (p *StateProvider) stateByRoot(ctx context.Context, stateRoot []byte) (stat // between the found state's slot and the target slot. // process_blocks is applied for all canonical blocks, and process_slots is called for any skipped // slots, or slots following the most recent canonical block up to and including the target slot. -func (p *StateProvider) StateBySlot(ctx context.Context, target types.Slot) (state.BeaconState, error) { +func (p *StateProvider) StateBySlot(ctx context.Context, target primitives.Slot) (state.BeaconState, error) { ctx, span := trace.StartSpan(ctx, "statefetcher.StateBySlot") defer span.End() @@ -302,7 +302,7 @@ func (p *StateProvider) stateRootByRoot(ctx context.Context, stateRoot []byte) ( return nil, &rootNotFoundErr } -func (p *StateProvider) stateRootBySlot(ctx context.Context, slot types.Slot) ([]byte, error) { +func (p *StateProvider) stateRootBySlot(ctx context.Context, slot primitives.Slot) ([]byte, error) { currentSlot := p.GenesisTimeFetcher.CurrentSlot() if slot > currentSlot { return nil, errors.New("slot cannot be in the future") diff --git a/beacon-chain/rpc/statefetcher/fetcher_test.go b/beacon-chain/rpc/statefetcher/fetcher_test.go index 4ec49ff847..77d321ded1 100644 --- a/beacon-chain/rpc/statefetcher/fetcher_test.go +++ b/beacon-chain/rpc/statefetcher/fetcher_test.go @@ -16,7 +16,7 @@ import ( testDB "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" mockstategen "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen/mock" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -27,7 +27,7 @@ import ( func TestGetState(t *testing.T) { ctx := context.Background() - headSlot := types.Slot(123) + headSlot := primitives.Slot(123) fillSlot := func(state *ethpb.BeaconState) error { state.Slot = headSlot return nil @@ -77,7 +77,7 @@ func TestGetState(t *testing.T) { cc := &mockstategen.MockCanonicalChecker{Is: true} cs := &mockstategen.MockCurrentSlotter{Slot: bs.Slot() + 1} ch := stategen.NewCanonicalHistory(db, cc, cs) - currentSlot := types.Slot(0) + currentSlot := primitives.Slot(0) p := StateProvider{ BeaconDB: db, ReplayerBuilder: ch, @@ -197,7 +197,7 @@ func TestGetState(t *testing.T) { func TestGetStateRoot(t *testing.T) { ctx := context.Background() - headSlot := types.Slot(123) + headSlot := primitives.Slot(123) fillSlot := func(state *ethpb.BeaconState) error { state.Slot = headSlot return nil @@ -354,7 +354,7 @@ func TestGetStateRoot(t *testing.T) { // a state is required to save checkpoint require.NoError(t, db.SaveState(ctx, st, root)) - slot := types.Slot(40) + slot := primitives.Slot(40) p := StateProvider{ GenesisTimeFetcher: &chainMock.ChainService{Slot: &slot}, BeaconDB: db, @@ -388,7 +388,7 @@ func TestNewStateNotFoundError(t *testing.T) { } func TestStateBySlot_FutureSlot(t *testing.T) { - slot := types.Slot(100) + slot := primitives.Slot(100) p := StateProvider{GenesisTimeFetcher: &chainMock.ChainService{Slot: &slot}} _, err := p.StateBySlot(context.Background(), 101) assert.ErrorContains(t, "requested slot is in the future", err) @@ -399,12 +399,12 @@ func TestStateBySlot_AfterHeadSlot(t *testing.T) { require.NoError(t, err) slotSt, err := statenative.InitializeFromProtoPhase0(ðpb.BeaconState{Slot: 101}) require.NoError(t, err) - currentSlot := types.Slot(102) + currentSlot := primitives.Slot(102) mock := &chainMock.ChainService{State: headSt, Slot: ¤tSlot} mockReplayer := mockstategen.NewMockReplayerBuilder() mockReplayer.SetMockStateForSlot(slotSt, 101) p := StateProvider{ChainInfoFetcher: mock, GenesisTimeFetcher: mock, ReplayerBuilder: mockReplayer} st, err := p.StateBySlot(context.Background(), 101) require.NoError(t, err) - assert.Equal(t, types.Slot(101), st.Slot()) + assert.Equal(t, primitives.Slot(101), st.Slot()) } diff --git a/beacon-chain/rpc/testutil/mock_genesis_timefetcher.go b/beacon-chain/rpc/testutil/mock_genesis_timefetcher.go index 5b102d7b74..312a3dd4be 100644 --- a/beacon-chain/rpc/testutil/mock_genesis_timefetcher.go +++ b/beacon-chain/rpc/testutil/mock_genesis_timefetcher.go @@ -4,7 +4,7 @@ import ( "time" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // MockGenesisTimeFetcher is a fake implementation of the blockchain.TimeFetcher @@ -16,6 +16,6 @@ func (m *MockGenesisTimeFetcher) GenesisTime() time.Time { return m.Genesis } -func (m *MockGenesisTimeFetcher) CurrentSlot() types.Slot { - return types.Slot(uint64(time.Now().Unix()-m.Genesis.Unix()) / params.BeaconConfig().SecondsPerSlot) +func (m *MockGenesisTimeFetcher) CurrentSlot() primitives.Slot { + return primitives.Slot(uint64(time.Now().Unix()-m.Genesis.Unix()) / params.BeaconConfig().SecondsPerSlot) } diff --git a/beacon-chain/rpc/testutil/mock_state_fetcher.go b/beacon-chain/rpc/testutil/mock_state_fetcher.go index f04f7e24b0..644b0054c7 100644 --- a/beacon-chain/rpc/testutil/mock_state_fetcher.go +++ b/beacon-chain/rpc/testutil/mock_state_fetcher.go @@ -4,14 +4,14 @@ import ( "context" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // MockFetcher is a fake implementation of statefetcher.Fetcher. type MockFetcher struct { BeaconState state.BeaconState BeaconStateRoot []byte - StatesBySlot map[types.Slot]state.BeaconState + StatesBySlot map[primitives.Slot]state.BeaconState } // State -- @@ -24,6 +24,6 @@ func (m *MockFetcher) StateRoot(context.Context, []byte) ([]byte, error) { return m.BeaconStateRoot, nil } -func (m *MockFetcher) StateBySlot(_ context.Context, s types.Slot) (state.BeaconState, error) { +func (m *MockFetcher) StateBySlot(_ context.Context, s primitives.Slot) (state.BeaconState, error) { return m.StatesBySlot[s], nil } diff --git a/beacon-chain/slasher/chunks.go b/beacon-chain/slasher/chunks.go index 70148a9aae..f4e161edff 100644 --- a/beacon-chain/slasher/chunks.go +++ b/beacon-chain/slasher/chunks.go @@ -8,7 +8,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/db" slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -19,7 +19,7 @@ type chunkUpdateArgs struct { kind slashertypes.ChunkKind chunkIndex uint64 validatorChunkIndex uint64 - currentEpoch types.Epoch + currentEpoch primitives.Epoch } // Chunker defines a struct which represents a slice containing a chunk for K different validator's @@ -32,17 +32,17 @@ type Chunker interface { CheckSlashable( ctx context.Context, slasherDB db.SlasherDatabase, - validatorIdx types.ValidatorIndex, + validatorIdx primitives.ValidatorIndex, attestation *slashertypes.IndexedAttestationWrapper, ) (*ethpb.AttesterSlashing, error) Update( args *chunkUpdateArgs, - validatorIndex types.ValidatorIndex, + validatorIndex primitives.ValidatorIndex, startEpoch, - newTargetEpoch types.Epoch, + newTargetEpoch primitives.Epoch, ) (keepGoing bool, err error) - StartEpoch(sourceEpoch, currentEpoch types.Epoch) (epoch types.Epoch, exists bool) - NextChunkStartEpoch(startEpoch types.Epoch) types.Epoch + StartEpoch(sourceEpoch, currentEpoch primitives.Epoch) (epoch primitives.Epoch, exists bool) + NextChunkStartEpoch(startEpoch primitives.Epoch) primitives.Epoch } // MinSpanChunksSlice represents a slice containing a chunk for K different validator's min spans. @@ -184,7 +184,7 @@ func (m *MaxSpanChunksSlice) Chunk() []uint16 { func (m *MinSpanChunksSlice) CheckSlashable( ctx context.Context, slasherDB db.SlasherDatabase, - validatorIdx types.ValidatorIndex, + validatorIdx primitives.ValidatorIndex, attestation *slashertypes.IndexedAttestationWrapper, ) (*ethpb.AttesterSlashing, error) { sourceEpoch := attestation.IndexedAttestation.Data.Source.Epoch @@ -231,7 +231,7 @@ func (m *MinSpanChunksSlice) CheckSlashable( func (m *MaxSpanChunksSlice) CheckSlashable( ctx context.Context, slasherDB db.SlasherDatabase, - validatorIdx types.ValidatorIndex, + validatorIdx primitives.ValidatorIndex, attestation *slashertypes.IndexedAttestationWrapper, ) (*ethpb.AttesterSlashing, error) { sourceEpoch := attestation.IndexedAttestation.Data.Source.Epoch @@ -319,12 +319,12 @@ func (m *MaxSpanChunksSlice) CheckSlashable( // to jump to another min span chunks slice to perform updates. func (m *MinSpanChunksSlice) Update( args *chunkUpdateArgs, - validatorIndex types.ValidatorIndex, + validatorIndex primitives.ValidatorIndex, startEpoch, - newTargetEpoch types.Epoch, + newTargetEpoch primitives.Epoch, ) (keepGoing bool, err error) { // The lowest epoch we need to update. - minEpoch := types.Epoch(0) + minEpoch := primitives.Epoch(0) if args.currentEpoch > (m.params.historyLength - 1) { minEpoch = args.currentEpoch - (m.params.historyLength - 1) } @@ -333,7 +333,7 @@ func (m *MinSpanChunksSlice) Update( // As long as the epoch, e, in the same chunk index and e >= min_epoch, we proceed with // a for loop. for m.params.chunkIndex(epochInChunk) == args.chunkIndex && epochInChunk >= minEpoch { - var chunkTarget types.Epoch + var chunkTarget primitives.Epoch chunkTarget, err = chunkDataAtEpoch(m.params, m.data, validatorIndex, epochInChunk) if err != nil { err = errors.Wrapf(err, "could not get chunk data at epoch %d", epochInChunk) @@ -368,16 +368,16 @@ func (m *MinSpanChunksSlice) Update( // MinSpanChunksSlice. func (m *MaxSpanChunksSlice) Update( args *chunkUpdateArgs, - validatorIndex types.ValidatorIndex, + validatorIndex primitives.ValidatorIndex, startEpoch, - newTargetEpoch types.Epoch, + newTargetEpoch primitives.Epoch, ) (keepGoing bool, err error) { epochInChunk := startEpoch // We go down the chunk for the validator, updating every value starting at start_epoch up to // and including the current epoch. As long as the epoch, e, is in the same chunk index and e <= currentEpoch, // we proceed with a for loop. for m.params.chunkIndex(epochInChunk) == args.chunkIndex && epochInChunk <= args.currentEpoch { - var chunkTarget types.Epoch + var chunkTarget primitives.Epoch chunkTarget, err = chunkDataAtEpoch(m.params, m.data, validatorIndex, epochInChunk) if err != nil { err = errors.Wrapf(err, "could not get chunk data at epoch %d", epochInChunk) @@ -409,8 +409,8 @@ func (m *MaxSpanChunksSlice) Update( // then the start epoch is source epoch - 1. Otherwise, we return to the caller a boolean signifying // the input argumets are invalid for the chunk and the start epoch does not exist. func (m *MinSpanChunksSlice) StartEpoch( - sourceEpoch, currentEpoch types.Epoch, -) (epoch types.Epoch, exists bool) { + sourceEpoch, currentEpoch primitives.Epoch, +) (epoch primitives.Epoch, exists bool) { // Given min span chunks are used for detecting surrounding votes, we have no need // for a start epoch of the chunk if the source epoch is 0 in the input arguments. // To further clarify, min span chunks are updated in reverse order [a, b, c, d] where @@ -420,7 +420,7 @@ func (m *MinSpanChunksSlice) StartEpoch( if sourceEpoch == 0 { return } - var difference types.Epoch + var difference primitives.Epoch if currentEpoch > m.params.historyLength { difference = currentEpoch - m.params.historyLength } @@ -435,8 +435,8 @@ func (m *MinSpanChunksSlice) StartEpoch( // StartEpoch given a source epoch and current epoch, determines the start epoch of // a max span chunk for use in chunk updates. The source epoch cannot be >= the current epoch. func (_ *MaxSpanChunksSlice) StartEpoch( - sourceEpoch, currentEpoch types.Epoch, -) (epoch types.Epoch, exists bool) { + sourceEpoch, currentEpoch primitives.Epoch, +) (epoch primitives.Epoch, exists bool) { if sourceEpoch >= currentEpoch { return } @@ -463,7 +463,7 @@ func (_ *MaxSpanChunksSlice) StartEpoch( // last_epoch(1 - 1) // last_epoch(0) // 2 -func (m *MinSpanChunksSlice) NextChunkStartEpoch(startEpoch types.Epoch) types.Epoch { +func (m *MinSpanChunksSlice) NextChunkStartEpoch(startEpoch primitives.Epoch) primitives.Epoch { prevChunkIdx := m.params.chunkIndex(startEpoch) if prevChunkIdx > 0 { prevChunkIdx-- @@ -486,15 +486,15 @@ func (m *MinSpanChunksSlice) NextChunkStartEpoch(startEpoch types.Epoch) types.E // first_epoch(1 + 1) // first_epoch(2) // 4 -func (m *MaxSpanChunksSlice) NextChunkStartEpoch(startEpoch types.Epoch) types.Epoch { +func (m *MaxSpanChunksSlice) NextChunkStartEpoch(startEpoch primitives.Epoch) primitives.Epoch { return m.params.firstEpoch(m.params.chunkIndex(startEpoch) + 1) } // Given a validator index and epoch, retrieves the target epoch at its specific // index for the validator index and epoch in a min/max span chunk. func chunkDataAtEpoch( - params *Parameters, chunk []uint16, validatorIdx types.ValidatorIndex, epoch types.Epoch, -) (types.Epoch, error) { + params *Parameters, chunk []uint16, validatorIdx primitives.ValidatorIndex, epoch primitives.Epoch, +) (primitives.Epoch, error) { requiredLen := params.chunkSize * params.validatorChunkSize if uint64(len(chunk)) != requiredLen { return 0, fmt.Errorf("chunk has wrong length, %d, expected %d", len(chunk), requiredLen) @@ -514,9 +514,9 @@ func chunkDataAtEpoch( func setChunkDataAtEpoch( params *Parameters, chunk []uint16, - validatorIdx types.ValidatorIndex, + validatorIdx primitives.ValidatorIndex, epochInChunk, - targetEpoch types.Epoch, + targetEpoch primitives.Epoch, ) error { distance, err := epochDistance(targetEpoch, epochInChunk) if err != nil { @@ -530,8 +530,8 @@ func setChunkDataAtEpoch( func setChunkRawDistance( params *Parameters, chunk []uint16, - validatorIdx types.ValidatorIndex, - epochInChunk types.Epoch, + validatorIdx primitives.ValidatorIndex, + epochInChunk primitives.Epoch, distance uint16, ) error { cellIdx := params.cellIndex(validatorIdx, epochInChunk) @@ -545,7 +545,7 @@ func setChunkRawDistance( // Computes a distance between two epochs. Given the result stored in // min/max spans is at maximum WEAK_SUBJECTIVITY_PERIOD, we are guaranteed the // distance can be represented as a uint16 safely. -func epochDistance(epoch, baseEpoch types.Epoch) (uint16, error) { +func epochDistance(epoch, baseEpoch primitives.Epoch) (uint16, error) { if baseEpoch > epoch { return 0, fmt.Errorf("base epoch %d cannot be less than epoch %d", baseEpoch, epoch) } diff --git a/beacon-chain/slasher/chunks_test.go b/beacon-chain/slasher/chunks_test.go index 4df191bca9..214d35db68 100644 --- a/beacon-chain/slasher/chunks_test.go +++ b/beacon-chain/slasher/chunks_test.go @@ -7,7 +7,7 @@ import ( dbtest "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -88,9 +88,9 @@ func TestMinSpanChunksSlice_CheckSlashable(t *testing.T) { validatorChunkSize: 2, historyLength: 3, } - validatorIdx := types.ValidatorIndex(1) - source := types.Epoch(1) - target := types.Epoch(2) + validatorIdx := primitives.ValidatorIndex(1) + source := primitives.Epoch(1) + target := primitives.Epoch(2) att := createAttestationWrapper(t, source, target, nil, nil) // A faulty chunk should lead to error. @@ -124,8 +124,8 @@ func TestMinSpanChunksSlice_CheckSlashable(t *testing.T) { // Next up we initialize an empty chunks slice and mark an attestation // with (source 1, target 2) as attested. chunk = EmptyMinSpanChunksSlice(params) - source = types.Epoch(1) - target = types.Epoch(2) + source = primitives.Epoch(1) + target = primitives.Epoch(2) att = createAttestationWrapper(t, source, target, nil, nil) chunkIdx := uint64(0) startEpoch := target @@ -139,8 +139,8 @@ func TestMinSpanChunksSlice_CheckSlashable(t *testing.T) { // Next up, we create a surrounding vote, but it should NOT be slashable // because we DO NOT have an existing attestation record in our database at the min target epoch. - source = types.Epoch(0) - target = types.Epoch(3) + source = primitives.Epoch(0) + target = primitives.Epoch(3) surroundingVote := createAttestationWrapper(t, source, target, nil, nil) slashing, err = chunk.CheckSlashable(ctx, slasherDB, validatorIdx, surroundingVote) @@ -170,9 +170,9 @@ func TestMaxSpanChunksSlice_CheckSlashable(t *testing.T) { validatorChunkSize: 2, historyLength: 4, } - validatorIdx := types.ValidatorIndex(1) - source := types.Epoch(1) - target := types.Epoch(2) + validatorIdx := primitives.ValidatorIndex(1) + source := primitives.Epoch(1) + target := primitives.Epoch(2) att := createAttestationWrapper(t, source, target, nil, nil) // A faulty chunk should lead to error. @@ -206,8 +206,8 @@ func TestMaxSpanChunksSlice_CheckSlashable(t *testing.T) { // Next up we initialize an empty chunks slice and mark an attestation // with (source 0, target 3) as attested. chunk = EmptyMaxSpanChunksSlice(params) - source = types.Epoch(0) - target = types.Epoch(3) + source = primitives.Epoch(0) + target = primitives.Epoch(3) att = createAttestationWrapper(t, source, target, nil, nil) chunkIdx := uint64(0) startEpoch := source @@ -221,8 +221,8 @@ func TestMaxSpanChunksSlice_CheckSlashable(t *testing.T) { // Next up, we create a surrounded vote, but it should NOT be slashable // because we DO NOT have an existing attestation record in our database at the max target epoch. - source = types.Epoch(1) - target = types.Epoch(2) + source = primitives.Epoch(1) + target = primitives.Epoch(2) surroundedVote := createAttestationWrapper(t, source, target, nil, nil) slashing, err = chunk.CheckSlashable(ctx, slasherDB, validatorIdx, surroundedVote) @@ -287,9 +287,9 @@ func TestMinSpanChunksSlice_Update_MultipleChunks(t *testing.T) { historyLength: 4, } chunk := EmptyMinSpanChunksSlice(params) - target := types.Epoch(3) + target := primitives.Epoch(3) chunkIdx := uint64(1) - validatorIdx := types.ValidatorIndex(0) + validatorIdx := primitives.ValidatorIndex(0) startEpoch := target currentEpoch := target args := &chunkUpdateArgs{ @@ -307,8 +307,8 @@ func TestMinSpanChunksSlice_Update_MultipleChunks(t *testing.T) { // Now we update for chunk index 0. chunk = EmptyMinSpanChunksSlice(params) chunkIdx = uint64(0) - validatorIdx = types.ValidatorIndex(0) - startEpoch = types.Epoch(1) + validatorIdx = primitives.ValidatorIndex(0) + startEpoch = primitives.Epoch(1) currentEpoch = target args = &chunkUpdateArgs{ chunkIndex: chunkIdx, @@ -328,10 +328,10 @@ func TestMaxSpanChunksSlice_Update_MultipleChunks(t *testing.T) { historyLength: 4, } chunk := EmptyMaxSpanChunksSlice(params) - target := types.Epoch(3) + target := primitives.Epoch(3) chunkIdx := uint64(0) - validatorIdx := types.ValidatorIndex(0) - startEpoch := types.Epoch(0) + validatorIdx := primitives.ValidatorIndex(0) + startEpoch := primitives.Epoch(0) currentEpoch := target args := &chunkUpdateArgs{ chunkIndex: chunkIdx, @@ -348,8 +348,8 @@ func TestMaxSpanChunksSlice_Update_MultipleChunks(t *testing.T) { // Now we update for chunk index 1. chunk = EmptyMaxSpanChunksSlice(params) chunkIdx = uint64(1) - validatorIdx = types.ValidatorIndex(0) - startEpoch = types.Epoch(2) + validatorIdx = primitives.ValidatorIndex(0) + startEpoch = primitives.Epoch(2) currentEpoch = target args = &chunkUpdateArgs{ chunkIndex: chunkIdx, @@ -392,9 +392,9 @@ func TestMinSpanChunksSlice_Update_SingleChunk(t *testing.T) { historyLength: 2, } chunk := EmptyMinSpanChunksSlice(params) - target := types.Epoch(1) + target := primitives.Epoch(1) chunkIdx := uint64(0) - validatorIdx := types.ValidatorIndex(0) + validatorIdx := primitives.ValidatorIndex(0) startEpoch := target currentEpoch := target args := &chunkUpdateArgs{ @@ -415,10 +415,10 @@ func TestMaxSpanChunksSlice_Update_SingleChunk(t *testing.T) { historyLength: 4, } chunk := EmptyMaxSpanChunksSlice(params) - target := types.Epoch(3) + target := primitives.Epoch(3) chunkIdx := uint64(0) - validatorIdx := types.ValidatorIndex(0) - startEpoch := types.Epoch(0) + validatorIdx := primitives.ValidatorIndex(0) + startEpoch := primitives.Epoch(0) currentEpoch := target args := &chunkUpdateArgs{ chunkIndex: chunkIdx, @@ -433,14 +433,14 @@ func TestMaxSpanChunksSlice_Update_SingleChunk(t *testing.T) { func TestMinSpanChunksSlice_StartEpoch(t *testing.T) { type args struct { - sourceEpoch types.Epoch - currentEpoch types.Epoch + sourceEpoch primitives.Epoch + currentEpoch primitives.Epoch } tests := []struct { name string params *Parameters args args - wantEpoch types.Epoch + wantEpoch primitives.Epoch shouldNotExist bool }{ { @@ -499,14 +499,14 @@ func TestMinSpanChunksSlice_StartEpoch(t *testing.T) { func TestMaxSpanChunksSlice_StartEpoch(t *testing.T) { type args struct { - sourceEpoch types.Epoch - currentEpoch types.Epoch + sourceEpoch primitives.Epoch + currentEpoch primitives.Epoch } tests := []struct { name string params *Parameters args args - wantEpoch types.Epoch + wantEpoch primitives.Epoch shouldNotExist bool }{ { @@ -553,8 +553,8 @@ func TestMinSpanChunksSlice_NextChunkStartEpoch(t *testing.T) { tests := []struct { name string params *Parameters - startEpoch types.Epoch - want types.Epoch + startEpoch primitives.Epoch + want primitives.Epoch }{ { name: "Start epoch 0", @@ -599,8 +599,8 @@ func TestMaxSpanChunksSlice_NextChunkStartEpoch(t *testing.T) { tests := []struct { name string params *Parameters - startEpoch types.Epoch - want types.Epoch + startEpoch primitives.Epoch + want primitives.Epoch }{ { name: "Start epoch 0", @@ -649,15 +649,15 @@ func Test_chunkDataAtEpoch_SetRetrieve(t *testing.T) { validatorChunkSize: 2, } chunk := []uint16{2, 2, 2, 2, 2, 2} - validatorIdx := types.ValidatorIndex(1) - epochInChunk := types.Epoch(1) + validatorIdx := primitives.ValidatorIndex(1) + epochInChunk := primitives.Epoch(1) // We expect a chunk with the wrong length to throw an error. _, err := chunkDataAtEpoch(params, []uint16{}, validatorIdx, epochInChunk) require.ErrorContains(t, "chunk has wrong length", err) // We update the value for epoch 1 using target epoch 6. - targetEpoch := types.Epoch(6) + targetEpoch := primitives.Epoch(6) err = setChunkDataAtEpoch(params, chunk, validatorIdx, epochInChunk, targetEpoch) require.NoError(t, err) diff --git a/beacon-chain/slasher/detect_attestations.go b/beacon-chain/slasher/detect_attestations.go index f63dcf4b57..dc7a9956cf 100644 --- a/beacon-chain/slasher/detect_attestations.go +++ b/beacon-chain/slasher/detect_attestations.go @@ -7,7 +7,7 @@ import ( "github.com/pkg/errors" slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/sirupsen/logrus" "go.opencensus.io/trace" @@ -16,7 +16,7 @@ import ( // Takes in a list of indexed attestation wrappers and returns any // found attester slashings to the caller. func (s *Service) checkSlashableAttestations( - ctx context.Context, currentEpoch types.Epoch, atts []*slashertypes.IndexedAttestationWrapper, + ctx context.Context, currentEpoch primitives.Epoch, atts []*slashertypes.IndexedAttestationWrapper, ) ([]*ethpb.AttesterSlashing, error) { slashings := make([]*ethpb.AttesterSlashing, 0) @@ -209,7 +209,7 @@ func (s *Service) epochUpdateForValidator( ctx context.Context, args *chunkUpdateArgs, updatedChunks map[uint64]Chunker, - validatorIndex types.ValidatorIndex, + validatorIndex primitives.ValidatorIndex, ) error { epoch := s.latestEpochWrittenForValidator[validatorIndex] if epoch == 0 { @@ -261,7 +261,7 @@ func (s *Service) updateSpans( for _, attestationBatch := range attestationsByChunkIdx { for _, att := range attestationBatch { for _, validatorIdx := range att.IndexedAttestation.AttestingIndices { - validatorIndex := types.ValidatorIndex(validatorIdx) + validatorIndex := primitives.ValidatorIndex(validatorIdx) computedValidatorChunkIdx := s.params.validatorChunkIndex(validatorIndex) // Every validator chunk index represents a range of validators. @@ -308,7 +308,7 @@ func (s *Service) updateSpans( func (s *Service) applyAttestationForValidator( ctx context.Context, args *chunkUpdateArgs, - validatorIndex types.ValidatorIndex, + validatorIndex primitives.ValidatorIndex, chunksByChunkIdx map[uint64]Chunker, attestation *slashertypes.IndexedAttestationWrapper, ) (*ethpb.AttesterSlashing, error) { diff --git a/beacon-chain/slasher/detect_attestations_test.go b/beacon-chain/slasher/detect_attestations_test.go index 78422b05a2..e35318912b 100644 --- a/beacon-chain/slasher/detect_attestations_test.go +++ b/beacon-chain/slasher/detect_attestations_test.go @@ -12,7 +12,7 @@ import ( slashingsmock "github.com/prysmaticlabs/prysm/v3/beacon-chain/operations/slashings/mock" slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -26,7 +26,7 @@ import ( func Test_processQueuedAttestations(t *testing.T) { type args struct { attestationQueue []*slashertypes.IndexedAttestationWrapper - currentEpoch types.Epoch + currentEpoch primitives.Epoch } tests := []struct { name string @@ -243,7 +243,7 @@ func Test_processQueuedAttestations(t *testing.T) { require.NoError(t, err) s.genesisTime = genesisTime - currentSlotChan := make(chan types.Slot) + currentSlotChan := make(chan primitives.Slot) exitChan := make(chan struct{}) go func() { s.processQueuedAttestations(ctx, currentSlotChan) @@ -275,8 +275,8 @@ func Test_processQueuedAttestations_MultipleChunkIndices(t *testing.T) { // What we want to test here is if we can proceed // with processing queued attestations once the chunk index changes. // For example, epochs 0 - 15 are chunk 0, epochs 16 - 31 are chunk 1, etc. - startEpoch := types.Epoch(slasherParams.chunkSize) - endEpoch := types.Epoch(slasherParams.chunkSize + 1) + startEpoch := primitives.Epoch(slasherParams.chunkSize) + endEpoch := primitives.Epoch(slasherParams.chunkSize + 1) currentTime := time.Now() totalSlots := uint64(startEpoch) * uint64(params.BeaconConfig().SlotsPerEpoch) @@ -300,7 +300,7 @@ func Test_processQueuedAttestations_MultipleChunkIndices(t *testing.T) { require.NoError(t, err) s.genesisTime = genesisTime - currentSlotChan := make(chan types.Slot) + currentSlotChan := make(chan primitives.Slot) exitChan := make(chan struct{}) go func() { s.processQueuedAttestations(ctx, currentSlotChan) @@ -308,8 +308,8 @@ func Test_processQueuedAttestations_MultipleChunkIndices(t *testing.T) { }() for i := startEpoch; i <= endEpoch; i++ { - source := types.Epoch(0) - target := types.Epoch(0) + source := primitives.Epoch(0) + target := primitives.Epoch(0) if i != 0 { source = i - 1 target = i @@ -341,7 +341,7 @@ func Test_processQueuedAttestations_OverlappingChunkIndices(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) slasherParams := DefaultParams() - startEpoch := types.Epoch(slasherParams.chunkSize) + startEpoch := primitives.Epoch(slasherParams.chunkSize) currentTime := time.Now() totalSlots := uint64(startEpoch) * uint64(params.BeaconConfig().SlotsPerEpoch) @@ -365,7 +365,7 @@ func Test_processQueuedAttestations_OverlappingChunkIndices(t *testing.T) { require.NoError(t, err) s.genesisTime = genesisTime - currentSlotChan := make(chan types.Slot) + currentSlotChan := make(chan primitives.Slot) exitChan := make(chan struct{}) go func() { s.processQueuedAttestations(ctx, currentSlotChan) @@ -373,8 +373,8 @@ func Test_processQueuedAttestations_OverlappingChunkIndices(t *testing.T) { }() // We create two attestations fully spanning chunk indices 0 and chunk 1 - att1 := createAttestationWrapper(t, types.Epoch(slasherParams.chunkSize-2), types.Epoch(slasherParams.chunkSize), []uint64{0, 1}, nil) - att2 := createAttestationWrapper(t, types.Epoch(slasherParams.chunkSize-1), types.Epoch(slasherParams.chunkSize+1), []uint64{0, 1}, nil) + att1 := createAttestationWrapper(t, primitives.Epoch(slasherParams.chunkSize-2), primitives.Epoch(slasherParams.chunkSize), []uint64{0, 1}, nil) + att2 := createAttestationWrapper(t, primitives.Epoch(slasherParams.chunkSize-1), primitives.Epoch(slasherParams.chunkSize+1), []uint64{0, 1}, nil) // We attempt to process the batch. s.attsQueue = newAttestationsQueue() @@ -405,16 +405,16 @@ func Test_epochUpdateForValidators(t *testing.T) { historyLength: 4, }, serviceCfg: &ServiceConfig{Database: slasherDB}, - latestEpochWrittenForValidator: map[types.ValidatorIndex]types.Epoch{}, + latestEpochWrittenForValidator: map[primitives.ValidatorIndex]primitives.Epoch{}, } t.Run("no update if no latest written epoch", func(t *testing.T) { - validators := []types.ValidatorIndex{ + validators := []primitives.ValidatorIndex{ 1, 2, } - currentEpoch := types.Epoch(3) + currentEpoch := primitives.Epoch(3) // No last written epoch for both validators. - s.latestEpochWrittenForValidator = map[types.ValidatorIndex]types.Epoch{} + s.latestEpochWrittenForValidator = map[primitives.ValidatorIndex]primitives.Epoch{} // Because the validators have no recorded latest epoch written, we expect // no chunks to be loaded nor updated to. @@ -434,14 +434,14 @@ func Test_epochUpdateForValidators(t *testing.T) { }) t.Run("update from latest written epoch", func(t *testing.T) { - validators := []types.ValidatorIndex{ + validators := []primitives.ValidatorIndex{ 1, 2, } - currentEpoch := types.Epoch(3) + currentEpoch := primitives.Epoch(3) // Set the latest written epoch for validators to current epoch - 1. latestWrittenEpoch := currentEpoch - 1 - s.latestEpochWrittenForValidator = map[types.ValidatorIndex]types.Epoch{ + s.latestEpochWrittenForValidator = map[primitives.ValidatorIndex]primitives.Epoch{ 1: latestWrittenEpoch, 2: latestWrittenEpoch, } @@ -481,8 +481,8 @@ func Test_applyAttestationForValidator_MinSpanChunk(t *testing.T) { // We initialize an empty chunks slice. chunk := EmptyMinSpanChunksSlice(defaultParams) chunkIdx := uint64(0) - currentEpoch := types.Epoch(3) - validatorIdx := types.ValidatorIndex(0) + currentEpoch := primitives.Epoch(3) + validatorIdx := primitives.ValidatorIndex(0) args := &chunkUpdateArgs{ chunkIndex: chunkIdx, currentEpoch: currentEpoch, @@ -492,8 +492,8 @@ func Test_applyAttestationForValidator_MinSpanChunk(t *testing.T) { } // We apply attestation with (source 1, target 2) for our validator. - source := types.Epoch(1) - target := types.Epoch(2) + source := primitives.Epoch(1) + target := primitives.Epoch(2) att := createAttestationWrapper(t, source, target, nil, nil) slashing, err := srv.applyAttestationForValidator( ctx, @@ -513,8 +513,8 @@ func Test_applyAttestationForValidator_MinSpanChunk(t *testing.T) { // Next, we apply an attestation with (source 0, target 3) and // expect a slashable offense to be returned. - source = types.Epoch(0) - target = types.Epoch(3) + source = primitives.Epoch(0) + target = primitives.Epoch(3) slashableAtt := createAttestationWrapper(t, source, target, nil, nil) slashing, err = srv.applyAttestationForValidator( ctx, @@ -541,8 +541,8 @@ func Test_applyAttestationForValidator_MaxSpanChunk(t *testing.T) { // We initialize an empty chunks slice. chunk := EmptyMaxSpanChunksSlice(defaultParams) chunkIdx := uint64(0) - currentEpoch := types.Epoch(3) - validatorIdx := types.ValidatorIndex(0) + currentEpoch := primitives.Epoch(3) + validatorIdx := primitives.ValidatorIndex(0) args := &chunkUpdateArgs{ chunkIndex: chunkIdx, currentEpoch: currentEpoch, @@ -552,8 +552,8 @@ func Test_applyAttestationForValidator_MaxSpanChunk(t *testing.T) { } // We apply attestation with (source 0, target 3) for our validator. - source := types.Epoch(0) - target := types.Epoch(3) + source := primitives.Epoch(0) + target := primitives.Epoch(3) att := createAttestationWrapper(t, source, target, nil, nil) slashing, err := srv.applyAttestationForValidator( ctx, @@ -573,8 +573,8 @@ func Test_applyAttestationForValidator_MaxSpanChunk(t *testing.T) { // Next, we apply an attestation with (source 1, target 2) and // expect a slashable offense to be returned. - source = types.Epoch(1) - target = types.Epoch(2) + source = primitives.Epoch(1) + target = primitives.Epoch(2) slashableAtt := createAttestationWrapper(t, source, target, nil, nil) slashing, err = srv.applyAttestationForValidator( ctx, @@ -714,9 +714,9 @@ func testLoadChunks(t *testing.T, kind slashertypes.ChunkKind) { } else { existingChunk = EmptyMaxSpanChunksSlice(defaultParams) } - validatorIdx := types.ValidatorIndex(0) - epochInChunk := types.Epoch(0) - targetEpoch := types.Epoch(2) + validatorIdx := primitives.ValidatorIndex(0) + epochInChunk := primitives.Epoch(0) + targetEpoch := primitives.Epoch(2) err = setChunkDataAtEpoch( defaultParams, existingChunk.Chunk(), @@ -776,7 +776,7 @@ func TestService_processQueuedAttestations(t *testing.T) { createAttestationWrapper(t, 0, 1, []uint64{0, 1} /* indices */, nil /* signingRoot */), }) ctx, cancel := context.WithCancel(context.Background()) - tickerChan := make(chan types.Slot) + tickerChan := make(chan primitives.Slot) exitChan := make(chan struct{}) go func() { s.processQueuedAttestations(ctx, tickerChan) @@ -795,7 +795,7 @@ func BenchmarkCheckSlashableAttestations(b *testing.B) { beaconState, err := util.NewBeaconState() require.NoError(b, err) - slot := types.Slot(0) + slot := primitives.Slot(0) mockChain := &mock.ChainService{ State: beaconState, Slot: &slot, @@ -855,8 +855,8 @@ func runAttestationsBenchmark(b *testing.B, s *Service, numAtts, numValidators u } atts := make([]*slashertypes.IndexedAttestationWrapper, numAtts) for i := uint64(0); i < numAtts; i++ { - source := types.Epoch(i) - target := types.Epoch(i + 1) + source := primitives.Epoch(i) + target := primitives.Epoch(i + 1) var signingRoot [32]byte copy(signingRoot[:], fmt.Sprintf("%d", i)) atts[i] = createAttestationWrapper( @@ -879,7 +879,7 @@ func runAttestationsBenchmark(b *testing.B, s *Service, numAtts, numValidators u } } -func createAttestationWrapper(t testing.TB, source, target types.Epoch, indices []uint64, signingRoot []byte) *slashertypes.IndexedAttestationWrapper { +func createAttestationWrapper(t testing.TB, source, target primitives.Epoch, indices []uint64, signingRoot []byte) *slashertypes.IndexedAttestationWrapper { data := ðpb.AttestationData{ BeaconBlockRoot: bytesutil.PadTo(signingRoot, 32), Source: ðpb.Checkpoint{ diff --git a/beacon-chain/slasher/detect_blocks.go b/beacon-chain/slasher/detect_blocks.go index d7b5edaa56..584b7218ad 100644 --- a/beacon-chain/slasher/detect_blocks.go +++ b/beacon-chain/slasher/detect_blocks.go @@ -5,7 +5,7 @@ import ( "github.com/pkg/errors" slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "go.opencensus.io/trace" ) @@ -69,7 +69,7 @@ func filterSafeProposals( proposerSlashings []*ethpb.ProposerSlashing, ) []*slashertypes.SignedBlockHeaderWrapper { // We initialize a map of proposers that are safe from slashing. - safeProposers := make(map[types.ValidatorIndex]*slashertypes.SignedBlockHeaderWrapper, len(proposedBlocks)) + safeProposers := make(map[primitives.ValidatorIndex]*slashertypes.SignedBlockHeaderWrapper, len(proposedBlocks)) for _, proposal := range proposedBlocks { safeProposers[proposal.SignedBeaconBlockHeader.Header.ProposerIndex] = proposal } diff --git a/beacon-chain/slasher/detect_blocks_test.go b/beacon-chain/slasher/detect_blocks_test.go index 10abb47325..2ef9f59b1b 100644 --- a/beacon-chain/slasher/detect_blocks_test.go +++ b/beacon-chain/slasher/detect_blocks_test.go @@ -12,7 +12,7 @@ import ( slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -72,7 +72,7 @@ func Test_processQueuedBlocks_DetectsDoubleProposals(t *testing.T) { err = s.serviceCfg.StateGen.SaveState(ctx, parentRoot, beaconState) require.NoError(t, err) - currentSlotChan := make(chan types.Slot) + currentSlotChan := make(chan primitives.Slot) exitChan := make(chan struct{}) go func() { s.processQueuedBlocks(ctx, currentSlotChan) @@ -103,7 +103,7 @@ func Test_processQueuedBlocks_DetectsDoubleProposals(t *testing.T) { s.blksQueue.extend(signedBlkHeaders) - currentSlot := types.Slot(4) + currentSlot := primitives.Slot(4) currentSlotChan <- currentSlot cancel() <-exitChan @@ -117,7 +117,7 @@ func Test_processQueuedBlocks_NotSlashable(t *testing.T) { beaconState, err := util.NewBeaconState() require.NoError(t, err) - currentSlot := types.Slot(4) + currentSlot := primitives.Slot(4) require.NoError(t, beaconState.SetSlot(currentSlot)) mockChain := &mock.ChainService{ State: beaconState, @@ -133,7 +133,7 @@ func Test_processQueuedBlocks_NotSlashable(t *testing.T) { params: DefaultParams(), blksQueue: newBlocksQueue(), } - currentSlotChan := make(chan types.Slot) + currentSlotChan := make(chan primitives.Slot) exitChan := make(chan struct{}) go func() { s.processQueuedBlocks(ctx, currentSlotChan) @@ -149,7 +149,7 @@ func Test_processQueuedBlocks_NotSlashable(t *testing.T) { require.LogsDoNotContain(t, hook, "Proposer slashing detected") } -func createProposalWrapper(t *testing.T, slot types.Slot, proposerIndex types.ValidatorIndex, signingRoot []byte) *slashertypes.SignedBlockHeaderWrapper { +func createProposalWrapper(t *testing.T, slot primitives.Slot, proposerIndex primitives.ValidatorIndex, signingRoot []byte) *slashertypes.SignedBlockHeaderWrapper { header := ðpb.BeaconBlockHeader{ Slot: slot, ProposerIndex: proposerIndex, diff --git a/beacon-chain/slasher/helpers.go b/beacon-chain/slasher/helpers.go index e9d3aefcac..afd2d8eb82 100644 --- a/beacon-chain/slasher/helpers.go +++ b/beacon-chain/slasher/helpers.go @@ -7,7 +7,7 @@ import ( slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/sirupsen/logrus" @@ -24,7 +24,7 @@ func (s *Service) groupByValidatorChunkIndex( for _, att := range attestations { validatorChunkIndices := make(map[uint64]bool) for _, validatorIdx := range att.IndexedAttestation.AttestingIndices { - validatorChunkIndex := s.params.validatorChunkIndex(types.ValidatorIndex(validatorIdx)) + validatorChunkIndex := s.params.validatorChunkIndex(primitives.ValidatorIndex(validatorIdx)) validatorChunkIndices[validatorChunkIndex] = true } for validatorChunkIndex := range validatorChunkIndices { @@ -52,7 +52,7 @@ func (s *Service) groupByChunkIndex( // This function returns a list of valid attestations, a list of attestations that are // valid in the future, and the number of attestations dropped. func (s *Service) filterAttestations( - atts []*slashertypes.IndexedAttestationWrapper, currentEpoch types.Epoch, + atts []*slashertypes.IndexedAttestationWrapper, currentEpoch primitives.Epoch, ) (valid, validInFuture []*slashertypes.IndexedAttestationWrapper, numDropped int) { valid = make([]*slashertypes.IndexedAttestationWrapper, 0, len(atts)) validInFuture = make([]*slashertypes.IndexedAttestationWrapper, 0, len(atts)) diff --git a/beacon-chain/slasher/helpers_test.go b/beacon-chain/slasher/helpers_test.go index 54f27689eb..4481c5ba4d 100644 --- a/beacon-chain/slasher/helpers_test.go +++ b/beacon-chain/slasher/helpers_test.go @@ -7,7 +7,7 @@ import ( slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" logTest "github.com/sirupsen/logrus/hooks/test" @@ -143,7 +143,7 @@ func TestService_filterAttestations(t *testing.T) { tests := []struct { name string input []*slashertypes.IndexedAttestationWrapper - inputEpoch types.Epoch + inputEpoch primitives.Epoch wantedValid []*slashertypes.IndexedAttestationWrapper wantedDeferred []*slashertypes.IndexedAttestationWrapper wantedDropped int diff --git a/beacon-chain/slasher/mock/mock_slashing_checker.go b/beacon-chain/slasher/mock/mock_slashing_checker.go index 7453d5acc6..991f47e499 100644 --- a/beacon-chain/slasher/mock/mock_slashing_checker.go +++ b/beacon-chain/slasher/mock/mock_slashing_checker.go @@ -4,18 +4,18 @@ import ( "context" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) type MockSlashingChecker struct { AttesterSlashingFound bool ProposerSlashingFound bool - HighestAtts map[types.ValidatorIndex]*ethpb.HighestAttestation + HighestAtts map[primitives.ValidatorIndex]*ethpb.HighestAttestation } func (s *MockSlashingChecker) HighestAttestations( - _ context.Context, indices []types.ValidatorIndex, + _ context.Context, indices []primitives.ValidatorIndex, ) ([]*ethpb.HighestAttestation, error) { atts := make([]*ethpb.HighestAttestation, 0, len(indices)) for _, valIdx := range indices { diff --git a/beacon-chain/slasher/params.go b/beacon-chain/slasher/params.go index d59b15b810..c5ce489218 100644 --- a/beacon-chain/slasher/params.go +++ b/beacon-chain/slasher/params.go @@ -2,7 +2,7 @@ package slasher import ( ssz "github.com/prysmaticlabs/fastssz" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // Parameters for slashing detection. @@ -19,7 +19,7 @@ import ( type Parameters struct { chunkSize uint64 validatorChunkSize uint64 - historyLength types.Epoch + historyLength primitives.Epoch } // DefaultParams defines default values for slasher's important parameters, defined @@ -47,14 +47,14 @@ func DefaultParams() *Parameters { // span = [-, -, -, -, -, -] // chunked = [[-, -], [-, -], [-, -]] // |-> epoch 4, chunk idx 2 -func (p *Parameters) chunkIndex(epoch types.Epoch) uint64 { +func (p *Parameters) chunkIndex(epoch primitives.Epoch) uint64 { return uint64(epoch.Mod(uint64(p.historyLength)).Div(p.chunkSize)) } // When storing data on disk, we take K validators' chunks. To figure out // which validator chunk index a validator index is for, we simply divide // the validator index, i, by K. -func (p *Parameters) validatorChunkIndex(validatorIndex types.ValidatorIndex) uint64 { +func (p *Parameters) validatorChunkIndex(validatorIndex primitives.ValidatorIndex) uint64 { return uint64(validatorIndex.Div(p.validatorChunkSize)) } @@ -67,8 +67,8 @@ func (p *Parameters) validatorChunkIndex(validatorIndex types.ValidatorIndex) ui // [[-, -, -], [-, -, -], [-, -, -], ...] // | // -> first epoch of chunk 1 equals 3 -func (p *Parameters) firstEpoch(chunkIndex uint64) types.Epoch { - return types.Epoch(chunkIndex * p.chunkSize) +func (p *Parameters) firstEpoch(chunkIndex uint64) primitives.Epoch { + return primitives.Epoch(chunkIndex * p.chunkSize) } // Returns the epoch at the last index of a chunk at the specified chunk index. @@ -80,7 +80,7 @@ func (p *Parameters) firstEpoch(chunkIndex uint64) types.Epoch { // [[-, -, -], [-, -, -], [-, -, -], ...] // | // -> last epoch of chunk 1 equals 5 -func (p *Parameters) lastEpoch(chunkIndex uint64) types.Epoch { +func (p *Parameters) lastEpoch(chunkIndex uint64) primitives.Epoch { return p.firstEpoch(chunkIndex).Add(p.chunkSize - 1) } @@ -106,19 +106,19 @@ func (p *Parameters) lastEpoch(chunkIndex uint64) types.Epoch { // { } { } { } // [-, -, -, -, -, -, -, -, -] // |-> epoch 1 for val2 -func (p *Parameters) cellIndex(validatorIndex types.ValidatorIndex, epoch types.Epoch) uint64 { +func (p *Parameters) cellIndex(validatorIndex primitives.ValidatorIndex, epoch primitives.Epoch) uint64 { validatorChunkOffset := p.validatorOffset(validatorIndex) chunkOffset := p.chunkOffset(epoch) return validatorChunkOffset*p.chunkSize + chunkOffset } // Computes the start index of a chunk given an epoch. -func (p *Parameters) chunkOffset(epoch types.Epoch) uint64 { +func (p *Parameters) chunkOffset(epoch primitives.Epoch) uint64 { return uint64(epoch.Mod(p.chunkSize)) } // Computes the start index of a validator chunk given a validator index. -func (p *Parameters) validatorOffset(validatorIndex types.ValidatorIndex) uint64 { +func (p *Parameters) validatorOffset(validatorIndex primitives.ValidatorIndex) uint64 { return uint64(validatorIndex.Mod(p.validatorChunkSize)) } @@ -147,12 +147,12 @@ func (p *Parameters) flatSliceID(validatorChunkIndex, chunkIndex uint64) []byte // Given a validator chunk index, we determine all of the validator // indices that will belong in that chunk. -func (p *Parameters) validatorIndicesInChunk(validatorChunkIdx uint64) []types.ValidatorIndex { - validatorIndices := make([]types.ValidatorIndex, 0) +func (p *Parameters) validatorIndicesInChunk(validatorChunkIdx uint64) []primitives.ValidatorIndex { + validatorIndices := make([]primitives.ValidatorIndex, 0) low := validatorChunkIdx * p.validatorChunkSize high := (validatorChunkIdx + 1) * p.validatorChunkSize for i := low; i < high; i++ { - validatorIndices = append(validatorIndices, types.ValidatorIndex(i)) + validatorIndices = append(validatorIndices, primitives.ValidatorIndex(i)) } return validatorIndices } diff --git a/beacon-chain/slasher/params_test.go b/beacon-chain/slasher/params_test.go index e0c2520254..99c6b4e123 100644 --- a/beacon-chain/slasher/params_test.go +++ b/beacon-chain/slasher/params_test.go @@ -5,7 +5,7 @@ import ( "testing" ssz "github.com/prysmaticlabs/fastssz" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" ) @@ -18,8 +18,8 @@ func TestDefaultParams(t *testing.T) { func TestParams_cellIndex(t *testing.T) { type args struct { - validatorIndex types.ValidatorIndex - epoch types.Epoch + validatorIndex primitives.ValidatorIndex + epoch primitives.Epoch } tests := []struct { name string @@ -160,7 +160,7 @@ func TestParams_chunkIndex(t *testing.T) { tests := []struct { name string fields *Parameters - epoch types.Epoch + epoch primitives.Epoch want uint64 }{ { @@ -311,7 +311,7 @@ func TestParams_validatorChunkIndex(t *testing.T) { tests := []struct { name string fields *Parameters - validatorIndex types.ValidatorIndex + validatorIndex primitives.ValidatorIndex want uint64 }{ { @@ -355,7 +355,7 @@ func TestParams_chunkOffset(t *testing.T) { tests := []struct { name string fields *Parameters - epoch types.Epoch + epoch primitives.Epoch want uint64 }{ { @@ -399,7 +399,7 @@ func TestParams_validatorOffset(t *testing.T) { tests := []struct { name string fields *Parameters - validatorIndex types.ValidatorIndex + validatorIndex primitives.ValidatorIndex want uint64 }{ { @@ -444,7 +444,7 @@ func TestParams_validatorIndicesInChunk(t *testing.T) { name string fields *Parameters validatorChunkIdx uint64 - want []types.ValidatorIndex + want []primitives.ValidatorIndex }{ { name: "Returns proper indices", @@ -452,7 +452,7 @@ func TestParams_validatorIndicesInChunk(t *testing.T) { validatorChunkSize: 3, }, validatorChunkIdx: 2, - want: []types.ValidatorIndex{6, 7, 8}, + want: []primitives.ValidatorIndex{6, 7, 8}, }, { name: "0 validator chunk size returns empty", @@ -460,7 +460,7 @@ func TestParams_validatorIndicesInChunk(t *testing.T) { validatorChunkSize: 0, }, validatorChunkIdx: 100, - want: []types.ValidatorIndex{}, + want: []primitives.ValidatorIndex{}, }, } for _, tt := range tests { @@ -480,7 +480,7 @@ func TestParameters_firstEpoch(t *testing.T) { name string params *Parameters chunkIndex uint64 - want types.Epoch + want primitives.Epoch }{ { name: "first epoch of chunk 0 is 0", @@ -511,7 +511,7 @@ func TestParameters_lastEpoch(t *testing.T) { name string params *Parameters chunkIndex uint64 - want types.Epoch + want primitives.Epoch }{ { name: "with chunk_size = 3, last epoch of chunk 0 is 2", diff --git a/beacon-chain/slasher/queue_test.go b/beacon-chain/slasher/queue_test.go index 8a6faf5807..8f40a8e2a4 100644 --- a/beacon-chain/slasher/queue_test.go +++ b/beacon-chain/slasher/queue_test.go @@ -4,7 +4,7 @@ import ( "testing" slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -43,8 +43,8 @@ func Test_blocksQueue(t *testing.T) { t.Run("push_and_dequeue", func(tt *testing.T) { blkQueue := newBlocksQueue() wantedBlks := []*slashertypes.SignedBlockHeaderWrapper{ - createProposalWrapper(t, 0, types.ValidatorIndex(1), make([]byte, 32)), - createProposalWrapper(t, 1, types.ValidatorIndex(1), make([]byte, 32)), + createProposalWrapper(t, 0, primitives.ValidatorIndex(1), make([]byte, 32)), + createProposalWrapper(t, 1, primitives.ValidatorIndex(1), make([]byte, 32)), } blkQueue.push(wantedBlks[0]) blkQueue.push(wantedBlks[1]) @@ -58,8 +58,8 @@ func Test_blocksQueue(t *testing.T) { t.Run("extend_and_dequeue", func(tt *testing.T) { blkQueue := newBlocksQueue() wantedBlks := []*slashertypes.SignedBlockHeaderWrapper{ - createProposalWrapper(t, 0, types.ValidatorIndex(1), make([]byte, 32)), - createProposalWrapper(t, 1, types.ValidatorIndex(1), make([]byte, 32)), + createProposalWrapper(t, 0, primitives.ValidatorIndex(1), make([]byte, 32)), + createProposalWrapper(t, 1, primitives.ValidatorIndex(1), make([]byte, 32)), } blkQueue.extend(wantedBlks) require.DeepEqual(t, 2, blkQueue.size()) diff --git a/beacon-chain/slasher/receive.go b/beacon-chain/slasher/receive.go index cdd4e1a582..5e4e0c1449 100644 --- a/beacon-chain/slasher/receive.go +++ b/beacon-chain/slasher/receive.go @@ -6,7 +6,7 @@ import ( "github.com/pkg/errors" slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" "github.com/sirupsen/logrus" @@ -76,7 +76,7 @@ func (s *Service) receiveBlocks(ctx context.Context, beaconBlockHeadersChan chan // these attestations from a queue, then group them all by validator chunk index. // This grouping will allow us to perform detection on batches of attestations // per validator chunk index which can be done concurrently. -func (s *Service) processQueuedAttestations(ctx context.Context, slotTicker <-chan types.Slot) { +func (s *Service) processQueuedAttestations(ctx context.Context, slotTicker <-chan primitives.Slot) { for { select { case currentSlot := <-slotTicker: @@ -131,7 +131,7 @@ func (s *Service) processQueuedAttestations(ctx context.Context, slotTicker <-ch // Process queued blocks every time an epoch ticker fires. We retrieve // these blocks from a queue, then perform double proposal detection. -func (s *Service) processQueuedBlocks(ctx context.Context, slotTicker <-chan types.Slot) { +func (s *Service) processQueuedBlocks(ctx context.Context, slotTicker <-chan primitives.Slot) { for { select { case currentSlot := <-slotTicker: @@ -171,7 +171,7 @@ func (s *Service) processQueuedBlocks(ctx context.Context, slotTicker <-chan typ } // Prunes slasher data on each slot tick to prevent unnecessary build-up of disk space usage. -func (s *Service) pruneSlasherData(ctx context.Context, slotTicker <-chan types.Slot) { +func (s *Service) pruneSlasherData(ctx context.Context, slotTicker <-chan primitives.Slot) { for { select { case <-slotTicker: @@ -190,8 +190,8 @@ func (s *Service) pruneSlasherData(ctx context.Context, slotTicker <-chan types. // All data before that window is unnecessary for slasher, so can be periodically deleted. // Say HISTORY_LENGTH is 4 and we have data for epochs 0, 1, 2, 3. Once we hit epoch 4, the sliding window // we care about is 1, 2, 3, 4, so we can delete data for epoch 0. -func (s *Service) pruneSlasherDataWithinSlidingWindow(ctx context.Context, currentEpoch types.Epoch) error { - var maxPruningEpoch types.Epoch +func (s *Service) pruneSlasherDataWithinSlidingWindow(ctx context.Context, currentEpoch primitives.Epoch) error { + var maxPruningEpoch primitives.Epoch if currentEpoch >= s.params.historyLength { maxPruningEpoch = currentEpoch - s.params.historyLength } else { diff --git a/beacon-chain/slasher/receive_test.go b/beacon-chain/slasher/receive_test.go index b06e4b2f4f..a18e4d6367 100644 --- a/beacon-chain/slasher/receive_test.go +++ b/beacon-chain/slasher/receive_test.go @@ -9,7 +9,7 @@ import ( dbtest "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" params2 "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -76,16 +76,16 @@ func TestService_pruneSlasherDataWithinSlidingWindow_AttestationsPruned(t *testi require.NoError(t, err) // Attempt to prune and discover that all data is still intact. - currentEpoch := types.Epoch(3) + currentEpoch := primitives.Epoch(3) err = s.pruneSlasherDataWithinSlidingWindow(ctx, currentEpoch) require.NoError(t, err) - epochs := []types.Epoch{0, 1, 2, 3} + epochs := []primitives.Epoch{0, 1, 2, 3} for _, epoch := range epochs { - att, err := slasherDB.AttestationRecordForValidator(ctx, types.ValidatorIndex(0), epoch) + att, err := slasherDB.AttestationRecordForValidator(ctx, primitives.ValidatorIndex(0), epoch) require.NoError(t, err) require.NotNil(t, att) - att, err = slasherDB.AttestationRecordForValidator(ctx, types.ValidatorIndex(1), epoch) + att, err = slasherDB.AttestationRecordForValidator(ctx, primitives.ValidatorIndex(1), epoch) require.NoError(t, err) require.NotNil(t, att) } @@ -98,25 +98,25 @@ func TestService_pruneSlasherDataWithinSlidingWindow_AttestationsPruned(t *testi require.NoError(t, err) // Attempt to prune again by setting current epoch to 4. - currentEpoch = types.Epoch(4) + currentEpoch = primitives.Epoch(4) err = s.pruneSlasherDataWithinSlidingWindow(ctx, currentEpoch) require.NoError(t, err) // We should now only have data for epochs 1, 2, 3, 4. We should // have pruned data from epoch 0. - att, err := slasherDB.AttestationRecordForValidator(ctx, types.ValidatorIndex(0), 0) + att, err := slasherDB.AttestationRecordForValidator(ctx, primitives.ValidatorIndex(0), 0) require.NoError(t, err) require.Equal(t, true, att == nil) - att, err = slasherDB.AttestationRecordForValidator(ctx, types.ValidatorIndex(1), 0) + att, err = slasherDB.AttestationRecordForValidator(ctx, primitives.ValidatorIndex(1), 0) require.NoError(t, err) require.Equal(t, true, att == nil) - epochs = []types.Epoch{1, 2, 3, 4} + epochs = []primitives.Epoch{1, 2, 3, 4} for _, epoch := range epochs { - att, err := slasherDB.AttestationRecordForValidator(ctx, types.ValidatorIndex(0), epoch) + att, err := slasherDB.AttestationRecordForValidator(ctx, primitives.ValidatorIndex(0), epoch) require.NoError(t, err) require.NotNil(t, att) - att, err = slasherDB.AttestationRecordForValidator(ctx, types.ValidatorIndex(1), epoch) + att, err = slasherDB.AttestationRecordForValidator(ctx, primitives.ValidatorIndex(1), epoch) require.NoError(t, err) require.NotNil(t, att) } @@ -155,16 +155,16 @@ func TestService_pruneSlasherDataWithinSlidingWindow_ProposalsPruned(t *testing. require.NoError(t, err) // Attempt to prune and discover that all data is still intact. - currentEpoch := types.Epoch(3) + currentEpoch := primitives.Epoch(3) err = s.pruneSlasherDataWithinSlidingWindow(ctx, currentEpoch) require.NoError(t, err) - slots := []types.Slot{0, 1, 2, 3} + slots := []primitives.Slot{0, 1, 2, 3} for _, slot := range slots { - blk, err := slasherDB.BlockProposalForValidator(ctx, types.ValidatorIndex(0), slot) + blk, err := slasherDB.BlockProposalForValidator(ctx, primitives.ValidatorIndex(0), slot) require.NoError(t, err) require.NotNil(t, blk) - blk, err = slasherDB.BlockProposalForValidator(ctx, types.ValidatorIndex(1), slot) + blk, err = slasherDB.BlockProposalForValidator(ctx, primitives.ValidatorIndex(1), slot) require.NoError(t, err) require.NotNil(t, blk) } @@ -177,25 +177,25 @@ func TestService_pruneSlasherDataWithinSlidingWindow_ProposalsPruned(t *testing. require.NoError(t, err) // Attempt to prune again by setting current epoch to 4. - currentEpoch = types.Epoch(4) + currentEpoch = primitives.Epoch(4) err = s.pruneSlasherDataWithinSlidingWindow(ctx, currentEpoch) require.NoError(t, err) // We should now only have data for epochs 1, 2, 3, 4. We should // have pruned data from epoch 0. - blk, err := slasherDB.BlockProposalForValidator(ctx, types.ValidatorIndex(0), 0) + blk, err := slasherDB.BlockProposalForValidator(ctx, primitives.ValidatorIndex(0), 0) require.NoError(t, err) require.Equal(t, true, blk == nil) - blk, err = slasherDB.BlockProposalForValidator(ctx, types.ValidatorIndex(1), 0) + blk, err = slasherDB.BlockProposalForValidator(ctx, primitives.ValidatorIndex(1), 0) require.NoError(t, err) require.Equal(t, true, blk == nil) - slots = []types.Slot{1, 2, 3, 4} + slots = []primitives.Slot{1, 2, 3, 4} for _, slot := range slots { - blk, err := slasherDB.BlockProposalForValidator(ctx, types.ValidatorIndex(0), slot) + blk, err := slasherDB.BlockProposalForValidator(ctx, primitives.ValidatorIndex(0), slot) require.NoError(t, err) require.NotNil(t, blk) - blk, err = slasherDB.BlockProposalForValidator(ctx, types.ValidatorIndex(1), slot) + blk, err = slasherDB.BlockProposalForValidator(ctx, primitives.ValidatorIndex(1), slot) require.NoError(t, err) require.NotNil(t, blk) } @@ -275,7 +275,7 @@ func TestService_processQueuedBlocks(t *testing.T) { beaconState, err := util.NewBeaconState() require.NoError(t, err) - currentSlot := types.Slot(0) + currentSlot := primitives.Slot(0) require.NoError(t, beaconState.SetSlot(currentSlot)) mockChain := &mock.ChainService{ State: beaconState, @@ -295,7 +295,7 @@ func TestService_processQueuedBlocks(t *testing.T) { createProposalWrapper(t, 0, 1, nil), }) ctx, cancel := context.WithCancel(context.Background()) - tickerChan := make(chan types.Slot) + tickerChan := make(chan primitives.Slot) exitChan := make(chan struct{}) go func() { s.processQueuedBlocks(ctx, tickerChan) diff --git a/beacon-chain/slasher/rpc.go b/beacon-chain/slasher/rpc.go index 1b7ab99030..933979f534 100644 --- a/beacon-chain/slasher/rpc.go +++ b/beacon-chain/slasher/rpc.go @@ -5,7 +5,7 @@ import ( "github.com/pkg/errors" slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" "google.golang.org/grpc/codes" @@ -14,7 +14,7 @@ import ( // HighestAttestations committed for an input list of validator indices. func (s *Service) HighestAttestations( - ctx context.Context, validatorIndices []types.ValidatorIndex, + ctx context.Context, validatorIndices []primitives.ValidatorIndex, ) ([]*ethpb.HighestAttestation, error) { atts, err := s.serviceCfg.Database.HighestAttestations(ctx, validatorIndices) if err != nil { diff --git a/beacon-chain/slasher/rpc_test.go b/beacon-chain/slasher/rpc_test.go index 8a27541504..5460ec3fbe 100644 --- a/beacon-chain/slasher/rpc_test.go +++ b/beacon-chain/slasher/rpc_test.go @@ -8,7 +8,7 @@ import ( dbtest "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" slashertypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/types" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -73,7 +73,7 @@ func TestIsSlashableAttestation(t *testing.T) { ctx := context.Background() slasherDB := dbtest.SetupSlasherDB(t) - currentEpoch := types.Epoch(3) + currentEpoch := primitives.Epoch(3) currentTime := time.Now() totalSlots := uint64(currentEpoch) * uint64(params.BeaconConfig().SlotsPerEpoch) secondsSinceGenesis := time.Duration(totalSlots * params.BeaconConfig().SecondsPerSlot) @@ -86,7 +86,7 @@ func TestIsSlashableAttestation(t *testing.T) { params: DefaultParams(), blksQueue: newBlocksQueue(), genesisTime: genesisTime, - latestEpochWrittenForValidator: map[types.ValidatorIndex]types.Epoch{}, + latestEpochWrittenForValidator: map[primitives.ValidatorIndex]primitives.Epoch{}, } prevAtts := []*slashertypes.IndexedAttestationWrapper{ createAttestationWrapper(t, 2, 3, []uint64{0}, []byte{1}), @@ -142,7 +142,7 @@ func TestService_HighestAttestations(t *testing.T) { ctx := context.Background() slasherDB := dbtest.SetupSlasherDB(t) - currentEpoch := types.Epoch(3) + currentEpoch := primitives.Epoch(3) currentTime := time.Now() totalSlots := uint64(currentEpoch) * uint64(params.BeaconConfig().SlotsPerEpoch) secondsSinceGenesis := time.Duration(totalSlots * params.BeaconConfig().SecondsPerSlot) @@ -163,36 +163,36 @@ func TestService_HighestAttestations(t *testing.T) { err := slasherDB.SaveAttestationRecordsForValidators(ctx, prevAtts) require.NoError(t, err) t.Run("single index not found", func(t *testing.T) { - atts, err := s.HighestAttestations(ctx, []types.ValidatorIndex{0}) + atts, err := s.HighestAttestations(ctx, []primitives.ValidatorIndex{0}) require.NoError(t, err) require.Equal(t, 0, len(atts)) }) t.Run("single index case 1", func(t *testing.T) { - atts, err := s.HighestAttestations(ctx, []types.ValidatorIndex{1}) + atts, err := s.HighestAttestations(ctx, []primitives.ValidatorIndex{1}) require.NoError(t, err) require.Equal(t, 1, len(atts)) require.DeepEqual(t, ðpb.HighestAttestation{ValidatorIndex: 1, HighestSourceEpoch: 0, HighestTargetEpoch: 1}, atts[0]) }) t.Run("single index case 2", func(t *testing.T) { - atts, err := s.HighestAttestations(ctx, []types.ValidatorIndex{2}) + atts, err := s.HighestAttestations(ctx, []primitives.ValidatorIndex{2}) require.NoError(t, err) require.Equal(t, 1, len(atts)) require.DeepEqual(t, ðpb.HighestAttestation{ValidatorIndex: 2, HighestSourceEpoch: 2, HighestTargetEpoch: 3}, atts[0]) }) t.Run("multiple indices all found", func(t *testing.T) { - atts, err := s.HighestAttestations(ctx, []types.ValidatorIndex{1, 2}) + atts, err := s.HighestAttestations(ctx, []primitives.ValidatorIndex{1, 2}) require.NoError(t, err) require.Equal(t, 2, len(atts)) require.DeepEqual(t, ðpb.HighestAttestation{ValidatorIndex: 1, HighestSourceEpoch: 0, HighestTargetEpoch: 1}, atts[0]) require.DeepEqual(t, ðpb.HighestAttestation{ValidatorIndex: 2, HighestSourceEpoch: 2, HighestTargetEpoch: 3}, atts[1]) }) t.Run("multiple indices all not found", func(t *testing.T) { - atts, err := s.HighestAttestations(ctx, []types.ValidatorIndex{3, 4}) + atts, err := s.HighestAttestations(ctx, []primitives.ValidatorIndex{3, 4}) require.NoError(t, err) require.Equal(t, 0, len(atts)) }) t.Run("multiple indices some not found", func(t *testing.T) { - atts, err := s.HighestAttestations(ctx, []types.ValidatorIndex{1, 4}) + atts, err := s.HighestAttestations(ctx, []primitives.ValidatorIndex{1, 4}) require.NoError(t, err) require.Equal(t, 1, len(atts)) require.DeepEqual(t, ðpb.HighestAttestation{ValidatorIndex: 1, HighestSourceEpoch: 0, HighestTargetEpoch: 1}, atts[0]) diff --git a/beacon-chain/slasher/service.go b/beacon-chain/slasher/service.go index 2b06c13a7b..fe0986658f 100644 --- a/beacon-chain/slasher/service.go +++ b/beacon-chain/slasher/service.go @@ -17,7 +17,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" ) @@ -46,7 +46,7 @@ type SlashingChecker interface { IsSlashableBlock(ctx context.Context, proposal *ethpb.SignedBeaconBlockHeader) (*ethpb.ProposerSlashing, error) IsSlashableAttestation(ctx context.Context, attestation *ethpb.IndexedAttestation) ([]*ethpb.AttesterSlashing, error) HighestAttestations( - ctx context.Context, indices []types.ValidatorIndex, + ctx context.Context, indices []primitives.ValidatorIndex, ) ([]*ethpb.HighestAttestation, error) } @@ -65,7 +65,7 @@ type Service struct { attsSlotTicker *slots.SlotTicker blocksSlotTicker *slots.SlotTicker pruningSlotTicker *slots.SlotTicker - latestEpochWrittenForValidator map[types.ValidatorIndex]types.Epoch + latestEpochWrittenForValidator map[primitives.ValidatorIndex]primitives.Epoch } // New instantiates a new slasher from configuration values. @@ -80,7 +80,7 @@ func New(ctx context.Context, srvCfg *ServiceConfig) (*Service, error) { blksQueue: newBlocksQueue(), ctx: ctx, cancel: cancel, - latestEpochWrittenForValidator: make(map[types.ValidatorIndex]types.Epoch), + latestEpochWrittenForValidator: make(map[primitives.ValidatorIndex]primitives.Epoch), }, nil } @@ -103,9 +103,9 @@ func (s *Service) run() { return } numVals := headState.NumValidators() - validatorIndices := make([]types.ValidatorIndex, numVals) + validatorIndices := make([]primitives.ValidatorIndex, numVals) for i := 0; i < numVals; i++ { - validatorIndices[i] = types.ValidatorIndex(i) + validatorIndices[i] = primitives.ValidatorIndex(i) } start := time.Now() log.Info("Reading last epoch written for each validator...") diff --git a/beacon-chain/slasher/service_test.go b/beacon-chain/slasher/service_test.go index b22fec6603..d53bd34471 100644 --- a/beacon-chain/slasher/service_test.go +++ b/beacon-chain/slasher/service_test.go @@ -13,7 +13,7 @@ import ( dbtest "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" mockslasher "github.com/prysmaticlabs/prysm/v3/beacon-chain/slasher/mock" mockSync "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -36,7 +36,7 @@ func TestService_StartStop_ChainInitialized(t *testing.T) { hook := logTest.NewGlobal() beaconState, err := util.NewBeaconState() require.NoError(t, err) - currentSlot := types.Slot(4) + currentSlot := primitives.Slot(4) require.NoError(t, beaconState.SetSlot(currentSlot)) mockChain := &mock.ChainService{ State: beaconState, diff --git a/beacon-chain/slasher/types/types.go b/beacon-chain/slasher/types/types.go index cb7bd3a134..20dd25c2b6 100644 --- a/beacon-chain/slasher/types/types.go +++ b/beacon-chain/slasher/types/types.go @@ -1,7 +1,7 @@ package types import ( - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -24,16 +24,16 @@ type IndexedAttestationWrapper struct { // AttesterDoubleVote represents a double vote instance // which is a slashable event for attesters. type AttesterDoubleVote struct { - Target types.Epoch - ValidatorIndex types.ValidatorIndex + Target primitives.Epoch + ValidatorIndex primitives.ValidatorIndex PrevAttestationWrapper *IndexedAttestationWrapper AttestationWrapper *IndexedAttestationWrapper } // DoubleBlockProposal containing an incoming and an existing proposal's signing root. type DoubleBlockProposal struct { - Slot types.Slot - ValidatorIndex types.ValidatorIndex + Slot primitives.Slot + ValidatorIndex primitives.ValidatorIndex PrevBeaconBlockWrapper *SignedBlockHeaderWrapper BeaconBlockWrapper *SignedBlockHeaderWrapper } @@ -48,6 +48,6 @@ type SignedBlockHeaderWrapper struct { // AttestedEpochForValidator encapsulates a previously attested epoch // for a validator index. type AttestedEpochForValidator struct { - ValidatorIndex types.ValidatorIndex - Epoch types.Epoch + ValidatorIndex primitives.ValidatorIndex + Epoch primitives.Epoch } diff --git a/beacon-chain/state/fieldtrie/BUILD.bazel b/beacon-chain/state/fieldtrie/BUILD.bazel index 1b03b60947..68d5c71461 100644 --- a/beacon-chain/state/fieldtrie/BUILD.bazel +++ b/beacon-chain/state/fieldtrie/BUILD.bazel @@ -12,7 +12,6 @@ go_library( "//beacon-chain/state/state-native/custom-types:go_default_library", "//beacon-chain/state/state-native/types:go_default_library", "//beacon-chain/state/stateutil:go_default_library", - "//beacon-chain/state/types:go_default_library", "//crypto/hash:go_default_library", "//encoding/bytesutil:go_default_library", "//math:go_default_library", @@ -34,7 +33,6 @@ go_test( "//beacon-chain/state/state-native/custom-types:go_default_library", "//beacon-chain/state/state-native/types:go_default_library", "//beacon-chain/state/stateutil:go_default_library", - "//beacon-chain/state/types:go_default_library", "//config/fieldparams:go_default_library", "//config/params:go_default_library", "//consensus-types/primitives:go_default_library", diff --git a/beacon-chain/state/fieldtrie/field_trie.go b/beacon-chain/state/fieldtrie/field_trie.go index f5db441631..ea6dadadf2 100644 --- a/beacon-chain/state/fieldtrie/field_trie.go +++ b/beacon-chain/state/fieldtrie/field_trie.go @@ -5,8 +5,8 @@ import ( "sync" "github.com/pkg/errors" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" - "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/types" pmath "github.com/prysmaticlabs/prysm/v3/math" ) @@ -21,7 +21,7 @@ type FieldTrie struct { *sync.RWMutex reference *stateutil.Reference fieldLayers [][]*[32]byte - field types.BeaconStateField + field types.FieldIndex dataType types.DataType length uint64 numOfElems int @@ -31,7 +31,7 @@ type FieldTrie struct { // NewFieldTrie is the constructor for the field trie data structure. It creates the corresponding // trie according to the given parameters. Depending on whether the field is a basic/composite array // which is either fixed/variable length, it will appropriately determine the trie. -func NewFieldTrie(field types.BeaconStateField, dataType types.DataType, elements interface{}, length uint64) (*FieldTrie, error) { +func NewFieldTrie(field types.FieldIndex, dataType types.DataType, elements interface{}, length uint64) (*FieldTrie, error) { if elements == nil { return &FieldTrie{ field: field, @@ -43,14 +43,7 @@ func NewFieldTrie(field types.BeaconStateField, dataType types.DataType, element }, nil } - var fieldRoots [][32]byte - var err error - if field.Native() { - fieldRoots, err = fieldConvertersNative(field, []uint64{}, elements, true) - } else { - fieldRoots, err = fieldConverters(field, []uint64{}, elements, true) - } - + fieldRoots, err := fieldConverters(field, []uint64{}, elements, true) if err != nil { return nil, err } @@ -100,13 +93,7 @@ func (f *FieldTrie) RecomputeTrie(indices []uint64, elements interface{}) ([32]b return f.TrieRoot() } - var fieldRoots [][32]byte - var err error - if f.field.Native() { - fieldRoots, err = fieldConvertersNative(f.field, indices, elements, false) - } else { - fieldRoots, err = fieldConverters(f.field, indices, elements, false) - } + fieldRoots, err := fieldConverters(f.field, indices, elements, false) if err != nil { return [32]byte{}, err } diff --git a/beacon-chain/state/fieldtrie/field_trie_helpers.go b/beacon-chain/state/fieldtrie/field_trie_helpers.go index 46b736263a..5cd1532957 100644 --- a/beacon-chain/state/fieldtrie/field_trie_helpers.go +++ b/beacon-chain/state/fieldtrie/field_trie_helpers.go @@ -7,9 +7,8 @@ import ( "github.com/pkg/errors" customtypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/custom-types" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" - "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/types" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" pmath "github.com/prysmaticlabs/prysm/v3/math" @@ -49,7 +48,7 @@ func (f *FieldTrie) validateIndices(idxs []uint64) error { return nil } -func validateElements(field types.BeaconStateField, dataType types.DataType, elements interface{}, length uint64) error { +func validateElements(field types.FieldIndex, dataType types.DataType, elements interface{}, length uint64) error { if dataType == types.CompressedArray { comLength, err := field.ElemsInChunk() if err != nil { @@ -65,7 +64,7 @@ func validateElements(field types.BeaconStateField, dataType types.DataType, ele } // fieldConverters converts the corresponding field and the provided elements to the appropriate roots. -func fieldConverters(field types.BeaconStateField, indices []uint64, elements interface{}, convertAll bool) ([][32]byte, error) { +func fieldConverters(field types.FieldIndex, indices []uint64, elements interface{}, convertAll bool) ([][32]byte, error) { switch field { case types.BlockRoots: return convertBlockRoots(indices, elements, convertAll) @@ -86,28 +85,6 @@ func fieldConverters(field types.BeaconStateField, indices []uint64, elements in } } -// fieldConvertersNative converts the corresponding field and the provided elements to the appropriate roots. -func fieldConvertersNative(field types.BeaconStateField, indices []uint64, elements interface{}, convertAll bool) ([][32]byte, error) { - switch field { - case nativetypes.BlockRoots: - return convertBlockRoots(indices, elements, convertAll) - case nativetypes.StateRoots: - return convertStateRoots(indices, elements, convertAll) - case nativetypes.RandaoMixes: - return convertRandaoMixes(indices, elements, convertAll) - case nativetypes.Eth1DataVotes: - return convertEth1DataVotes(indices, elements, convertAll) - case nativetypes.Validators: - return convertValidators(indices, elements, convertAll) - case nativetypes.PreviousEpochAttestations, nativetypes.CurrentEpochAttestations: - return convertAttestations(indices, elements, convertAll) - case nativetypes.Balances: - return convertBalances(indices, elements, convertAll) - default: - return [][32]byte{}, errors.Errorf("got unsupported type of %v", reflect.TypeOf(elements).Name()) - } -} - func convertBlockRoots(indices []uint64, elements interface{}, convertAll bool) ([][32]byte, error) { switch val := elements.(type) { case [][]byte: diff --git a/beacon-chain/state/fieldtrie/field_trie_test.go b/beacon-chain/state/fieldtrie/field_trie_test.go index 4d7d2a9fcc..39ad973acf 100644 --- a/beacon-chain/state/fieldtrie/field_trie_test.go +++ b/beacon-chain/state/fieldtrie/field_trie_test.go @@ -4,10 +4,10 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/fieldtrie" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" - stateTypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/types" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -18,7 +18,7 @@ func TestFieldTrie_NewTrie(t *testing.T) { newState, _ := util.DeterministicGenesisState(t, 40) // 5 represents the enum value of state roots - trie, err := fieldtrie.NewFieldTrie(stateTypes.FieldIndex(5), stateTypes.BasicArray, newState.StateRoots(), uint64(params.BeaconConfig().SlotsPerHistoricalRoot)) + trie, err := fieldtrie.NewFieldTrie(types.FieldIndex(5), types.BasicArray, newState.StateRoots(), uint64(params.BeaconConfig().SlotsPerHistoricalRoot)) require.NoError(t, err) root, err := stateutil.RootsArrayHashTreeRoot(newState.StateRoots(), uint64(params.BeaconConfig().SlotsPerHistoricalRoot)) require.NoError(t, err) @@ -28,7 +28,7 @@ func TestFieldTrie_NewTrie(t *testing.T) { } func TestFieldTrie_NewTrie_NilElements(t *testing.T) { - trie, err := fieldtrie.NewFieldTrie(stateTypes.FieldIndex(5), stateTypes.BasicArray, nil, 8234) + trie, err := fieldtrie.NewFieldTrie(types.FieldIndex(5), types.BasicArray, nil, 8234) require.NoError(t, err) _, err = trie.TrieRoot() require.ErrorIs(t, err, fieldtrie.ErrEmptyFieldTrie) @@ -37,7 +37,7 @@ func TestFieldTrie_NewTrie_NilElements(t *testing.T) { func TestFieldTrie_RecomputeTrie(t *testing.T) { newState, _ := util.DeterministicGenesisState(t, 32) // 10 represents the enum value of validators - trie, err := fieldtrie.NewFieldTrie(stateTypes.FieldIndex(11), stateTypes.CompositeArray, newState.Validators(), params.BeaconConfig().ValidatorRegistryLimit) + trie, err := fieldtrie.NewFieldTrie(types.FieldIndex(11), types.CompositeArray, newState.Validators(), params.BeaconConfig().ValidatorRegistryLimit) require.NoError(t, err) oldroot, err := trie.TrieRoot() @@ -56,8 +56,8 @@ func TestFieldTrie_RecomputeTrie(t *testing.T) { val2.ExitEpoch = 40 changedVals := []*ethpb.Validator{val1, val2} - require.NoError(t, newState.UpdateValidatorAtIndex(types.ValidatorIndex(changedIdx[0]), changedVals[0])) - require.NoError(t, newState.UpdateValidatorAtIndex(types.ValidatorIndex(changedIdx[1]), changedVals[1])) + require.NoError(t, newState.UpdateValidatorAtIndex(primitives.ValidatorIndex(changedIdx[0]), changedVals[0])) + require.NoError(t, newState.UpdateValidatorAtIndex(primitives.ValidatorIndex(changedIdx[1]), changedVals[1])) expectedRoot, err := stateutil.ValidatorRegistryRoot(newState.Validators()) require.NoError(t, err) @@ -68,12 +68,12 @@ func TestFieldTrie_RecomputeTrie(t *testing.T) { func TestFieldTrie_RecomputeTrie_CompressedArray(t *testing.T) { newState, _ := util.DeterministicGenesisState(t, 32) - trie, err := fieldtrie.NewFieldTrie(stateTypes.FieldIndex(12), stateTypes.CompressedArray, newState.Balances(), stateutil.ValidatorLimitForBalancesChunks()) + trie, err := fieldtrie.NewFieldTrie(types.FieldIndex(12), types.CompressedArray, newState.Balances(), stateutil.ValidatorLimitForBalancesChunks()) require.NoError(t, err) require.Equal(t, trie.Length(), stateutil.ValidatorLimitForBalancesChunks()) changedIdx := []uint64{4, 8} - require.NoError(t, newState.UpdateBalancesAtIndex(types.ValidatorIndex(changedIdx[0]), uint64(100000000))) - require.NoError(t, newState.UpdateBalancesAtIndex(types.ValidatorIndex(changedIdx[1]), uint64(200000000))) + require.NoError(t, newState.UpdateBalancesAtIndex(primitives.ValidatorIndex(changedIdx[0]), uint64(100000000))) + require.NoError(t, newState.UpdateBalancesAtIndex(primitives.ValidatorIndex(changedIdx[1]), uint64(200000000))) expectedRoot, err := stateutil.Uint64ListRootWithRegistryLimit(newState.Balances()) require.NoError(t, err) root, err := trie.RecomputeTrie(changedIdx, newState.Balances()) @@ -85,14 +85,14 @@ func TestFieldTrie_RecomputeTrie_CompressedArray(t *testing.T) { func TestNewFieldTrie_UnknownType(t *testing.T) { newState, _ := util.DeterministicGenesisState(t, 32) - _, err := fieldtrie.NewFieldTrie(stateTypes.FieldIndex(12), 4, newState.Balances(), 32) + _, err := fieldtrie.NewFieldTrie(types.FieldIndex(12), 4, newState.Balances(), 32) require.ErrorContains(t, "unrecognized data type", err) } func TestFieldTrie_CopyTrieImmutable(t *testing.T) { newState, _ := util.DeterministicGenesisState(t, 32) // 12 represents the enum value of randao mixes. - trie, err := fieldtrie.NewFieldTrie(stateTypes.FieldIndex(13), stateTypes.BasicArray, newState.RandaoMixes(), uint64(params.BeaconConfig().EpochsPerHistoricalVector)) + trie, err := fieldtrie.NewFieldTrie(types.FieldIndex(13), types.BasicArray, newState.RandaoMixes(), uint64(params.BeaconConfig().EpochsPerHistoricalVector)) require.NoError(t, err) newTrie := trie.CopyTrie() @@ -113,7 +113,7 @@ func TestFieldTrie_CopyTrieImmutable(t *testing.T) { } func TestFieldTrie_CopyAndTransferEmpty(t *testing.T) { - trie, err := fieldtrie.NewFieldTrie(stateTypes.FieldIndex(13), stateTypes.BasicArray, nil, uint64(params.BeaconConfig().EpochsPerHistoricalVector)) + trie, err := fieldtrie.NewFieldTrie(types.FieldIndex(13), types.BasicArray, nil, uint64(params.BeaconConfig().EpochsPerHistoricalVector)) require.NoError(t, err) require.DeepEqual(t, trie, trie.CopyTrie()) @@ -123,7 +123,7 @@ func TestFieldTrie_CopyAndTransferEmpty(t *testing.T) { func TestFieldTrie_TransferTrie(t *testing.T) { newState, _ := util.DeterministicGenesisState(t, 32) maxLength := (params.BeaconConfig().ValidatorRegistryLimit*8 + 31) / 32 - trie, err := fieldtrie.NewFieldTrie(stateTypes.FieldIndex(12), stateTypes.CompressedArray, newState.Balances(), maxLength) + trie, err := fieldtrie.NewFieldTrie(types.FieldIndex(12), types.CompressedArray, newState.Balances(), maxLength) require.NoError(t, err) oldRoot, err := trie.TrieRoot() require.NoError(t, err) @@ -144,14 +144,14 @@ func FuzzFieldTrie(f *testing.F) { for _, root := range newState.StateRoots() { data = append(data, root...) } - f.Add(5, int(stateTypes.BasicArray), data, uint64(params.BeaconConfig().SlotsPerHistoricalRoot)) + f.Add(5, int(types.BasicArray), data, uint64(params.BeaconConfig().SlotsPerHistoricalRoot)) f.Fuzz(func(t *testing.T, idx, typ int, data []byte, slotsPerHistRoot uint64) { var roots [][]byte for i := 32; i < len(data); i += 32 { roots = append(roots, data[i-32:i]) } - trie, err := fieldtrie.NewFieldTrie(stateTypes.FieldIndex(idx), stateTypes.DataType(typ), roots, slotsPerHistRoot) + trie, err := fieldtrie.NewFieldTrie(types.FieldIndex(idx), types.DataType(typ), roots, slotsPerHistRoot) if err != nil { return // invalid inputs } diff --git a/beacon-chain/state/fieldtrie/helpers_test.go b/beacon-chain/state/fieldtrie/helpers_test.go index d61db6312f..f97951c3ae 100644 --- a/beacon-chain/state/fieldtrie/helpers_test.go +++ b/beacon-chain/state/fieldtrie/helpers_test.go @@ -9,9 +9,8 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" customtypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/custom-types" - nativeStateTypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" - stateTypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/types" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -78,8 +77,8 @@ func TestValidateIndices_CompressedField(t *testing.T) { RWMutex: new(sync.RWMutex), reference: stateutil.NewRef(0), fieldLayers: nil, - field: stateTypes.Balances, - dataType: stateTypes.CompressedArray, + field: types.Balances, + dataType: types.CompressedArray, length: params.BeaconConfig().ValidatorRegistryLimit / 4, numOfElems: 0, } @@ -93,7 +92,7 @@ func TestValidateIndices_CompressedField(t *testing.T) { func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { type args struct { - field stateTypes.BeaconStateField + field types.FieldIndex indices []uint64 elements interface{} convertAll bool @@ -108,7 +107,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "BlockRoots [][]bytes", args: &args{ - field: nativeStateTypes.FieldIndex(5), + field: types.FieldIndex(5), indices: []uint64{}, elements: [][]byte{[]byte("dfsadfsadf")}, convertAll: true, @@ -118,7 +117,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "BlockRoots customtypes.BlockRoots", args: &args{ - field: nativeStateTypes.FieldIndex(5), + field: types.FieldIndex(5), indices: []uint64{}, elements: &customtypes.BlockRoots{}, convertAll: true, @@ -129,7 +128,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "BlockRoots type not found", args: &args{ - field: nativeStateTypes.FieldIndex(5), + field: types.FieldIndex(5), indices: []uint64{}, elements: 123, convertAll: true, @@ -140,7 +139,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "BlockRoots [][]bytes", args: &args{ - field: nativeStateTypes.FieldIndex(5), + field: types.FieldIndex(5), indices: []uint64{}, elements: [][]byte{[]byte("dfsadfsadf")}, convertAll: true, @@ -150,7 +149,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "StateRoots [][]bytes", args: &args{ - field: nativeStateTypes.FieldIndex(6), + field: types.FieldIndex(6), indices: []uint64{}, elements: [][]byte{[]byte("dfsadfsadf")}, convertAll: true, @@ -160,7 +159,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "StateRoots customtypes.StateRoots", args: &args{ - field: nativeStateTypes.FieldIndex(6), + field: types.FieldIndex(6), indices: []uint64{}, elements: &customtypes.StateRoots{}, convertAll: true, @@ -171,7 +170,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "StateRoots type not found", args: &args{ - field: nativeStateTypes.FieldIndex(6), + field: types.FieldIndex(6), indices: []uint64{}, elements: 123, convertAll: true, @@ -182,7 +181,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "StateRoots [][]bytes convert all false", args: &args{ - field: nativeStateTypes.FieldIndex(6), + field: types.FieldIndex(6), indices: []uint64{}, elements: [][]byte{[]byte("dfsadfsadf")}, convertAll: false, @@ -192,7 +191,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "StateRoots customtypes.StateRoots convert all false", args: &args{ - field: nativeStateTypes.FieldIndex(6), + field: types.FieldIndex(6), indices: []uint64{}, elements: &customtypes.StateRoots{}, convertAll: false, @@ -203,7 +202,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "RandaoMixes [][]bytes", args: &args{ - field: nativeStateTypes.FieldIndex(13), + field: types.FieldIndex(13), indices: []uint64{}, elements: [][]byte{[]byte("dfsadfsadf")}, convertAll: true, @@ -213,7 +212,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "RandaoMixes customtypes.RandaoMixes", args: &args{ - field: nativeStateTypes.FieldIndex(13), + field: types.FieldIndex(13), indices: []uint64{}, elements: &customtypes.RandaoMixes{}, convertAll: true, @@ -224,7 +223,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "RandaoMixes type not found", args: &args{ - field: nativeStateTypes.FieldIndex(13), + field: types.FieldIndex(13), indices: []uint64{}, elements: 123, convertAll: true, @@ -235,7 +234,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "Eth1DataVotes type not found", args: &args{ - field: nativeStateTypes.FieldIndex(9), + field: types.FieldIndex(9), indices: []uint64{}, elements: []*ethpb.Eth1Data{ { @@ -250,7 +249,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "Eth1DataVotes convertAll false", args: &args{ - field: nativeStateTypes.FieldIndex(9), + field: types.FieldIndex(9), indices: []uint64{1}, elements: []*ethpb.Eth1Data{ { @@ -265,7 +264,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "Eth1DataVotes type not found", args: &args{ - field: nativeStateTypes.FieldIndex(9), + field: types.FieldIndex(9), indices: []uint64{}, elements: 123, convertAll: true, @@ -276,7 +275,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "Balance", args: &args{ - field: nativeStateTypes.FieldIndex(12), + field: types.FieldIndex(12), indices: []uint64{}, elements: []uint64{12321312321, 12131241234123123}, convertAll: true, @@ -286,7 +285,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "Validators", args: &args{ - field: nativeStateTypes.FieldIndex(11), + field: types.FieldIndex(11), indices: []uint64{}, elements: []*ethpb.Validator{ { @@ -300,7 +299,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "Validators not found", args: &args{ - field: nativeStateTypes.FieldIndex(11), + field: types.FieldIndex(11), indices: []uint64{}, elements: 123, convertAll: true, @@ -311,7 +310,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "Attestations", args: &args{ - field: nativeStateTypes.FieldIndex(15), + field: types.FieldIndex(15), indices: []uint64{}, elements: []*ethpb.PendingAttestation{ { @@ -325,7 +324,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "Attestations", args: &args{ - field: nativeStateTypes.FieldIndex(15), + field: types.FieldIndex(15), indices: []uint64{1}, elements: []*ethpb.PendingAttestation{ { @@ -339,7 +338,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { { name: "Type not found", args: &args{ - field: nativeStateTypes.FieldIndex(999), + field: types.FieldIndex(999), indices: []uint64{}, elements: []*ethpb.PendingAttestation{ { @@ -353,7 +352,7 @@ func TestFieldTrie_NativeState_fieldConvertersNative(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - roots, err := fieldConvertersNative(tt.args.field, tt.args.indices, tt.args.elements, tt.args.convertAll) + roots, err := fieldConverters(tt.args.field, tt.args.indices, tt.args.elements, tt.args.convertAll) if err != nil && tt.errMsg != "" { require.ErrorContains(t, tt.errMsg, err) } else { diff --git a/beacon-chain/state/interfaces.go b/beacon-chain/state/interfaces.go index 9da91ba2e9..0bcd6f072a 100644 --- a/beacon-chain/state/interfaces.go +++ b/beacon-chain/state/interfaces.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/go-bitfield" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -56,7 +56,7 @@ type ReadOnlyBeaconState interface { ToProto() interface{} GenesisTime() uint64 GenesisValidatorsRoot() []byte - Slot() types.Slot + Slot() primitives.Slot Fork() *ethpb.Fork LatestBlockHeader() *ethpb.BeaconBlockHeader HistoricalRoots() ([][]byte, error) @@ -84,7 +84,7 @@ type WriteOnlyBeaconState interface { WriteOnlySyncCommittee SetGenesisTime(val uint64) error SetGenesisValidatorsRoot(val []byte) error - SetSlot(val types.Slot) error + SetSlot(val primitives.Slot) error SetFork(val *ethpb.Fork) error SetLatestBlockHeader(val *ethpb.BeaconBlockHeader) error SetHistoricalRoots(val [][]byte) error @@ -94,20 +94,20 @@ type WriteOnlyBeaconState interface { AppendHistoricalSummaries(*ethpb.HistoricalSummary) error SetLatestExecutionPayloadHeader(payload interfaces.ExecutionData) error SetNextWithdrawalIndex(i uint64) error - SetNextWithdrawalValidatorIndex(i types.ValidatorIndex) error + SetNextWithdrawalValidatorIndex(i primitives.ValidatorIndex) error } // ReadOnlyValidator defines a struct which only has read access to validator methods. type ReadOnlyValidator interface { EffectiveBalance() uint64 - ActivationEligibilityEpoch() types.Epoch - ActivationEpoch() types.Epoch - WithdrawableEpoch() types.Epoch - ExitEpoch() types.Epoch + ActivationEligibilityEpoch() primitives.Epoch + ActivationEpoch() primitives.Epoch + WithdrawableEpoch() primitives.Epoch + ExitEpoch() primitives.Epoch PublicKey() [fieldparams.BLSPubkeyLength]byte WithdrawalCredentials() []byte HasETH1WithdrawalCredential() bool - IsFullyWithdrawable(types.Epoch) bool + IsFullyWithdrawable(primitives.Epoch) bool IsPartiallyWithdrawable(uint64) bool Slashed() bool IsNil() bool @@ -116,10 +116,10 @@ type ReadOnlyValidator interface { // ReadOnlyValidators defines a struct which only has read access to validators methods. type ReadOnlyValidators interface { Validators() []*ethpb.Validator - ValidatorAtIndex(idx types.ValidatorIndex) (*ethpb.Validator, error) - ValidatorAtIndexReadOnly(idx types.ValidatorIndex) (ReadOnlyValidator, error) - ValidatorIndexByPubkey(key [fieldparams.BLSPubkeyLength]byte) (types.ValidatorIndex, bool) - PubkeyAtIndex(idx types.ValidatorIndex) [fieldparams.BLSPubkeyLength]byte + ValidatorAtIndex(idx primitives.ValidatorIndex) (*ethpb.Validator, error) + ValidatorAtIndexReadOnly(idx primitives.ValidatorIndex) (ReadOnlyValidator, error) + ValidatorIndexByPubkey(key [fieldparams.BLSPubkeyLength]byte) (primitives.ValidatorIndex, bool) + PubkeyAtIndex(idx primitives.ValidatorIndex) [fieldparams.BLSPubkeyLength]byte NumValidators() int ReadFromEveryValidator(f func(idx int, val ReadOnlyValidator) error) error } @@ -127,7 +127,7 @@ type ReadOnlyValidators interface { // ReadOnlyBalances defines a struct which only has read access to balances methods. type ReadOnlyBalances interface { Balances() []uint64 - BalanceAtIndex(idx types.ValidatorIndex) (uint64, error) + BalanceAtIndex(idx primitives.ValidatorIndex) (uint64, error) BalancesLength() int } @@ -138,7 +138,7 @@ type ReadOnlyCheckpoint interface { MatchCurrentJustifiedCheckpoint(c *ethpb.Checkpoint) bool MatchPreviousJustifiedCheckpoint(c *ethpb.Checkpoint) bool FinalizedCheckpoint() *ethpb.Checkpoint - FinalizedCheckpointEpoch() types.Epoch + FinalizedCheckpointEpoch() primitives.Epoch JustificationBits() bitfield.Bitvector4 UnrealizedCheckpointBalances() (uint64, uint64, uint64, error) } @@ -178,7 +178,7 @@ type ReadOnlyAttestations interface { // ReadOnlyWithdrawals defines a struct which only has read access to withdrawal methods. type ReadOnlyWithdrawals interface { ExpectedWithdrawals() ([]*enginev1.Withdrawal, error) - NextWithdrawalValidatorIndex() (types.ValidatorIndex, error) + NextWithdrawalValidatorIndex() (primitives.ValidatorIndex, error) NextWithdrawalIndex() (uint64, error) } @@ -223,14 +223,14 @@ type WriteOnlyEth1Data interface { type WriteOnlyValidators interface { SetValidators(val []*ethpb.Validator) error ApplyToEveryValidator(f func(idx int, val *ethpb.Validator) (bool, *ethpb.Validator, error)) error - UpdateValidatorAtIndex(idx types.ValidatorIndex, val *ethpb.Validator) error + UpdateValidatorAtIndex(idx primitives.ValidatorIndex, val *ethpb.Validator) error AppendValidator(val *ethpb.Validator) error } // WriteOnlyBalances defines a struct which only has write access to balances methods. type WriteOnlyBalances interface { SetBalances(val []uint64) error - UpdateBalancesAtIndex(idx types.ValidatorIndex, val uint64) error + UpdateBalancesAtIndex(idx primitives.ValidatorIndex, val uint64) error AppendBalance(bal uint64) error } diff --git a/beacon-chain/state/state-native/BUILD.bazel b/beacon-chain/state/state-native/BUILD.bazel index 98a5dd50dd..daf72b134a 100644 --- a/beacon-chain/state/state-native/BUILD.bazel +++ b/beacon-chain/state/state-native/BUILD.bazel @@ -49,7 +49,6 @@ go_library( "//beacon-chain/state/state-native/custom-types:go_default_library", "//beacon-chain/state/state-native/types:go_default_library", "//beacon-chain/state/stateutil:go_default_library", - "//beacon-chain/state/types:go_default_library", "//config/fieldparams:go_default_library", "//config/params:go_default_library", "//consensus-types/blocks:go_default_library", diff --git a/beacon-chain/state/state-native/beacon_state_mainnet.go b/beacon-chain/state/state-native/beacon_state_mainnet.go index 66fc51dd9a..c27131484d 100644 --- a/beacon-chain/state/state-native/beacon_state_mainnet.go +++ b/beacon-chain/state/state-native/beacon_state_mainnet.go @@ -8,9 +8,9 @@ import ( "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/fieldtrie" customtypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/custom-types" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" - eth2types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -21,7 +21,7 @@ type BeaconState struct { version int genesisTime uint64 genesisValidatorsRoot [32]byte - slot eth2types.Slot + slot primitives.Slot fork *ethpb.Fork latestBlockHeader *ethpb.BeaconBlockHeader blockRoots *customtypes.BlockRoots @@ -49,14 +49,14 @@ type BeaconState struct { latestExecutionPayloadHeader *enginev1.ExecutionPayloadHeader latestExecutionPayloadHeaderCapella *enginev1.ExecutionPayloadHeaderCapella nextWithdrawalIndex uint64 - nextWithdrawalValidatorIndex eth2types.ValidatorIndex + nextWithdrawalValidatorIndex primitives.ValidatorIndex lock sync.RWMutex - dirtyFields map[nativetypes.FieldIndex]bool - dirtyIndices map[nativetypes.FieldIndex][]uint64 - stateFieldLeaves map[nativetypes.FieldIndex]*fieldtrie.FieldTrie - rebuildTrie map[nativetypes.FieldIndex]bool + dirtyFields map[types.FieldIndex]bool + dirtyIndices map[types.FieldIndex][]uint64 + stateFieldLeaves map[types.FieldIndex]*fieldtrie.FieldTrie + rebuildTrie map[types.FieldIndex]bool valMapHandler *stateutil.ValidatorMapHandler merkleLayers [][][]byte - sharedFieldReferences map[nativetypes.FieldIndex]*stateutil.Reference + sharedFieldReferences map[types.FieldIndex]*stateutil.Reference } diff --git a/beacon-chain/state/state-native/beacon_state_minimal.go b/beacon-chain/state/state-native/beacon_state_minimal.go index b9a61a8eba..045305961e 100644 --- a/beacon-chain/state/state-native/beacon_state_minimal.go +++ b/beacon-chain/state/state-native/beacon_state_minimal.go @@ -8,9 +8,9 @@ import ( "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/fieldtrie" customtypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/custom-types" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" - eth2types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -21,7 +21,7 @@ type BeaconState struct { version int genesisTime uint64 genesisValidatorsRoot [32]byte - slot eth2types.Slot + slot primitives.Slot fork *ethpb.Fork latestBlockHeader *ethpb.BeaconBlockHeader blockRoots *customtypes.BlockRoots @@ -49,14 +49,14 @@ type BeaconState struct { latestExecutionPayloadHeader *enginev1.ExecutionPayloadHeader latestExecutionPayloadHeaderCapella *enginev1.ExecutionPayloadHeaderCapella nextWithdrawalIndex uint64 - nextWithdrawalValidatorIndex eth2types.ValidatorIndex + nextWithdrawalValidatorIndex primitives.ValidatorIndex lock sync.RWMutex - dirtyFields map[nativetypes.FieldIndex]bool - dirtyIndices map[nativetypes.FieldIndex][]uint64 - stateFieldLeaves map[nativetypes.FieldIndex]*fieldtrie.FieldTrie - rebuildTrie map[nativetypes.FieldIndex]bool + dirtyFields map[types.FieldIndex]bool + dirtyIndices map[types.FieldIndex][]uint64 + stateFieldLeaves map[types.FieldIndex]*fieldtrie.FieldTrie + rebuildTrie map[types.FieldIndex]bool valMapHandler *stateutil.ValidatorMapHandler merkleLayers [][][]byte - sharedFieldReferences map[nativetypes.FieldIndex]*stateutil.Reference + sharedFieldReferences map[types.FieldIndex]*stateutil.Reference } diff --git a/beacon-chain/state/state-native/getters_checkpoint.go b/beacon-chain/state/state-native/getters_checkpoint.go index 6c93384247..d84a462d50 100644 --- a/beacon-chain/state/state-native/getters_checkpoint.go +++ b/beacon-chain/state/state-native/getters_checkpoint.go @@ -4,7 +4,7 @@ import ( "bytes" "github.com/prysmaticlabs/go-bitfield" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -113,7 +113,7 @@ func (b *BeaconState) finalizedCheckpointVal() *ethpb.Checkpoint { } // FinalizedCheckpointEpoch returns the epoch value of the finalized checkpoint. -func (b *BeaconState) FinalizedCheckpointEpoch() types.Epoch { +func (b *BeaconState) FinalizedCheckpointEpoch() primitives.Epoch { if b.finalizedCheckpoint == nil { return 0 } diff --git a/beacon-chain/state/state-native/getters_misc.go b/beacon-chain/state/state-native/getters_misc.go index 310256b030..49901fc2c7 100644 --- a/beacon-chain/state/state-native/getters_misc.go +++ b/beacon-chain/state/state-native/getters_misc.go @@ -1,7 +1,7 @@ package state_native import ( - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" ) @@ -30,7 +30,7 @@ func (b *BeaconState) Version() int { } // Slot of the current beacon chain state. -func (b *BeaconState) Slot() types.Slot { +func (b *BeaconState) Slot() primitives.Slot { b.lock.RLock() defer b.lock.RUnlock() diff --git a/beacon-chain/state/state-native/getters_validator.go b/beacon-chain/state/state-native/getters_validator.go index 9a957db89a..bf65a62ad5 100644 --- a/beacon-chain/state/state-native/getters_validator.go +++ b/beacon-chain/state/state-native/getters_validator.go @@ -6,7 +6,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -19,7 +19,7 @@ type ValidatorIndexOutOfRangeError struct { } // NewValidatorIndexOutOfRangeError creates a new error instance. -func NewValidatorIndexOutOfRangeError(index types.ValidatorIndex) ValidatorIndexOutOfRangeError { +func NewValidatorIndexOutOfRangeError(index primitives.ValidatorIndex) ValidatorIndexOutOfRangeError { return ValidatorIndexOutOfRangeError{ message: fmt.Sprintf("index %d out of range", index), } @@ -81,7 +81,7 @@ func (b *BeaconState) validatorsReferences() []*ethpb.Validator { } // ValidatorAtIndex is the validator at the provided index. -func (b *BeaconState) ValidatorAtIndex(idx types.ValidatorIndex) (*ethpb.Validator, error) { +func (b *BeaconState) ValidatorAtIndex(idx primitives.ValidatorIndex) (*ethpb.Validator, error) { if b.validators == nil { return ðpb.Validator{}, nil } @@ -99,7 +99,7 @@ func (b *BeaconState) ValidatorAtIndex(idx types.ValidatorIndex) (*ethpb.Validat // ValidatorAtIndexReadOnly is the validator at the provided index. This method // doesn't clone the validator. -func (b *BeaconState) ValidatorAtIndexReadOnly(idx types.ValidatorIndex) (state.ReadOnlyValidator, error) { +func (b *BeaconState) ValidatorAtIndexReadOnly(idx primitives.ValidatorIndex) (state.ReadOnlyValidator, error) { if b.validators == nil { return nil, state.ErrNilValidatorsInState } @@ -115,7 +115,7 @@ func (b *BeaconState) ValidatorAtIndexReadOnly(idx types.ValidatorIndex) (state. } // ValidatorIndexByPubkey returns a given validator by its 48-byte public key. -func (b *BeaconState) ValidatorIndexByPubkey(key [fieldparams.BLSPubkeyLength]byte) (types.ValidatorIndex, bool) { +func (b *BeaconState) ValidatorIndexByPubkey(key [fieldparams.BLSPubkeyLength]byte) (primitives.ValidatorIndex, bool) { if b == nil || b.valMapHandler == nil || b.valMapHandler.IsNil() { return 0, false } @@ -124,15 +124,15 @@ func (b *BeaconState) ValidatorIndexByPubkey(key [fieldparams.BLSPubkeyLength]by numOfVals := len(b.validators) idx, ok := b.valMapHandler.Get(key) - if ok && types.ValidatorIndex(numOfVals) <= idx { - return types.ValidatorIndex(0), false + if ok && primitives.ValidatorIndex(numOfVals) <= idx { + return primitives.ValidatorIndex(0), false } return idx, ok } // PubkeyAtIndex returns the pubkey at the given // validator index. -func (b *BeaconState) PubkeyAtIndex(idx types.ValidatorIndex) [fieldparams.BLSPubkeyLength]byte { +func (b *BeaconState) PubkeyAtIndex(idx primitives.ValidatorIndex) [fieldparams.BLSPubkeyLength]byte { if uint64(idx) >= uint64(len(b.validators)) { return [fieldparams.BLSPubkeyLength]byte{} } @@ -201,7 +201,7 @@ func (b *BeaconState) balancesVal() []uint64 { } // BalanceAtIndex of validator with the provided index. -func (b *BeaconState) BalanceAtIndex(idx types.ValidatorIndex) (uint64, error) { +func (b *BeaconState) BalanceAtIndex(idx primitives.ValidatorIndex) (uint64, error) { if b.balances == nil { return 0, nil } diff --git a/beacon-chain/state/state-native/getters_withdrawal.go b/beacon-chain/state/state-native/getters_withdrawal.go index 0d3d5e5f7d..c072ebb194 100644 --- a/beacon-chain/state/state-native/getters_withdrawal.go +++ b/beacon-chain/state/state-native/getters_withdrawal.go @@ -2,7 +2,7 @@ package state_native import ( "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" mathutil "github.com/prysmaticlabs/prysm/v3/math" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" @@ -27,7 +27,7 @@ func (b *BeaconState) NextWithdrawalIndex() (uint64, error) { // NextWithdrawalValidatorIndex returns the index of the validator which is // next in line for a withdrawal. -func (b *BeaconState) NextWithdrawalValidatorIndex() (types.ValidatorIndex, error) { +func (b *BeaconState) NextWithdrawalValidatorIndex() (primitives.ValidatorIndex, error) { if b.version < version.Capella { return 0, errNotSupported("NextWithdrawalValidatorIndex", b.version) } @@ -99,7 +99,7 @@ func hasETH1WithdrawalCredential(val *ethpb.Validator) bool { // isFullyWithdrawableValidator returns whether the validator is able to perform a full // withdrawal. This differ from the spec helper in that the balance > 0 is not // checked. This function assumes that the caller holds a lock on the state -func isFullyWithdrawableValidator(val *ethpb.Validator, epoch types.Epoch) bool { +func isFullyWithdrawableValidator(val *ethpb.Validator, epoch primitives.Epoch) bool { if val == nil { return false } diff --git a/beacon-chain/state/state-native/getters_withdrawal_test.go b/beacon-chain/state/state-native/getters_withdrawal_test.go index 6aa3d50cc3..bee75d4165 100644 --- a/beacon-chain/state/state-native/getters_withdrawal_test.go +++ b/beacon-chain/state/state-native/getters_withdrawal_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -31,7 +31,7 @@ func TestLastWithdrawalValidatorIndex(t *testing.T) { s := BeaconState{version: version.Capella, nextWithdrawalValidatorIndex: 123} i, err := s.NextWithdrawalValidatorIndex() require.NoError(t, err) - assert.Equal(t, types.ValidatorIndex(123), i) + assert.Equal(t, primitives.ValidatorIndex(123), i) }) t.Run("version before Capella not supported", func(t *testing.T) { s := BeaconState{version: version.Bellatrix} @@ -122,7 +122,7 @@ func TestExpectedWithdrawals(t *testing.T) { val := ðpb.Validator{ WithdrawalCredentials: make([]byte, 32), EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, - WithdrawableEpoch: types.Epoch(1), + WithdrawableEpoch: primitives.Epoch(1), } val.WithdrawalCredentials[0] = params.BeaconConfig().ETH1AddressWithdrawalPrefixByte s.validators[i] = val @@ -143,12 +143,12 @@ func TestExpectedWithdrawals(t *testing.T) { val := ðpb.Validator{ WithdrawalCredentials: make([]byte, 32), EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, - WithdrawableEpoch: types.Epoch(1), + WithdrawableEpoch: primitives.Epoch(1), } val.WithdrawalCredentials[0] = params.BeaconConfig().ETH1AddressWithdrawalPrefixByte s.validators[i] = val } - s.validators[3].WithdrawableEpoch = types.Epoch(0) + s.validators[3].WithdrawableEpoch = primitives.Epoch(0) expected, err := s.ExpectedWithdrawals() require.NoError(t, err) require.Equal(t, 1, len(expected)) @@ -171,7 +171,7 @@ func TestExpectedWithdrawals(t *testing.T) { val := ðpb.Validator{ WithdrawalCredentials: make([]byte, 32), EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, - WithdrawableEpoch: types.Epoch(1), + WithdrawableEpoch: primitives.Epoch(1), } val.WithdrawalCredentials[0] = params.BeaconConfig().ETH1AddressWithdrawalPrefixByte s.validators[i] = val @@ -199,14 +199,14 @@ func TestExpectedWithdrawals(t *testing.T) { val := ðpb.Validator{ WithdrawalCredentials: make([]byte, 32), EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, - WithdrawableEpoch: types.Epoch(1), + WithdrawableEpoch: primitives.Epoch(1), } val.WithdrawalCredentials[0] = params.BeaconConfig().ETH1AddressWithdrawalPrefixByte val.WithdrawalCredentials[31] = byte(i) s.validators[i] = val } s.balances[3] += params.BeaconConfig().MinDepositAmount - s.validators[7].WithdrawableEpoch = types.Epoch(0) + s.validators[7].WithdrawableEpoch = primitives.Epoch(0) expected, err := s.ExpectedWithdrawals() require.NoError(t, err) require.Equal(t, 2, len(expected)) @@ -237,7 +237,7 @@ func TestExpectedWithdrawals(t *testing.T) { val := ðpb.Validator{ WithdrawalCredentials: make([]byte, 32), EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, - WithdrawableEpoch: types.Epoch(1), + WithdrawableEpoch: primitives.Epoch(1), } val.WithdrawalCredentials[0] = params.BeaconConfig().ETH1AddressWithdrawalPrefixByte s.validators[i] = val @@ -264,7 +264,7 @@ func TestExpectedWithdrawals(t *testing.T) { val := ðpb.Validator{ WithdrawalCredentials: make([]byte, 32), EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, - WithdrawableEpoch: types.Epoch(0), + WithdrawableEpoch: primitives.Epoch(0), } val.WithdrawalCredentials[0] = params.BeaconConfig().ETH1AddressWithdrawalPrefixByte s.validators[i] = val @@ -291,7 +291,7 @@ func TestExpectedWithdrawals(t *testing.T) { val := ðpb.Validator{ WithdrawalCredentials: make([]byte, 32), EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, - WithdrawableEpoch: types.Epoch(0), + WithdrawableEpoch: primitives.Epoch(0), } val.WithdrawalCredentials[0] = params.BeaconConfig().ETH1AddressWithdrawalPrefixByte s.validators[i] = val @@ -319,12 +319,12 @@ func TestExpectedWithdrawals(t *testing.T) { val := ðpb.Validator{ WithdrawalCredentials: make([]byte, 32), EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, - WithdrawableEpoch: types.Epoch(1), + WithdrawableEpoch: primitives.Epoch(1), } val.WithdrawalCredentials[0] = params.BeaconConfig().ETH1AddressWithdrawalPrefixByte s.validators[i] = val } - s.validators[3].WithdrawableEpoch = types.Epoch(0) + s.validators[3].WithdrawableEpoch = primitives.Epoch(0) s.balances[3] = 0 expected, err := s.ExpectedWithdrawals() require.NoError(t, err) @@ -341,7 +341,7 @@ func TestExpectedWithdrawals(t *testing.T) { val := ðpb.Validator{ WithdrawalCredentials: make([]byte, 32), EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, - WithdrawableEpoch: types.Epoch(1), + WithdrawableEpoch: primitives.Epoch(1), } val.WithdrawalCredentials[0] = params.BeaconConfig().ETH1AddressWithdrawalPrefixByte s.validators[i] = val diff --git a/beacon-chain/state/state-native/hasher.go b/beacon-chain/state/state-native/hasher.go index 11efe56501..7707adc214 100644 --- a/beacon-chain/state/state-native/hasher.go +++ b/beacon-chain/state/state-native/hasher.go @@ -5,7 +5,7 @@ import ( "encoding/binary" "github.com/pkg/errors" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" @@ -39,30 +39,30 @@ func ComputeFieldRootsWithHasher(ctx context.Context, state *BeaconState) ([][]b // Genesis time root. genesisRoot := ssz.Uint64Root(state.genesisTime) - fieldRoots[nativetypes.GenesisTime.RealPosition()] = genesisRoot[:] + fieldRoots[types.GenesisTime.RealPosition()] = genesisRoot[:] // Genesis validators root. var r [32]byte copy(r[:], state.genesisValidatorsRoot[:]) - fieldRoots[nativetypes.GenesisValidatorsRoot.RealPosition()] = r[:] + fieldRoots[types.GenesisValidatorsRoot.RealPosition()] = r[:] // Slot root. slotRoot := ssz.Uint64Root(uint64(state.slot)) - fieldRoots[nativetypes.Slot.RealPosition()] = slotRoot[:] + fieldRoots[types.Slot.RealPosition()] = slotRoot[:] // Fork data structure root. forkHashTreeRoot, err := ssz.ForkRoot(state.fork) if err != nil { return nil, errors.Wrap(err, "could not compute fork merkleization") } - fieldRoots[nativetypes.Fork.RealPosition()] = forkHashTreeRoot[:] + fieldRoots[types.Fork.RealPosition()] = forkHashTreeRoot[:] // BeaconBlockHeader data structure root. headerHashTreeRoot, err := stateutil.BlockHeaderRoot(state.latestBlockHeader) if err != nil { return nil, errors.Wrap(err, "could not compute block header merkleization") } - fieldRoots[nativetypes.LatestBlockHeader.RealPosition()] = headerHashTreeRoot[:] + fieldRoots[types.LatestBlockHeader.RealPosition()] = headerHashTreeRoot[:] // BlockRoots array root. bRoots := make([][]byte, len(state.blockRoots)) @@ -73,7 +73,7 @@ func ComputeFieldRootsWithHasher(ctx context.Context, state *BeaconState) ([][]b if err != nil { return nil, errors.Wrap(err, "could not compute block roots merkleization") } - fieldRoots[nativetypes.BlockRoots.RealPosition()] = blockRootsRoot[:] + fieldRoots[types.BlockRoots.RealPosition()] = blockRootsRoot[:] // StateRoots array root. sRoots := make([][]byte, len(state.stateRoots)) @@ -84,7 +84,7 @@ func ComputeFieldRootsWithHasher(ctx context.Context, state *BeaconState) ([][]b if err != nil { return nil, errors.Wrap(err, "could not compute state roots merkleization") } - fieldRoots[nativetypes.StateRoots.RealPosition()] = stateRootsRoot[:] + fieldRoots[types.StateRoots.RealPosition()] = stateRootsRoot[:] // HistoricalRoots slice root. hRoots := make([][]byte, len(state.historicalRoots)) @@ -95,41 +95,41 @@ func ComputeFieldRootsWithHasher(ctx context.Context, state *BeaconState) ([][]b if err != nil { return nil, errors.Wrap(err, "could not compute historical roots merkleization") } - fieldRoots[nativetypes.HistoricalRoots.RealPosition()] = historicalRootsRt[:] + fieldRoots[types.HistoricalRoots.RealPosition()] = historicalRootsRt[:] // Eth1Data data structure root. eth1HashTreeRoot, err := stateutil.Eth1Root(hasher, state.eth1Data) if err != nil { return nil, errors.Wrap(err, "could not compute eth1data merkleization") } - fieldRoots[nativetypes.Eth1Data.RealPosition()] = eth1HashTreeRoot[:] + fieldRoots[types.Eth1Data.RealPosition()] = eth1HashTreeRoot[:] // Eth1DataVotes slice root. eth1VotesRoot, err := stateutil.Eth1DataVotesRoot(state.eth1DataVotes) if err != nil { return nil, errors.Wrap(err, "could not compute eth1data votes merkleization") } - fieldRoots[nativetypes.Eth1DataVotes.RealPosition()] = eth1VotesRoot[:] + fieldRoots[types.Eth1DataVotes.RealPosition()] = eth1VotesRoot[:] // Eth1DepositIndex root. eth1DepositIndexBuf := make([]byte, 8) binary.LittleEndian.PutUint64(eth1DepositIndexBuf, state.eth1DepositIndex) eth1DepositBuf := bytesutil.ToBytes32(eth1DepositIndexBuf) - fieldRoots[nativetypes.Eth1DepositIndex.RealPosition()] = eth1DepositBuf[:] + fieldRoots[types.Eth1DepositIndex.RealPosition()] = eth1DepositBuf[:] // Validators slice root. validatorsRoot, err := stateutil.ValidatorRegistryRoot(state.validators) if err != nil { return nil, errors.Wrap(err, "could not compute validator registry merkleization") } - fieldRoots[nativetypes.Validators.RealPosition()] = validatorsRoot[:] + fieldRoots[types.Validators.RealPosition()] = validatorsRoot[:] // Balances slice root. balancesRoot, err := stateutil.Uint64ListRootWithRegistryLimit(state.balances) if err != nil { return nil, errors.Wrap(err, "could not compute validator balances merkleization") } - fieldRoots[nativetypes.Balances.RealPosition()] = balancesRoot[:] + fieldRoots[types.Balances.RealPosition()] = balancesRoot[:] // RandaoMixes array root. mixes := make([][]byte, len(state.randaoMixes)) @@ -140,14 +140,14 @@ func ComputeFieldRootsWithHasher(ctx context.Context, state *BeaconState) ([][]b if err != nil { return nil, errors.Wrap(err, "could not compute randao roots merkleization") } - fieldRoots[nativetypes.RandaoMixes.RealPosition()] = randaoRootsRoot[:] + fieldRoots[types.RandaoMixes.RealPosition()] = randaoRootsRoot[:] // Slashings array root. slashingsRootsRoot, err := ssz.SlashingsRoot(state.slashings) if err != nil { return nil, errors.Wrap(err, "could not compute slashings merkleization") } - fieldRoots[nativetypes.Slashings.RealPosition()] = slashingsRootsRoot[:] + fieldRoots[types.Slashings.RealPosition()] = slashingsRootsRoot[:] if state.version == version.Phase0 { // PreviousEpochAttestations slice root. @@ -155,14 +155,14 @@ func ComputeFieldRootsWithHasher(ctx context.Context, state *BeaconState) ([][]b if err != nil { return nil, errors.Wrap(err, "could not compute previous epoch attestations merkleization") } - fieldRoots[nativetypes.PreviousEpochAttestations.RealPosition()] = prevAttsRoot[:] + fieldRoots[types.PreviousEpochAttestations.RealPosition()] = prevAttsRoot[:] // CurrentEpochAttestations slice root. currAttsRoot, err := stateutil.EpochAttestationsRoot(state.currentEpochAttestations) if err != nil { return nil, errors.Wrap(err, "could not compute current epoch attestations merkleization") } - fieldRoots[nativetypes.CurrentEpochAttestations.RealPosition()] = currAttsRoot[:] + fieldRoots[types.CurrentEpochAttestations.RealPosition()] = currAttsRoot[:] } if state.version >= version.Altair { @@ -171,40 +171,40 @@ func ComputeFieldRootsWithHasher(ctx context.Context, state *BeaconState) ([][]b if err != nil { return nil, errors.Wrap(err, "could not compute previous epoch participation merkleization") } - fieldRoots[nativetypes.PreviousEpochParticipationBits.RealPosition()] = prevParticipationRoot[:] + fieldRoots[types.PreviousEpochParticipationBits.RealPosition()] = prevParticipationRoot[:] // CurrentEpochParticipation slice root. currParticipationRoot, err := stateutil.ParticipationBitsRoot(state.currentEpochParticipation) if err != nil { return nil, errors.Wrap(err, "could not compute current epoch participation merkleization") } - fieldRoots[nativetypes.CurrentEpochParticipationBits.RealPosition()] = currParticipationRoot[:] + fieldRoots[types.CurrentEpochParticipationBits.RealPosition()] = currParticipationRoot[:] } // JustificationBits root. justifiedBitsRoot := bytesutil.ToBytes32(state.justificationBits) - fieldRoots[nativetypes.JustificationBits.RealPosition()] = justifiedBitsRoot[:] + fieldRoots[types.JustificationBits.RealPosition()] = justifiedBitsRoot[:] // PreviousJustifiedCheckpoint data structure root. prevCheckRoot, err := ssz.CheckpointRoot(hasher, state.previousJustifiedCheckpoint) if err != nil { return nil, errors.Wrap(err, "could not compute previous justified checkpoint merkleization") } - fieldRoots[nativetypes.PreviousJustifiedCheckpoint.RealPosition()] = prevCheckRoot[:] + fieldRoots[types.PreviousJustifiedCheckpoint.RealPosition()] = prevCheckRoot[:] // CurrentJustifiedCheckpoint data structure root. currJustRoot, err := ssz.CheckpointRoot(hasher, state.currentJustifiedCheckpoint) if err != nil { return nil, errors.Wrap(err, "could not compute current justified checkpoint merkleization") } - fieldRoots[nativetypes.CurrentJustifiedCheckpoint.RealPosition()] = currJustRoot[:] + fieldRoots[types.CurrentJustifiedCheckpoint.RealPosition()] = currJustRoot[:] // FinalizedCheckpoint data structure root. finalRoot, err := ssz.CheckpointRoot(hasher, state.finalizedCheckpoint) if err != nil { return nil, errors.Wrap(err, "could not compute finalized checkpoint merkleization") } - fieldRoots[nativetypes.FinalizedCheckpoint.RealPosition()] = finalRoot[:] + fieldRoots[types.FinalizedCheckpoint.RealPosition()] = finalRoot[:] if state.version >= version.Altair { // Inactivity scores root. @@ -212,21 +212,21 @@ func ComputeFieldRootsWithHasher(ctx context.Context, state *BeaconState) ([][]b if err != nil { return nil, errors.Wrap(err, "could not compute inactivityScoreRoot") } - fieldRoots[nativetypes.InactivityScores.RealPosition()] = inactivityScoresRoot[:] + fieldRoots[types.InactivityScores.RealPosition()] = inactivityScoresRoot[:] // Current sync committee root. currentSyncCommitteeRoot, err := stateutil.SyncCommitteeRoot(state.currentSyncCommittee) if err != nil { return nil, errors.Wrap(err, "could not compute sync committee merkleization") } - fieldRoots[nativetypes.CurrentSyncCommittee.RealPosition()] = currentSyncCommitteeRoot[:] + fieldRoots[types.CurrentSyncCommittee.RealPosition()] = currentSyncCommitteeRoot[:] // Next sync committee root. nextSyncCommitteeRoot, err := stateutil.SyncCommitteeRoot(state.nextSyncCommittee) if err != nil { return nil, errors.Wrap(err, "could not compute sync committee merkleization") } - fieldRoots[nativetypes.NextSyncCommittee.RealPosition()] = nextSyncCommitteeRoot[:] + fieldRoots[types.NextSyncCommittee.RealPosition()] = nextSyncCommitteeRoot[:] } if state.version == version.Bellatrix { @@ -235,7 +235,7 @@ func ComputeFieldRootsWithHasher(ctx context.Context, state *BeaconState) ([][]b if err != nil { return nil, err } - fieldRoots[nativetypes.LatestExecutionPayloadHeader.RealPosition()] = executionPayloadRoot[:] + fieldRoots[types.LatestExecutionPayloadHeader.RealPosition()] = executionPayloadRoot[:] } if state.version == version.Capella { @@ -244,24 +244,24 @@ func ComputeFieldRootsWithHasher(ctx context.Context, state *BeaconState) ([][]b if err != nil { return nil, err } - fieldRoots[nativetypes.LatestExecutionPayloadHeaderCapella.RealPosition()] = executionPayloadRoot[:] + fieldRoots[types.LatestExecutionPayloadHeaderCapella.RealPosition()] = executionPayloadRoot[:] // Next withdrawal index root. nextWithdrawalIndexRoot := make([]byte, 32) binary.LittleEndian.PutUint64(nextWithdrawalIndexRoot, state.nextWithdrawalIndex) - fieldRoots[nativetypes.NextWithdrawalIndex.RealPosition()] = nextWithdrawalIndexRoot + fieldRoots[types.NextWithdrawalIndex.RealPosition()] = nextWithdrawalIndexRoot // Next partial withdrawal validator index root. nextWithdrawalValidatorIndexRoot := make([]byte, 32) binary.LittleEndian.PutUint64(nextWithdrawalValidatorIndexRoot, uint64(state.nextWithdrawalValidatorIndex)) - fieldRoots[nativetypes.NextWithdrawalValidatorIndex.RealPosition()] = nextWithdrawalValidatorIndexRoot + fieldRoots[types.NextWithdrawalValidatorIndex.RealPosition()] = nextWithdrawalValidatorIndexRoot // Historical summary root. historicalSummaryRoot, err := stateutil.HistoricalSummariesRoot(state.historicalSummaries) if err != nil { return nil, errors.Wrap(err, "could not compute historical summary merkleization") } - fieldRoots[nativetypes.HistoricalSummaries.RealPosition()] = historicalSummaryRoot[:] + fieldRoots[types.HistoricalSummaries.RealPosition()] = historicalSummaryRoot[:] } return fieldRoots, nil diff --git a/beacon-chain/state/state-native/proofs.go b/beacon-chain/state/state-native/proofs.go index d806430b90..d5e2a9546b 100644 --- a/beacon-chain/state/state-native/proofs.go +++ b/beacon-chain/state/state-native/proofs.go @@ -5,7 +5,7 @@ import ( "encoding/binary" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/fieldtrie" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/runtime/version" ) @@ -25,7 +25,7 @@ func (b *BeaconState) CurrentSyncCommitteeGeneralizedIndex() (uint64, error) { return 0, errNotSupported("CurrentSyncCommitteeGeneralizedIndex", b.version) } - return uint64(nativetypes.CurrentSyncCommittee.RealPosition()), nil + return uint64(types.CurrentSyncCommittee.RealPosition()), nil } // NextSyncCommitteeGeneralizedIndex for the beacon state. @@ -34,7 +34,7 @@ func (b *BeaconState) NextSyncCommitteeGeneralizedIndex() (uint64, error) { return 0, errNotSupported("NextSyncCommitteeGeneralizedIndex", b.version) } - return uint64(nativetypes.NextSyncCommittee.RealPosition()), nil + return uint64(types.NextSyncCommittee.RealPosition()), nil } // CurrentSyncCommitteeProof from the state's Merkle trie representation. @@ -56,7 +56,7 @@ func (b *BeaconState) CurrentSyncCommitteeProof(ctx context.Context) ([][]byte, if err := b.recomputeDirtyFields(ctx); err != nil { return nil, err } - return fieldtrie.ProofFromMerkleLayers(b.merkleLayers, nativetypes.CurrentSyncCommittee.RealPosition()), nil + return fieldtrie.ProofFromMerkleLayers(b.merkleLayers, types.CurrentSyncCommittee.RealPosition()), nil } // NextSyncCommitteeProof from the state's Merkle trie representation. @@ -74,7 +74,7 @@ func (b *BeaconState) NextSyncCommitteeProof(ctx context.Context) ([][]byte, err if err := b.recomputeDirtyFields(ctx); err != nil { return nil, err } - return fieldtrie.ProofFromMerkleLayers(b.merkleLayers, nativetypes.NextSyncCommittee.RealPosition()), nil + return fieldtrie.ProofFromMerkleLayers(b.merkleLayers, types.NextSyncCommittee.RealPosition()), nil } // FinalizedRootProof crafts a Merkle proof for the finalized root @@ -102,7 +102,7 @@ func (b *BeaconState) FinalizedRootProof(ctx context.Context) ([][]byte, error) epochRoot := bytesutil.ToBytes32(epochBuf) proof := make([][]byte, 0) proof = append(proof, epochRoot[:]) - branch := fieldtrie.ProofFromMerkleLayers(b.merkleLayers, nativetypes.FinalizedCheckpoint.RealPosition()) + branch := fieldtrie.ProofFromMerkleLayers(b.merkleLayers, types.FinalizedCheckpoint.RealPosition()) proof = append(proof, branch...) return proof, nil } diff --git a/beacon-chain/state/state-native/readonly_validator.go b/beacon-chain/state/state-native/readonly_validator.go index 9fb71036b3..035fa735ff 100644 --- a/beacon-chain/state/state-native/readonly_validator.go +++ b/beacon-chain/state/state-native/readonly_validator.go @@ -5,7 +5,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -41,25 +41,25 @@ func (v readOnlyValidator) EffectiveBalance() uint64 { // ActivationEligibilityEpoch returns the activation eligibility epoch of the // read only validator. -func (v readOnlyValidator) ActivationEligibilityEpoch() types.Epoch { +func (v readOnlyValidator) ActivationEligibilityEpoch() primitives.Epoch { return v.validator.ActivationEligibilityEpoch } // ActivationEpoch returns the activation epoch of the // read only validator. -func (v readOnlyValidator) ActivationEpoch() types.Epoch { +func (v readOnlyValidator) ActivationEpoch() primitives.Epoch { return v.validator.ActivationEpoch } // WithdrawableEpoch returns the withdrawable epoch of the // read only validator. -func (v readOnlyValidator) WithdrawableEpoch() types.Epoch { +func (v readOnlyValidator) WithdrawableEpoch() primitives.Epoch { return v.validator.WithdrawableEpoch } // ExitEpoch returns the exit epoch of the // read only validator. -func (v readOnlyValidator) ExitEpoch() types.Epoch { +func (v readOnlyValidator) ExitEpoch() primitives.Epoch { return v.validator.ExitEpoch } @@ -89,7 +89,7 @@ func (v readOnlyValidator) HasETH1WithdrawalCredential() bool { // IsFullyWithdrawable returns whether the validator is able to perform a full // withdrawal. This differ from the spec helper in that the balance > 0 is not // checked. -func (v readOnlyValidator) IsFullyWithdrawable(epoch types.Epoch) bool { +func (v readOnlyValidator) IsFullyWithdrawable(epoch primitives.Epoch) bool { return v.HasETH1WithdrawalCredential() && v.WithdrawableEpoch() <= epoch } diff --git a/beacon-chain/state/state-native/readonly_validator_test.go b/beacon-chain/state/state-native/readonly_validator_test.go index 442208276e..77f44c8c2d 100644 --- a/beacon-chain/state/state-native/readonly_validator_test.go +++ b/beacon-chain/state/state-native/readonly_validator_test.go @@ -6,7 +6,7 @@ import ( statenative "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -26,28 +26,28 @@ func TestReadOnlyValidator_EffectiveBalance(t *testing.T) { } func TestReadOnlyValidator_ActivationEligibilityEpoch(t *testing.T) { - epoch := types.Epoch(234) + epoch := primitives.Epoch(234) v, err := statenative.NewValidator(ðpb.Validator{ActivationEligibilityEpoch: epoch}) require.NoError(t, err) assert.Equal(t, epoch, v.ActivationEligibilityEpoch()) } func TestReadOnlyValidator_ActivationEpoch(t *testing.T) { - epoch := types.Epoch(234) + epoch := primitives.Epoch(234) v, err := statenative.NewValidator(ðpb.Validator{ActivationEpoch: epoch}) require.NoError(t, err) assert.Equal(t, epoch, v.ActivationEpoch()) } func TestReadOnlyValidator_WithdrawableEpoch(t *testing.T) { - epoch := types.Epoch(234) + epoch := primitives.Epoch(234) v, err := statenative.NewValidator(ðpb.Validator{WithdrawableEpoch: epoch}) require.NoError(t, err) assert.Equal(t, epoch, v.WithdrawableEpoch()) } func TestReadOnlyValidator_ExitEpoch(t *testing.T) { - epoch := types.Epoch(234) + epoch := primitives.Epoch(234) v, err := statenative.NewValidator(ðpb.Validator{ExitEpoch: epoch}) require.NoError(t, err) assert.Equal(t, epoch, v.ExitEpoch()) diff --git a/beacon-chain/state/state-native/references_test.go b/beacon-chain/state/state-native/references_test.go index 43f7cab834..c5d797b3f2 100644 --- a/beacon-chain/state/state-native/references_test.go +++ b/beacon-chain/state/state-native/references_test.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -22,24 +22,24 @@ func TestStateReferenceSharing_Finalizer_Phase0(t *testing.T) { require.NoError(t, err) a, ok := s.(*BeaconState) require.Equal(t, true, ok) - assert.Equal(t, uint(1), a.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected a single reference for RANDAO mixes") + assert.Equal(t, uint(1), a.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected a single reference for RANDAO mixes") func() { // Create object in a different scope for GC b := a.Copy() - assert.Equal(t, uint(2), a.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected 2 references to RANDAO mixes") + assert.Equal(t, uint(2), a.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected 2 references to RANDAO mixes") _ = b }() runtime.GC() // Should run finalizer on object b - assert.Equal(t, uint(1), a.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected 1 shared reference to RANDAO mixes!") + assert.Equal(t, uint(1), a.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected 1 shared reference to RANDAO mixes!") copied := a.Copy() b, ok := copied.(*BeaconState) require.Equal(t, true, ok) - assert.Equal(t, uint(2), b.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected 2 shared references to RANDAO mixes") + assert.Equal(t, uint(2), b.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected 2 shared references to RANDAO mixes") require.NoError(t, b.UpdateRandaoMixesAtIndex(0, []byte("bar"))) - if b.sharedFieldReferences[nativetypes.RandaoMixes].Refs() != 1 || a.sharedFieldReferences[nativetypes.RandaoMixes].Refs() != 1 { + if b.sharedFieldReferences[types.RandaoMixes].Refs() != 1 || a.sharedFieldReferences[types.RandaoMixes].Refs() != 1 { t.Error("Expected 1 shared reference to RANDAO mix for both a and b") } } @@ -51,24 +51,24 @@ func TestStateReferenceSharing_Finalizer_Altair(t *testing.T) { require.NoError(t, err) a, ok := s.(*BeaconState) require.Equal(t, true, ok) - assert.Equal(t, uint(1), a.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected a single reference for RANDAO mixes") + assert.Equal(t, uint(1), a.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected a single reference for RANDAO mixes") func() { // Create object in a different scope for GC b := a.Copy() - assert.Equal(t, uint(2), a.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected 2 references to RANDAO mixes") + assert.Equal(t, uint(2), a.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected 2 references to RANDAO mixes") _ = b }() runtime.GC() // Should run finalizer on object b - assert.Equal(t, uint(1), a.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected 1 shared reference to RANDAO mixes!") + assert.Equal(t, uint(1), a.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected 1 shared reference to RANDAO mixes!") copied := a.Copy() b, ok := copied.(*BeaconState) require.Equal(t, true, ok) - assert.Equal(t, uint(2), b.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected 2 shared references to RANDAO mixes") + assert.Equal(t, uint(2), b.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected 2 shared references to RANDAO mixes") require.NoError(t, b.UpdateRandaoMixesAtIndex(0, []byte("bar"))) - if b.sharedFieldReferences[nativetypes.RandaoMixes].Refs() != 1 || a.sharedFieldReferences[nativetypes.RandaoMixes].Refs() != 1 { + if b.sharedFieldReferences[types.RandaoMixes].Refs() != 1 || a.sharedFieldReferences[types.RandaoMixes].Refs() != 1 { t.Error("Expected 1 shared reference to RANDAO mix for both a and b") } } @@ -80,24 +80,24 @@ func TestStateReferenceSharing_Finalizer_Bellatrix(t *testing.T) { require.NoError(t, err) a, ok := s.(*BeaconState) require.Equal(t, true, ok) - assert.Equal(t, uint(1), a.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected a single reference for RANDAO mixes") + assert.Equal(t, uint(1), a.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected a single reference for RANDAO mixes") func() { // Create object in a different scope for GC b := a.Copy() - assert.Equal(t, uint(2), a.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected 2 references to RANDAO mixes") + assert.Equal(t, uint(2), a.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected 2 references to RANDAO mixes") _ = b }() runtime.GC() // Should run finalizer on object b - assert.Equal(t, uint(1), a.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected 1 shared reference to RANDAO mixes!") + assert.Equal(t, uint(1), a.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected 1 shared reference to RANDAO mixes!") copied := a.Copy() b, ok := copied.(*BeaconState) require.Equal(t, true, ok) - assert.Equal(t, uint(2), b.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected 2 shared references to RANDAO mixes") + assert.Equal(t, uint(2), b.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected 2 shared references to RANDAO mixes") require.NoError(t, b.UpdateRandaoMixesAtIndex(0, []byte("bar"))) - if b.sharedFieldReferences[nativetypes.RandaoMixes].Refs() != 1 || a.sharedFieldReferences[nativetypes.RandaoMixes].Refs() != 1 { + if b.sharedFieldReferences[types.RandaoMixes].Refs() != 1 || a.sharedFieldReferences[types.RandaoMixes].Refs() != 1 { t.Error("Expected 1 shared reference to RANDAO mix for both a and b") } } @@ -109,24 +109,24 @@ func TestStateReferenceSharing_Finalizer_Capella(t *testing.T) { require.NoError(t, err) a, ok := s.(*BeaconState) require.Equal(t, true, ok) - assert.Equal(t, uint(1), a.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected a single reference for RANDAO mixes") + assert.Equal(t, uint(1), a.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected a single reference for RANDAO mixes") func() { // Create object in a different scope for GC b := a.Copy() - assert.Equal(t, uint(2), a.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected 2 references to RANDAO mixes") + assert.Equal(t, uint(2), a.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected 2 references to RANDAO mixes") _ = b }() runtime.GC() // Should run finalizer on object b - assert.Equal(t, uint(1), a.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected 1 shared reference to RANDAO mixes!") + assert.Equal(t, uint(1), a.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected 1 shared reference to RANDAO mixes!") copied := a.Copy() b, ok := copied.(*BeaconState) require.Equal(t, true, ok) - assert.Equal(t, uint(2), b.sharedFieldReferences[nativetypes.RandaoMixes].Refs(), "Expected 2 shared references to RANDAO mixes") + assert.Equal(t, uint(2), b.sharedFieldReferences[types.RandaoMixes].Refs(), "Expected 2 shared references to RANDAO mixes") require.NoError(t, b.UpdateRandaoMixesAtIndex(0, []byte("bar"))) - if b.sharedFieldReferences[nativetypes.RandaoMixes].Refs() != 1 || a.sharedFieldReferences[nativetypes.RandaoMixes].Refs() != 1 { + if b.sharedFieldReferences[types.RandaoMixes].Refs() != 1 || a.sharedFieldReferences[types.RandaoMixes].Refs() != 1 { t.Error("Expected 1 shared reference to RANDAO mix for both a and b") } } @@ -145,17 +145,17 @@ func TestStateReferenceCopy_NoUnexpectedRootsMutation_Phase0(t *testing.T) { a, ok := s.(*BeaconState) require.Equal(t, true, ok) require.NoError(t, err) - assertRefCount(t, a, nativetypes.BlockRoots, 1) - assertRefCount(t, a, nativetypes.StateRoots, 1) + assertRefCount(t, a, types.BlockRoots, 1) + assertRefCount(t, a, types.StateRoots, 1) // Copy, increases reference count. copied := a.Copy() b, ok := copied.(*BeaconState) require.Equal(t, true, ok) - assertRefCount(t, a, nativetypes.BlockRoots, 2) - assertRefCount(t, a, nativetypes.StateRoots, 2) - assertRefCount(t, b, nativetypes.BlockRoots, 2) - assertRefCount(t, b, nativetypes.StateRoots, 2) + assertRefCount(t, a, types.BlockRoots, 2) + assertRefCount(t, a, types.StateRoots, 2) + assertRefCount(t, b, types.BlockRoots, 2) + assertRefCount(t, b, types.StateRoots, 2) // Assert shared state. blockRootsA := a.BlockRoots() @@ -184,10 +184,10 @@ func TestStateReferenceCopy_NoUnexpectedRootsMutation_Phase0(t *testing.T) { assert.DeepEqual(t, root1[:], stateRootsB[0], "Unexpected mutation found") // Copy on write happened, reference counters are reset. - assertRefCount(t, a, nativetypes.BlockRoots, 1) - assertRefCount(t, a, nativetypes.StateRoots, 1) - assertRefCount(t, b, nativetypes.BlockRoots, 1) - assertRefCount(t, b, nativetypes.StateRoots, 1) + assertRefCount(t, a, types.BlockRoots, 1) + assertRefCount(t, a, types.StateRoots, 1) + assertRefCount(t, b, types.BlockRoots, 1) + assertRefCount(t, b, types.StateRoots, 1) } func TestStateReferenceCopy_NoUnexpectedRootsMutation_Altair(t *testing.T) { @@ -204,17 +204,17 @@ func TestStateReferenceCopy_NoUnexpectedRootsMutation_Altair(t *testing.T) { a, ok := s.(*BeaconState) require.Equal(t, true, ok) require.NoError(t, err) - assertRefCount(t, a, nativetypes.BlockRoots, 1) - assertRefCount(t, a, nativetypes.StateRoots, 1) + assertRefCount(t, a, types.BlockRoots, 1) + assertRefCount(t, a, types.StateRoots, 1) // Copy, increases reference count. copied := a.Copy() b, ok := copied.(*BeaconState) require.Equal(t, true, ok) - assertRefCount(t, a, nativetypes.BlockRoots, 2) - assertRefCount(t, a, nativetypes.StateRoots, 2) - assertRefCount(t, b, nativetypes.BlockRoots, 2) - assertRefCount(t, b, nativetypes.StateRoots, 2) + assertRefCount(t, a, types.BlockRoots, 2) + assertRefCount(t, a, types.StateRoots, 2) + assertRefCount(t, b, types.BlockRoots, 2) + assertRefCount(t, b, types.StateRoots, 2) // Assert shared state. blockRootsA := a.BlockRoots() @@ -243,10 +243,10 @@ func TestStateReferenceCopy_NoUnexpectedRootsMutation_Altair(t *testing.T) { assert.DeepEqual(t, root1[:], stateRootsB[0], "Unexpected mutation found") // Copy on write happened, reference counters are reset. - assertRefCount(t, a, nativetypes.BlockRoots, 1) - assertRefCount(t, a, nativetypes.StateRoots, 1) - assertRefCount(t, b, nativetypes.BlockRoots, 1) - assertRefCount(t, b, nativetypes.StateRoots, 1) + assertRefCount(t, a, types.BlockRoots, 1) + assertRefCount(t, a, types.StateRoots, 1) + assertRefCount(t, b, types.BlockRoots, 1) + assertRefCount(t, b, types.StateRoots, 1) } func TestStateReferenceCopy_NoUnexpectedRootsMutation_Bellatrix(t *testing.T) { @@ -263,17 +263,17 @@ func TestStateReferenceCopy_NoUnexpectedRootsMutation_Bellatrix(t *testing.T) { a, ok := s.(*BeaconState) require.Equal(t, true, ok) require.NoError(t, err) - assertRefCount(t, a, nativetypes.BlockRoots, 1) - assertRefCount(t, a, nativetypes.StateRoots, 1) + assertRefCount(t, a, types.BlockRoots, 1) + assertRefCount(t, a, types.StateRoots, 1) // Copy, increases reference count. copied := a.Copy() b, ok := copied.(*BeaconState) require.Equal(t, true, ok) - assertRefCount(t, a, nativetypes.BlockRoots, 2) - assertRefCount(t, a, nativetypes.StateRoots, 2) - assertRefCount(t, b, nativetypes.BlockRoots, 2) - assertRefCount(t, b, nativetypes.StateRoots, 2) + assertRefCount(t, a, types.BlockRoots, 2) + assertRefCount(t, a, types.StateRoots, 2) + assertRefCount(t, b, types.BlockRoots, 2) + assertRefCount(t, b, types.StateRoots, 2) // Assert shared state. blockRootsA := a.BlockRoots() @@ -302,10 +302,10 @@ func TestStateReferenceCopy_NoUnexpectedRootsMutation_Bellatrix(t *testing.T) { assert.DeepEqual(t, root1[:], stateRootsB[0], "Unexpected mutation found") // Copy on write happened, reference counters are reset. - assertRefCount(t, a, nativetypes.BlockRoots, 1) - assertRefCount(t, a, nativetypes.StateRoots, 1) - assertRefCount(t, b, nativetypes.BlockRoots, 1) - assertRefCount(t, b, nativetypes.StateRoots, 1) + assertRefCount(t, a, types.BlockRoots, 1) + assertRefCount(t, a, types.StateRoots, 1) + assertRefCount(t, b, types.BlockRoots, 1) + assertRefCount(t, b, types.StateRoots, 1) } func TestStateReferenceCopy_NoUnexpectedRootsMutation_Capella(t *testing.T) { @@ -322,17 +322,17 @@ func TestStateReferenceCopy_NoUnexpectedRootsMutation_Capella(t *testing.T) { a, ok := s.(*BeaconState) require.Equal(t, true, ok) require.NoError(t, err) - assertRefCount(t, a, nativetypes.BlockRoots, 1) - assertRefCount(t, a, nativetypes.StateRoots, 1) + assertRefCount(t, a, types.BlockRoots, 1) + assertRefCount(t, a, types.StateRoots, 1) // Copy, increases reference count. copied := a.Copy() b, ok := copied.(*BeaconState) require.Equal(t, true, ok) - assertRefCount(t, a, nativetypes.BlockRoots, 2) - assertRefCount(t, a, nativetypes.StateRoots, 2) - assertRefCount(t, b, nativetypes.BlockRoots, 2) - assertRefCount(t, b, nativetypes.StateRoots, 2) + assertRefCount(t, a, types.BlockRoots, 2) + assertRefCount(t, a, types.StateRoots, 2) + assertRefCount(t, b, types.BlockRoots, 2) + assertRefCount(t, b, types.StateRoots, 2) // Assert shared state. blockRootsA := a.BlockRoots() @@ -361,10 +361,10 @@ func TestStateReferenceCopy_NoUnexpectedRootsMutation_Capella(t *testing.T) { assert.DeepEqual(t, root1[:], stateRootsB[0], "Unexpected mutation found") // Copy on write happened, reference counters are reset. - assertRefCount(t, a, nativetypes.BlockRoots, 1) - assertRefCount(t, a, nativetypes.StateRoots, 1) - assertRefCount(t, b, nativetypes.BlockRoots, 1) - assertRefCount(t, b, nativetypes.StateRoots, 1) + assertRefCount(t, a, types.BlockRoots, 1) + assertRefCount(t, a, types.StateRoots, 1) + assertRefCount(t, b, types.BlockRoots, 1) + assertRefCount(t, b, types.StateRoots, 1) } func TestStateReferenceCopy_NoUnexpectedRandaoMutation_Phase0(t *testing.T) { @@ -378,14 +378,14 @@ func TestStateReferenceCopy_NoUnexpectedRandaoMutation_Phase0(t *testing.T) { a, ok := s.(*BeaconState) require.Equal(t, true, ok) require.NoError(t, err) - assertRefCount(t, a, nativetypes.RandaoMixes, 1) + assertRefCount(t, a, types.RandaoMixes, 1) // Copy, increases reference count. copied := a.Copy() b, ok := copied.(*BeaconState) require.Equal(t, true, ok) - assertRefCount(t, a, nativetypes.RandaoMixes, 2) - assertRefCount(t, b, nativetypes.RandaoMixes, 2) + assertRefCount(t, a, types.RandaoMixes, 2) + assertRefCount(t, b, types.RandaoMixes, 2) // Assert shared state. mixesA := a.RandaoMixes() @@ -407,8 +407,8 @@ func TestStateReferenceCopy_NoUnexpectedRandaoMutation_Phase0(t *testing.T) { assert.DeepEqual(t, val1[:], mixesB[0], "Unexpected mutation found") // Copy on write happened, reference counters are reset. - assertRefCount(t, a, nativetypes.RandaoMixes, 1) - assertRefCount(t, b, nativetypes.RandaoMixes, 1) + assertRefCount(t, a, types.RandaoMixes, 1) + assertRefCount(t, b, types.RandaoMixes, 1) } func TestStateReferenceCopy_NoUnexpectedRandaoMutation_Altair(t *testing.T) { @@ -422,14 +422,14 @@ func TestStateReferenceCopy_NoUnexpectedRandaoMutation_Altair(t *testing.T) { a, ok := s.(*BeaconState) require.Equal(t, true, ok) require.NoError(t, err) - assertRefCount(t, a, nativetypes.RandaoMixes, 1) + assertRefCount(t, a, types.RandaoMixes, 1) // Copy, increases reference count. copied := a.Copy() b, ok := copied.(*BeaconState) require.Equal(t, true, ok) - assertRefCount(t, a, nativetypes.RandaoMixes, 2) - assertRefCount(t, b, nativetypes.RandaoMixes, 2) + assertRefCount(t, a, types.RandaoMixes, 2) + assertRefCount(t, b, types.RandaoMixes, 2) // Assert shared state. mixesA := a.RandaoMixes() @@ -451,8 +451,8 @@ func TestStateReferenceCopy_NoUnexpectedRandaoMutation_Altair(t *testing.T) { assert.DeepEqual(t, val1[:], mixesB[0], "Unexpected mutation found") // Copy on write happened, reference counters are reset. - assertRefCount(t, a, nativetypes.RandaoMixes, 1) - assertRefCount(t, b, nativetypes.RandaoMixes, 1) + assertRefCount(t, a, types.RandaoMixes, 1) + assertRefCount(t, b, types.RandaoMixes, 1) } func TestStateReferenceCopy_NoUnexpectedRandaoMutation_Bellatrix(t *testing.T) { @@ -466,14 +466,14 @@ func TestStateReferenceCopy_NoUnexpectedRandaoMutation_Bellatrix(t *testing.T) { a, ok := s.(*BeaconState) require.Equal(t, true, ok) require.NoError(t, err) - assertRefCount(t, a, nativetypes.RandaoMixes, 1) + assertRefCount(t, a, types.RandaoMixes, 1) // Copy, increases reference count. copied := a.Copy() b, ok := copied.(*BeaconState) require.Equal(t, true, ok) - assertRefCount(t, a, nativetypes.RandaoMixes, 2) - assertRefCount(t, b, nativetypes.RandaoMixes, 2) + assertRefCount(t, a, types.RandaoMixes, 2) + assertRefCount(t, b, types.RandaoMixes, 2) // Assert shared state. mixesA := a.RandaoMixes() @@ -495,8 +495,8 @@ func TestStateReferenceCopy_NoUnexpectedRandaoMutation_Bellatrix(t *testing.T) { assert.DeepEqual(t, val1[:], mixesB[0], "Unexpected mutation found") // Copy on write happened, reference counters are reset. - assertRefCount(t, a, nativetypes.RandaoMixes, 1) - assertRefCount(t, b, nativetypes.RandaoMixes, 1) + assertRefCount(t, a, types.RandaoMixes, 1) + assertRefCount(t, b, types.RandaoMixes, 1) } func TestStateReferenceCopy_NoUnexpectedRandaoMutation_Capella(t *testing.T) { @@ -510,14 +510,14 @@ func TestStateReferenceCopy_NoUnexpectedRandaoMutation_Capella(t *testing.T) { a, ok := s.(*BeaconState) require.Equal(t, true, ok) require.NoError(t, err) - assertRefCount(t, a, nativetypes.RandaoMixes, 1) + assertRefCount(t, a, types.RandaoMixes, 1) // Copy, increases reference count. copied := a.Copy() b, ok := copied.(*BeaconState) require.Equal(t, true, ok) - assertRefCount(t, a, nativetypes.RandaoMixes, 2) - assertRefCount(t, b, nativetypes.RandaoMixes, 2) + assertRefCount(t, a, types.RandaoMixes, 2) + assertRefCount(t, b, types.RandaoMixes, 2) // Assert shared state. mixesA := a.RandaoMixes() @@ -539,8 +539,8 @@ func TestStateReferenceCopy_NoUnexpectedRandaoMutation_Capella(t *testing.T) { assert.DeepEqual(t, val1[:], mixesB[0], "Unexpected mutation found") // Copy on write happened, reference counters are reset. - assertRefCount(t, a, nativetypes.RandaoMixes, 1) - assertRefCount(t, b, nativetypes.RandaoMixes, 1) + assertRefCount(t, a, types.RandaoMixes, 1) + assertRefCount(t, b, types.RandaoMixes, 1) } func TestStateReferenceCopy_NoUnexpectedAttestationsMutation(t *testing.T) { @@ -567,8 +567,8 @@ func TestStateReferenceCopy_NoUnexpectedAttestationsMutation(t *testing.T) { require.NoError(t, err) a, ok := s.(*BeaconState) require.Equal(t, true, ok) - assertRefCount(t, a, nativetypes.PreviousEpochAttestations, 1) - assertRefCount(t, a, nativetypes.CurrentEpochAttestations, 1) + assertRefCount(t, a, types.PreviousEpochAttestations, 1) + assertRefCount(t, a, types.CurrentEpochAttestations, 1) // Update initial state. atts := []*ethpb.PendingAttestation{ @@ -588,10 +588,10 @@ func TestStateReferenceCopy_NoUnexpectedAttestationsMutation(t *testing.T) { copied := a.Copy() b, ok := copied.(*BeaconState) require.Equal(t, true, ok) - assertRefCount(t, a, nativetypes.PreviousEpochAttestations, 2) - assertRefCount(t, a, nativetypes.CurrentEpochAttestations, 2) - assertRefCount(t, b, nativetypes.PreviousEpochAttestations, 2) - assertRefCount(t, b, nativetypes.CurrentEpochAttestations, 2) + assertRefCount(t, a, types.PreviousEpochAttestations, 2) + assertRefCount(t, a, types.CurrentEpochAttestations, 2) + assertRefCount(t, b, types.PreviousEpochAttestations, 2) + assertRefCount(t, b, types.CurrentEpochAttestations, 2) prevAtts, err := b.PreviousEpochAttestations() require.NoError(t, err) assert.Equal(t, 1, len(prevAtts), "Unexpected number of attestations") @@ -702,10 +702,10 @@ func TestStateReferenceCopy_NoUnexpectedAttestationsMutation(t *testing.T) { assertAttNotFound(prevAttsB, 2) // Copy on write happened, reference counters are reset. - assertRefCount(t, a, nativetypes.CurrentEpochAttestations, 1) - assertRefCount(t, b, nativetypes.CurrentEpochAttestations, 1) - assertRefCount(t, a, nativetypes.PreviousEpochAttestations, 1) - assertRefCount(t, b, nativetypes.PreviousEpochAttestations, 1) + assertRefCount(t, a, types.CurrentEpochAttestations, 1) + assertRefCount(t, b, types.CurrentEpochAttestations, 1) + assertRefCount(t, a, types.PreviousEpochAttestations, 1) + assertRefCount(t, b, types.PreviousEpochAttestations, 1) } func TestValidatorReferences_RemainsConsistent_Phase0(t *testing.T) { @@ -850,7 +850,7 @@ func TestValidatorReferences_RemainsConsistent_Bellatrix(t *testing.T) { // assertRefCount checks whether reference count for a given state // at a given index is equal to expected amount. -func assertRefCount(t *testing.T, b *BeaconState, idx nativetypes.FieldIndex, want uint) { +func assertRefCount(t *testing.T, b *BeaconState, idx types.FieldIndex, want uint) { if cnt := b.sharedFieldReferences[idx].Refs(); cnt != want { t.Errorf("Unexpected count of references for index %d, want: %v, got: %v", idx, want, cnt) } diff --git a/beacon-chain/state/state-native/setters_attestation.go b/beacon-chain/state/state-native/setters_attestation.go index f1f2810c64..697b23a913 100644 --- a/beacon-chain/state/state-native/setters_attestation.go +++ b/beacon-chain/state/state-native/setters_attestation.go @@ -3,7 +3,7 @@ package state_native import ( "fmt" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" "github.com/prysmaticlabs/prysm/v3/config/params" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -26,21 +26,21 @@ func (b *BeaconState) RotateAttestations() error { } func (b *BeaconState) setPreviousEpochAttestations(val []*ethpb.PendingAttestation) { - b.sharedFieldReferences[nativetypes.PreviousEpochAttestations].MinusRef() - b.sharedFieldReferences[nativetypes.PreviousEpochAttestations] = stateutil.NewRef(1) + b.sharedFieldReferences[types.PreviousEpochAttestations].MinusRef() + b.sharedFieldReferences[types.PreviousEpochAttestations] = stateutil.NewRef(1) b.previousEpochAttestations = val - b.markFieldAsDirty(nativetypes.PreviousEpochAttestations) - b.rebuildTrie[nativetypes.PreviousEpochAttestations] = true + b.markFieldAsDirty(types.PreviousEpochAttestations) + b.rebuildTrie[types.PreviousEpochAttestations] = true } func (b *BeaconState) setCurrentEpochAttestations(val []*ethpb.PendingAttestation) { - b.sharedFieldReferences[nativetypes.CurrentEpochAttestations].MinusRef() - b.sharedFieldReferences[nativetypes.CurrentEpochAttestations] = stateutil.NewRef(1) + b.sharedFieldReferences[types.CurrentEpochAttestations].MinusRef() + b.sharedFieldReferences[types.CurrentEpochAttestations] = stateutil.NewRef(1) b.currentEpochAttestations = val - b.markFieldAsDirty(nativetypes.CurrentEpochAttestations) - b.rebuildTrie[nativetypes.CurrentEpochAttestations] = true + b.markFieldAsDirty(types.CurrentEpochAttestations) + b.rebuildTrie[types.CurrentEpochAttestations] = true } // AppendCurrentEpochAttestations for the beacon state. Appends the new value @@ -59,17 +59,17 @@ func (b *BeaconState) AppendCurrentEpochAttestations(val *ethpb.PendingAttestati return fmt.Errorf("current pending attestation exceeds max length %d", max) } - if b.sharedFieldReferences[nativetypes.CurrentEpochAttestations].Refs() > 1 { + if b.sharedFieldReferences[types.CurrentEpochAttestations].Refs() > 1 { // Copy elements in underlying array by reference. atts = make([]*ethpb.PendingAttestation, len(b.currentEpochAttestations)) copy(atts, b.currentEpochAttestations) - b.sharedFieldReferences[nativetypes.CurrentEpochAttestations].MinusRef() - b.sharedFieldReferences[nativetypes.CurrentEpochAttestations] = stateutil.NewRef(1) + b.sharedFieldReferences[types.CurrentEpochAttestations].MinusRef() + b.sharedFieldReferences[types.CurrentEpochAttestations] = stateutil.NewRef(1) } b.currentEpochAttestations = append(atts, val) - b.markFieldAsDirty(nativetypes.CurrentEpochAttestations) - b.addDirtyIndices(nativetypes.CurrentEpochAttestations, []uint64{uint64(len(b.currentEpochAttestations) - 1)}) + b.markFieldAsDirty(types.CurrentEpochAttestations) + b.addDirtyIndices(types.CurrentEpochAttestations, []uint64{uint64(len(b.currentEpochAttestations) - 1)}) return nil } @@ -89,16 +89,16 @@ func (b *BeaconState) AppendPreviousEpochAttestations(val *ethpb.PendingAttestat return fmt.Errorf("previous pending attestation exceeds max length %d", max) } - if b.sharedFieldReferences[nativetypes.PreviousEpochAttestations].Refs() > 1 { + if b.sharedFieldReferences[types.PreviousEpochAttestations].Refs() > 1 { atts = make([]*ethpb.PendingAttestation, len(b.previousEpochAttestations)) copy(atts, b.previousEpochAttestations) - b.sharedFieldReferences[nativetypes.PreviousEpochAttestations].MinusRef() - b.sharedFieldReferences[nativetypes.PreviousEpochAttestations] = stateutil.NewRef(1) + b.sharedFieldReferences[types.PreviousEpochAttestations].MinusRef() + b.sharedFieldReferences[types.PreviousEpochAttestations] = stateutil.NewRef(1) } b.previousEpochAttestations = append(atts, val) - b.markFieldAsDirty(nativetypes.PreviousEpochAttestations) - b.addDirtyIndices(nativetypes.PreviousEpochAttestations, []uint64{uint64(len(b.previousEpochAttestations) - 1)}) + b.markFieldAsDirty(types.PreviousEpochAttestations) + b.addDirtyIndices(types.PreviousEpochAttestations, []uint64{uint64(len(b.previousEpochAttestations) - 1)}) return nil } diff --git a/beacon-chain/state/state-native/setters_attestation_test.go b/beacon-chain/state/state-native/setters_attestation_test.go index ce3b493827..7fa604211d 100644 --- a/beacon-chain/state/state-native/setters_attestation_test.go +++ b/beacon-chain/state/state-native/setters_attestation_test.go @@ -4,9 +4,9 @@ import ( "context" "testing" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -24,7 +24,7 @@ func TestBeaconState_RotateAttestations(t *testing.T) { s, ok := st.(*BeaconState) require.Equal(t, true, ok) require.Equal(t, 0, len(s.currentEpochAttestationsVal())) - require.Equal(t, types.Slot(456), s.previousEpochAttestationsVal()[0].Data.Slot) + require.Equal(t, primitives.Slot(456), s.previousEpochAttestationsVal()[0].Data.Slot) } func TestAppendBeyondIndicesLimit(t *testing.T) { @@ -57,7 +57,7 @@ func TestAppendBeyondIndicesLimit(t *testing.T) { require.NoError(t, err) s, ok := st.(*BeaconState) require.Equal(t, true, ok) - for i := nativetypes.FieldIndex(0); i < nativetypes.FieldIndex(params.BeaconConfig().BeaconStateFieldCount); i++ { + for i := types.FieldIndex(0); i < types.FieldIndex(params.BeaconConfig().BeaconStateFieldCount); i++ { s.dirtyFields[i] = true } _, err = st.HashTreeRoot(context.Background()) @@ -65,12 +65,12 @@ func TestAppendBeyondIndicesLimit(t *testing.T) { for i := 0; i < 10; i++ { assert.NoError(t, st.AppendValidator(ðpb.Validator{})) } - assert.Equal(t, false, s.rebuildTrie[nativetypes.Validators]) - assert.NotEqual(t, len(s.dirtyIndices[nativetypes.Validators]), 0) + assert.Equal(t, false, s.rebuildTrie[types.Validators]) + assert.NotEqual(t, len(s.dirtyIndices[types.Validators]), 0) for i := 0; i < indicesLimit; i++ { assert.NoError(t, st.AppendValidator(ðpb.Validator{})) } - assert.Equal(t, true, s.rebuildTrie[nativetypes.Validators]) - assert.Equal(t, len(s.dirtyIndices[nativetypes.Validators]), 0) + assert.Equal(t, true, s.rebuildTrie[types.Validators]) + assert.Equal(t, len(s.dirtyIndices[types.Validators]), 0) } diff --git a/beacon-chain/state/state-native/setters_block.go b/beacon-chain/state/state-native/setters_block.go index cc7f06e790..b667eda496 100644 --- a/beacon-chain/state/state-native/setters_block.go +++ b/beacon-chain/state/state-native/setters_block.go @@ -4,7 +4,7 @@ import ( "fmt" customtypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/custom-types" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -16,7 +16,7 @@ func (b *BeaconState) SetLatestBlockHeader(val *ethpb.BeaconBlockHeader) error { defer b.lock.Unlock() b.latestBlockHeader = ethpb.CopyBeaconBlockHeader(val) - b.markFieldAsDirty(nativetypes.LatestBlockHeader) + b.markFieldAsDirty(types.LatestBlockHeader) return nil } @@ -26,8 +26,8 @@ func (b *BeaconState) SetBlockRoots(val [][]byte) error { b.lock.Lock() defer b.lock.Unlock() - b.sharedFieldReferences[nativetypes.BlockRoots].MinusRef() - b.sharedFieldReferences[nativetypes.BlockRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.BlockRoots].MinusRef() + b.sharedFieldReferences[types.BlockRoots] = stateutil.NewRef(1) var rootsArr [fieldparams.BlockRootsLength][32]byte for i := 0; i < len(rootsArr); i++ { @@ -35,8 +35,8 @@ func (b *BeaconState) SetBlockRoots(val [][]byte) error { } roots := customtypes.BlockRoots(rootsArr) b.blockRoots = &roots - b.markFieldAsDirty(nativetypes.BlockRoots) - b.rebuildTrie[nativetypes.BlockRoots] = true + b.markFieldAsDirty(types.BlockRoots) + b.rebuildTrie[types.BlockRoots] = true return nil } @@ -50,19 +50,19 @@ func (b *BeaconState) UpdateBlockRootAtIndex(idx uint64, blockRoot [32]byte) err defer b.lock.Unlock() r := b.blockRoots - if ref := b.sharedFieldReferences[nativetypes.BlockRoots]; ref.Refs() > 1 { + if ref := b.sharedFieldReferences[types.BlockRoots]; ref.Refs() > 1 { // Copy elements in underlying array by reference. roots := *b.blockRoots rootsCopy := roots r = &rootsCopy ref.MinusRef() - b.sharedFieldReferences[nativetypes.BlockRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.BlockRoots] = stateutil.NewRef(1) } r[idx] = blockRoot b.blockRoots = r - b.markFieldAsDirty(nativetypes.BlockRoots) - b.addDirtyIndices(nativetypes.BlockRoots, []uint64{idx}) + b.markFieldAsDirty(types.BlockRoots) + b.addDirtyIndices(types.BlockRoots, []uint64{idx}) return nil } diff --git a/beacon-chain/state/state-native/setters_checkpoint.go b/beacon-chain/state/state-native/setters_checkpoint.go index bbbbd34aef..21a382f041 100644 --- a/beacon-chain/state/state-native/setters_checkpoint.go +++ b/beacon-chain/state/state-native/setters_checkpoint.go @@ -2,7 +2,7 @@ package state_native import ( "github.com/prysmaticlabs/go-bitfield" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -12,7 +12,7 @@ func (b *BeaconState) SetJustificationBits(val bitfield.Bitvector4) error { defer b.lock.Unlock() b.justificationBits = val - b.markFieldAsDirty(nativetypes.JustificationBits) + b.markFieldAsDirty(types.JustificationBits) return nil } @@ -22,7 +22,7 @@ func (b *BeaconState) SetPreviousJustifiedCheckpoint(val *ethpb.Checkpoint) erro defer b.lock.Unlock() b.previousJustifiedCheckpoint = val - b.markFieldAsDirty(nativetypes.PreviousJustifiedCheckpoint) + b.markFieldAsDirty(types.PreviousJustifiedCheckpoint) return nil } @@ -32,7 +32,7 @@ func (b *BeaconState) SetCurrentJustifiedCheckpoint(val *ethpb.Checkpoint) error defer b.lock.Unlock() b.currentJustifiedCheckpoint = val - b.markFieldAsDirty(nativetypes.CurrentJustifiedCheckpoint) + b.markFieldAsDirty(types.CurrentJustifiedCheckpoint) return nil } @@ -42,6 +42,6 @@ func (b *BeaconState) SetFinalizedCheckpoint(val *ethpb.Checkpoint) error { defer b.lock.Unlock() b.finalizedCheckpoint = val - b.markFieldAsDirty(nativetypes.FinalizedCheckpoint) + b.markFieldAsDirty(types.FinalizedCheckpoint) return nil } diff --git a/beacon-chain/state/state-native/setters_eth1.go b/beacon-chain/state/state-native/setters_eth1.go index 0140323f40..4e19f9a321 100644 --- a/beacon-chain/state/state-native/setters_eth1.go +++ b/beacon-chain/state/state-native/setters_eth1.go @@ -1,7 +1,7 @@ package state_native import ( - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -12,7 +12,7 @@ func (b *BeaconState) SetEth1Data(val *ethpb.Eth1Data) error { defer b.lock.Unlock() b.eth1Data = val - b.markFieldAsDirty(nativetypes.Eth1Data) + b.markFieldAsDirty(types.Eth1Data) return nil } @@ -22,12 +22,12 @@ func (b *BeaconState) SetEth1DataVotes(val []*ethpb.Eth1Data) error { b.lock.Lock() defer b.lock.Unlock() - b.sharedFieldReferences[nativetypes.Eth1DataVotes].MinusRef() - b.sharedFieldReferences[nativetypes.Eth1DataVotes] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Eth1DataVotes].MinusRef() + b.sharedFieldReferences[types.Eth1DataVotes] = stateutil.NewRef(1) b.eth1DataVotes = val - b.markFieldAsDirty(nativetypes.Eth1DataVotes) - b.rebuildTrie[nativetypes.Eth1DataVotes] = true + b.markFieldAsDirty(types.Eth1DataVotes) + b.rebuildTrie[types.Eth1DataVotes] = true return nil } @@ -37,7 +37,7 @@ func (b *BeaconState) SetEth1DepositIndex(val uint64) error { defer b.lock.Unlock() b.eth1DepositIndex = val - b.markFieldAsDirty(nativetypes.Eth1DepositIndex) + b.markFieldAsDirty(types.Eth1DepositIndex) return nil } @@ -48,16 +48,16 @@ func (b *BeaconState) AppendEth1DataVotes(val *ethpb.Eth1Data) error { defer b.lock.Unlock() votes := b.eth1DataVotes - if b.sharedFieldReferences[nativetypes.Eth1DataVotes].Refs() > 1 { + if b.sharedFieldReferences[types.Eth1DataVotes].Refs() > 1 { // Copy elements in underlying array by reference. votes = make([]*ethpb.Eth1Data, len(b.eth1DataVotes)) copy(votes, b.eth1DataVotes) - b.sharedFieldReferences[nativetypes.Eth1DataVotes].MinusRef() - b.sharedFieldReferences[nativetypes.Eth1DataVotes] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Eth1DataVotes].MinusRef() + b.sharedFieldReferences[types.Eth1DataVotes] = stateutil.NewRef(1) } b.eth1DataVotes = append(votes, val) - b.markFieldAsDirty(nativetypes.Eth1DataVotes) - b.addDirtyIndices(nativetypes.Eth1DataVotes, []uint64{uint64(len(b.eth1DataVotes) - 1)}) + b.markFieldAsDirty(types.Eth1DataVotes) + b.addDirtyIndices(types.Eth1DataVotes, []uint64{uint64(len(b.eth1DataVotes) - 1)}) return nil } diff --git a/beacon-chain/state/state-native/setters_misc.go b/beacon-chain/state/state-native/setters_misc.go index 81d20839b3..9e9c4c71d4 100644 --- a/beacon-chain/state/state-native/setters_misc.go +++ b/beacon-chain/state/state-native/setters_misc.go @@ -2,10 +2,10 @@ package state_native import ( "github.com/pkg/errors" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -47,7 +47,7 @@ func (b *BeaconState) SetGenesisTime(val uint64) error { defer b.lock.Unlock() b.genesisTime = val - b.markFieldAsDirty(nativetypes.GenesisTime) + b.markFieldAsDirty(types.GenesisTime) return nil } @@ -60,17 +60,17 @@ func (b *BeaconState) SetGenesisValidatorsRoot(val []byte) error { return errors.New("incorrect validators root length") } b.genesisValidatorsRoot = bytesutil.ToBytes32(val) - b.markFieldAsDirty(nativetypes.GenesisValidatorsRoot) + b.markFieldAsDirty(types.GenesisValidatorsRoot) return nil } // SetSlot for the beacon state. -func (b *BeaconState) SetSlot(val types.Slot) error { +func (b *BeaconState) SetSlot(val primitives.Slot) error { b.lock.Lock() defer b.lock.Unlock() b.slot = val - b.markFieldAsDirty(nativetypes.Slot) + b.markFieldAsDirty(types.Slot) return nil } @@ -84,7 +84,7 @@ func (b *BeaconState) SetFork(val *ethpb.Fork) error { return errors.New("proto.Clone did not return a fork proto") } b.fork = fk - b.markFieldAsDirty(nativetypes.Fork) + b.markFieldAsDirty(types.Fork) return nil } @@ -94,15 +94,15 @@ func (b *BeaconState) SetHistoricalRoots(val [][]byte) error { b.lock.Lock() defer b.lock.Unlock() - b.sharedFieldReferences[nativetypes.HistoricalRoots].MinusRef() - b.sharedFieldReferences[nativetypes.HistoricalRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.HistoricalRoots].MinusRef() + b.sharedFieldReferences[types.HistoricalRoots] = stateutil.NewRef(1) roots := make([][32]byte, len(val)) for i, r := range val { copy(roots[i][:], r) } b.historicalRoots = roots - b.markFieldAsDirty(nativetypes.HistoricalRoots) + b.markFieldAsDirty(types.HistoricalRoots) return nil } @@ -117,15 +117,15 @@ func (b *BeaconState) AppendHistoricalRoots(root [32]byte) error { } roots := b.historicalRoots - if b.sharedFieldReferences[nativetypes.HistoricalRoots].Refs() > 1 { + if b.sharedFieldReferences[types.HistoricalRoots].Refs() > 1 { roots = make([][32]byte, len(b.historicalRoots)) copy(roots, b.historicalRoots) - b.sharedFieldReferences[nativetypes.HistoricalRoots].MinusRef() - b.sharedFieldReferences[nativetypes.HistoricalRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.HistoricalRoots].MinusRef() + b.sharedFieldReferences[types.HistoricalRoots] = stateutil.NewRef(1) } b.historicalRoots = append(roots, root) - b.markFieldAsDirty(nativetypes.HistoricalRoots) + b.markFieldAsDirty(types.HistoricalRoots) return nil } @@ -140,15 +140,15 @@ func (b *BeaconState) AppendHistoricalSummaries(summary *ethpb.HistoricalSummary } summaries := b.historicalSummaries - if b.sharedFieldReferences[nativetypes.HistoricalSummaries].Refs() > 1 { + if b.sharedFieldReferences[types.HistoricalSummaries].Refs() > 1 { summaries = make([]*ethpb.HistoricalSummary, len(b.historicalSummaries)) copy(summaries, b.historicalSummaries) - b.sharedFieldReferences[nativetypes.HistoricalSummaries].MinusRef() - b.sharedFieldReferences[nativetypes.HistoricalSummaries] = stateutil.NewRef(1) + b.sharedFieldReferences[types.HistoricalSummaries].MinusRef() + b.sharedFieldReferences[types.HistoricalSummaries] = stateutil.NewRef(1) } b.historicalSummaries = append(summaries, summary) - b.markFieldAsDirty(nativetypes.HistoricalSummaries) + b.markFieldAsDirty(types.HistoricalSummaries) return nil } @@ -187,13 +187,13 @@ func (b *BeaconState) recomputeRoot(idx int) { b.merkleLayers = layers } -func (b *BeaconState) markFieldAsDirty(field nativetypes.FieldIndex) { +func (b *BeaconState) markFieldAsDirty(field types.FieldIndex) { b.dirtyFields[field] = true } // addDirtyIndices adds the relevant dirty field indices, so that they // can be recomputed. -func (b *BeaconState) addDirtyIndices(index nativetypes.FieldIndex, indices []uint64) { +func (b *BeaconState) addDirtyIndices(index types.FieldIndex, indices []uint64) { if b.rebuildTrie[index] { return } diff --git a/beacon-chain/state/state-native/setters_participation.go b/beacon-chain/state/state-native/setters_participation.go index eba285e8b6..0cc2a44273 100644 --- a/beacon-chain/state/state-native/setters_participation.go +++ b/beacon-chain/state/state-native/setters_participation.go @@ -1,7 +1,7 @@ package state_native import ( - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" "github.com/prysmaticlabs/prysm/v3/runtime/version" ) @@ -16,12 +16,12 @@ func (b *BeaconState) SetPreviousParticipationBits(val []byte) error { return errNotSupported("SetPreviousParticipationBits", b.version) } - b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits].MinusRef() - b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits] = stateutil.NewRef(1) + b.sharedFieldReferences[types.PreviousEpochParticipationBits].MinusRef() + b.sharedFieldReferences[types.PreviousEpochParticipationBits] = stateutil.NewRef(1) b.previousEpochParticipation = val - b.markFieldAsDirty(nativetypes.PreviousEpochParticipationBits) - b.rebuildTrie[nativetypes.PreviousEpochParticipationBits] = true + b.markFieldAsDirty(types.PreviousEpochParticipationBits) + b.rebuildTrie[types.PreviousEpochParticipationBits] = true return nil } @@ -35,12 +35,12 @@ func (b *BeaconState) SetCurrentParticipationBits(val []byte) error { return errNotSupported("SetCurrentParticipationBits", b.version) } - b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits].MinusRef() - b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits] = stateutil.NewRef(1) + b.sharedFieldReferences[types.CurrentEpochParticipationBits].MinusRef() + b.sharedFieldReferences[types.CurrentEpochParticipationBits] = stateutil.NewRef(1) b.currentEpochParticipation = val - b.markFieldAsDirty(nativetypes.CurrentEpochParticipationBits) - b.rebuildTrie[nativetypes.CurrentEpochParticipationBits] = true + b.markFieldAsDirty(types.CurrentEpochParticipationBits) + b.rebuildTrie[types.CurrentEpochParticipationBits] = true return nil } @@ -55,17 +55,17 @@ func (b *BeaconState) AppendCurrentParticipationBits(val byte) error { } participation := b.currentEpochParticipation - if b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits].Refs() > 1 { + if b.sharedFieldReferences[types.CurrentEpochParticipationBits].Refs() > 1 { // Copy elements in underlying array by reference. participation = make([]byte, len(b.currentEpochParticipation)) copy(participation, b.currentEpochParticipation) - b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits].MinusRef() - b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits] = stateutil.NewRef(1) + b.sharedFieldReferences[types.CurrentEpochParticipationBits].MinusRef() + b.sharedFieldReferences[types.CurrentEpochParticipationBits] = stateutil.NewRef(1) } b.currentEpochParticipation = append(participation, val) - b.markFieldAsDirty(nativetypes.CurrentEpochParticipationBits) - b.addDirtyIndices(nativetypes.CurrentEpochParticipationBits, []uint64{uint64(len(b.currentEpochParticipation) - 1)}) + b.markFieldAsDirty(types.CurrentEpochParticipationBits) + b.addDirtyIndices(types.CurrentEpochParticipationBits, []uint64{uint64(len(b.currentEpochParticipation) - 1)}) return nil } @@ -80,16 +80,16 @@ func (b *BeaconState) AppendPreviousParticipationBits(val byte) error { } bits := b.previousEpochParticipation - if b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits].Refs() > 1 { + if b.sharedFieldReferences[types.PreviousEpochParticipationBits].Refs() > 1 { bits = make([]byte, len(b.previousEpochParticipation)) copy(bits, b.previousEpochParticipation) - b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits].MinusRef() - b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits] = stateutil.NewRef(1) + b.sharedFieldReferences[types.PreviousEpochParticipationBits].MinusRef() + b.sharedFieldReferences[types.PreviousEpochParticipationBits] = stateutil.NewRef(1) } b.previousEpochParticipation = append(bits, val) - b.markFieldAsDirty(nativetypes.PreviousEpochParticipationBits) - b.addDirtyIndices(nativetypes.PreviousEpochParticipationBits, []uint64{uint64(len(b.previousEpochParticipation) - 1)}) + b.markFieldAsDirty(types.PreviousEpochParticipationBits) + b.addDirtyIndices(types.PreviousEpochParticipationBits, []uint64{uint64(len(b.previousEpochParticipation) - 1)}) return nil } @@ -105,12 +105,12 @@ func (b *BeaconState) ModifyPreviousParticipationBits(mutator func(val []byte) ( } participation := b.previousEpochParticipation - if b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits].Refs() > 1 { + if b.sharedFieldReferences[types.PreviousEpochParticipationBits].Refs() > 1 { // Copy elements in underlying array by reference. participation = make([]byte, len(b.previousEpochParticipation)) copy(participation, b.previousEpochParticipation) - b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits].MinusRef() - b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits] = stateutil.NewRef(1) + b.sharedFieldReferences[types.PreviousEpochParticipationBits].MinusRef() + b.sharedFieldReferences[types.PreviousEpochParticipationBits] = stateutil.NewRef(1) } // Lock is released so that mutator can // acquire it. @@ -124,8 +124,8 @@ func (b *BeaconState) ModifyPreviousParticipationBits(mutator func(val []byte) ( b.lock.Lock() defer b.lock.Unlock() b.previousEpochParticipation = participation - b.markFieldAsDirty(nativetypes.PreviousEpochParticipationBits) - b.rebuildTrie[nativetypes.PreviousEpochParticipationBits] = true + b.markFieldAsDirty(types.PreviousEpochParticipationBits) + b.rebuildTrie[types.PreviousEpochParticipationBits] = true return nil } @@ -140,12 +140,12 @@ func (b *BeaconState) ModifyCurrentParticipationBits(mutator func(val []byte) ([ } participation := b.currentEpochParticipation - if b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits].Refs() > 1 { + if b.sharedFieldReferences[types.CurrentEpochParticipationBits].Refs() > 1 { // Copy elements in underlying array by reference. participation = make([]byte, len(b.currentEpochParticipation)) copy(participation, b.currentEpochParticipation) - b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits].MinusRef() - b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits] = stateutil.NewRef(1) + b.sharedFieldReferences[types.CurrentEpochParticipationBits].MinusRef() + b.sharedFieldReferences[types.CurrentEpochParticipationBits] = stateutil.NewRef(1) } // Lock is released so that mutator can // acquire it. @@ -159,7 +159,7 @@ func (b *BeaconState) ModifyCurrentParticipationBits(mutator func(val []byte) ([ b.lock.Lock() defer b.lock.Unlock() b.currentEpochParticipation = participation - b.markFieldAsDirty(nativetypes.CurrentEpochParticipationBits) - b.rebuildTrie[nativetypes.CurrentEpochParticipationBits] = true + b.markFieldAsDirty(types.CurrentEpochParticipationBits) + b.rebuildTrie[types.CurrentEpochParticipationBits] = true return nil } diff --git a/beacon-chain/state/state-native/setters_payload_header.go b/beacon-chain/state/state-native/setters_payload_header.go index 20dcb854c3..ccced2e7d4 100644 --- a/beacon-chain/state/state-native/setters_payload_header.go +++ b/beacon-chain/state/state-native/setters_payload_header.go @@ -2,7 +2,7 @@ package state_native import ( "github.com/pkg/errors" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" @@ -26,7 +26,7 @@ func (b *BeaconState) SetLatestExecutionPayloadHeader(val interfaces.ExecutionDa return errors.Wrap(err, "could not convert payload to header") } b.latestExecutionPayloadHeader = latest - b.markFieldAsDirty(nativetypes.LatestExecutionPayloadHeader) + b.markFieldAsDirty(types.LatestExecutionPayloadHeader) return nil case *enginev1.ExecutionPayloadCapella: latest, err := consensusblocks.PayloadToHeaderCapella(val) @@ -34,15 +34,15 @@ func (b *BeaconState) SetLatestExecutionPayloadHeader(val interfaces.ExecutionDa return errors.Wrap(err, "could not convert payload to header") } b.latestExecutionPayloadHeaderCapella = latest - b.markFieldAsDirty(nativetypes.LatestExecutionPayloadHeaderCapella) + b.markFieldAsDirty(types.LatestExecutionPayloadHeaderCapella) return nil case *enginev1.ExecutionPayloadHeader: b.latestExecutionPayloadHeader = header - b.markFieldAsDirty(nativetypes.LatestExecutionPayloadHeader) + b.markFieldAsDirty(types.LatestExecutionPayloadHeader) return nil case *enginev1.ExecutionPayloadHeaderCapella: b.latestExecutionPayloadHeaderCapella = header - b.markFieldAsDirty(nativetypes.LatestExecutionPayloadHeaderCapella) + b.markFieldAsDirty(types.LatestExecutionPayloadHeaderCapella) return nil default: return errors.New("value must be an execution payload header") diff --git a/beacon-chain/state/state-native/setters_randao.go b/beacon-chain/state/state-native/setters_randao.go index c41338b0e3..743d23fb03 100644 --- a/beacon-chain/state/state-native/setters_randao.go +++ b/beacon-chain/state/state-native/setters_randao.go @@ -3,7 +3,7 @@ package state_native import ( "github.com/pkg/errors" customtypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/custom-types" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -15,8 +15,8 @@ func (b *BeaconState) SetRandaoMixes(val [][]byte) error { b.lock.Lock() defer b.lock.Unlock() - b.sharedFieldReferences[nativetypes.RandaoMixes].MinusRef() - b.sharedFieldReferences[nativetypes.RandaoMixes] = stateutil.NewRef(1) + b.sharedFieldReferences[types.RandaoMixes].MinusRef() + b.sharedFieldReferences[types.RandaoMixes] = stateutil.NewRef(1) var mixesArr [fieldparams.RandaoMixesLength][32]byte for i := 0; i < len(mixesArr); i++ { @@ -24,8 +24,8 @@ func (b *BeaconState) SetRandaoMixes(val [][]byte) error { } mixes := customtypes.RandaoMixes(mixesArr) b.randaoMixes = &mixes - b.markFieldAsDirty(nativetypes.RandaoMixes) - b.rebuildTrie[nativetypes.RandaoMixes] = true + b.markFieldAsDirty(types.RandaoMixes) + b.rebuildTrie[types.RandaoMixes] = true return nil } @@ -39,19 +39,19 @@ func (b *BeaconState) UpdateRandaoMixesAtIndex(idx uint64, val []byte) error { defer b.lock.Unlock() mixes := b.randaoMixes - if refs := b.sharedFieldReferences[nativetypes.RandaoMixes].Refs(); refs > 1 { + if refs := b.sharedFieldReferences[types.RandaoMixes].Refs(); refs > 1 { // Copy elements in underlying array by reference. m := *b.randaoMixes mCopy := m mixes = &mCopy - b.sharedFieldReferences[nativetypes.RandaoMixes].MinusRef() - b.sharedFieldReferences[nativetypes.RandaoMixes] = stateutil.NewRef(1) + b.sharedFieldReferences[types.RandaoMixes].MinusRef() + b.sharedFieldReferences[types.RandaoMixes] = stateutil.NewRef(1) } mixes[idx] = bytesutil.ToBytes32(val) b.randaoMixes = mixes - b.markFieldAsDirty(nativetypes.RandaoMixes) - b.addDirtyIndices(nativetypes.RandaoMixes, []uint64{idx}) + b.markFieldAsDirty(types.RandaoMixes) + b.addDirtyIndices(types.RandaoMixes, []uint64{idx}) return nil } diff --git a/beacon-chain/state/state-native/setters_state.go b/beacon-chain/state/state-native/setters_state.go index 7b6dee496a..ff056f9293 100644 --- a/beacon-chain/state/state-native/setters_state.go +++ b/beacon-chain/state/state-native/setters_state.go @@ -3,7 +3,7 @@ package state_native import ( "github.com/pkg/errors" customtypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/custom-types" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" ) @@ -14,8 +14,8 @@ func (b *BeaconState) SetStateRoots(val [][]byte) error { b.lock.Lock() defer b.lock.Unlock() - b.sharedFieldReferences[nativetypes.StateRoots].MinusRef() - b.sharedFieldReferences[nativetypes.StateRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.StateRoots].MinusRef() + b.sharedFieldReferences[types.StateRoots] = stateutil.NewRef(1) var rootsArr [fieldparams.StateRootsLength][32]byte for i := 0; i < len(rootsArr); i++ { @@ -23,8 +23,8 @@ func (b *BeaconState) SetStateRoots(val [][]byte) error { } roots := customtypes.StateRoots(rootsArr) b.stateRoots = &roots - b.markFieldAsDirty(nativetypes.StateRoots) - b.rebuildTrie[nativetypes.StateRoots] = true + b.markFieldAsDirty(types.StateRoots) + b.rebuildTrie[types.StateRoots] = true return nil } @@ -43,19 +43,19 @@ func (b *BeaconState) UpdateStateRootAtIndex(idx uint64, stateRoot [32]byte) err // Check if we hold the only reference to the shared state roots slice. r := b.stateRoots - if ref := b.sharedFieldReferences[nativetypes.StateRoots]; ref.Refs() > 1 { + if ref := b.sharedFieldReferences[types.StateRoots]; ref.Refs() > 1 { // Copy elements in underlying array by reference. roots := *b.stateRoots rootsCopy := roots r = &rootsCopy ref.MinusRef() - b.sharedFieldReferences[nativetypes.StateRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.StateRoots] = stateutil.NewRef(1) } r[idx] = stateRoot b.stateRoots = r - b.markFieldAsDirty(nativetypes.StateRoots) - b.addDirtyIndices(nativetypes.StateRoots, []uint64{idx}) + b.markFieldAsDirty(types.StateRoots) + b.addDirtyIndices(types.StateRoots, []uint64{idx}) return nil } diff --git a/beacon-chain/state/state-native/setters_sync_committee.go b/beacon-chain/state/state-native/setters_sync_committee.go index 068ef6a8bd..1865132062 100644 --- a/beacon-chain/state/state-native/setters_sync_committee.go +++ b/beacon-chain/state/state-native/setters_sync_committee.go @@ -1,7 +1,7 @@ package state_native import ( - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" ) @@ -16,7 +16,7 @@ func (b *BeaconState) SetCurrentSyncCommittee(val *ethpb.SyncCommittee) error { } b.currentSyncCommittee = val - b.markFieldAsDirty(nativetypes.CurrentSyncCommittee) + b.markFieldAsDirty(types.CurrentSyncCommittee) return nil } @@ -30,6 +30,6 @@ func (b *BeaconState) SetNextSyncCommittee(val *ethpb.SyncCommittee) error { } b.nextSyncCommittee = val - b.markFieldAsDirty(nativetypes.NextSyncCommittee) + b.markFieldAsDirty(types.NextSyncCommittee) return nil } diff --git a/beacon-chain/state/state-native/setters_validator.go b/beacon-chain/state/state-native/setters_validator.go index 3153e9a17c..8f4a6beb52 100644 --- a/beacon-chain/state/state-native/setters_validator.go +++ b/beacon-chain/state/state-native/setters_validator.go @@ -2,9 +2,9 @@ package state_native import ( "github.com/pkg/errors" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" @@ -17,10 +17,10 @@ func (b *BeaconState) SetValidators(val []*ethpb.Validator) error { defer b.lock.Unlock() b.validators = val - b.sharedFieldReferences[nativetypes.Validators].MinusRef() - b.sharedFieldReferences[nativetypes.Validators] = stateutil.NewRef(1) - b.markFieldAsDirty(nativetypes.Validators) - b.rebuildTrie[nativetypes.Validators] = true + b.sharedFieldReferences[types.Validators].MinusRef() + b.sharedFieldReferences[types.Validators] = stateutil.NewRef(1) + b.markFieldAsDirty(types.Validators) + b.rebuildTrie[types.Validators] = true b.valMapHandler = stateutil.NewValMapHandler(b.validators) return nil } @@ -30,10 +30,10 @@ func (b *BeaconState) SetValidators(val []*ethpb.Validator) error { func (b *BeaconState) ApplyToEveryValidator(f func(idx int, val *ethpb.Validator) (bool, *ethpb.Validator, error)) error { b.lock.Lock() v := b.validators - if ref := b.sharedFieldReferences[nativetypes.Validators]; ref.Refs() > 1 { + if ref := b.sharedFieldReferences[types.Validators]; ref.Refs() > 1 { v = b.validatorsReferences() ref.MinusRef() - b.sharedFieldReferences[nativetypes.Validators] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Validators] = stateutil.NewRef(1) } b.lock.Unlock() var changedVals []uint64 @@ -52,15 +52,15 @@ func (b *BeaconState) ApplyToEveryValidator(f func(idx int, val *ethpb.Validator defer b.lock.Unlock() b.validators = v - b.markFieldAsDirty(nativetypes.Validators) - b.addDirtyIndices(nativetypes.Validators, changedVals) + b.markFieldAsDirty(types.Validators) + b.addDirtyIndices(types.Validators, changedVals) return nil } // UpdateValidatorAtIndex for the beacon state. Updates the validator // at a specific index to a new value. -func (b *BeaconState) UpdateValidatorAtIndex(idx types.ValidatorIndex, val *ethpb.Validator) error { +func (b *BeaconState) UpdateValidatorAtIndex(idx primitives.ValidatorIndex, val *ethpb.Validator) error { if uint64(len(b.validators)) <= uint64(idx) { return errors.Errorf("invalid index provided %d", idx) } @@ -68,16 +68,16 @@ func (b *BeaconState) UpdateValidatorAtIndex(idx types.ValidatorIndex, val *ethp defer b.lock.Unlock() v := b.validators - if ref := b.sharedFieldReferences[nativetypes.Validators]; ref.Refs() > 1 { + if ref := b.sharedFieldReferences[types.Validators]; ref.Refs() > 1 { v = b.validatorsReferences() ref.MinusRef() - b.sharedFieldReferences[nativetypes.Validators] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Validators] = stateutil.NewRef(1) } v[idx] = val b.validators = v - b.markFieldAsDirty(nativetypes.Validators) - b.addDirtyIndices(nativetypes.Validators, []uint64{uint64(idx)}) + b.markFieldAsDirty(types.Validators) + b.addDirtyIndices(types.Validators, []uint64{uint64(idx)}) return nil } @@ -88,18 +88,18 @@ func (b *BeaconState) SetBalances(val []uint64) error { b.lock.Lock() defer b.lock.Unlock() - b.sharedFieldReferences[nativetypes.Balances].MinusRef() - b.sharedFieldReferences[nativetypes.Balances] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Balances].MinusRef() + b.sharedFieldReferences[types.Balances] = stateutil.NewRef(1) b.balances = val - b.markFieldAsDirty(nativetypes.Balances) - b.rebuildTrie[nativetypes.Balances] = true + b.markFieldAsDirty(types.Balances) + b.rebuildTrie[types.Balances] = true return nil } // UpdateBalancesAtIndex for the beacon state. This method updates the balance // at a specific index to a new value. -func (b *BeaconState) UpdateBalancesAtIndex(idx types.ValidatorIndex, val uint64) error { +func (b *BeaconState) UpdateBalancesAtIndex(idx primitives.ValidatorIndex, val uint64) error { if uint64(len(b.balances)) <= uint64(idx) { return errors.Errorf("invalid index provided %d", idx) } @@ -107,16 +107,16 @@ func (b *BeaconState) UpdateBalancesAtIndex(idx types.ValidatorIndex, val uint64 defer b.lock.Unlock() bals := b.balances - if b.sharedFieldReferences[nativetypes.Balances].Refs() > 1 { + if b.sharedFieldReferences[types.Balances].Refs() > 1 { bals = b.balancesVal() - b.sharedFieldReferences[nativetypes.Balances].MinusRef() - b.sharedFieldReferences[nativetypes.Balances] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Balances].MinusRef() + b.sharedFieldReferences[types.Balances] = stateutil.NewRef(1) } bals[idx] = val b.balances = bals - b.markFieldAsDirty(nativetypes.Balances) - b.addDirtyIndices(nativetypes.Balances, []uint64{uint64(idx)}) + b.markFieldAsDirty(types.Balances) + b.addDirtyIndices(types.Balances, []uint64{uint64(idx)}) return nil } @@ -126,11 +126,11 @@ func (b *BeaconState) SetSlashings(val []uint64) error { b.lock.Lock() defer b.lock.Unlock() - b.sharedFieldReferences[nativetypes.Slashings].MinusRef() - b.sharedFieldReferences[nativetypes.Slashings] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Slashings].MinusRef() + b.sharedFieldReferences[types.Slashings] = stateutil.NewRef(1) b.slashings = val - b.markFieldAsDirty(nativetypes.Slashings) + b.markFieldAsDirty(types.Slashings) return nil } @@ -144,17 +144,17 @@ func (b *BeaconState) UpdateSlashingsAtIndex(idx, val uint64) error { defer b.lock.Unlock() s := b.slashings - if b.sharedFieldReferences[nativetypes.Slashings].Refs() > 1 { + if b.sharedFieldReferences[types.Slashings].Refs() > 1 { s = b.slashingsVal() - b.sharedFieldReferences[nativetypes.Slashings].MinusRef() - b.sharedFieldReferences[nativetypes.Slashings] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Slashings].MinusRef() + b.sharedFieldReferences[types.Slashings] = stateutil.NewRef(1) } s[idx] = val b.slashings = s - b.markFieldAsDirty(nativetypes.Slashings) + b.markFieldAsDirty(types.Slashings) return nil } @@ -165,20 +165,20 @@ func (b *BeaconState) AppendValidator(val *ethpb.Validator) error { defer b.lock.Unlock() vals := b.validators - if b.sharedFieldReferences[nativetypes.Validators].Refs() > 1 { + if b.sharedFieldReferences[types.Validators].Refs() > 1 { vals = b.validatorsReferences() - b.sharedFieldReferences[nativetypes.Validators].MinusRef() - b.sharedFieldReferences[nativetypes.Validators] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Validators].MinusRef() + b.sharedFieldReferences[types.Validators] = stateutil.NewRef(1) } // append validator to slice b.validators = append(vals, val) - valIdx := types.ValidatorIndex(len(b.validators) - 1) + valIdx := primitives.ValidatorIndex(len(b.validators) - 1) b.valMapHandler.Set(bytesutil.ToBytes48(val.PublicKey), valIdx) - b.markFieldAsDirty(nativetypes.Validators) - b.addDirtyIndices(nativetypes.Validators, []uint64{uint64(valIdx)}) + b.markFieldAsDirty(types.Validators) + b.addDirtyIndices(types.Validators, []uint64{uint64(valIdx)}) return nil } @@ -189,16 +189,16 @@ func (b *BeaconState) AppendBalance(bal uint64) error { defer b.lock.Unlock() bals := b.balances - if b.sharedFieldReferences[nativetypes.Balances].Refs() > 1 { + if b.sharedFieldReferences[types.Balances].Refs() > 1 { bals = b.balancesVal() - b.sharedFieldReferences[nativetypes.Balances].MinusRef() - b.sharedFieldReferences[nativetypes.Balances] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Balances].MinusRef() + b.sharedFieldReferences[types.Balances] = stateutil.NewRef(1) } b.balances = append(bals, bal) balIdx := len(b.balances) - 1 - b.markFieldAsDirty(nativetypes.Balances) - b.addDirtyIndices(nativetypes.Balances, []uint64{uint64(balIdx)}) + b.markFieldAsDirty(types.Balances) + b.addDirtyIndices(types.Balances, []uint64{uint64(balIdx)}) return nil } @@ -212,14 +212,14 @@ func (b *BeaconState) AppendInactivityScore(s uint64) error { } scores := b.inactivityScores - if b.sharedFieldReferences[nativetypes.InactivityScores].Refs() > 1 { + if b.sharedFieldReferences[types.InactivityScores].Refs() > 1 { scores = b.inactivityScoresVal() - b.sharedFieldReferences[nativetypes.InactivityScores].MinusRef() - b.sharedFieldReferences[nativetypes.InactivityScores] = stateutil.NewRef(1) + b.sharedFieldReferences[types.InactivityScores].MinusRef() + b.sharedFieldReferences[types.InactivityScores] = stateutil.NewRef(1) } b.inactivityScores = append(scores, s) - b.markFieldAsDirty(nativetypes.InactivityScores) + b.markFieldAsDirty(types.InactivityScores) return nil } @@ -233,10 +233,10 @@ func (b *BeaconState) SetInactivityScores(val []uint64) error { return errNotSupported("SetInactivityScores", b.version) } - b.sharedFieldReferences[nativetypes.InactivityScores].MinusRef() - b.sharedFieldReferences[nativetypes.InactivityScores] = stateutil.NewRef(1) + b.sharedFieldReferences[types.InactivityScores].MinusRef() + b.sharedFieldReferences[types.InactivityScores] = stateutil.NewRef(1) b.inactivityScores = val - b.markFieldAsDirty(nativetypes.InactivityScores) + b.markFieldAsDirty(types.InactivityScores) return nil } diff --git a/beacon-chain/state/state-native/setters_withdrawal.go b/beacon-chain/state/state-native/setters_withdrawal.go index 34cdf73497..5ccb035b1e 100644 --- a/beacon-chain/state/state-native/setters_withdrawal.go +++ b/beacon-chain/state/state-native/setters_withdrawal.go @@ -1,8 +1,8 @@ package state_native import ( - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/runtime/version" ) @@ -16,13 +16,13 @@ func (b *BeaconState) SetNextWithdrawalIndex(i uint64) error { defer b.lock.Unlock() b.nextWithdrawalIndex = i - b.markFieldAsDirty(nativetypes.NextWithdrawalIndex) + b.markFieldAsDirty(types.NextWithdrawalIndex) return nil } // SetNextWithdrawalValidatorIndex sets the index of the validator which is // next in line for a partial withdrawal. -func (b *BeaconState) SetNextWithdrawalValidatorIndex(i types.ValidatorIndex) error { +func (b *BeaconState) SetNextWithdrawalValidatorIndex(i primitives.ValidatorIndex) error { if b.version < version.Capella { return errNotSupported("SetNextWithdrawalValidatorIndex", b.version) } @@ -31,6 +31,6 @@ func (b *BeaconState) SetNextWithdrawalValidatorIndex(i types.ValidatorIndex) er defer b.lock.Unlock() b.nextWithdrawalValidatorIndex = i - b.markFieldAsDirty(nativetypes.NextWithdrawalValidatorIndex) + b.markFieldAsDirty(types.NextWithdrawalValidatorIndex) return nil } diff --git a/beacon-chain/state/state-native/setters_withdrawal_test.go b/beacon-chain/state/state-native/setters_withdrawal_test.go index e40c628e57..bc22bd3400 100644 --- a/beacon-chain/state/state-native/setters_withdrawal_test.go +++ b/beacon-chain/state/state-native/setters_withdrawal_test.go @@ -3,8 +3,8 @@ package state_native import ( "testing" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/runtime/version" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -13,20 +13,20 @@ func TestSetNextWithdrawalIndex(t *testing.T) { s := BeaconState{ version: version.Capella, nextWithdrawalIndex: 3, - dirtyFields: make(map[nativetypes.FieldIndex]bool), + dirtyFields: make(map[types.FieldIndex]bool), } require.NoError(t, s.SetNextWithdrawalIndex(5)) require.Equal(t, uint64(5), s.nextWithdrawalIndex) - require.Equal(t, true, s.dirtyFields[nativetypes.NextWithdrawalIndex]) + require.Equal(t, true, s.dirtyFields[types.NextWithdrawalIndex]) } func TestSetLastWithdrawalValidatorIndex(t *testing.T) { s := BeaconState{ version: version.Capella, nextWithdrawalValidatorIndex: 3, - dirtyFields: make(map[nativetypes.FieldIndex]bool), + dirtyFields: make(map[types.FieldIndex]bool), } require.NoError(t, s.SetNextWithdrawalValidatorIndex(5)) - require.Equal(t, types.ValidatorIndex(5), s.nextWithdrawalValidatorIndex) - require.Equal(t, true, s.dirtyFields[nativetypes.NextWithdrawalValidatorIndex]) + require.Equal(t, primitives.ValidatorIndex(5), s.nextWithdrawalValidatorIndex) + require.Equal(t, true, s.dirtyFields[types.NextWithdrawalValidatorIndex]) } diff --git a/beacon-chain/state/state-native/state_fuzz_test.go b/beacon-chain/state/state-native/state_fuzz_test.go index cf36943df9..98e21ae200 100644 --- a/beacon-chain/state/state-native/state_fuzz_test.go +++ b/beacon-chain/state/state-native/state_fuzz_test.go @@ -6,7 +6,7 @@ import ( coreState "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/transition" native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/rand" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -44,7 +44,7 @@ func FuzzPhase0StateHashTreeRoot(f *testing.F) { slotsToTransition %= 100 stateObj, err := native.InitializeFromProtoUnsafePhase0(pbState) assert.NoError(t, err) - for stateObj.Slot() < types.Slot(slotsToTransition) { + for stateObj.Slot() < primitives.Slot(slotsToTransition) { stateObj, err = coreState.ProcessSlots(context.Background(), stateObj, stateObj.Slot()+1) assert.NoError(t, err) stateObj.Copy() @@ -115,7 +115,7 @@ func FuzzAltairStateHashTreeRoot(f *testing.F) { slotsToTransition %= 100 stateObj, err := native.InitializeFromProtoUnsafeAltair(pbState) assert.NoError(t, err) - for stateObj.Slot() < types.Slot(slotsToTransition) { + for stateObj.Slot() < primitives.Slot(slotsToTransition) { stateObj, err = coreState.ProcessSlots(context.Background(), stateObj, stateObj.Slot()+1) assert.NoError(t, err) stateObj.Copy() @@ -185,7 +185,7 @@ func FuzzBellatrixStateHashTreeRoot(f *testing.F) { slotsToTransition %= 100 stateObj, err := native.InitializeFromProtoUnsafeBellatrix(pbState) assert.NoError(t, err) - for stateObj.Slot() < types.Slot(slotsToTransition) { + for stateObj.Slot() < primitives.Slot(slotsToTransition) { stateObj, err = coreState.ProcessSlots(context.Background(), stateObj, stateObj.Slot()+1) assert.NoError(t, err) stateObj.Copy() @@ -255,7 +255,7 @@ func FuzzCapellaStateHashTreeRoot(f *testing.F) { slotsToTransition %= 100 stateObj, err := native.InitializeFromProtoUnsafeCapella(pbState) assert.NoError(t, err) - for stateObj.Slot() < types.Slot(slotsToTransition) { + for stateObj.Slot() < primitives.Slot(slotsToTransition) { stateObj, err = coreState.ProcessSlots(context.Background(), stateObj, stateObj.Slot()+1) assert.NoError(t, err) stateObj.Copy() diff --git a/beacon-chain/state/state-native/state_test.go b/beacon-chain/state/state-native/state_test.go index 52194169f8..8dfb7aeb45 100644 --- a/beacon-chain/state/state-native/state_test.go +++ b/beacon-chain/state/state-native/state_test.go @@ -7,11 +7,11 @@ import ( "testing" "github.com/prysmaticlabs/go-bitfield" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -341,7 +341,7 @@ func TestBeaconState_AppendBalanceWithTrie(t *testing.T) { for i := 0; i < 100; i++ { if i%2 == 0 { - assert.NoError(t, st.UpdateBalancesAtIndex(types.ValidatorIndex(i), 1000)) + assert.NoError(t, st.UpdateBalancesAtIndex(primitives.ValidatorIndex(i), 1000)) } if i%3 == 0 { assert.NoError(t, st.AppendBalance(1000)) @@ -349,7 +349,7 @@ func TestBeaconState_AppendBalanceWithTrie(t *testing.T) { } _, err = st.HashTreeRoot(context.Background()) assert.NoError(t, err) - newRt := bytesutil.ToBytes32(st.merkleLayers[0][nativetypes.Balances]) + newRt := bytesutil.ToBytes32(st.merkleLayers[0][types.Balances]) wantedRt, err := stateutil.Uint64ListRootWithRegistryLimit(st.Balances()) assert.NoError(t, err) assert.Equal(t, wantedRt, newRt, "state roots are unequal") diff --git a/beacon-chain/state/state-native/state_trie.go b/beacon-chain/state/state-native/state_trie.go index 6796fd0a16..c65b80cf1d 100644 --- a/beacon-chain/state/state-native/state_trie.go +++ b/beacon-chain/state/state-native/state_trie.go @@ -9,9 +9,8 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/fieldtrie" customtypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/custom-types" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" - "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/types" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/container/slice" @@ -24,65 +23,65 @@ import ( "google.golang.org/protobuf/proto" ) -var phase0Fields = []nativetypes.FieldIndex{ - nativetypes.GenesisTime, - nativetypes.GenesisValidatorsRoot, - nativetypes.Slot, - nativetypes.Fork, - nativetypes.LatestBlockHeader, - nativetypes.BlockRoots, - nativetypes.StateRoots, - nativetypes.HistoricalRoots, - nativetypes.Eth1Data, - nativetypes.Eth1DataVotes, - nativetypes.Eth1DepositIndex, - nativetypes.Validators, - nativetypes.Balances, - nativetypes.RandaoMixes, - nativetypes.Slashings, - nativetypes.PreviousEpochAttestations, - nativetypes.CurrentEpochAttestations, - nativetypes.JustificationBits, - nativetypes.PreviousJustifiedCheckpoint, - nativetypes.CurrentJustifiedCheckpoint, - nativetypes.FinalizedCheckpoint, +var phase0Fields = []types.FieldIndex{ + types.GenesisTime, + types.GenesisValidatorsRoot, + types.Slot, + types.Fork, + types.LatestBlockHeader, + types.BlockRoots, + types.StateRoots, + types.HistoricalRoots, + types.Eth1Data, + types.Eth1DataVotes, + types.Eth1DepositIndex, + types.Validators, + types.Balances, + types.RandaoMixes, + types.Slashings, + types.PreviousEpochAttestations, + types.CurrentEpochAttestations, + types.JustificationBits, + types.PreviousJustifiedCheckpoint, + types.CurrentJustifiedCheckpoint, + types.FinalizedCheckpoint, } -var altairFields = []nativetypes.FieldIndex{ - nativetypes.GenesisTime, - nativetypes.GenesisValidatorsRoot, - nativetypes.Slot, - nativetypes.Fork, - nativetypes.LatestBlockHeader, - nativetypes.BlockRoots, - nativetypes.StateRoots, - nativetypes.HistoricalRoots, - nativetypes.Eth1Data, - nativetypes.Eth1DataVotes, - nativetypes.Eth1DepositIndex, - nativetypes.Validators, - nativetypes.Balances, - nativetypes.RandaoMixes, - nativetypes.Slashings, - nativetypes.PreviousEpochParticipationBits, - nativetypes.CurrentEpochParticipationBits, - nativetypes.JustificationBits, - nativetypes.PreviousJustifiedCheckpoint, - nativetypes.CurrentJustifiedCheckpoint, - nativetypes.FinalizedCheckpoint, - nativetypes.InactivityScores, - nativetypes.CurrentSyncCommittee, - nativetypes.NextSyncCommittee, +var altairFields = []types.FieldIndex{ + types.GenesisTime, + types.GenesisValidatorsRoot, + types.Slot, + types.Fork, + types.LatestBlockHeader, + types.BlockRoots, + types.StateRoots, + types.HistoricalRoots, + types.Eth1Data, + types.Eth1DataVotes, + types.Eth1DepositIndex, + types.Validators, + types.Balances, + types.RandaoMixes, + types.Slashings, + types.PreviousEpochParticipationBits, + types.CurrentEpochParticipationBits, + types.JustificationBits, + types.PreviousJustifiedCheckpoint, + types.CurrentJustifiedCheckpoint, + types.FinalizedCheckpoint, + types.InactivityScores, + types.CurrentSyncCommittee, + types.NextSyncCommittee, } -var bellatrixFields = append(altairFields, nativetypes.LatestExecutionPayloadHeader) +var bellatrixFields = append(altairFields, types.LatestExecutionPayloadHeader) var capellaFields = append( altairFields, - nativetypes.LatestExecutionPayloadHeaderCapella, - nativetypes.NextWithdrawalIndex, - nativetypes.NextWithdrawalValidatorIndex, - nativetypes.HistoricalSummaries, + types.LatestExecutionPayloadHeaderCapella, + types.NextWithdrawalIndex, + types.NextWithdrawalValidatorIndex, + types.HistoricalSummaries, ) const ( @@ -161,11 +160,11 @@ func InitializeFromProtoUnsafePhase0(st *ethpb.BeaconState) (state.BeaconState, currentJustifiedCheckpoint: st.CurrentJustifiedCheckpoint, finalizedCheckpoint: st.FinalizedCheckpoint, - dirtyFields: make(map[nativetypes.FieldIndex]bool, fieldCount), - dirtyIndices: make(map[nativetypes.FieldIndex][]uint64, fieldCount), - stateFieldLeaves: make(map[nativetypes.FieldIndex]*fieldtrie.FieldTrie, fieldCount), - sharedFieldReferences: make(map[nativetypes.FieldIndex]*stateutil.Reference, phase0SharedFieldRefCount), - rebuildTrie: make(map[nativetypes.FieldIndex]bool, fieldCount), + dirtyFields: make(map[types.FieldIndex]bool, fieldCount), + dirtyIndices: make(map[types.FieldIndex][]uint64, fieldCount), + stateFieldLeaves: make(map[types.FieldIndex]*fieldtrie.FieldTrie, fieldCount), + sharedFieldReferences: make(map[types.FieldIndex]*stateutil.Reference, phase0SharedFieldRefCount), + rebuildTrie: make(map[types.FieldIndex]bool, fieldCount), valMapHandler: stateutil.NewValMapHandler(st.Validators), } @@ -181,16 +180,16 @@ func InitializeFromProtoUnsafePhase0(st *ethpb.BeaconState) (state.BeaconState, } // Initialize field reference tracking for shared data. - b.sharedFieldReferences[nativetypes.BlockRoots] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.StateRoots] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.HistoricalRoots] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Eth1DataVotes] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Validators] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Balances] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.RandaoMixes] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Slashings] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.PreviousEpochAttestations] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.CurrentEpochAttestations] = stateutil.NewRef(1) + b.sharedFieldReferences[types.BlockRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.StateRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.HistoricalRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Eth1DataVotes] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Validators] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Balances] = stateutil.NewRef(1) + b.sharedFieldReferences[types.RandaoMixes] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Slashings] = stateutil.NewRef(1) + b.sharedFieldReferences[types.PreviousEpochAttestations] = stateutil.NewRef(1) + b.sharedFieldReferences[types.CurrentEpochAttestations] = stateutil.NewRef(1) state.StateCount.Inc() // Finalizer runs when dst is being destroyed in garbage collection. @@ -250,11 +249,11 @@ func InitializeFromProtoUnsafeAltair(st *ethpb.BeaconStateAltair) (state.BeaconS currentSyncCommittee: st.CurrentSyncCommittee, nextSyncCommittee: st.NextSyncCommittee, - dirtyFields: make(map[nativetypes.FieldIndex]bool, fieldCount), - dirtyIndices: make(map[nativetypes.FieldIndex][]uint64, fieldCount), - stateFieldLeaves: make(map[nativetypes.FieldIndex]*fieldtrie.FieldTrie, fieldCount), - sharedFieldReferences: make(map[nativetypes.FieldIndex]*stateutil.Reference, altairSharedFieldRefCount), - rebuildTrie: make(map[nativetypes.FieldIndex]bool, fieldCount), + dirtyFields: make(map[types.FieldIndex]bool, fieldCount), + dirtyIndices: make(map[types.FieldIndex][]uint64, fieldCount), + stateFieldLeaves: make(map[types.FieldIndex]*fieldtrie.FieldTrie, fieldCount), + sharedFieldReferences: make(map[types.FieldIndex]*stateutil.Reference, altairSharedFieldRefCount), + rebuildTrie: make(map[types.FieldIndex]bool, fieldCount), valMapHandler: stateutil.NewValMapHandler(st.Validators), } @@ -270,17 +269,17 @@ func InitializeFromProtoUnsafeAltair(st *ethpb.BeaconStateAltair) (state.BeaconS } // Initialize field reference tracking for shared data. - b.sharedFieldReferences[nativetypes.BlockRoots] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.StateRoots] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.HistoricalRoots] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Eth1DataVotes] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Validators] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Balances] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.RandaoMixes] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Slashings] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits] = stateutil.NewRef(1) // New in Altair. - b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits] = stateutil.NewRef(1) // New in Altair. - b.sharedFieldReferences[nativetypes.InactivityScores] = stateutil.NewRef(1) // New in Altair. + b.sharedFieldReferences[types.BlockRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.StateRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.HistoricalRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Eth1DataVotes] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Validators] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Balances] = stateutil.NewRef(1) + b.sharedFieldReferences[types.RandaoMixes] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Slashings] = stateutil.NewRef(1) + b.sharedFieldReferences[types.PreviousEpochParticipationBits] = stateutil.NewRef(1) // New in Altair. + b.sharedFieldReferences[types.CurrentEpochParticipationBits] = stateutil.NewRef(1) // New in Altair. + b.sharedFieldReferences[types.InactivityScores] = stateutil.NewRef(1) // New in Altair. state.StateCount.Inc() // Finalizer runs when dst is being destroyed in garbage collection. @@ -341,11 +340,11 @@ func InitializeFromProtoUnsafeBellatrix(st *ethpb.BeaconStateBellatrix) (state.B nextSyncCommittee: st.NextSyncCommittee, latestExecutionPayloadHeader: st.LatestExecutionPayloadHeader, - dirtyFields: make(map[nativetypes.FieldIndex]bool, fieldCount), - dirtyIndices: make(map[nativetypes.FieldIndex][]uint64, fieldCount), - stateFieldLeaves: make(map[nativetypes.FieldIndex]*fieldtrie.FieldTrie, fieldCount), - sharedFieldReferences: make(map[nativetypes.FieldIndex]*stateutil.Reference, bellatrixSharedFieldRefCount), - rebuildTrie: make(map[nativetypes.FieldIndex]bool, fieldCount), + dirtyFields: make(map[types.FieldIndex]bool, fieldCount), + dirtyIndices: make(map[types.FieldIndex][]uint64, fieldCount), + stateFieldLeaves: make(map[types.FieldIndex]*fieldtrie.FieldTrie, fieldCount), + sharedFieldReferences: make(map[types.FieldIndex]*stateutil.Reference, bellatrixSharedFieldRefCount), + rebuildTrie: make(map[types.FieldIndex]bool, fieldCount), valMapHandler: stateutil.NewValMapHandler(st.Validators), } @@ -361,18 +360,18 @@ func InitializeFromProtoUnsafeBellatrix(st *ethpb.BeaconStateBellatrix) (state.B } // Initialize field reference tracking for shared data. - b.sharedFieldReferences[nativetypes.BlockRoots] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.StateRoots] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.HistoricalRoots] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Eth1DataVotes] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Validators] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Balances] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.RandaoMixes] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Slashings] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.InactivityScores] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.LatestExecutionPayloadHeader] = stateutil.NewRef(1) // New in Bellatrix. + b.sharedFieldReferences[types.BlockRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.StateRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.HistoricalRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Eth1DataVotes] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Validators] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Balances] = stateutil.NewRef(1) + b.sharedFieldReferences[types.RandaoMixes] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Slashings] = stateutil.NewRef(1) + b.sharedFieldReferences[types.PreviousEpochParticipationBits] = stateutil.NewRef(1) + b.sharedFieldReferences[types.CurrentEpochParticipationBits] = stateutil.NewRef(1) + b.sharedFieldReferences[types.InactivityScores] = stateutil.NewRef(1) + b.sharedFieldReferences[types.LatestExecutionPayloadHeader] = stateutil.NewRef(1) // New in Bellatrix. state.StateCount.Inc() // Finalizer runs when dst is being destroyed in garbage collection. @@ -436,11 +435,11 @@ func InitializeFromProtoUnsafeCapella(st *ethpb.BeaconStateCapella) (state.Beaco nextWithdrawalValidatorIndex: st.NextWithdrawalValidatorIndex, historicalSummaries: st.HistoricalSummaries, - dirtyFields: make(map[nativetypes.FieldIndex]bool, fieldCount), - dirtyIndices: make(map[nativetypes.FieldIndex][]uint64, fieldCount), - stateFieldLeaves: make(map[nativetypes.FieldIndex]*fieldtrie.FieldTrie, fieldCount), - sharedFieldReferences: make(map[nativetypes.FieldIndex]*stateutil.Reference, capellaSharedFieldRefCount), - rebuildTrie: make(map[nativetypes.FieldIndex]bool, fieldCount), + dirtyFields: make(map[types.FieldIndex]bool, fieldCount), + dirtyIndices: make(map[types.FieldIndex][]uint64, fieldCount), + stateFieldLeaves: make(map[types.FieldIndex]*fieldtrie.FieldTrie, fieldCount), + sharedFieldReferences: make(map[types.FieldIndex]*stateutil.Reference, capellaSharedFieldRefCount), + rebuildTrie: make(map[types.FieldIndex]bool, fieldCount), valMapHandler: stateutil.NewValMapHandler(st.Validators), } @@ -456,19 +455,19 @@ func InitializeFromProtoUnsafeCapella(st *ethpb.BeaconStateCapella) (state.Beaco } // Initialize field reference tracking for shared data. - b.sharedFieldReferences[nativetypes.BlockRoots] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.StateRoots] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.HistoricalRoots] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Eth1DataVotes] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Validators] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Balances] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.RandaoMixes] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.Slashings] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.InactivityScores] = stateutil.NewRef(1) - b.sharedFieldReferences[nativetypes.LatestExecutionPayloadHeaderCapella] = stateutil.NewRef(1) // New in Capella. - b.sharedFieldReferences[nativetypes.HistoricalSummaries] = stateutil.NewRef(1) // New in Capella. + b.sharedFieldReferences[types.BlockRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.StateRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.HistoricalRoots] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Eth1DataVotes] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Validators] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Balances] = stateutil.NewRef(1) + b.sharedFieldReferences[types.RandaoMixes] = stateutil.NewRef(1) + b.sharedFieldReferences[types.Slashings] = stateutil.NewRef(1) + b.sharedFieldReferences[types.PreviousEpochParticipationBits] = stateutil.NewRef(1) + b.sharedFieldReferences[types.CurrentEpochParticipationBits] = stateutil.NewRef(1) + b.sharedFieldReferences[types.InactivityScores] = stateutil.NewRef(1) + b.sharedFieldReferences[types.LatestExecutionPayloadHeaderCapella] = stateutil.NewRef(1) // New in Capella. + b.sharedFieldReferences[types.HistoricalSummaries] = stateutil.NewRef(1) // New in Capella. state.StateCount.Inc() // Finalizer runs when dst is being destroyed in garbage collection. @@ -496,7 +495,7 @@ func (b *BeaconState) Copy() state.BeaconState { dst := &BeaconState{ version: b.version, - // Primitive nativetypes, safe to copy. + // Primitive types, safe to copy. genesisTime: b.genesisTime, slot: b.slot, eth1DepositIndex: b.eth1DepositIndex, @@ -535,10 +534,10 @@ func (b *BeaconState) Copy() state.BeaconState { latestExecutionPayloadHeader: b.latestExecutionPayloadHeaderVal(), latestExecutionPayloadHeaderCapella: b.latestExecutionPayloadHeaderCapellaVal(), - dirtyFields: make(map[nativetypes.FieldIndex]bool, fieldCount), - dirtyIndices: make(map[nativetypes.FieldIndex][]uint64, fieldCount), - rebuildTrie: make(map[nativetypes.FieldIndex]bool, fieldCount), - stateFieldLeaves: make(map[nativetypes.FieldIndex]*fieldtrie.FieldTrie, fieldCount), + dirtyFields: make(map[types.FieldIndex]bool, fieldCount), + dirtyIndices: make(map[types.FieldIndex][]uint64, fieldCount), + rebuildTrie: make(map[types.FieldIndex]bool, fieldCount), + stateFieldLeaves: make(map[types.FieldIndex]*fieldtrie.FieldTrie, fieldCount), // Share the reference to validator index map. valMapHandler: b.valMapHandler, @@ -546,13 +545,13 @@ func (b *BeaconState) Copy() state.BeaconState { switch b.version { case version.Phase0: - dst.sharedFieldReferences = make(map[nativetypes.FieldIndex]*stateutil.Reference, phase0SharedFieldRefCount) + dst.sharedFieldReferences = make(map[types.FieldIndex]*stateutil.Reference, phase0SharedFieldRefCount) case version.Altair: - dst.sharedFieldReferences = make(map[nativetypes.FieldIndex]*stateutil.Reference, altairSharedFieldRefCount) + dst.sharedFieldReferences = make(map[types.FieldIndex]*stateutil.Reference, altairSharedFieldRefCount) case version.Bellatrix: - dst.sharedFieldReferences = make(map[nativetypes.FieldIndex]*stateutil.Reference, bellatrixSharedFieldRefCount) + dst.sharedFieldReferences = make(map[types.FieldIndex]*stateutil.Reference, bellatrixSharedFieldRefCount) case version.Capella: - dst.sharedFieldReferences = make(map[nativetypes.FieldIndex]*stateutil.Reference, capellaSharedFieldRefCount) + dst.sharedFieldReferences = make(map[types.FieldIndex]*stateutil.Reference, capellaSharedFieldRefCount) } for field, ref := range b.sharedFieldReferences { @@ -635,13 +634,13 @@ func (b *BeaconState) initializeMerkleLayers(ctx context.Context) error { b.merkleLayers = layers switch b.version { case version.Phase0: - b.dirtyFields = make(map[nativetypes.FieldIndex]bool, params.BeaconConfig().BeaconStateFieldCount) + b.dirtyFields = make(map[types.FieldIndex]bool, params.BeaconConfig().BeaconStateFieldCount) case version.Altair: - b.dirtyFields = make(map[nativetypes.FieldIndex]bool, params.BeaconConfig().BeaconStateAltairFieldCount) + b.dirtyFields = make(map[types.FieldIndex]bool, params.BeaconConfig().BeaconStateAltairFieldCount) case version.Bellatrix: - b.dirtyFields = make(map[nativetypes.FieldIndex]bool, params.BeaconConfig().BeaconStateBellatrixFieldCount) + b.dirtyFields = make(map[types.FieldIndex]bool, params.BeaconConfig().BeaconStateBellatrixFieldCount) case version.Capella: - b.dirtyFields = make(map[nativetypes.FieldIndex]bool, params.BeaconConfig().BeaconStateCapellaFieldCount) + b.dirtyFields = make(map[types.FieldIndex]bool, params.BeaconConfig().BeaconStateCapellaFieldCount) } return nil @@ -690,26 +689,26 @@ func (b *BeaconState) IsNil() bool { return b == nil } -func (b *BeaconState) rootSelector(ctx context.Context, field nativetypes.FieldIndex) ([32]byte, error) { +func (b *BeaconState) rootSelector(ctx context.Context, field types.FieldIndex) ([32]byte, error) { ctx, span := trace.StartSpan(ctx, "beaconState.rootSelector") defer span.End() span.AddAttributes(trace.StringAttribute("field", field.String(b.version))) hasher := hash.CustomSHA256Hasher() switch field { - case nativetypes.GenesisTime: + case types.GenesisTime: return ssz.Uint64Root(b.genesisTime), nil - case nativetypes.GenesisValidatorsRoot: + case types.GenesisValidatorsRoot: return b.genesisValidatorsRoot, nil - case nativetypes.Slot: + case types.Slot: return ssz.Uint64Root(uint64(b.slot)), nil - case nativetypes.Eth1DepositIndex: + case types.Eth1DepositIndex: return ssz.Uint64Root(b.eth1DepositIndex), nil - case nativetypes.Fork: + case types.Fork: return ssz.ForkRoot(b.fork) - case nativetypes.LatestBlockHeader: + case types.LatestBlockHeader: return stateutil.BlockHeaderRoot(b.latestBlockHeader) - case nativetypes.BlockRoots: + case types.BlockRoots: if b.rebuildTrie[field] { err := b.resetFieldTrie(field, b.blockRoots, fieldparams.BlockRootsLength) if err != nil { @@ -719,7 +718,7 @@ func (b *BeaconState) rootSelector(ctx context.Context, field nativetypes.FieldI return b.stateFieldLeaves[field].TrieRoot() } return b.recomputeFieldTrie(field, b.blockRoots) - case nativetypes.StateRoots: + case types.StateRoots: if b.rebuildTrie[field] { err := b.resetFieldTrie(field, b.stateRoots, fieldparams.StateRootsLength) if err != nil { @@ -729,15 +728,15 @@ func (b *BeaconState) rootSelector(ctx context.Context, field nativetypes.FieldI return b.stateFieldLeaves[field].TrieRoot() } return b.recomputeFieldTrie(field, b.stateRoots) - case nativetypes.HistoricalRoots: + case types.HistoricalRoots: hRoots := make([][]byte, len(b.historicalRoots)) for i := range hRoots { hRoots[i] = b.historicalRoots[i][:] } return ssz.ByteArrayRootWithLimit(hRoots, fieldparams.HistoricalRootsLength) - case nativetypes.Eth1Data: + case types.Eth1Data: return stateutil.Eth1Root(hasher, b.eth1Data) - case nativetypes.Eth1DataVotes: + case types.Eth1DataVotes: if b.rebuildTrie[field] { err := b.resetFieldTrie( field, @@ -751,7 +750,7 @@ func (b *BeaconState) rootSelector(ctx context.Context, field nativetypes.FieldI return b.stateFieldLeaves[field].TrieRoot() } return b.recomputeFieldTrie(field, b.eth1DataVotes) - case nativetypes.Validators: + case types.Validators: if b.rebuildTrie[field] { err := b.resetFieldTrie(field, b.validators, fieldparams.ValidatorRegistryLimit) if err != nil { @@ -761,7 +760,7 @@ func (b *BeaconState) rootSelector(ctx context.Context, field nativetypes.FieldI return b.stateFieldLeaves[field].TrieRoot() } return b.recomputeFieldTrie(11, b.validators) - case nativetypes.Balances: + case types.Balances: if b.rebuildTrie[field] { err := b.resetFieldTrie(field, b.balances, stateutil.ValidatorLimitForBalancesChunks()) if err != nil { @@ -771,7 +770,7 @@ func (b *BeaconState) rootSelector(ctx context.Context, field nativetypes.FieldI return b.stateFieldLeaves[field].TrieRoot() } return b.recomputeFieldTrie(12, b.balances) - case nativetypes.RandaoMixes: + case types.RandaoMixes: if b.rebuildTrie[field] { err := b.resetFieldTrie(field, b.randaoMixes, fieldparams.RandaoMixesLength) if err != nil { @@ -781,9 +780,9 @@ func (b *BeaconState) rootSelector(ctx context.Context, field nativetypes.FieldI return b.stateFieldLeaves[field].TrieRoot() } return b.recomputeFieldTrie(13, b.randaoMixes) - case nativetypes.Slashings: + case types.Slashings: return ssz.SlashingsRoot(b.slashings) - case nativetypes.PreviousEpochAttestations: + case types.PreviousEpochAttestations: if b.rebuildTrie[field] { err := b.resetFieldTrie( field, @@ -797,7 +796,7 @@ func (b *BeaconState) rootSelector(ctx context.Context, field nativetypes.FieldI return b.stateFieldLeaves[field].TrieRoot() } return b.recomputeFieldTrie(field, b.previousEpochAttestations) - case nativetypes.CurrentEpochAttestations: + case types.CurrentEpochAttestations: if b.rebuildTrie[field] { err := b.resetFieldTrie( field, @@ -811,39 +810,39 @@ func (b *BeaconState) rootSelector(ctx context.Context, field nativetypes.FieldI return b.stateFieldLeaves[field].TrieRoot() } return b.recomputeFieldTrie(field, b.currentEpochAttestations) - case nativetypes.PreviousEpochParticipationBits: + case types.PreviousEpochParticipationBits: return stateutil.ParticipationBitsRoot(b.previousEpochParticipation) - case nativetypes.CurrentEpochParticipationBits: + case types.CurrentEpochParticipationBits: return stateutil.ParticipationBitsRoot(b.currentEpochParticipation) - case nativetypes.JustificationBits: + case types.JustificationBits: return bytesutil.ToBytes32(b.justificationBits), nil - case nativetypes.PreviousJustifiedCheckpoint: + case types.PreviousJustifiedCheckpoint: return ssz.CheckpointRoot(hasher, b.previousJustifiedCheckpoint) - case nativetypes.CurrentJustifiedCheckpoint: + case types.CurrentJustifiedCheckpoint: return ssz.CheckpointRoot(hasher, b.currentJustifiedCheckpoint) - case nativetypes.FinalizedCheckpoint: + case types.FinalizedCheckpoint: return ssz.CheckpointRoot(hasher, b.finalizedCheckpoint) - case nativetypes.InactivityScores: + case types.InactivityScores: return stateutil.Uint64ListRootWithRegistryLimit(b.inactivityScores) - case nativetypes.CurrentSyncCommittee: + case types.CurrentSyncCommittee: return stateutil.SyncCommitteeRoot(b.currentSyncCommittee) - case nativetypes.NextSyncCommittee: + case types.NextSyncCommittee: return stateutil.SyncCommitteeRoot(b.nextSyncCommittee) - case nativetypes.LatestExecutionPayloadHeader: + case types.LatestExecutionPayloadHeader: return b.latestExecutionPayloadHeader.HashTreeRoot() - case nativetypes.LatestExecutionPayloadHeaderCapella: + case types.LatestExecutionPayloadHeaderCapella: return b.latestExecutionPayloadHeaderCapella.HashTreeRoot() - case nativetypes.NextWithdrawalIndex: + case types.NextWithdrawalIndex: return ssz.Uint64Root(b.nextWithdrawalIndex), nil - case nativetypes.NextWithdrawalValidatorIndex: + case types.NextWithdrawalValidatorIndex: return ssz.Uint64Root(uint64(b.nextWithdrawalValidatorIndex)), nil - case nativetypes.HistoricalSummaries: + case types.HistoricalSummaries: return stateutil.HistoricalSummariesRoot(b.historicalSummaries) } return [32]byte{}, errors.New("invalid field index provided") } -func (b *BeaconState) recomputeFieldTrie(index nativetypes.FieldIndex, elements interface{}) ([32]byte, error) { +func (b *BeaconState) recomputeFieldTrie(index types.FieldIndex, elements interface{}) ([32]byte, error) { fTrie := b.stateFieldLeaves[index] fTrieMutex := fTrie.RWMutex // We can't lock the trie directly because the trie's variable gets reassigned, @@ -884,7 +883,7 @@ func (b *BeaconState) recomputeFieldTrie(index nativetypes.FieldIndex, elements return root, nil } -func (b *BeaconState) resetFieldTrie(index nativetypes.FieldIndex, elements interface{}, length uint64) error { +func (b *BeaconState) resetFieldTrie(index types.FieldIndex, elements interface{}, length uint64) error { fTrie, err := fieldtrie.NewFieldTrie(index, fieldMap[index], elements, length) if err != nil { return err diff --git a/beacon-chain/state/state-native/types.go b/beacon-chain/state/state-native/types.go index 5571aa94c5..d49be0b888 100644 --- a/beacon-chain/state/state-native/types.go +++ b/beacon-chain/state/state-native/types.go @@ -4,8 +4,7 @@ import ( "fmt" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" - nativetypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" - "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/types" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native/types" "github.com/prysmaticlabs/prysm/v3/runtime/version" ) @@ -13,23 +12,23 @@ import ( var _ state.BeaconState = (*BeaconState)(nil) func init() { - fieldMap = make(map[nativetypes.FieldIndex]types.DataType) + fieldMap = make(map[types.FieldIndex]types.DataType) // Initialize the fixed sized arrays. - fieldMap[nativetypes.BlockRoots] = types.BasicArray - fieldMap[nativetypes.StateRoots] = types.BasicArray - fieldMap[nativetypes.RandaoMixes] = types.BasicArray + fieldMap[types.BlockRoots] = types.BasicArray + fieldMap[types.StateRoots] = types.BasicArray + fieldMap[types.RandaoMixes] = types.BasicArray // Initialize the composite arrays. - fieldMap[nativetypes.Eth1DataVotes] = types.CompositeArray - fieldMap[nativetypes.Validators] = types.CompositeArray - fieldMap[nativetypes.PreviousEpochAttestations] = types.CompositeArray - fieldMap[nativetypes.CurrentEpochAttestations] = types.CompositeArray - fieldMap[nativetypes.Balances] = types.CompressedArray + fieldMap[types.Eth1DataVotes] = types.CompositeArray + fieldMap[types.Validators] = types.CompositeArray + fieldMap[types.PreviousEpochAttestations] = types.CompositeArray + fieldMap[types.CurrentEpochAttestations] = types.CompositeArray + fieldMap[types.Balances] = types.CompressedArray } // fieldMap keeps track of each field // to its corresponding data type. -var fieldMap map[nativetypes.FieldIndex]types.DataType +var fieldMap map[types.FieldIndex]types.DataType func errNotSupported(funcName string, ver int) error { return fmt.Errorf("%s is not supported for %s", funcName, version.String(ver)) diff --git a/beacon-chain/state/state-native/types/types.go b/beacon-chain/state/state-native/types/types.go index 35e22e29ed..d3769b2c5e 100644 --- a/beacon-chain/state/state-native/types/types.go +++ b/beacon-chain/state/state-native/types/types.go @@ -4,6 +4,22 @@ import ( "github.com/pkg/errors" ) +// DataType signifies the data type of the field. +type DataType int + +// List of current data types the state supports. +const ( + // BasicArray represents a simple array type for a field. + BasicArray DataType = iota + // CompositeArray represents a variable length array with + // a non primitive type. + CompositeArray + // CompressedArray represents a variable length array which + // can pack multiple elements into a leaf of the underlying + // trie. + CompressedArray +) + // FieldIndex represents the relevant field position in the // state struct for a field. type FieldIndex int @@ -154,10 +170,6 @@ func (f FieldIndex) ElemsInChunk() (uint64, error) { } } -func (FieldIndex) Native() bool { - return true -} - // Below we define a set of useful enum values for the field // indices of the beacon state. For example, genesisTime is the // 0th field of the beacon state. This is helpful when we are diff --git a/beacon-chain/state/stategen/epoch_boundary_state_cache.go b/beacon-chain/state/stategen/epoch_boundary_state_cache.go index e2e551ca00..1538f20c61 100644 --- a/beacon-chain/state/stategen/epoch_boundary_state_cache.go +++ b/beacon-chain/state/stategen/epoch_boundary_state_cache.go @@ -6,7 +6,7 @@ import ( "sync" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "k8s.io/client-go/tools/cache" ) @@ -20,7 +20,7 @@ var ( // slotRootInfo specifies the slot root info in the epoch boundary state cache. type slotRootInfo struct { - slot types.Slot + slot primitives.Slot blockRoot [32]byte } @@ -106,7 +106,7 @@ func (e *epochBoundaryState) getByBlockRootLockFree(r [32]byte) (*rootStateInfo, } // get epoch boundary state by its slot. Returns copied state in state info object if exists. Otherwise returns nil. -func (e *epochBoundaryState) getBySlot(s types.Slot) (*rootStateInfo, bool, error) { +func (e *epochBoundaryState) getBySlot(s primitives.Slot) (*rootStateInfo, bool, error) { e.lock.RLock() defer e.lock.RUnlock() @@ -175,6 +175,6 @@ func popProcessNoopFunc(_ interface{}) error { } // Converts input uint64 to string. To be used as key for slot to get root. -func slotToString(s types.Slot) string { +func slotToString(s primitives.Slot) string { return strconv.FormatUint(uint64(s), 10) } diff --git a/beacon-chain/state/stategen/epoch_boundary_state_cache_test.go b/beacon-chain/state/stategen/epoch_boundary_state_cache_test.go index 89af2c09be..4f3eeeea97 100644 --- a/beacon-chain/state/stategen/epoch_boundary_state_cache_test.go +++ b/beacon-chain/state/stategen/epoch_boundary_state_cache_test.go @@ -3,7 +3,7 @@ package stategen import ( "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -61,8 +61,8 @@ func TestEpochBoundaryStateCache_CanSaveAndDelete(t *testing.T) { func TestEpochBoundaryStateCache_CanTrim(t *testing.T) { e := newBoundaryStateCache() - offSet := types.Slot(10) - for i := types.Slot(0); i < offSet.Add(maxCacheSize); i++ { + offSet := primitives.Slot(10) + for i := primitives.Slot(0); i < offSet.Add(maxCacheSize); i++ { s, err := util.NewBeaconState() require.NoError(t, err) require.NoError(t, s.SetSlot(i)) diff --git a/beacon-chain/state/stategen/getter.go b/beacon-chain/state/stategen/getter.go index 6d7d064d51..cfb1e1b372 100644 --- a/beacon-chain/state/stategen/getter.go +++ b/beacon-chain/state/stategen/getter.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "go.opencensus.io/trace" @@ -327,7 +327,7 @@ func (s *State) CombinedCache() *CombinedCache { return &CombinedCache{getters: getters} } -func (s *State) slotAvailable(slot types.Slot) bool { +func (s *State) slotAvailable(slot primitives.Slot) bool { // default to assuming node was initialized from genesis - backfill only needs to be specified for checkpoint sync if s.backfillStatus == nil { return true diff --git a/beacon-chain/state/stategen/getter_test.go b/beacon-chain/state/stategen/getter_test.go index 74a933d5d1..8cbf7a19f4 100644 --- a/beacon-chain/state/stategen/getter_test.go +++ b/beacon-chain/state/stategen/getter_test.go @@ -8,7 +8,7 @@ import ( testDB "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" doublylinkedtree "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/doubly-linked-tree" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -116,7 +116,7 @@ func TestStateByRoot_HotStateUsingEpochBoundaryCacheNoReplay(t *testing.T) { require.NoError(t, service.epochBoundaryStateCache.put(blkRoot, beaconState)) loadedState, err := service.StateByRoot(ctx, blkRoot) require.NoError(t, err) - assert.Equal(t, types.Slot(10), loadedState.Slot(), "Did not correctly load state") + assert.Equal(t, primitives.Slot(10), loadedState.Slot(), "Did not correctly load state") } func TestStateByRoot_HotStateUsingEpochBoundaryCacheWithReplay(t *testing.T) { @@ -130,7 +130,7 @@ func TestStateByRoot_HotStateUsingEpochBoundaryCacheWithReplay(t *testing.T) { blkRoot, err := blk.Block.HashTreeRoot() require.NoError(t, err) require.NoError(t, service.epochBoundaryStateCache.put(blkRoot, beaconState)) - targetSlot := types.Slot(10) + targetSlot := primitives.Slot(10) targetBlock := util.NewBeaconBlock() targetBlock.Block.Slot = 11 targetBlock.Block.ParentRoot = blkRoot[:] @@ -213,7 +213,7 @@ func TestStateByRootInitialSync_UseEpochStateCache(t *testing.T) { service := New(beaconDB, doublylinkedtree.New()) beaconState, _ := util.DeterministicGenesisState(t, 32) - targetSlot := types.Slot(10) + targetSlot := primitives.Slot(10) require.NoError(t, beaconState.SetSlot(targetSlot)) blk := util.NewBeaconBlock() blkRoot, err := blk.Block.HashTreeRoot() @@ -253,7 +253,7 @@ func TestStateByRootInitialSync_CanProcessUpTo(t *testing.T) { blkRoot, err := blk.Block.HashTreeRoot() require.NoError(t, err) require.NoError(t, service.epochBoundaryStateCache.put(blkRoot, beaconState)) - targetSlot := types.Slot(10) + targetSlot := primitives.Slot(10) targetBlk := util.NewBeaconBlock() targetBlk.Block.Slot = 11 targetBlk.Block.ParentRoot = blkRoot[:] @@ -329,7 +329,7 @@ func TestLoadeStateByRoot_EpochBoundaryStateCanProcess(t *testing.T) { // This tests where hot state was not cached and needs processing. loadedState, err := service.loadStateByRoot(ctx, blkRoot) require.NoError(t, err) - assert.Equal(t, types.Slot(10), loadedState.Slot(), "Did not correctly load state") + assert.Equal(t, primitives.Slot(10), loadedState.Slot(), "Did not correctly load state") } func TestLoadeStateByRoot_FromDBBoundaryCase(t *testing.T) { @@ -355,7 +355,7 @@ func TestLoadeStateByRoot_FromDBBoundaryCase(t *testing.T) { // This tests where hot state was not cached and needs processing. loadedState, err := service.loadStateByRoot(ctx, blkRoot) require.NoError(t, err) - assert.Equal(t, types.Slot(10), loadedState.Slot(), "Did not correctly load state") + assert.Equal(t, primitives.Slot(10), loadedState.Slot(), "Did not correctly load state") } func TestLastAncestorState_CanGetUsingDB(t *testing.T) { diff --git a/beacon-chain/state/stategen/history.go b/beacon-chain/state/stategen/history.go index e08a62324c..8840274084 100644 --- a/beacon-chain/state/stategen/history.go +++ b/beacon-chain/state/stategen/history.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "go.opencensus.io/trace" ) @@ -41,11 +41,11 @@ type CanonicalHistory struct { cache CachedGetter } -func (c *CanonicalHistory) ReplayerForSlot(target types.Slot) Replayer { +func (c *CanonicalHistory) ReplayerForSlot(target primitives.Slot) Replayer { return &stateReplayer{chainer: c, method: forSlot, target: target} } -func (c *CanonicalHistory) BlockRootForSlot(ctx context.Context, target types.Slot) ([32]byte, error) { +func (c *CanonicalHistory) BlockRootForSlot(ctx context.Context, target primitives.Slot) ([32]byte, error) { if currentSlot := c.cs.CurrentSlot(); target > currentSlot { return [32]byte{}, errors.Wrap(ErrFutureSlotRequested, fmt.Sprintf("requested=%d, current=%d", target, currentSlot)) } @@ -103,7 +103,7 @@ func (c *CanonicalHistory) bestForSlot(ctx context.Context, roots [][32]byte) ([ // and the stategen transition helper methods. This implementation uses the following algorithm: // - find the highest canonical block <= the target slot // - starting with this block, recursively search backwards for a stored state, and accumulate intervening blocks -func (c *CanonicalHistory) chainForSlot(ctx context.Context, target types.Slot) (state.BeaconState, []interfaces.SignedBeaconBlock, error) { +func (c *CanonicalHistory) chainForSlot(ctx context.Context, target primitives.Slot) (state.BeaconState, []interfaces.SignedBeaconBlock, error) { ctx, span := trace.StartSpan(ctx, "canonicalChainer.chainForSlot") defer span.End() r, err := c.BlockRootForSlot(ctx, target) diff --git a/beacon-chain/state/stategen/history_test.go b/beacon-chain/state/stategen/history_test.go index 2e725be325..ddbc02ee72 100644 --- a/beacon-chain/state/stategen/history_test.go +++ b/beacon-chain/state/stategen/history_test.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" "github.com/prysmaticlabs/prysm/v3/consensus-types/mock" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -103,7 +103,7 @@ func TestBestForSlot(t *testing.T) { // happy path tests func TestCanonicalBlockForSlotHappy(t *testing.T) { ctx := context.Background() - var begin, middle, end types.Slot = 100, 150, 155 + var begin, middle, end primitives.Slot = 100, 150, 155 specs := []mockHistorySpec{ {slot: begin}, {slot: middle, savedState: true}, @@ -115,9 +115,9 @@ func TestCanonicalBlockForSlotHappy(t *testing.T) { // since only the end block and genesis are canonical, once the slot drops below // end, we should always get genesis cases := []struct { - slot types.Slot - highest types.Slot - canon types.Slot + slot primitives.Slot + highest primitives.Slot + canon primitives.Slot name string }{ {slot: hist.current, highest: end, canon: end, name: "slot > end"}, @@ -144,7 +144,7 @@ func TestCanonicalBlockForSlotHappy(t *testing.T) { func TestCanonicalBlockForSlotNonHappy(t *testing.T) { ctx := context.Background() - var begin, middle, end types.Slot = 100, 150, 155 + var begin, middle, end primitives.Slot = 100, 150, 155 specs := []mockHistorySpec{ {slot: begin}, {slot: middle, savedState: true}, @@ -154,22 +154,22 @@ func TestCanonicalBlockForSlotNonHappy(t *testing.T) { genesis, err := hist.GenesisBlockRoot(ctx) require.NoError(t, err) - slotOrderObserved := make([]types.Slot, 0) + slotOrderObserved := make([]primitives.Slot, 0) derp := errors.New("HighestRootsBelowSlot don't work") // since only the end block and genesis are canonical, once the slot drops below // end, we should always get genesis cases := []struct { name string - slot types.Slot + slot primitives.Slot canon CanonicalChecker - overrideHighest func(context.Context, types.Slot) (types.Slot, [][32]byte, error) - slotOrderExpected []types.Slot + overrideHighest func(context.Context, primitives.Slot) (primitives.Slot, [][32]byte, error) + slotOrderExpected []primitives.Slot err error root [32]byte }{ { name: "HighestRootsBelowSlot not called for genesis", - overrideHighest: func(_ context.Context, _ types.Slot) (types.Slot, [][32]byte, error) { + overrideHighest: func(_ context.Context, _ primitives.Slot) (primitives.Slot, [][32]byte, error) { return 0, [][32]byte{}, derp }, root: hist.slotMap[0], @@ -177,7 +177,7 @@ func TestCanonicalBlockForSlotNonHappy(t *testing.T) { { name: "wrapped error from HighestRootsBelowSlot returned", err: derp, - overrideHighest: func(_ context.Context, _ types.Slot) (types.Slot, [][32]byte, error) { + overrideHighest: func(_ context.Context, _ primitives.Slot) (primitives.Slot, [][32]byte, error) { return 0, [][32]byte{}, derp }, slot: end, @@ -185,7 +185,7 @@ func TestCanonicalBlockForSlotNonHappy(t *testing.T) { { name: "HighestRootsBelowSlot empty list", err: ErrNoBlocksBelowSlot, - overrideHighest: func(_ context.Context, _ types.Slot) (types.Slot, [][32]byte, error) { + overrideHighest: func(_ context.Context, _ primitives.Slot) (primitives.Slot, [][32]byte, error) { return 0, [][32]byte{}, nil }, slot: end, @@ -204,13 +204,13 @@ func TestCanonicalBlockForSlotNonHappy(t *testing.T) { } return false, nil }}, - overrideHighest: func(_ context.Context, s types.Slot) (types.Slot, [][32]byte, error) { + overrideHighest: func(_ context.Context, s primitives.Slot) (primitives.Slot, [][32]byte, error) { slotOrderObserved = append(slotOrderObserved, s) // this allows the mock HighestRootsBelowSlot to continue to execute now that we've recorded // the slot in our channel return 0, nil, errFallThroughOverride }, - slotOrderExpected: []types.Slot{156, 155, 150, 100}, + slotOrderExpected: []primitives.Slot{156, 155, 150, 100}, slot: end, root: hist.slotMap[0], }, @@ -222,13 +222,13 @@ func TestCanonicalBlockForSlotNonHappy(t *testing.T) { } return false, nil }}, - overrideHighest: func(_ context.Context, s types.Slot) (types.Slot, [][32]byte, error) { + overrideHighest: func(_ context.Context, s primitives.Slot) (primitives.Slot, [][32]byte, error) { slotOrderObserved = append(slotOrderObserved, s) // this allows the mock HighestRootsBelowSlot to continue to execute now that we've recorded // the slot in our channel return 0, nil, errFallThroughOverride }, - slotOrderExpected: []types.Slot{156, 155, 150}, + slotOrderExpected: []primitives.Slot{156, 155, 150}, slot: end, root: hist.slotMap[100], }, @@ -256,16 +256,16 @@ func TestCanonicalBlockForSlotNonHappy(t *testing.T) { if c.root != [32]byte{} { require.Equal(t, c.root, r) } - slotOrderObserved = make([]types.Slot, 0) + slotOrderObserved = make([]primitives.Slot, 0) }) } } type mockCurrentSlotter struct { - Slot types.Slot + Slot primitives.Slot } -func (c *mockCurrentSlotter) CurrentSlot() types.Slot { +func (c *mockCurrentSlotter) CurrentSlot() primitives.Slot { return c.Slot } @@ -273,7 +273,7 @@ var _ CurrentSlotter = &mockCurrentSlotter{} func TestAncestorChainCache(t *testing.T) { ctx := context.Background() - var begin, middle, end types.Slot = 100, 150, 155 + var begin, middle, end primitives.Slot = 100, 150, 155 specs := []mockHistorySpec{ {slot: begin, canonicalBlock: true}, {slot: middle, canonicalBlock: true}, @@ -346,7 +346,7 @@ func TestAncestorChainCache(t *testing.T) { func TestAncestorChainOK(t *testing.T) { ctx := context.Background() - var begin, middle, end types.Slot = 100, 150, 155 + var begin, middle, end primitives.Slot = 100, 150, 155 specs := []mockHistorySpec{ {slot: begin}, {slot: middle, savedState: true}, @@ -379,7 +379,7 @@ func TestAncestorChainOK(t *testing.T) { func TestChainForSlot(t *testing.T) { ctx := context.Background() - var zero, one, two, three types.Slot = 50, 51, 150, 151 + var zero, one, two, three primitives.Slot = 50, 51, 150, 151 specs := []mockHistorySpec{ {slot: zero, canonicalBlock: true, savedState: true}, {slot: one, canonicalBlock: true}, @@ -394,7 +394,7 @@ func TestChainForSlot(t *testing.T) { cases := []struct { name string - slot types.Slot + slot primitives.Slot stateRoot [32]byte blockRoots [][32]byte }{ @@ -448,7 +448,7 @@ func TestChainForSlot(t *testing.T) { func TestAncestorChainOrdering(t *testing.T) { ctx := context.Background() - var zero, one, two, three, four, five types.Slot = 50, 51, 150, 151, 152, 200 + var zero, one, two, three, four, five primitives.Slot = 50, 51, 150, 151, 152, 200 specs := []mockHistorySpec{ {slot: zero}, {slot: one, savedState: true}, @@ -474,7 +474,7 @@ func TestAncestorChainOrdering(t *testing.T) { // one has the savedState. one is applied to the savedState, so it should be omitted // that means we should get two, three, four, five (length of 4) require.Equal(t, 4, len(bs)) - for i, slot := range []types.Slot{two, three, four, five} { + for i, slot := range []primitives.Slot{two, three, four, five} { require.Equal(t, slot, bs[i].Block().Slot(), fmt.Sprintf("wrong value at index %d", i)) } @@ -511,7 +511,7 @@ func TestAncestorChainOrdering(t *testing.T) { require.NoError(t, err) require.Equal(t, expectedRoot, actualRoot) require.Equal(t, 3, len(bs)) - for i, slot := range []types.Slot{two, three, four} { + for i, slot := range []primitives.Slot{two, three, four} { require.Equal(t, slot, bs[i].Block().Slot(), fmt.Sprintf("wrong value at index %d", i)) } } diff --git a/beacon-chain/state/stategen/migrate_test.go b/beacon-chain/state/stategen/migrate_test.go index fbabf7dc1d..725ab7bfe7 100644 --- a/beacon-chain/state/stategen/migrate_test.go +++ b/beacon-chain/state/stategen/migrate_test.go @@ -8,7 +8,7 @@ import ( testDB "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" doublylinkedtree "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice/doubly-linked-tree" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -41,7 +41,7 @@ func TestMigrateToCold_HappyPath(t *testing.T) { service := New(beaconDB, doublylinkedtree.New()) service.slotsPerArchivedPoint = 1 beaconState, _ := util.DeterministicGenesisState(t, 32) - stateSlot := types.Slot(1) + stateSlot := primitives.Slot(1) require.NoError(t, beaconState.SetSlot(stateSlot)) b := util.NewBeaconBlock() b.Block.Slot = 2 @@ -58,7 +58,7 @@ func TestMigrateToCold_HappyPath(t *testing.T) { assert.Equal(t, fRoot, gotRoot, "Did not save archived root") lastIndex, err := service.beaconDB.LastArchivedSlot(ctx) require.NoError(t, err) - assert.Equal(t, types.Slot(1), lastIndex, "Did not save last archived index") + assert.Equal(t, primitives.Slot(1), lastIndex, "Did not save last archived index") require.LogsContain(t, hook, "Saved state in DB") } @@ -103,12 +103,12 @@ func TestMigrateToCold_RegeneratePath(t *testing.T) { s1, err := service.beaconDB.State(ctx, r1) require.NoError(t, err) - assert.Equal(t, s1.Slot(), types.Slot(1), "Did not save state") + assert.Equal(t, s1.Slot(), primitives.Slot(1), "Did not save state") gotRoot := service.beaconDB.ArchivedPointRoot(ctx, 1/service.slotsPerArchivedPoint) assert.Equal(t, r1, gotRoot, "Did not save archived root") lastIndex, err := service.beaconDB.LastArchivedSlot(ctx) require.NoError(t, err) - assert.Equal(t, types.Slot(1), lastIndex, "Did not save last archived index") + assert.Equal(t, primitives.Slot(1), lastIndex, "Did not save last archived index") require.LogsContain(t, hook, "Saved state in DB") } @@ -121,7 +121,7 @@ func TestMigrateToCold_StateExistsInDB(t *testing.T) { service := New(beaconDB, doublylinkedtree.New()) service.slotsPerArchivedPoint = 1 beaconState, _ := util.DeterministicGenesisState(t, 32) - stateSlot := types.Slot(1) + stateSlot := primitives.Slot(1) require.NoError(t, beaconState.SetSlot(stateSlot)) b := util.NewBeaconBlock() b.Block.Slot = 2 @@ -204,10 +204,10 @@ func TestMigrateToCold_ParallelCalls(t *testing.T) { s1, err := service.beaconDB.State(ctx, r1) require.NoError(t, err) - assert.Equal(t, s1.Slot(), types.Slot(1), "Did not save state") + assert.Equal(t, s1.Slot(), primitives.Slot(1), "Did not save state") s4, err := service.beaconDB.State(ctx, r4) require.NoError(t, err) - assert.Equal(t, s4.Slot(), types.Slot(4), "Did not save state") + assert.Equal(t, s4.Slot(), primitives.Slot(4), "Did not save state") gotRoot := service.beaconDB.ArchivedPointRoot(ctx, 1/service.slotsPerArchivedPoint) assert.Equal(t, r1, gotRoot, "Did not save archived root") @@ -215,7 +215,7 @@ func TestMigrateToCold_ParallelCalls(t *testing.T) { assert.Equal(t, r4, gotRoot, "Did not save archived root") lastIndex, err := service.beaconDB.LastArchivedSlot(ctx) require.NoError(t, err) - assert.Equal(t, types.Slot(4), lastIndex, "Did not save last archived index") + assert.Equal(t, primitives.Slot(4), lastIndex, "Did not save last archived index") assert.DeepEqual(t, [][32]byte{r7}, service.saveHotStateDB.blockRootsOfSavedStates, "Did not remove all saved hot state roots") require.LogsContain(t, hook, "Saved state in DB") } diff --git a/beacon-chain/state/stategen/mock/mock.go b/beacon-chain/state/stategen/mock/mock.go index 108e39d559..a07818d214 100644 --- a/beacon-chain/state/stategen/mock/mock.go +++ b/beacon-chain/state/stategen/mock/mock.go @@ -4,20 +4,20 @@ import ( "context" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // MockStateManager is a fake implementation of StateManager. type MockStateManager struct { StatesByRoot map[[32]byte]state.BeaconState - StatesBySlot map[types.Slot]state.BeaconState + StatesBySlot map[primitives.Slot]state.BeaconState } // NewMockService -- func NewMockService() *MockStateManager { return &MockStateManager{ StatesByRoot: make(map[[32]byte]state.BeaconState), - StatesBySlot: make(map[types.Slot]state.BeaconState), + StatesBySlot: make(map[primitives.Slot]state.BeaconState), } } @@ -32,7 +32,7 @@ func (_ *MockStateManager) Resume(_ context.Context, _ state.BeaconState) (state } // SaveFinalizedState -- -func (_ *MockStateManager) SaveFinalizedState(_ types.Slot, _ [32]byte, _ state.BeaconState) { +func (_ *MockStateManager) SaveFinalizedState(_ primitives.Slot, _ [32]byte, _ state.BeaconState) { panic("implement me") } @@ -62,7 +62,7 @@ func (_ *MockStateManager) StateByRootInitialSync(_ context.Context, _ [32]byte) } // StateBySlot -- -func (m *MockStateManager) StateBySlot(_ context.Context, slot types.Slot) (state.BeaconState, error) { +func (m *MockStateManager) StateBySlot(_ context.Context, slot primitives.Slot) (state.BeaconState, error) { return m.StatesBySlot[slot], nil } @@ -92,7 +92,7 @@ func (m *MockStateManager) AddStateForRoot(state state.BeaconState, blockRoot [3 } // AddStateForSlot -- -func (m *MockStateManager) AddStateForSlot(state state.BeaconState, slot types.Slot) { +func (m *MockStateManager) AddStateForSlot(state state.BeaconState, slot primitives.Slot) { m.StatesBySlot[slot] = state } diff --git a/beacon-chain/state/stategen/mock/replayer.go b/beacon-chain/state/stategen/mock/replayer.go index f347cab3d7..fc347c3add 100644 --- a/beacon-chain/state/stategen/mock/replayer.go +++ b/beacon-chain/state/stategen/mock/replayer.go @@ -5,7 +5,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) func NewMockReplayerBuilder(opt ...MockReplayerBuilderOption) *MockReplayerBuilder { @@ -25,31 +25,31 @@ func WithMockState(s state.BeaconState) MockReplayerBuilderOption { } type MockReplayerBuilder struct { - forSlot map[types.Slot]*MockReplayer + forSlot map[primitives.Slot]*MockReplayer } func (b *MockReplayerBuilder) SetMockState(s state.BeaconState) { if b.forSlot == nil { - b.forSlot = make(map[types.Slot]*MockReplayer) + b.forSlot = make(map[primitives.Slot]*MockReplayer) } b.forSlot[s.Slot()] = &MockReplayer{State: s} } -func (b *MockReplayerBuilder) SetMockStateForSlot(s state.BeaconState, slot types.Slot) { +func (b *MockReplayerBuilder) SetMockStateForSlot(s state.BeaconState, slot primitives.Slot) { if b.forSlot == nil { - b.forSlot = make(map[types.Slot]*MockReplayer) + b.forSlot = make(map[primitives.Slot]*MockReplayer) } b.forSlot[slot] = &MockReplayer{State: s} } -func (b *MockReplayerBuilder) SetMockSlotError(s types.Slot, e error) { +func (b *MockReplayerBuilder) SetMockSlotError(s primitives.Slot, e error) { if b.forSlot == nil { - b.forSlot = make(map[types.Slot]*MockReplayer) + b.forSlot = make(map[primitives.Slot]*MockReplayer) } b.forSlot[s] = &MockReplayer{Err: e} } -func (b *MockReplayerBuilder) ReplayerForSlot(target types.Slot) stategen.Replayer { +func (b *MockReplayerBuilder) ReplayerForSlot(target primitives.Slot) stategen.Replayer { return b.forSlot[target] } @@ -64,7 +64,7 @@ func (m *MockReplayer) ReplayBlocks(_ context.Context) (state.BeaconState, error return m.State, m.Err } -func (m *MockReplayer) ReplayToSlot(_ context.Context, _ types.Slot) (state.BeaconState, error) { +func (m *MockReplayer) ReplayToSlot(_ context.Context, _ primitives.Slot) (state.BeaconState, error) { return m.State, m.Err } @@ -82,10 +82,10 @@ func (m *MockCanonicalChecker) IsCanonical(_ context.Context, _ [32]byte) (bool, var _ stategen.CanonicalChecker = &MockCanonicalChecker{} type MockCurrentSlotter struct { - Slot types.Slot + Slot primitives.Slot } -func (c *MockCurrentSlotter) CurrentSlot() types.Slot { +func (c *MockCurrentSlotter) CurrentSlot() primitives.Slot { return c.Slot } diff --git a/beacon-chain/state/stategen/mock_test.go b/beacon-chain/state/stategen/mock_test.go index 00b6594daf..bda8c9d0b4 100644 --- a/beacon-chain/state/stategen/mock_test.go +++ b/beacon-chain/state/stategen/mock_test.go @@ -15,14 +15,14 @@ import ( consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" blocktest "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks/testing" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" ) func TestMockHistoryStates(t *testing.T) { ctx := context.Background() - var begin, middle, end types.Slot = 100, 150, 155 + var begin, middle, end primitives.Slot = 100, 150, 155 specs := []mockHistorySpec{ {slot: begin}, {slot: middle, savedState: true}, @@ -35,7 +35,7 @@ func TestMockHistoryStates(t *testing.T) { st, err := hist.StateOrError(ctx, genesisRoot) require.NoError(t, err) require.DeepEqual(t, hist.states[genesisRoot], st) - require.Equal(t, types.Slot(0), st.Slot()) + require.Equal(t, primitives.Slot(0), st.Slot()) shouldExist, err := hist.StateOrError(ctx, hist.slotMap[middle]) require.NoError(t, err) @@ -53,7 +53,7 @@ func TestMockHistoryStates(t *testing.T) { func TestMockHistoryParentRoot(t *testing.T) { ctx := context.Background() - var begin, middle, end types.Slot = 100, 150, 155 + var begin, middle, end primitives.Slot = 100, 150, 155 specs := []mockHistorySpec{ {slot: begin}, {slot: middle, savedState: true}, @@ -68,23 +68,23 @@ func TestMockHistoryParentRoot(t *testing.T) { } type mockHistorySpec struct { - slot types.Slot + slot primitives.Slot savedState bool canonicalBlock bool } type mockHistory struct { blocks map[[32]byte]interfaces.SignedBeaconBlock - slotMap map[types.Slot][32]byte + slotMap map[primitives.Slot][32]byte slotIndex slotList canonical map[[32]byte]bool states map[[32]byte]state.BeaconState hiddenStates map[[32]byte]state.BeaconState - current types.Slot - overrideHighestSlotBlocksBelow func(context.Context, types.Slot) (types.Slot, [][32]byte, error) + current primitives.Slot + overrideHighestSlotBlocksBelow func(context.Context, primitives.Slot) (primitives.Slot, [][32]byte, error) } -type slotList []types.Slot +type slotList []primitives.Slot func (m slotList) Len() int { return len(m) @@ -100,7 +100,7 @@ func (m slotList) Swap(i, j int) { var errFallThroughOverride = errors.New("override yielding control back to real HighestRootsBelowSlot") -func (m *mockHistory) HighestRootsBelowSlot(_ context.Context, slot types.Slot) (types.Slot, [][32]byte, error) { +func (m *mockHistory) HighestRootsBelowSlot(_ context.Context, slot primitives.Slot) (primitives.Slot, [][32]byte, error) { if m.overrideHighestSlotBlocksBelow != nil { s, r, err := m.overrideHighestSlotBlocksBelow(context.Background(), slot) if !errors.Is(err, errFallThroughOverride) { @@ -150,7 +150,7 @@ func (m *mockHistory) IsCanonical(_ context.Context, blockRoot [32]byte) (bool, return ok && canon, nil } -func (m *mockHistory) CurrentSlot() types.Slot { +func (m *mockHistory) CurrentSlot() primitives.Slot { return m.current } @@ -169,7 +169,7 @@ func (h *mockHistory) hideState(root [32]byte, s state.BeaconState) { } func (h *mockHistory) validateRoots() error { - uniqParentRoots := make(map[[32]byte]types.Slot) + uniqParentRoots := make(map[[32]byte]primitives.Slot) for s, root := range h.slotMap { b := h.blocks[root] htr, err := b.Block().HashTreeRoot() @@ -187,14 +187,14 @@ func (h *mockHistory) validateRoots() error { return nil } -func newMockHistory(t *testing.T, hist []mockHistorySpec, current types.Slot) *mockHistory { +func newMockHistory(t *testing.T, hist []mockHistorySpec, current primitives.Slot) *mockHistory { ctx := context.Background() mh := &mockHistory{ blocks: map[[32]byte]interfaces.SignedBeaconBlock{}, canonical: map[[32]byte]bool{}, states: map[[32]byte]state.BeaconState{}, hiddenStates: map[[32]byte]state.BeaconState{}, - slotMap: map[types.Slot][32]byte{}, + slotMap: map[primitives.Slot][32]byte{}, slotIndex: slotList{}, current: current, } diff --git a/beacon-chain/state/stategen/replay.go b/beacon-chain/state/stategen/replay.go index de975e8a5c..69abd36538 100644 --- a/beacon-chain/state/stategen/replay.go +++ b/beacon-chain/state/stategen/replay.go @@ -15,7 +15,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" "github.com/prysmaticlabs/prysm/v3/runtime/version" "github.com/sirupsen/logrus" @@ -29,7 +29,7 @@ func (_ *State) replayBlocks( ctx context.Context, state state.BeaconState, signed []interfaces.SignedBeaconBlock, - targetSlot types.Slot, + targetSlot primitives.Slot, ) (state.BeaconState, error) { ctx, span := trace.StartSpan(ctx, "stateGen.replayBlocks") defer span.End() @@ -80,7 +80,7 @@ func (_ *State) replayBlocks( // loadBlocks loads the blocks between start slot and end slot by recursively fetching from end block root. // The Blocks are returned in slot-descending order. -func (s *State) loadBlocks(ctx context.Context, startSlot, endSlot types.Slot, endBlockRoot [32]byte) ([]interfaces.SignedBeaconBlock, error) { +func (s *State) loadBlocks(ctx context.Context, startSlot, endSlot primitives.Slot, endBlockRoot [32]byte) ([]interfaces.SignedBeaconBlock, error) { // Nothing to load for invalid range. if startSlot > endSlot { return nil, fmt.Errorf("start slot %d > end slot %d", startSlot, endSlot) @@ -175,7 +175,7 @@ func executeStateTransitionStateGen( // There's no skip slot cache involved given state gen only works with already stored block and state in DB. // // WARNING: This method should not be used for future slot. -func ReplayProcessSlots(ctx context.Context, state state.BeaconState, slot types.Slot) (state.BeaconState, error) { +func ReplayProcessSlots(ctx context.Context, state state.BeaconState, slot primitives.Slot) (state.BeaconState, error) { ctx, span := trace.StartSpan(ctx, "stategen.ReplayProcessSlots") defer span.End() if state == nil || state.IsNil() { @@ -250,7 +250,7 @@ func ReplayProcessSlots(ctx context.Context, state state.BeaconState, slot types // Given the start slot and the end slot, this returns the finalized beacon blocks in between. // Since hot states don't have finalized blocks, this should ONLY be used for replaying cold state. -func (s *State) loadFinalizedBlocks(ctx context.Context, startSlot, endSlot types.Slot) ([]interfaces.SignedBeaconBlock, error) { +func (s *State) loadFinalizedBlocks(ctx context.Context, startSlot, endSlot primitives.Slot) ([]interfaces.SignedBeaconBlock, error) { f := filters.NewFilter().SetStartSlot(startSlot).SetEndSlot(endSlot) bs, bRoots, err := s.beaconDB.Blocks(ctx, f) if err != nil { diff --git a/beacon-chain/state/stategen/replayer.go b/beacon-chain/state/stategen/replayer.go index c1f0f93df3..c5f95f03ed 100644 --- a/beacon-chain/state/stategen/replayer.go +++ b/beacon-chain/state/stategen/replayer.go @@ -8,7 +8,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/sirupsen/logrus" "go.opencensus.io/trace" ) @@ -26,7 +26,7 @@ const ( // HistoryAccessor describes the minimum set of database methods needed to support the ReplayerBuilder. type HistoryAccessor interface { - HighestRootsBelowSlot(ctx context.Context, slot types.Slot) (types.Slot, [][32]byte, error) + HighestRootsBelowSlot(ctx context.Context, slot primitives.Slot) (primitives.Slot, [][32]byte, error) GenesisBlockRoot(ctx context.Context) ([32]byte, error) Block(ctx context.Context, blockRoot [32]byte) (interfaces.SignedBeaconBlock, error) StateOrError(ctx context.Context, blockRoot [32]byte) (state.BeaconState, error) @@ -40,7 +40,7 @@ type CanonicalChecker interface { // CurrentSlotter provides the current Slot. type CurrentSlotter interface { - CurrentSlot() types.Slot + CurrentSlot() primitives.Slot } // Replayer encapsulates database query and replay logic. It can be constructed via a ReplayerBuilder. @@ -51,7 +51,7 @@ type Replayer interface { // but then also runs process_slots to advance the state past the root or slot used in the builder. // For example, if you wanted the state to be at the target slot, but only integrating blocks up to // slot-1, you could request Builder.ReplayerForSlot(slot-1).ReplayToSlot(slot) - ReplayToSlot(ctx context.Context, target types.Slot) (state.BeaconState, error) + ReplayToSlot(ctx context.Context, target primitives.Slot) (state.BeaconState, error) } var _ Replayer = &stateReplayer{} @@ -59,11 +59,11 @@ var _ Replayer = &stateReplayer{} // chainer is responsible for supplying the chain components necessary to rebuild a state, // namely a starting BeaconState and all available blocks from the starting state up to and including the target slot type chainer interface { - chainForSlot(ctx context.Context, target types.Slot) (state.BeaconState, []interfaces.SignedBeaconBlock, error) + chainForSlot(ctx context.Context, target primitives.Slot) (state.BeaconState, []interfaces.SignedBeaconBlock, error) } type stateReplayer struct { - target types.Slot + target primitives.Slot method retrievalMethod chainer chainer } @@ -127,7 +127,7 @@ func (rs *stateReplayer) ReplayBlocks(ctx context.Context) (state.BeaconState, e // but then also runs process_slots to advance the state past the root or slot used in the builder. // for example, if you wanted the state to be at the target slot, but only integrating blocks up to // slot-1, you could request Builder.ReplayerForSlot(slot-1).ReplayToSlot(slot) -func (rs *stateReplayer) ReplayToSlot(ctx context.Context, replayTo types.Slot) (state.BeaconState, error) { +func (rs *stateReplayer) ReplayToSlot(ctx context.Context, replayTo primitives.Slot) (state.BeaconState, error) { ctx, span := trace.StartSpan(ctx, "stateGen.stateReplayer.ReplayToSlot") defer span.End() @@ -171,5 +171,5 @@ type ReplayerBuilder interface { // The resulting Replayer will always yield a state with .Slot=target; if there are skipped blocks // between the highest canonical block in the db and the target, the replayer will fast-forward past the intervening // slots via process_slots. - ReplayerForSlot(target types.Slot) Replayer + ReplayerForSlot(target primitives.Slot) Replayer } diff --git a/beacon-chain/state/stategen/replayer_test.go b/beacon-chain/state/stategen/replayer_test.go index c2565c4f91..2dca9d5c8f 100644 --- a/beacon-chain/state/stategen/replayer_test.go +++ b/beacon-chain/state/stategen/replayer_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -29,7 +29,7 @@ func headerFromBlock(b interfaces.SignedBeaconBlock) (*ethpb.BeaconBlockHeader, func TestReplayBlocks(t *testing.T) { ctx := context.Background() - var zero, one, two, three, four, five types.Slot = 50, 51, 150, 151, 152, 200 + var zero, one, two, three, four, five primitives.Slot = 50, 51, 150, 151, 152, 200 specs := []mockHistorySpec{ {slot: zero}, {slot: one, savedState: true}, @@ -78,7 +78,7 @@ func TestReplayBlocks(t *testing.T) { func TestReplayToSlot(t *testing.T) { ctx := context.Background() - var zero, one, two, three, four, five types.Slot = 50, 51, 150, 151, 152, 200 + var zero, one, two, three, four, five primitives.Slot = 50, 51, 150, 151, 152, 200 specs := []mockHistorySpec{ {slot: zero}, {slot: one, savedState: true}, diff --git a/beacon-chain/state/stategen/service.go b/beacon-chain/state/stategen/service.go index 8c40f13d2b..eefa1115df 100644 --- a/beacon-chain/state/stategen/service.go +++ b/beacon-chain/state/stategen/service.go @@ -13,12 +13,12 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/backfill" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "go.opencensus.io/trace" ) -var defaultHotStateDBInterval types.Slot = 128 +var defaultHotStateDBInterval primitives.Slot = 128 // StateManager represents a management object that handles the internal // logic of maintaining both hot and cold states in DB. @@ -30,7 +30,7 @@ type StateManager interface { DeleteStateFromCaches(ctx context.Context, blockRoot [32]byte) error ForceCheckpoint(ctx context.Context, root []byte) error SaveState(ctx context.Context, blockRoot [32]byte, st state.BeaconState) error - SaveFinalizedState(fSlot types.Slot, fRoot [32]byte, fState state.BeaconState) + SaveFinalizedState(fSlot primitives.Slot, fRoot [32]byte, fState state.BeaconState) MigrateToCold(ctx context.Context, fRoot [32]byte) error StateByRoot(ctx context.Context, blockRoot [32]byte) (state.BeaconState, error) BalancesByRoot(context.Context, [32]byte) ([]uint64, error) @@ -41,7 +41,7 @@ type StateManager interface { // State is a concrete implementation of StateManager. type State struct { beaconDB db.NoHeadAccessDatabase - slotsPerArchivedPoint types.Slot + slotsPerArchivedPoint primitives.Slot hotStateCache *hotStateCache finalizedInfo *finalizedInfo epochBoundaryStateCache *epochBoundaryState @@ -57,14 +57,14 @@ type State struct { type saveHotStateDbConfig struct { enabled bool lock sync.Mutex - duration types.Slot + duration primitives.Slot blockRootsOfSavedStates [][32]byte } // This tracks the finalized point. It's also the point where slot and the block root of // cold and hot sections of the DB splits. type finalizedInfo struct { - slot types.Slot + slot primitives.Slot root [32]byte state state.BeaconState lock sync.RWMutex @@ -143,7 +143,7 @@ func (s *State) Resume(ctx context.Context, fState state.BeaconState) (state.Bea // SaveFinalizedState saves the finalized slot, root and state into memory to be used by state gen service. // This used for migration at the correct start slot and used for hot state play back to ensure // lower bound to start is always at the last finalized state. -func (s *State) SaveFinalizedState(fSlot types.Slot, fRoot [32]byte, fState state.BeaconState) { +func (s *State) SaveFinalizedState(fSlot primitives.Slot, fRoot [32]byte, fState state.BeaconState) { s.finalizedInfo.lock.Lock() defer s.finalizedInfo.lock.Unlock() s.finalizedInfo.root = fRoot diff --git a/beacon-chain/state/stateutil/trie_helpers_test.go b/beacon-chain/state/stateutil/trie_helpers_test.go index 274b9caa5f..7414b8327d 100644 --- a/beacon-chain/state/stateutil/trie_helpers_test.go +++ b/beacon-chain/state/stateutil/trie_helpers_test.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stateutil" "github.com/prysmaticlabs/prysm/v3/config/features" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -195,8 +195,8 @@ func TestRecomputeFromLayer_VariableSizedArray(t *testing.T) { val2.ExitEpoch = 40 changedVals := []*ethpb.Validator{val1, val2} - require.NoError(t, newState.UpdateValidatorAtIndex(types.ValidatorIndex(changedIdx[0]), changedVals[0])) - require.NoError(t, newState.UpdateValidatorAtIndex(types.ValidatorIndex(changedIdx[1]), changedVals[1])) + require.NoError(t, newState.UpdateValidatorAtIndex(primitives.ValidatorIndex(changedIdx[0]), changedVals[0])) + require.NoError(t, newState.UpdateValidatorAtIndex(primitives.ValidatorIndex(changedIdx[1]), changedVals[1])) expectedRoot, err := stateutil.ValidatorRegistryRoot(newState.Validators()) require.NoError(t, err) diff --git a/beacon-chain/state/stateutil/unrealized_justification.go b/beacon-chain/state/stateutil/unrealized_justification.go index 812c1f1acf..0a867c5e0e 100644 --- a/beacon-chain/state/stateutil/unrealized_justification.go +++ b/beacon-chain/state/stateutil/unrealized_justification.go @@ -3,7 +3,7 @@ package stateutil import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/math" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -13,7 +13,7 @@ import ( // current epoch correctly attested for target balance. It takes the current and // previous epoch participation bits as parameters so implicitly only works for // beacon states post-Altair. -func UnrealizedCheckpointBalances(cp, pp []byte, validators []*ethpb.Validator, currentEpoch types.Epoch) (uint64, uint64, uint64, error) { +func UnrealizedCheckpointBalances(cp, pp []byte, validators []*ethpb.Validator, currentEpoch primitives.Epoch) (uint64, uint64, uint64, error) { targetIdx := params.BeaconConfig().TimelyTargetFlagIndex activeBalance := uint64(0) currentTarget := uint64(0) diff --git a/beacon-chain/state/stateutil/validator_map_handler.go b/beacon-chain/state/stateutil/validator_map_handler.go index a31499f324..cb6839cf31 100644 --- a/beacon-chain/state/stateutil/validator_map_handler.go +++ b/beacon-chain/state/stateutil/validator_map_handler.go @@ -5,14 +5,14 @@ import ( coreutils "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/transition/stateutils" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) // ValidatorMapHandler is a container to hold the map and a reference tracker for how many // states shared this. type ValidatorMapHandler struct { - valIdxMap map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex + valIdxMap map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex mapRef *Reference *sync.RWMutex } @@ -39,11 +39,11 @@ func (v *ValidatorMapHandler) IsNil() bool { // Copy the whole map and returns a map handler with the copied map. func (v *ValidatorMapHandler) Copy() *ValidatorMapHandler { if v == nil || v.valIdxMap == nil { - return &ValidatorMapHandler{valIdxMap: map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex{}, mapRef: new(Reference), RWMutex: new(sync.RWMutex)} + return &ValidatorMapHandler{valIdxMap: map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex{}, mapRef: new(Reference), RWMutex: new(sync.RWMutex)} } v.RLock() defer v.RUnlock() - m := make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex, len(v.valIdxMap)) + m := make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex, len(v.valIdxMap)) for k, v := range v.valIdxMap { m[k] = v } @@ -55,7 +55,7 @@ func (v *ValidatorMapHandler) Copy() *ValidatorMapHandler { } // Get the validator index using the corresponding public key. -func (v *ValidatorMapHandler) Get(key [fieldparams.BLSPubkeyLength]byte) (types.ValidatorIndex, bool) { +func (v *ValidatorMapHandler) Get(key [fieldparams.BLSPubkeyLength]byte) (primitives.ValidatorIndex, bool) { v.RLock() defer v.RUnlock() idx, ok := v.valIdxMap[key] @@ -66,7 +66,7 @@ func (v *ValidatorMapHandler) Get(key [fieldparams.BLSPubkeyLength]byte) (types. } // Set the validator index using the corresponding public key. -func (v *ValidatorMapHandler) Set(key [fieldparams.BLSPubkeyLength]byte, index types.ValidatorIndex) { +func (v *ValidatorMapHandler) Set(key [fieldparams.BLSPubkeyLength]byte, index primitives.ValidatorIndex) { v.Lock() defer v.Unlock() v.valIdxMap[key] = index diff --git a/beacon-chain/state/testing/getters.go b/beacon-chain/state/testing/getters.go index 3f5655c663..7998015c13 100644 --- a/beacon-chain/state/testing/getters.go +++ b/beacon-chain/state/testing/getters.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -65,8 +65,8 @@ func VerifyBeaconStateValidatorByPubkey(t *testing.T, factory getState) { name string modifyFunc func(b state.BeaconState, k [fieldparams.BLSPubkeyLength]byte) exists bool - expectedIdx types.ValidatorIndex - largestIdxInSet types.ValidatorIndex + expectedIdx primitives.ValidatorIndex + largestIdxInSet primitives.ValidatorIndex }{ { name: "retrieve validator", diff --git a/beacon-chain/state/testing/getters_checkpoint.go b/beacon-chain/state/testing/getters_checkpoint.go index f1f826517f..26b79990d3 100644 --- a/beacon-chain/state/testing/getters_checkpoint.go +++ b/beacon-chain/state/testing/getters_checkpoint.go @@ -4,7 +4,7 @@ import ( "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -79,7 +79,7 @@ func VerifyBeaconStateFinalizedCheckpointNil(t *testing.T, factory getState) { checkpoint := s.FinalizedCheckpoint() require.Equal(t, (*ethpb.Checkpoint)(nil), checkpoint) epoch := s.FinalizedCheckpointEpoch() - require.Equal(t, types.Epoch(0), epoch) + require.Equal(t, primitives.Epoch(0), epoch) } func VerifyBeaconStateFinalizedCheckpoint(t *testing.T, factory getStateWithCheckpoint) { diff --git a/beacon-chain/state/types/BUILD.bazel b/beacon-chain/state/types/BUILD.bazel deleted file mode 100644 index c783bccfea..0000000000 --- a/beacon-chain/state/types/BUILD.bazel +++ /dev/null @@ -1,19 +0,0 @@ -load("@prysm//tools/go:def.bzl", "go_library", "go_test") - -go_library( - name = "go_default_library", - srcs = ["types.go"], - importpath = "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/types", - visibility = ["//beacon-chain:__subpackages__"], - deps = [ - "//runtime/version:go_default_library", - "@com_github_pkg_errors//:go_default_library", - ], -) - -go_test( - name = "go_default_test", - srcs = ["types_test.go"], - embed = [":go_default_library"], - deps = ["//testing/assert:go_default_library"], -) diff --git a/beacon-chain/state/types/types.go b/beacon-chain/state/types/types.go deleted file mode 100644 index 51cbb0ef84..0000000000 --- a/beacon-chain/state/types/types.go +++ /dev/null @@ -1,172 +0,0 @@ -package types - -import ( - "github.com/pkg/errors" - "github.com/prysmaticlabs/prysm/v3/runtime/version" -) - -// FieldIndex represents the relevant field position in the -// state struct for a field. -type FieldIndex int - -// DataType signifies the data type of the field. -type DataType int - -// List of current data types the state supports. -const ( - // BasicArray represents a simple array type for a field. - BasicArray DataType = iota - // CompositeArray represents a variable length array with - // a non primitive type. - CompositeArray - // CompressedArray represents a variable length array which - // can pack multiple elements into a leaf of the underlying - // trie. - CompressedArray -) - -// BeaconStateField represents a field of the beacon state. -type BeaconStateField interface { - String(stateVersion int) string - RealPosition() int - ElemsInChunk() (uint64, error) - Native() bool -} - -// String returns the name of the field index. -func (f FieldIndex) String(stateVersion int) string { - switch f { - case GenesisTime: - return "genesisTime" - case GenesisValidatorsRoot: - return "genesisValidatorsRoot" - case Slot: - return "slot" - case Fork: - return "fork" - case LatestBlockHeader: - return "latestBlockHeader" - case BlockRoots: - return "blockRoots" - case StateRoots: - return "stateRoots" - case HistoricalRoots: - return "historicalRoots" - case Eth1Data: - return "eth1Data" - case Eth1DataVotes: - return "eth1DataVotes" - case Eth1DepositIndex: - return "eth1DepositIndex" - case Validators: - return "validators" - case Balances: - return "balances" - case RandaoMixes: - return "randaoMixes" - case Slashings: - return "slashings" - case PreviousEpochAttestations: - if stateVersion > version.Phase0 { - return "previousEpochParticipationBits" - } - return "previousEpochAttestations" - case CurrentEpochAttestations: - if stateVersion > version.Phase0 { - return "currentEpochParticipationBits" - } - return "currentEpochAttestations" - case JustificationBits: - return "justificationBits" - case PreviousJustifiedCheckpoint: - return "previousJustifiedCheckpoint" - case CurrentJustifiedCheckpoint: - return "currentJustifiedCheckpoint" - case FinalizedCheckpoint: - return "finalizedCheckpoint" - case InactivityScores: - return "inactivityScores" - case CurrentSyncCommittee: - return "currentSyncCommittee" - case NextSyncCommittee: - return "nextSyncCommittee" - case LatestExecutionPayloadHeader: - return "latestExecutionPayloadHeader" - case LatestExecutionPayloadHeaderCapella: - return "latestExecutionPayloadHeaderCapella" - case NextWithdrawalIndex: - return "nextWithdrawalIndex" - case NextWithdrawalValidatorIndex: - return "nextWithdrawalValidatorIndex" - default: - return "" - } -} - -// RealPosition denotes the position of the field in the beacon state. -// The value might differ for different state versions. -func (f FieldIndex) RealPosition() int { - return int(f) -} - -// ElemsInChunk returns the number of elements in the chunk (number of -// elements that are able to be packed). -func (f FieldIndex) ElemsInChunk() (uint64, error) { - switch f { - case Balances: - return 4, nil - default: - return 0, errors.Errorf("field %d doesn't support element compression", f) - } -} - -func (FieldIndex) Native() bool { - return false -} - -// Below we define a set of useful enum values for the field -// indices of the beacon state. For example, genesisTime is the -// 0th field of the beacon state. This is helpful when we are -// updating the Merkle branches up the trie representation -// of the beacon state. The below field indexes correspond -// to the v1 state. -const ( - GenesisTime FieldIndex = iota - GenesisValidatorsRoot - Slot - Fork - LatestBlockHeader - BlockRoots - StateRoots - HistoricalRoots - Eth1Data - Eth1DataVotes - Eth1DepositIndex - Validators - Balances - RandaoMixes - Slashings - PreviousEpochAttestations - CurrentEpochAttestations - JustificationBits - PreviousJustifiedCheckpoint - CurrentJustifiedCheckpoint - FinalizedCheckpoint - // State Fields Added in Altair. - InactivityScores - CurrentSyncCommittee - NextSyncCommittee - // State fields added in Bellatrix. - LatestExecutionPayloadHeader - // State fields added in Capella - LatestExecutionPayloadHeaderCapella - NextWithdrawalIndex - NextWithdrawalValidatorIndex -) - -// Altair fields which replaced previous phase 0 fields. -const ( - // Epoch Attestations is switched with participation bits in Altair. - PreviousEpochParticipationBits = PreviousEpochAttestations - CurrentEpochParticipationBits = CurrentEpochAttestations -) diff --git a/beacon-chain/state/types/types_test.go b/beacon-chain/state/types/types_test.go deleted file mode 100644 index 43716a268d..0000000000 --- a/beacon-chain/state/types/types_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package types - -import ( - "testing" - - "github.com/prysmaticlabs/prysm/v3/testing/assert" -) - -func TestStateFieldIndexes(t *testing.T) { - assert.Equal(t, FieldIndex(0), GenesisTime) - assert.Equal(t, FieldIndex(1), GenesisValidatorsRoot) - assert.Equal(t, FieldIndex(2), Slot) - assert.Equal(t, FieldIndex(3), Fork) - assert.Equal(t, FieldIndex(4), LatestBlockHeader) - assert.Equal(t, FieldIndex(5), BlockRoots) - assert.Equal(t, FieldIndex(6), StateRoots) - assert.Equal(t, FieldIndex(7), HistoricalRoots) - assert.Equal(t, FieldIndex(8), Eth1Data) - assert.Equal(t, FieldIndex(9), Eth1DataVotes) - assert.Equal(t, FieldIndex(10), Eth1DepositIndex) - assert.Equal(t, FieldIndex(11), Validators) - assert.Equal(t, FieldIndex(12), Balances) - assert.Equal(t, FieldIndex(13), RandaoMixes) - assert.Equal(t, FieldIndex(14), Slashings) - assert.Equal(t, FieldIndex(15), PreviousEpochAttestations) - assert.Equal(t, FieldIndex(15), PreviousEpochParticipationBits) - assert.Equal(t, FieldIndex(16), CurrentEpochAttestations) - assert.Equal(t, FieldIndex(16), CurrentEpochParticipationBits) - assert.Equal(t, FieldIndex(17), JustificationBits) - assert.Equal(t, FieldIndex(18), PreviousJustifiedCheckpoint) - assert.Equal(t, FieldIndex(19), CurrentJustifiedCheckpoint) - assert.Equal(t, FieldIndex(20), FinalizedCheckpoint) - assert.Equal(t, FieldIndex(21), InactivityScores) - assert.Equal(t, FieldIndex(22), CurrentSyncCommittee) - assert.Equal(t, FieldIndex(23), NextSyncCommittee) -} diff --git a/beacon-chain/sync/backfill/status.go b/beacon-chain/sync/backfill/status.go index 440ae44d5a..ac48c31d15 100644 --- a/beacon-chain/sync/backfill/status.go +++ b/beacon-chain/sync/backfill/status.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/db" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // NewStatus correctly initializes a Status value with the required database value. @@ -23,8 +23,8 @@ func NewStatus(store BackfillDB) *Status { // end of the missing block range via the Advance() method, to check whether a Slot is missing from the database // via the SlotCovered() method, and to see the current StartGap() and EndGap(). type Status struct { - start types.Slot - end types.Slot + start primitives.Slot + end primitives.Slot store BackfillDB genesisSync bool } @@ -32,7 +32,7 @@ type Status struct { // SlotCovered uses StartGap() and EndGap() to determine if the given slot is covered by the current chain history. // If the slot is <= StartGap(), or >= EndGap(), the result is true. // If the slot is between StartGap() and EndGap(), the result is false. -func (s *Status) SlotCovered(sl types.Slot) bool { +func (s *Status) SlotCovered(sl primitives.Slot) bool { // short circuit if the node was synced from genesis if s.genesisSync { return true @@ -44,12 +44,12 @@ func (s *Status) SlotCovered(sl types.Slot) bool { } // StartGap returns the slot at the beginning of the range that needs to be backfilled. -func (s *Status) StartGap() types.Slot { +func (s *Status) StartGap() primitives.Slot { return s.start } // EndGap returns the slot at the end of the range that needs to be backfilled. -func (s *Status) EndGap() types.Slot { +func (s *Status) EndGap() primitives.Slot { return s.end } @@ -58,7 +58,7 @@ var ErrAdvancePastOrigin = errors.New("cannot advance backfill Status beyond the // Advance advances the backfill position to the given slot & root. // It updates the backfill block root entry in the database, // and also updates the Status value's copy of the backfill position slot. -func (s *Status) Advance(ctx context.Context, upTo types.Slot, root [32]byte) error { +func (s *Status) Advance(ctx context.Context, upTo primitives.Slot, root [32]byte) error { if upTo > s.end { return errors.Wrapf(ErrAdvancePastOrigin, "advance slot=%d, origin slot=%d", upTo, s.end) } diff --git a/beacon-chain/sync/backfill/status_test.go b/beacon-chain/sync/backfill/status_test.go index 7a1bd108c8..f57864d817 100644 --- a/beacon-chain/sync/backfill/status_test.go +++ b/beacon-chain/sync/backfill/status_test.go @@ -10,7 +10,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" ) @@ -65,7 +65,7 @@ func (db *mockBackfillDB) Block(ctx context.Context, blockRoot [32]byte) (interf func TestSlotCovered(t *testing.T) { cases := []struct { name string - slot types.Slot + slot primitives.Slot status *Status result bool }{ @@ -142,7 +142,7 @@ func goodBlockRoot(root [32]byte) func(ctx context.Context) ([32]byte, error) { } } -func setupTestBlock(slot types.Slot) (interfaces.SignedBeaconBlock, error) { +func setupTestBlock(slot primitives.Slot) (interfaces.SignedBeaconBlock, error) { bRaw := util.NewBeaconBlock() b, err := blocks.NewSignedBeaconBlock(bRaw) if err != nil { @@ -155,13 +155,13 @@ func TestReload(t *testing.T) { ctx := context.Background() derp := errors.New("derp") - originSlot := types.Slot(100) + originSlot := primitives.Slot(100) var originRoot [32]byte copy(originRoot[:], []byte{0x01}) originBlock, err := setupTestBlock(originSlot) require.NoError(t, err) - backfillSlot := types.Slot(50) + backfillSlot := primitives.Slot(50) var backfillRoot [32]byte copy(originRoot[:], []byte{0x02}) backfillBlock, err := setupTestBlock(backfillSlot) diff --git a/beacon-chain/sync/broadcast_bls_changes.go b/beacon-chain/sync/broadcast_bls_changes.go index 045fc9c2a5..e87541649b 100644 --- a/beacon-chain/sync/broadcast_bls_changes.go +++ b/beacon-chain/sync/broadcast_bls_changes.go @@ -3,12 +3,12 @@ package sync import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/time/slots" ) // This routine broadcasts all known BLS changes at the Capella fork. -func (s *Service) broadcastBLSChanges(currSlot types.Slot) error { +func (s *Service) broadcastBLSChanges(currSlot primitives.Slot) error { capellaSlotStart, err := slots.EpochStart(params.BeaconConfig().CapellaForkEpoch) if err != nil { // only possible error is an overflow, so we exit early from the method diff --git a/beacon-chain/sync/fork_watcher.go b/beacon-chain/sync/fork_watcher.go index ca619bf698..731e02eb5c 100644 --- a/beacon-chain/sync/fork_watcher.go +++ b/beacon-chain/sync/fork_watcher.go @@ -4,7 +4,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/network/forks" "github.com/prysmaticlabs/prysm/v3/time/slots" ) @@ -44,7 +44,7 @@ func (s *Service) forkWatcher() { // Checks if there is a fork in the next epoch and if there is // it registers the appropriate gossip and rpc topics. -func (s *Service) registerForUpcomingFork(currEpoch types.Epoch) error { +func (s *Service) registerForUpcomingFork(currEpoch primitives.Epoch) error { genRoot := s.cfg.chain.GenesisValidatorsRoot() isNextForkEpoch, err := forks.IsForkNextEpoch(s.cfg.chain.GenesisTime(), genRoot[:]) if err != nil { @@ -72,7 +72,7 @@ func (s *Service) registerForUpcomingFork(currEpoch types.Epoch) error { // Checks if there was a fork in the previous epoch, and if there // was then we deregister the topics from that particular fork. -func (s *Service) deregisterFromPastFork(currEpoch types.Epoch) error { +func (s *Service) deregisterFromPastFork(currEpoch primitives.Epoch) error { genRoot := s.cfg.chain.GenesisValidatorsRoot() // This method takes care of the de-registration of // old gossip pubsub handlers. Once we are at the epoch diff --git a/beacon-chain/sync/fork_watcher_test.go b/beacon-chain/sync/fork_watcher_test.go index 1a3e169d66..9a0c7a93d0 100644 --- a/beacon-chain/sync/fork_watcher_test.go +++ b/beacon-chain/sync/fork_watcher_test.go @@ -11,7 +11,7 @@ import ( p2ptest "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/testing" mockSync "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/network/forks" "github.com/prysmaticlabs/prysm/v3/testing/assert" ) @@ -21,7 +21,7 @@ func TestService_CheckForNextEpochFork(t *testing.T) { tests := []struct { name string svcCreator func(t *testing.T) *Service - currEpoch types.Epoch + currEpoch primitives.Epoch wantErr bool postSvcCheck func(t *testing.T, s *Service) }{ @@ -155,7 +155,7 @@ func TestService_CheckForPreviousEpochFork(t *testing.T) { tests := []struct { name string svcCreator func(t *testing.T) *Service - currEpoch types.Epoch + currEpoch primitives.Epoch wantErr bool postSvcCheck func(t *testing.T, s *Service) }{ diff --git a/beacon-chain/sync/initial-sync/blocks_fetcher.go b/beacon-chain/sync/initial-sync/blocks_fetcher.go index 8e10b6d1a7..0d8f1576f4 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher.go @@ -15,7 +15,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" leakybucket "github.com/prysmaticlabs/prysm/v3/container/leaky-bucket" "github.com/prysmaticlabs/prysm/v3/crypto/rand" "github.com/prysmaticlabs/prysm/v3/math" @@ -97,7 +97,7 @@ type peerLock struct { // fetchRequestParams holds parameters necessary to schedule a fetch request. type fetchRequestParams struct { ctx context.Context // if provided, it is used instead of global fetcher's context - start types.Slot // starting slot + start primitives.Slot // starting slot count uint64 // how many slots to receive (fetcher may return fewer slots) } @@ -105,7 +105,7 @@ type fetchRequestParams struct { // Valid usage pattern will be to check whether result's `err` is nil, before using `blocks`. type fetchRequestResponse struct { pid peer.ID - start types.Slot + start primitives.Slot count uint64 blocks []interfaces.SignedBeaconBlock err error @@ -222,7 +222,7 @@ func (f *blocksFetcher) loop() { } // scheduleRequest adds request to incoming queue. -func (f *blocksFetcher) scheduleRequest(ctx context.Context, start types.Slot, count uint64) error { +func (f *blocksFetcher) scheduleRequest(ctx context.Context, start primitives.Slot, count uint64) error { if ctx.Err() != nil { return ctx.Err() } @@ -241,7 +241,7 @@ func (f *blocksFetcher) scheduleRequest(ctx context.Context, start types.Slot, c } // handleRequest parses fetch request and forwards it to response builder. -func (f *blocksFetcher) handleRequest(ctx context.Context, start types.Slot, count uint64) *fetchRequestResponse { +func (f *blocksFetcher) handleRequest(ctx context.Context, start primitives.Slot, count uint64) *fetchRequestResponse { ctx, span := trace.StartSpan(ctx, "initialsync.handleRequest") defer span.End() @@ -280,7 +280,7 @@ func (f *blocksFetcher) handleRequest(ctx context.Context, start types.Slot, cou // fetchBlocksFromPeer fetches blocks from a single randomly selected peer. func (f *blocksFetcher) fetchBlocksFromPeer( ctx context.Context, - start types.Slot, count uint64, + start primitives.Slot, count uint64, peers []peer.ID, ) ([]interfaces.SignedBeaconBlock, peer.ID, error) { ctx, span := trace.StartSpan(ctx, "initialsync.fetchBlocksFromPeer") diff --git a/beacon-chain/sync/initial-sync/blocks_fetcher_peers_test.go b/beacon-chain/sync/initial-sync/blocks_fetcher_peers_test.go index 7dfab5de41..833d6b4ccd 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher_peers_test.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher_peers_test.go @@ -11,7 +11,7 @@ import ( "github.com/libp2p/go-libp2p/core/peer" "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/peers/scorers" "github.com/prysmaticlabs/prysm/v3/cmd/beacon-chain/flags" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" leakybucket "github.com/prysmaticlabs/prysm/v3/container/leaky-bucket" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -230,7 +230,7 @@ func TestBlocksFetcher_filterPeers(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - mc, p2p, _ := initializeTestServices(t, []types.Slot{}, []*peerData{}) + mc, p2p, _ := initializeTestServices(t, []primitives.Slot{}, []*peerData{}) fetcher := newBlocksFetcher(context.Background(), &blocksFetcherConfig{ chain: mc, p2p: p2p, diff --git a/beacon-chain/sync/initial-sync/blocks_fetcher_test.go b/beacon-chain/sync/initial-sync/blocks_fetcher_test.go index fc1000290a..0a7f23512f 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher_test.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher_test.go @@ -19,7 +19,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" leakybucket "github.com/prysmaticlabs/prysm/v3/container/leaky-bucket" "github.com/prysmaticlabs/prysm/v3/container/slice" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -32,7 +32,7 @@ import ( ) func TestBlocksFetcher_InitStartStop(t *testing.T) { - mc, p2p, _ := initializeTestServices(t, []types.Slot{}, []*peerData{}) + mc, p2p, _ := initializeTestServices(t, []primitives.Slot{}, []*peerData{}) ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -100,8 +100,8 @@ func TestBlocksFetcher_InitStartStop(t *testing.T) { } func TestBlocksFetcher_RoundRobin(t *testing.T) { - slotsInBatch := types.Slot(flags.Get().BlockBatchLimit) - requestsGenerator := func(start, end, batchSize types.Slot) []*fetchRequestParams { + slotsInBatch := primitives.Slot(flags.Get().BlockBatchLimit) + requestsGenerator := func(start, end, batchSize primitives.Slot) []*fetchRequestParams { var requests []*fetchRequestParams for i := start; i <= end; i += batchSize { requests = append(requests, &fetchRequestParams{ @@ -113,7 +113,7 @@ func TestBlocksFetcher_RoundRobin(t *testing.T) { } tests := []struct { name string - expectedBlockSlots []types.Slot + expectedBlockSlots []primitives.Slot peers []*peerData requests []*fetchRequestParams }{ @@ -343,7 +343,7 @@ func TestBlocksFetcher_RoundRobin(t *testing.T) { return blocks[i].Block().Slot() < blocks[j].Block().Slot() }) - ss := make([]types.Slot, len(blocks)) + ss := make([]primitives.Slot, len(blocks)) for i, block := range blocks { ss[i] = block.Block().Slot() } @@ -357,7 +357,7 @@ func TestBlocksFetcher_RoundRobin(t *testing.T) { t.Errorf("Too many blocks returned. Wanted %d got %d", maxExpectedBlocks, len(blocks)) } assert.Equal(t, len(tt.expectedBlockSlots), len(blocks), "Processes wrong number of blocks") - var receivedBlockSlots []types.Slot + var receivedBlockSlots []primitives.Slot for _, blk := range blocks { receivedBlockSlots = append(receivedBlockSlots, blk.Block().Slot()) } @@ -395,10 +395,10 @@ func TestBlocksFetcher_scheduleRequest(t *testing.T) { func TestBlocksFetcher_handleRequest(t *testing.T) { blockBatchLimit := flags.Get().BlockBatchLimit chainConfig := struct { - expectedBlockSlots []types.Slot + expectedBlockSlots []primitives.Slot peers []*peerData }{ - expectedBlockSlots: makeSequence(1, types.Slot(blockBatchLimit)), + expectedBlockSlots: makeSequence(1, primitives.Slot(blockBatchLimit)), peers: []*peerData{ { blocks: makeSequence(1, 320), @@ -461,7 +461,7 @@ func TestBlocksFetcher_handleRequest(t *testing.T) { t.Errorf("incorrect number of blocks returned, expected: %v, got: %v", blockBatchLimit, len(blocks)) } - var receivedBlockSlots []types.Slot + var receivedBlockSlots []primitives.Slot for _, blk := range blocks { receivedBlockSlots = append(receivedBlockSlots, blk.Block().Slot()) } @@ -475,7 +475,7 @@ func TestBlocksFetcher_handleRequest(t *testing.T) { func TestBlocksFetcher_requestBeaconBlocksByRange(t *testing.T) { blockBatchLimit := flags.Get().BlockBatchLimit chainConfig := struct { - expectedBlockSlots []types.Slot + expectedBlockSlots []primitives.Slot peers []*peerData }{ expectedBlockSlots: makeSequence(1, 320), @@ -644,7 +644,7 @@ func TestBlocksFetcher_requestBlocksFromPeerReturningInvalidBlocks(t *testing.T) }, handlerGenFn: func(req *ethpb.BeaconBlocksByRangeRequest) func(stream network.Stream) { return func(stream network.Stream) { - for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += primitives.Slot(req.Step) { blk := util.NewBeaconBlock() blk.Block.Slot = i mchain := &mock.ChainService{Genesis: time.Now(), ValidatorsRoot: [32]byte{}} @@ -668,7 +668,7 @@ func TestBlocksFetcher_requestBlocksFromPeerReturningInvalidBlocks(t *testing.T) }, handlerGenFn: func(req *ethpb.BeaconBlocksByRangeRequest) func(stream network.Stream) { return func(stream network.Stream) { - for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step+1); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step+1); i += primitives.Slot(req.Step) { blk := util.NewBeaconBlock() blk.Block.Slot = i chain := &mock.ChainService{Genesis: time.Now(), ValidatorsRoot: [32]byte{}} @@ -755,7 +755,7 @@ func TestBlocksFetcher_requestBlocksFromPeerReturningInvalidBlocks(t *testing.T) defer func() { assert.NoError(t, stream.Close()) }() - for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += primitives.Slot(req.Step) { blk := util.NewBeaconBlock() chain := &mock.ChainService{Genesis: time.Now(), ValidatorsRoot: [32]byte{}} // Patch mid block, with invalid slot number. @@ -790,7 +790,7 @@ func TestBlocksFetcher_requestBlocksFromPeerReturningInvalidBlocks(t *testing.T) defer func() { assert.NoError(t, stream.Close()) }() - for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += primitives.Slot(req.Step) { blk := util.NewBeaconBlock() chain := &mock.ChainService{Genesis: time.Now(), ValidatorsRoot: [32]byte{}} // Patch mid block, with invalid slot number. diff --git a/beacon-chain/sync/initial-sync/blocks_fetcher_utils.go b/beacon-chain/sync/initial-sync/blocks_fetcher_utils.go index 02d8bbcc6f..cb32c6c2ac 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher_utils.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher_utils.go @@ -11,7 +11,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" p2ppb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" "github.com/sirupsen/logrus" @@ -31,7 +31,7 @@ type forkData struct { // non-skipped slot. This shouldn't be a problem, as in case of adversary peer, we might get incorrect // data anyway, so code that relies on this function must be robust enough to re-request, if no progress // is possible with a returned value. -func (f *blocksFetcher) nonSkippedSlotAfter(ctx context.Context, slot types.Slot) (types.Slot, error) { +func (f *blocksFetcher) nonSkippedSlotAfter(ctx context.Context, slot primitives.Slot) (primitives.Slot, error) { ctx, span := trace.StartSpan(ctx, "initialsync.nonSkippedSlotAfter") defer span.End() @@ -55,8 +55,8 @@ func (f *blocksFetcher) nonSkippedSlotAfter(ctx context.Context, slot types.Slot // 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 types.Slot, peers []peer.ID, targetEpoch types.Epoch, -) (types.Slot, error) { + ctx context.Context, slot primitives.Slot, peers []peer.ID, targetEpoch primitives.Epoch, +) (primitives.Slot, error) { // Exit early if no peers are ready. if len(peers) == 0 { return 0, errNoPeersAvailable @@ -65,7 +65,7 @@ func (f *blocksFetcher) nonSkippedSlotAfterWithPeersTarget( slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch pidInd := 0 - fetch := func(pid peer.ID, start types.Slot, count, step uint64) (types.Slot, error) { + fetch := func(pid peer.ID, start primitives.Slot, count, step uint64) (primitives.Slot, error) { req := &p2ppb.BeaconBlocksByRangeRequest{ StartSlot: start, Count: count, @@ -147,7 +147,7 @@ func (f *blocksFetcher) nonSkippedSlotAfterWithPeersTarget( // findFork queries all peers that have higher head slot, in an attempt to find // ones that feature blocks from alternative branches. Once found, peer is further queried // to find common ancestor slot. On success, all obtained blocks and peer is returned. -func (f *blocksFetcher) findFork(ctx context.Context, slot types.Slot) (*forkData, error) { +func (f *blocksFetcher) findFork(ctx context.Context, slot primitives.Slot) (*forkData, error) { ctx, span := trace.StartSpan(ctx, "initialsync.findFork") defer span.End() @@ -201,7 +201,7 @@ func (f *blocksFetcher) findFork(ctx context.Context, slot types.Slot) (*forkDat } // findForkWithPeer loads some blocks from a peer in an attempt to find alternative blocks. -func (f *blocksFetcher) findForkWithPeer(ctx context.Context, pid peer.ID, slot types.Slot) (*forkData, error) { +func (f *blocksFetcher) findForkWithPeer(ctx context.Context, pid peer.ID, slot primitives.Slot) (*forkData, error) { // Safe-guard, since previous epoch is used when calculating. slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch if slot < slotsPerEpoch*2 { @@ -289,7 +289,7 @@ func (f *blocksFetcher) findAncestor(ctx context.Context, pid peer.ID, b interfa } // bestFinalizedSlot returns the highest finalized slot of the majority of connected peers. -func (f *blocksFetcher) bestFinalizedSlot() types.Slot { +func (f *blocksFetcher) bestFinalizedSlot() primitives.Slot { cp := f.chain.FinalizedCheckpt() finalizedEpoch, _ := f.p2p.Peers().BestFinalized( params.BeaconConfig().MaxPeersToSync, cp.Epoch) @@ -297,7 +297,7 @@ func (f *blocksFetcher) bestFinalizedSlot() types.Slot { } // bestNonFinalizedSlot returns the highest non-finalized slot of enough number of connected peers. -func (f *blocksFetcher) bestNonFinalizedSlot() types.Slot { +func (f *blocksFetcher) bestNonFinalizedSlot() primitives.Slot { headEpoch := slots.ToEpoch(f.chain.HeadSlot()) targetEpoch, _ := f.p2p.Peers().BestNonFinalized(flags.Get().MinimumSyncPeers*2, headEpoch) return params.BeaconConfig().SlotsPerEpoch.Mul(uint64(targetEpoch)) @@ -305,7 +305,7 @@ func (f *blocksFetcher) bestNonFinalizedSlot() types.Slot { // 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 types.Epoch, peers []peer.ID) { +func (f *blocksFetcher) calculateHeadAndTargetEpochs() (headEpoch, targetEpoch primitives.Epoch, peers []peer.ID) { if f.mode == modeStopOnFinalizedEpoch { cp := f.chain.FinalizedCheckpt() headEpoch = cp.Epoch 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 c513dead15..5775ac0c43 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher_utils_test.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher_utils_test.go @@ -16,7 +16,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" leakybucket "github.com/prysmaticlabs/prysm/v3/container/leaky-bucket" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -48,7 +48,7 @@ func TestBlocksFetcher_nonSkippedSlotAfter(t *testing.T) { peers: peersGen(5), } - mc, p2p, _ := initializeTestServices(t, []types.Slot{}, chainConfig.peers) + mc, p2p, _ := initializeTestServices(t, []primitives.Slot{}, chainConfig.peers) ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -60,7 +60,7 @@ func TestBlocksFetcher_nonSkippedSlotAfter(t *testing.T) { }, ) fetcher.rateLimiter = leakybucket.NewCollector(6400, 6400, 1*time.Second, false) - seekSlots := map[types.Slot]types.Slot{ + seekSlots := map[primitives.Slot]primitives.Slot{ 0: 1, 10: 11, 31: 32, @@ -85,8 +85,8 @@ func TestBlocksFetcher_nonSkippedSlotAfter(t *testing.T) { } t.Run("test isolated non-skipped slot", func(t *testing.T) { - seekSlot := types.Slot(51264) - expectedSlot := types.Slot(55000) + seekSlot := primitives.Slot(51264) + expectedSlot := primitives.Slot(55000) var wg sync.WaitGroup wg.Add(1) @@ -137,13 +137,13 @@ func TestBlocksFetcher_nonSkippedSlotAfter(t *testing.T) { fetcher.mode = modeStopOnFinalizedEpoch slot, err := fetcher.nonSkippedSlotAfter(ctx, 160) assert.ErrorContains(t, errSlotIsTooHigh.Error(), err) - assert.Equal(t, types.Slot(0), slot) + assert.Equal(t, primitives.Slot(0), slot) fetcher.mode = modeNonConstrained require.NoError(t, mc.State.SetSlot(20*params.BeaconConfig().SlotsPerEpoch)) slot, err = fetcher.nonSkippedSlotAfter(ctx, 160) assert.ErrorContains(t, errSlotIsTooHigh.Error(), err) - assert.Equal(t, types.Slot(0), slot) + assert.Equal(t, primitives.Slot(0), slot) }) } @@ -159,7 +159,7 @@ func TestBlocksFetcher_findFork(t *testing.T) { // Chain contains blocks from 8 epochs (from 0 to 7, 256 is the start slot of epoch8). chain1 := extendBlockSequence(t, []*ethpb.SignedBeaconBlock{}, 250) - finalizedSlot := types.Slot(63) + finalizedSlot := primitives.Slot(63) finalizedEpoch := slots.ToEpoch(finalizedSlot) genesisBlock := chain1[0] @@ -204,7 +204,7 @@ func TestBlocksFetcher_findFork(t *testing.T) { pidInd := 0 for i := uint64(1); i < uint64(len(chain1)); i += blockBatchLimit { req := ðpb.BeaconBlocksByRangeRequest{ - StartSlot: types.Slot(i), + StartSlot: primitives.Slot(i), Step: 1, Count: blockBatchLimit, } @@ -223,7 +223,7 @@ func TestBlocksFetcher_findFork(t *testing.T) { require.NoError(t, err) require.Equal(t, true, beaconDB.HasBlock(ctx, blkRoot) || mc.HasBlock(ctx, blkRoot)) } - assert.Equal(t, types.Slot(250), mc.HeadSlot()) + assert.Equal(t, primitives.Slot(250), mc.HeadSlot()) // Assert no blocks on further requests, disallowing to progress. req := ðpb.BeaconBlocksByRangeRequest{ @@ -262,7 +262,7 @@ func TestBlocksFetcher_findFork(t *testing.T) { util.SaveBlock(t, ctx, beaconDB, blk) require.NoError(t, st.SetSlot(blk.Block.Slot)) } - forkSlot := types.Slot(129) + forkSlot := primitives.Slot(129) chain2 := extendBlockSequence(t, chain1[:forkSlot], 165) // Assert that forked blocks from chain2 are unknown. assert.Equal(t, 294, len(chain2)) @@ -290,7 +290,7 @@ func TestBlocksFetcher_findFork(t *testing.T) { require.NoError(t, st.SetSlot(blk.Block().Slot())) } assert.Equal(t, forkSlot.Add(uint64(len(fork.blocks)-1)), mc.HeadSlot()) - for i := forkSlot.Add(uint64(len(fork.blocks))); i < types.Slot(len(chain2)); i++ { + for i := forkSlot.Add(uint64(len(fork.blocks))); i < primitives.Slot(len(chain2)); i++ { blk := chain2[i] require.Equal(t, blk.Block.Slot, i, "incorrect block selected for slot %d", i) // Only save is parent block exists. @@ -383,7 +383,7 @@ func TestBlocksFetcher_findForkWithPeer(t *testing.T) { }) t.Run("first block is diverging - backtrack successfully", func(t *testing.T) { - forkedSlot := types.Slot(24) + forkedSlot := primitives.Slot(24) altBlocks := extendBlockSequence(t, knownBlocks[:forkedSlot], 128) p2 := connectPeerHavingBlocks(t, p1, altBlocks, 128, p1.Peers()) time.Sleep(100 * time.Millisecond) @@ -408,7 +408,7 @@ func TestBlocksFetcher_findForkWithPeer(t *testing.T) { }) t.Run("mid block is diverging - no backtrack is necessary", func(t *testing.T) { - forkedSlot := types.Slot(60) + forkedSlot := primitives.Slot(60) altBlocks := extendBlockSequence(t, knownBlocks[:forkedSlot], 128) p2 := connectPeerHavingBlocks(t, p1, altBlocks, 128, p1.Peers()) time.Sleep(100 * time.Millisecond) @@ -418,7 +418,7 @@ func TestBlocksFetcher_findForkWithPeer(t *testing.T) { fork, err := fetcher.findForkWithPeer(ctx, p2, 64) require.NoError(t, err) require.Equal(t, 64, len(fork.blocks)) - assert.Equal(t, types.Slot(33), fork.blocks[0].Block().Slot()) + assert.Equal(t, primitives.Slot(33), fork.blocks[0].Block().Slot()) }) } @@ -427,7 +427,7 @@ func TestBlocksFetcher_findAncestor(t *testing.T) { p2p := p2pt.NewTestP2P(t) knownBlocks := extendBlockSequence(t, []*ethpb.SignedBeaconBlock{}, 128) - finalizedSlot := types.Slot(63) + finalizedSlot := primitives.Slot(63) finalizedEpoch := slots.ToEpoch(finalizedSlot) genesisBlock := knownBlocks[0] @@ -494,10 +494,10 @@ func TestBlocksFetcher_currentHeadAndTargetEpochs(t *testing.T) { name string syncMode syncMode peers []*peerData - ourFinalizedEpoch types.Epoch - ourHeadSlot types.Slot - expectedHeadEpoch types.Epoch - targetEpoch types.Epoch + ourFinalizedEpoch primitives.Epoch + ourHeadSlot primitives.Slot + expectedHeadEpoch primitives.Epoch + targetEpoch primitives.Epoch targetEpochSupport int }{ { @@ -569,7 +569,7 @@ func TestBlocksFetcher_currentHeadAndTargetEpochs(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - mc, p2p, _ := initializeTestServices(t, []types.Slot{}, tt.peers) + mc, p2p, _ := initializeTestServices(t, []primitives.Slot{}, tt.peers) ctx, cancel := context.WithCancel(context.Background()) defer cancel() fetcher := newBlocksFetcher( diff --git a/beacon-chain/sync/initial-sync/blocks_queue.go b/beacon-chain/sync/initial-sync/blocks_queue.go index a0122daa9f..9f70775434 100644 --- a/beacon-chain/sync/initial-sync/blocks_queue.go +++ b/beacon-chain/sync/initial-sync/blocks_queue.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p" beaconsync "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/time/slots" "github.com/sirupsen/logrus" ) @@ -62,7 +62,7 @@ type syncMode uint8 type blocksQueueConfig struct { blocksFetcher *blocksFetcher chain blockchainService - highestExpectedSlot types.Slot + highestExpectedSlot primitives.Slot p2p p2p.P2P db db.ReadOnlyDatabase mode syncMode @@ -76,13 +76,13 @@ type blocksQueue struct { smm *stateMachineManager blocksFetcher *blocksFetcher chain blockchainService - highestExpectedSlot types.Slot + highestExpectedSlot primitives.Slot mode syncMode exitConditions struct { noRequiredPeersErrRetries int } fetchedData chan *blocksQueueFetchedData // output channel for ready blocks - staleEpochs map[types.Epoch]uint8 // counter to keep track of stale FSMs + staleEpochs map[primitives.Epoch]uint8 // counter to keep track of stale FSMs quit chan struct{} // termination notifier } @@ -125,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[types.Epoch]uint8), + staleEpochs: make(map[primitives.Epoch]uint8), } // Configure state machines. @@ -180,7 +180,7 @@ func (q *blocksQueue) loop() { startSlot -= startBackSlots } blocksPerRequest := q.blocksFetcher.blocksPerPeriod - for i := startSlot; i < startSlot.Add(blocksPerRequest*lookaheadSteps); i += types.Slot(blocksPerRequest) { + for i := startSlot; i < startSlot.Add(blocksPerRequest*lookaheadSteps); i += primitives.Slot(blocksPerRequest) { q.smm.addStateMachine(i) } diff --git a/beacon-chain/sync/initial-sync/blocks_queue_test.go b/beacon-chain/sync/initial-sync/blocks_queue_test.go index d46dcda74f..1f6237e353 100644 --- a/beacon-chain/sync/initial-sync/blocks_queue_test.go +++ b/beacon-chain/sync/initial-sync/blocks_queue_test.go @@ -15,7 +15,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" leakybucket "github.com/prysmaticlabs/prysm/v3/container/leaky-bucket" "github.com/prysmaticlabs/prysm/v3/container/slice" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -30,7 +30,7 @@ import ( func TestBlocksQueue_InitStartStop(t *testing.T) { blockBatchLimit := flags.Get().BlockBatchLimit - mc, p2p, _ := initializeTestServices(t, []types.Slot{}, []*peerData{}) + mc, p2p, _ := initializeTestServices(t, []primitives.Slot{}, []*peerData{}) ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -44,7 +44,7 @@ func TestBlocksQueue_InitStartStop(t *testing.T) { defer cancel() queue := newBlocksQueue(ctx, &blocksQueueConfig{ chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) assert.ErrorContains(t, errQueueTakesTooLongToStop.Error(), queue.stop()) }) @@ -54,7 +54,7 @@ func TestBlocksQueue_InitStartStop(t *testing.T) { defer cancel() queue := newBlocksQueue(ctx, &blocksQueueConfig{ chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) assert.NoError(t, queue.start()) }) @@ -64,7 +64,7 @@ func TestBlocksQueue_InitStartStop(t *testing.T) { defer cancel() queue := newBlocksQueue(ctx, &blocksQueueConfig{ chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) assert.NoError(t, queue.start()) assert.ErrorContains(t, errQueueTakesTooLongToStop.Error(), queue.stop()) @@ -76,7 +76,7 @@ func TestBlocksQueue_InitStartStop(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) assert.NoError(t, queue.start()) @@ -100,7 +100,7 @@ func TestBlocksQueue_InitStartStop(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) assert.NoError(t, queue.start()) assert.NoError(t, queue.stop()) @@ -113,7 +113,7 @@ func TestBlocksQueue_InitStartStop(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) assert.NoError(t, queue.start()) assert.NoError(t, queue.stop()) @@ -125,7 +125,7 @@ func TestBlocksQueue_InitStartStop(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) assert.NoError(t, queue.start()) cancel() @@ -141,8 +141,8 @@ func TestBlocksQueue_Loop(t *testing.T) { }() tests := []struct { name string - highestExpectedSlot types.Slot - expectedBlockSlots []types.Slot + highestExpectedSlot primitives.Slot + expectedBlockSlots []primitives.Slot peers []*peerData }{ { @@ -287,7 +287,7 @@ func TestBlocksQueue_Loop(t *testing.T) { len(tt.expectedBlockSlots), queue.chain.HeadSlot()) } assert.Equal(t, len(tt.expectedBlockSlots), len(blocks), "Processes wrong number of blocks") - var receivedBlockSlots []types.Slot + var receivedBlockSlots []primitives.Slot for _, blk := range blocks { receivedBlockSlots = append(receivedBlockSlots, blk.Block().Slot()) } @@ -301,7 +301,7 @@ func TestBlocksQueue_Loop(t *testing.T) { func TestBlocksQueue_onScheduleEvent(t *testing.T) { blockBatchLimit := flags.Get().BlockBatchLimit - mc, p2p, _ := initializeTestServices(t, []types.Slot{}, []*peerData{}) + mc, p2p, _ := initializeTestServices(t, []primitives.Slot{}, []*peerData{}) ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -315,7 +315,7 @@ func TestBlocksQueue_onScheduleEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) handlerFn := queue.onScheduleEvent(ctx) cancel() @@ -330,7 +330,7 @@ func TestBlocksQueue_onScheduleEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) invalidStates := []stateID{stateScheduled, stateDataParsed, stateSkipped, stateSent} @@ -350,7 +350,7 @@ func TestBlocksQueue_onScheduleEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) handlerFn := queue.onScheduleEvent(ctx) @@ -366,7 +366,7 @@ func TestBlocksQueue_onScheduleEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) // Cancel to make fetcher spit error when trying to schedule next FSM. requestCtx, requestCtxCancel := context.WithCancel(context.Background()) @@ -383,7 +383,7 @@ func TestBlocksQueue_onScheduleEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) handlerFn := queue.onScheduleEvent(ctx) updatedState, err := handlerFn(&stateMachine{ @@ -396,7 +396,7 @@ func TestBlocksQueue_onScheduleEvent(t *testing.T) { func TestBlocksQueue_onDataReceivedEvent(t *testing.T) { blockBatchLimit := flags.Get().BlockBatchLimit - mc, p2p, _ := initializeTestServices(t, []types.Slot{}, []*peerData{}) + mc, p2p, _ := initializeTestServices(t, []primitives.Slot{}, []*peerData{}) ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -410,7 +410,7 @@ func TestBlocksQueue_onDataReceivedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) handlerFn := queue.onDataReceivedEvent(ctx) cancel() @@ -425,7 +425,7 @@ func TestBlocksQueue_onDataReceivedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) invalidStates := []stateID{stateNew, stateDataParsed, stateSkipped, stateSent} @@ -445,7 +445,7 @@ func TestBlocksQueue_onDataReceivedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) handlerFn := queue.onDataReceivedEvent(ctx) @@ -460,7 +460,7 @@ func TestBlocksQueue_onDataReceivedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) handlerFn := queue.onDataReceivedEvent(ctx) @@ -478,7 +478,7 @@ func TestBlocksQueue_onDataReceivedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) // Mark previous machine as skipped - to test effect of re-requesting. @@ -503,7 +503,7 @@ func TestBlocksQueue_onDataReceivedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) hook := logTest.NewGlobal() @@ -524,7 +524,7 @@ func TestBlocksQueue_onDataReceivedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) wsb, err := blocks.NewSignedBeaconBlock(util.NewBeaconBlock()) require.NoError(t, err) @@ -553,7 +553,7 @@ func TestBlocksQueue_onDataReceivedEvent(t *testing.T) { func TestBlocksQueue_onReadyToSendEvent(t *testing.T) { blockBatchLimit := flags.Get().BlockBatchLimit - mc, p2p, _ := initializeTestServices(t, []types.Slot{}, []*peerData{}) + mc, p2p, _ := initializeTestServices(t, []primitives.Slot{}, []*peerData{}) ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -567,7 +567,7 @@ func TestBlocksQueue_onReadyToSendEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) handlerFn := queue.onReadyToSendEvent(ctx) cancel() @@ -582,7 +582,7 @@ func TestBlocksQueue_onReadyToSendEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) invalidStates := []stateID{stateNew, stateScheduled, stateSkipped, stateSent} @@ -602,7 +602,7 @@ func TestBlocksQueue_onReadyToSendEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) handlerFn := queue.onReadyToSendEvent(ctx) @@ -623,7 +623,7 @@ func TestBlocksQueue_onReadyToSendEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) wsb, err := blocks.NewSignedBeaconBlock(util.NewBeaconBlock()) require.NoError(t, err) @@ -650,7 +650,7 @@ func TestBlocksQueue_onReadyToSendEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) wsb, err := blocks.NewSignedBeaconBlock(util.NewBeaconBlock()) require.NoError(t, err) @@ -683,7 +683,7 @@ func TestBlocksQueue_onReadyToSendEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) wsb, err := blocks.NewSignedBeaconBlock(util.NewBeaconBlock()) require.NoError(t, err) @@ -705,7 +705,7 @@ func TestBlocksQueue_onReadyToSendEvent(t *testing.T) { func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { blockBatchLimit := flags.Get().BlockBatchLimit - mc, p2p, _ := initializeTestServices(t, []types.Slot{}, []*peerData{}) + mc, p2p, _ := initializeTestServices(t, []primitives.Slot{}, []*peerData{}) ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -719,7 +719,7 @@ func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) handlerFn := queue.onProcessSkippedEvent(ctx) cancel() @@ -734,7 +734,7 @@ func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) invalidStates := []stateID{stateNew, stateScheduled, stateDataParsed, stateSent} @@ -754,7 +754,7 @@ func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) queue.smm.addStateMachine(256) @@ -773,7 +773,7 @@ func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) queue.smm.addStateMachine(256) @@ -792,7 +792,7 @@ func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) queue.smm.addStateMachine(192) @@ -811,7 +811,7 @@ func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) queue.smm.addStateMachine(192) @@ -845,17 +845,17 @@ func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) startSlot := queue.chain.HeadSlot() blocksPerRequest := queue.blocksFetcher.blocksPerPeriod - for i := startSlot; i < startSlot.Add(blocksPerRequest*lookaheadSteps); i += types.Slot(blocksPerRequest) { + for i := startSlot; i < startSlot.Add(blocksPerRequest*lookaheadSteps); i += primitives.Slot(blocksPerRequest) { queue.smm.addStateMachine(i).setState(stateSkipped) } handlerFn := queue.onProcessSkippedEvent(ctx) - updatedState, err := handlerFn(queue.smm.machines[types.Slot(blocksPerRequest*(lookaheadSteps-1))], nil) + updatedState, err := handlerFn(queue.smm.machines[primitives.Slot(blocksPerRequest*(lookaheadSteps-1))], nil) assert.ErrorContains(t, "invalid range for non-skipped slot", err) assert.Equal(t, stateSkipped, updatedState) }) @@ -872,14 +872,14 @@ func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) - assert.Equal(t, types.Slot(blockBatchLimit), queue.highestExpectedSlot) + assert.Equal(t, primitives.Slot(blockBatchLimit), queue.highestExpectedSlot) startSlot := queue.chain.HeadSlot() blocksPerRequest := queue.blocksFetcher.blocksPerPeriod - var machineSlots []types.Slot - for i := startSlot; i < startSlot.Add(blocksPerRequest*lookaheadSteps); i += types.Slot(blocksPerRequest) { + var machineSlots []primitives.Slot + for i := startSlot; i < startSlot.Add(blocksPerRequest*lookaheadSteps); i += primitives.Slot(blocksPerRequest) { queue.smm.addStateMachine(i).setState(stateSkipped) machineSlots = append(machineSlots, i) } @@ -889,14 +889,14 @@ func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { } // Update head slot, so that machines are re-arranged starting from the next slot i.e. // there's no point to reset machines for some slot that has already been processed. - updatedSlot := types.Slot(100) + updatedSlot := primitives.Slot(100) defer func() { require.NoError(t, mc.State.SetSlot(0)) }() require.NoError(t, mc.State.SetSlot(updatedSlot)) handlerFn := queue.onProcessSkippedEvent(ctx) - updatedState, err := handlerFn(queue.smm.machines[types.Slot(blocksPerRequest*(lookaheadSteps-1))], nil) + updatedState, err := handlerFn(queue.smm.machines[primitives.Slot(blocksPerRequest*(lookaheadSteps-1))], nil) assert.NoError(t, err) assert.Equal(t, stateSkipped, updatedState) // Assert that machines have been re-arranged. @@ -907,7 +907,7 @@ func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { assert.Equal(t, true, ok) } // Assert highest expected slot is extended. - assert.Equal(t, types.Slot(blocksPerRequest*lookaheadSteps), queue.highestExpectedSlot) + assert.Equal(t, primitives.Slot(blocksPerRequest*lookaheadSteps), queue.highestExpectedSlot) }) t.Run("ready to update machines - unconstrained mode", func(t *testing.T) { @@ -922,15 +922,15 @@ func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) queue.mode = modeNonConstrained - assert.Equal(t, types.Slot(blockBatchLimit), queue.highestExpectedSlot) + assert.Equal(t, primitives.Slot(blockBatchLimit), queue.highestExpectedSlot) startSlot := queue.chain.HeadSlot() blocksPerRequest := queue.blocksFetcher.blocksPerPeriod - var machineSlots []types.Slot - for i := startSlot; i < startSlot.Add(blocksPerRequest*lookaheadSteps); i += types.Slot(blocksPerRequest) { + var machineSlots []primitives.Slot + for i := startSlot; i < startSlot.Add(blocksPerRequest*lookaheadSteps); i += primitives.Slot(blocksPerRequest) { queue.smm.addStateMachine(i).setState(stateSkipped) machineSlots = append(machineSlots, i) } @@ -940,11 +940,11 @@ func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { } // Update head slot, so that machines are re-arranged starting from the next slot i.e. // there's no point to reset machines for some slot that has already been processed. - updatedSlot := types.Slot(100) + updatedSlot := primitives.Slot(100) require.NoError(t, mc.State.SetSlot(updatedSlot)) handlerFn := queue.onProcessSkippedEvent(ctx) - updatedState, err := handlerFn(queue.smm.machines[types.Slot(blocksPerRequest*(lookaheadSteps-1))], nil) + updatedState, err := handlerFn(queue.smm.machines[primitives.Slot(blocksPerRequest*(lookaheadSteps-1))], nil) assert.NoError(t, err) assert.Equal(t, stateSkipped, updatedState) // Assert that machines have been re-arranged. @@ -955,13 +955,13 @@ func TestBlocksQueue_onProcessSkippedEvent(t *testing.T) { assert.Equal(t, true, ok) } // Assert highest expected slot is extended. - assert.Equal(t, types.Slot(blocksPerRequest*(lookaheadSteps+1)), queue.highestExpectedSlot) + assert.Equal(t, primitives.Slot(blocksPerRequest*(lookaheadSteps+1)), queue.highestExpectedSlot) }) } func TestBlocksQueue_onCheckStaleEvent(t *testing.T) { blockBatchLimit := flags.Get().BlockBatchLimit - mc, p2p, _ := initializeTestServices(t, []types.Slot{}, []*peerData{}) + mc, p2p, _ := initializeTestServices(t, []primitives.Slot{}, []*peerData{}) ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -975,7 +975,7 @@ func TestBlocksQueue_onCheckStaleEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) handlerFn := queue.onCheckStaleEvent(ctx) cancel() @@ -990,7 +990,7 @@ func TestBlocksQueue_onCheckStaleEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) invalidStates := []stateID{stateNew, stateScheduled, stateDataParsed, stateSkipped} @@ -1010,7 +1010,7 @@ func TestBlocksQueue_onCheckStaleEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) handlerFn := queue.onCheckStaleEvent(ctx) updatedState, err := handlerFn(&stateMachine{ @@ -1026,7 +1026,7 @@ func TestBlocksQueue_onCheckStaleEvent(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(blockBatchLimit), + highestExpectedSlot: primitives.Slot(blockBatchLimit), }) handlerFn := queue.onCheckStaleEvent(ctx) updatedState, err := handlerFn(&stateMachine{ @@ -1046,9 +1046,9 @@ func TestBlocksQueue_stuckInUnfavourableFork(t *testing.T) { // The chain1 contains 250 blocks and is a dead end. // The chain2 contains 296 blocks, with fork started at slot 128 of chain1. chain1 := extendBlockSequence(t, []*eth.SignedBeaconBlock{}, 250) - forkedSlot := types.Slot(201) + forkedSlot := primitives.Slot(201) chain2 := extendBlockSequence(t, chain1[:forkedSlot], 100) - finalizedSlot := types.Slot(63) + finalizedSlot := primitives.Slot(63) finalizedEpoch := slots.ToEpoch(finalizedSlot) genesisBlock := chain1[0] @@ -1085,7 +1085,7 @@ func TestBlocksQueue_stuckInUnfavourableFork(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(len(chain2) - 1), + highestExpectedSlot: primitives.Slot(len(chain2) - 1), mode: modeNonConstrained, }) @@ -1098,7 +1098,7 @@ func TestBlocksQueue_stuckInUnfavourableFork(t *testing.T) { require.NoError(t, st.SetSlot(blk.Block.Slot)) } } - require.Equal(t, types.Slot(len(chain1)-1), mc.HeadSlot()) + require.Equal(t, primitives.Slot(len(chain1)-1), mc.HeadSlot()) hook := logTest.NewGlobal() t.Run("unfavourable fork and no alternative branches", func(t *testing.T) { @@ -1119,8 +1119,8 @@ func TestBlocksQueue_stuckInUnfavourableFork(t *testing.T) { startSlot := mc.HeadSlot() + 1 blocksPerRequest := queue.blocksFetcher.blocksPerPeriod - machineSlots := make([]types.Slot, 0) - for i := startSlot; i < startSlot.Add(blocksPerRequest*lookaheadSteps); i += types.Slot(blocksPerRequest) { + machineSlots := make([]primitives.Slot, 0) + for i := startSlot; i < startSlot.Add(blocksPerRequest*lookaheadSteps); i += primitives.Slot(blocksPerRequest) { queue.smm.addStateMachine(i).setState(stateSkipped) machineSlots = append(machineSlots, i) } @@ -1169,8 +1169,8 @@ func TestBlocksQueue_stuckInUnfavourableFork(t *testing.T) { forkedPeer := connectPeerHavingBlocks(t, p2p, chain2, finalizedSlot, p2p.Peers()) startSlot := mc.HeadSlot() + 1 blocksPerRequest := queue.blocksFetcher.blocksPerPeriod - machineSlots := make([]types.Slot, 0) - for i := startSlot; i < startSlot.Add(blocksPerRequest*lookaheadSteps); i += types.Slot(blocksPerRequest) { + machineSlots := make([]primitives.Slot, 0) + for i := startSlot; i < startSlot.Add(blocksPerRequest*lookaheadSteps); i += primitives.Slot(blocksPerRequest) { queue.smm.addStateMachine(i).setState(stateSkipped) machineSlots = append(machineSlots, i) } @@ -1233,7 +1233,7 @@ func TestBlocksQueue_stuckInUnfavourableFork(t *testing.T) { // Assert that machines are in the expected state. startSlot = forkedEpochStartSlot.Add(1 + uint64(len(firstFSM.blocks))) - for i := startSlot; i < startSlot.Add(blocksPerRequest*(lookaheadSteps-1)); i += types.Slot(blocksPerRequest) { + for i := startSlot; i < startSlot.Add(blocksPerRequest*(lookaheadSteps-1)); i += primitives.Slot(blocksPerRequest) { fsm, ok := queue.smm.findStateMachine(i) require.Equal(t, true, ok) assert.Equal(t, stateSkipped, fsm.state) @@ -1249,7 +1249,7 @@ func TestBlocksQueue_stuckWhenHeadIsSetToOrphanedBlock(t *testing.T) { p2p := p2pt.NewTestP2P(t) chain := extendBlockSequence(t, []*eth.SignedBeaconBlock{}, 128) - finalizedSlot := types.Slot(82) + finalizedSlot := primitives.Slot(82) finalizedEpoch := slots.ToEpoch(finalizedSlot) genesisBlock := chain[0] @@ -1280,7 +1280,7 @@ func TestBlocksQueue_stuckWhenHeadIsSetToOrphanedBlock(t *testing.T) { require.NoError(t, st.SetSlot(blk.Block.Slot)) } } - require.Equal(t, types.Slot(83), mc.HeadSlot()) + require.Equal(t, primitives.Slot(83), mc.HeadSlot()) require.Equal(t, chain[83].Block.Slot, mc.HeadSlot()) // Set head to slot 85, while we do not have block with slot 84 in DB, so block is orphaned. @@ -1290,7 +1290,7 @@ func TestBlocksQueue_stuckWhenHeadIsSetToOrphanedBlock(t *testing.T) { orphanedBlock.Block.StateRoot = util.Random32Bytes(t) util.SaveBlock(t, ctx, beaconDB, orphanedBlock) require.NoError(t, st.SetSlot(orphanedBlock.Block.Slot)) - require.Equal(t, types.Slot(85), mc.HeadSlot()) + require.Equal(t, primitives.Slot(85), mc.HeadSlot()) fetcher := newBlocksFetcher( ctx, @@ -1312,7 +1312,7 @@ func TestBlocksQueue_stuckWhenHeadIsSetToOrphanedBlock(t *testing.T) { queue := newBlocksQueue(ctx, &blocksQueueConfig{ blocksFetcher: fetcher, chain: mc, - highestExpectedSlot: types.Slot(len(chain) - 1), + highestExpectedSlot: primitives.Slot(len(chain) - 1), mode: modeNonConstrained, }) diff --git a/beacon-chain/sync/initial-sync/blocks_queue_utils.go b/beacon-chain/sync/initial-sync/blocks_queue_utils.go index 73624832ff..ea39bf94bd 100644 --- a/beacon-chain/sync/initial-sync/blocks_queue_utils.go +++ b/beacon-chain/sync/initial-sync/blocks_queue_utils.go @@ -4,7 +4,7 @@ import ( "context" "errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // resetWithBlocks removes all state machines, then re-adds enough machines to contain all provided @@ -33,7 +33,7 @@ func (q *blocksQueue) resetFromFork(fork *forkData) error { // The rest of machines are in skipped state. startSlot := firstBlock.Slot().Add(uint64(len(fork.blocks))) - for i := startSlot; i < startSlot.Add(blocksPerRequest*(lookaheadSteps-1)); i += types.Slot(blocksPerRequest) { + for i := startSlot; i < startSlot.Add(blocksPerRequest*(lookaheadSteps-1)); i += primitives.Slot(blocksPerRequest) { fsm := q.smm.addStateMachine(i) fsm.state = stateSkipped } @@ -43,13 +43,13 @@ func (q *blocksQueue) resetFromFork(fork *forkData) error { // resetFromSlot removes all state machines, and re-adds them starting with a given slot. // The last machine added relies on calculated non-skipped slot (to allow FSMs to jump over // long periods with skipped slots). -func (q *blocksQueue) resetFromSlot(ctx context.Context, startSlot types.Slot) error { +func (q *blocksQueue) resetFromSlot(ctx context.Context, startSlot primitives.Slot) error { // Shift start position of all the machines except for the last one. blocksPerRequest := q.blocksFetcher.blocksPerPeriod if err := q.smm.removeAllStateMachines(); err != nil { return err } - for i := startSlot; i < startSlot.Add(blocksPerRequest*(lookaheadSteps-1)); i += types.Slot(blocksPerRequest) { + for i := startSlot; i < startSlot.Add(blocksPerRequest*(lookaheadSteps-1)); i += primitives.Slot(blocksPerRequest) { q.smm.addStateMachine(i) } diff --git a/beacon-chain/sync/initial-sync/fsm.go b/beacon-chain/sync/initial-sync/fsm.go index db122480d0..8fccff056b 100644 --- a/beacon-chain/sync/initial-sync/fsm.go +++ b/beacon-chain/sync/initial-sync/fsm.go @@ -8,7 +8,7 @@ import ( "github.com/libp2p/go-libp2p/core/peer" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" prysmTime "github.com/prysmaticlabs/prysm/v3/time" "github.com/prysmaticlabs/prysm/v3/time/slots" ) @@ -34,8 +34,8 @@ type eventID uint8 // stateMachineManager is a collection of managed FSMs. type stateMachineManager struct { - keys []types.Slot - machines map[types.Slot]*stateMachine + keys []primitives.Slot + machines map[primitives.Slot]*stateMachine handlers map[stateID]map[eventID]eventHandlerFn } @@ -43,7 +43,7 @@ type stateMachineManager struct { // Each FSM allows deterministic state transitions: State(S) x Event(E) -> Actions (A), State(S'). type stateMachine struct { smm *stateMachineManager - start types.Slot + start primitives.Slot state stateID pid peer.ID blocks []interfaces.SignedBeaconBlock @@ -56,8 +56,8 @@ type eventHandlerFn func(m *stateMachine, data interface{}) (newState stateID, e // newStateMachineManager returns fully initialized state machine manager. func newStateMachineManager() *stateMachineManager { return &stateMachineManager{ - keys: make([]types.Slot, 0, lookaheadSteps), - machines: make(map[types.Slot]*stateMachine, lookaheadSteps), + keys: make([]primitives.Slot, 0, lookaheadSteps), + machines: make(map[primitives.Slot]*stateMachine, lookaheadSteps), handlers: make(map[stateID]map[eventID]eventHandlerFn), } } @@ -73,7 +73,7 @@ func (smm *stateMachineManager) addEventHandler(event eventID, state stateID, fn } // addStateMachine allocates memory for new FSM. -func (smm *stateMachineManager) addStateMachine(startSlot types.Slot) *stateMachine { +func (smm *stateMachineManager) addStateMachine(startSlot primitives.Slot) *stateMachine { smm.machines[startSlot] = &stateMachine{ smm: smm, start: startSlot, @@ -86,7 +86,7 @@ func (smm *stateMachineManager) addStateMachine(startSlot types.Slot) *stateMach } // removeStateMachine frees memory of a processed/finished FSM. -func (smm *stateMachineManager) removeStateMachine(startSlot types.Slot) error { +func (smm *stateMachineManager) removeStateMachine(startSlot primitives.Slot) error { if _, ok := smm.machines[startSlot]; !ok { return fmt.Errorf("state for machine %v is not found", startSlot) } @@ -109,7 +109,7 @@ func (smm *stateMachineManager) removeAllStateMachines() error { // recalculateMachineAttribs updates cached attributes, which are used for efficiency. func (smm *stateMachineManager) recalculateMachineAttribs() { - keys := make([]types.Slot, 0, lookaheadSteps) + keys := make([]primitives.Slot, 0, lookaheadSteps) for key := range smm.machines { keys = append(keys, key) } @@ -120,13 +120,13 @@ func (smm *stateMachineManager) recalculateMachineAttribs() { } // findStateMachine returns a state machine for a given start slot (if exists). -func (smm *stateMachineManager) findStateMachine(startSlot types.Slot) (*stateMachine, bool) { +func (smm *stateMachineManager) findStateMachine(startSlot primitives.Slot) (*stateMachine, bool) { fsm, ok := smm.machines[startSlot] return fsm, ok } // highestStartSlot returns the start slot for the latest known state machine. -func (smm *stateMachineManager) highestStartSlot() (types.Slot, error) { +func (smm *stateMachineManager) highestStartSlot() (primitives.Slot, error) { if len(smm.keys) == 0 { return 0, errors.New("no state machine exist") } diff --git a/beacon-chain/sync/initial-sync/fsm_test.go b/beacon-chain/sync/initial-sync/fsm_test.go index 57b932e3ef..9f17d5aab4 100644 --- a/beacon-chain/sync/initial-sync/fsm_test.go +++ b/beacon-chain/sync/initial-sync/fsm_test.go @@ -5,7 +5,7 @@ import ( "fmt" "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -13,17 +13,17 @@ import ( func TestStateMachineManager_String(t *testing.T) { tests := []struct { name string - machines map[types.Slot]*stateMachine + machines map[primitives.Slot]*stateMachine want string }{ { "empty epoch state list", - map[types.Slot]*stateMachine{}, + map[primitives.Slot]*stateMachine{}, "map[]", }, { "newly created state machine", - map[types.Slot]*stateMachine{ + map[primitives.Slot]*stateMachine{ 0: {start: 64 * 0, state: stateNew}, 64: {start: 64 * 1, state: stateScheduled}, 128: {start: 64 * 2, state: stateDataParsed}, @@ -96,20 +96,20 @@ func TestStateMachine_trigger(t *testing.T) { type args struct { name eventID returnState stateID - epoch types.Epoch + epoch primitives.Epoch data interface{} } tests := []struct { name string events []event - epochs []types.Epoch + epochs []primitives.Epoch args args err error }{ { name: "event not found", events: []event{}, - epochs: []types.Epoch{12, 13}, + epochs: []primitives.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"), }, @@ -118,7 +118,7 @@ func TestStateMachine_trigger(t *testing.T) { events: []event{ {stateNew, eventTick, stateScheduled, false}, }, - epochs: []types.Epoch{12, 13}, + epochs: []primitives.Epoch{12, 13}, args: args{name: eventTick, epoch: 12, data: nil, returnState: stateScheduled}, err: nil, }, @@ -129,7 +129,7 @@ func TestStateMachine_trigger(t *testing.T) { {stateScheduled, eventTick, stateSent, true}, {stateSent, eventTick, stateSkipped, false}, }, - epochs: []types.Epoch{12, 13}, + epochs: []primitives.Epoch{12, 13}, args: args{name: eventTick, epoch: 12, data: nil, returnState: stateScheduled}, err: nil, }, @@ -140,7 +140,7 @@ func TestStateMachine_trigger(t *testing.T) { {stateScheduled, eventTick, stateSent, false}, {stateSent, eventTick, stateSkipped, false}, }, - epochs: []types.Epoch{12, 13}, + epochs: []primitives.Epoch{12, 13}, args: args{name: eventTick, epoch: 12, data: nil, returnState: stateScheduled}, err: nil, }, @@ -151,7 +151,7 @@ func TestStateMachine_trigger(t *testing.T) { {stateScheduled, eventTick, stateSent, false}, {stateNew, eventTick, stateSkipped, false}, }, - epochs: []types.Epoch{12, 13}, + epochs: []primitives.Epoch{12, 13}, args: args{name: eventTick, epoch: 12, data: nil, returnState: stateScheduled}, err: nil, }, @@ -175,9 +175,9 @@ func TestStateMachine_trigger(t *testing.T) { } } for _, epoch := range tt.epochs { - smm.addStateMachine(types.Slot(epoch * 32)) + smm.addStateMachine(primitives.Slot(epoch * 32)) } - state := smm.machines[types.Slot(tt.args.epoch*32)] + state := smm.machines[primitives.Slot(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) @@ -186,7 +186,7 @@ func TestStateMachine_trigger(t *testing.T) { if err != nil && !expectHandlerError { t.Error(err) } - ind := types.Slot(tt.args.epoch * 32) + ind := primitives.Slot(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) @@ -225,7 +225,7 @@ func TestStateMachineManager_QueueLoop(t *testing.T) { smm.addStateMachine(64) smm.addStateMachine(512) - assertState := func(startSlot types.Slot, state stateID) { + assertState := func(startSlot primitives.Slot, state stateID) { fsm, ok := smm.findStateMachine(startSlot) require.Equal(t, true, ok, "State machine not found") assert.Equal(t, state, fsm.state, "Unexpected state machine state") @@ -276,12 +276,12 @@ func TestStateMachineManager_removeAllStateMachines(t *testing.T) { smm.addStateMachine(64) smm.addStateMachine(128) smm.addStateMachine(196) - keys := []types.Slot{64, 128, 196} + keys := []primitives.Slot{64, 128, 196} assert.DeepEqual(t, smm.keys, keys, "Keys not sorted") assert.Equal(t, 3, len(smm.machines), "Unexpected list size") assert.NoError(t, smm.removeAllStateMachines()) - keys = []types.Slot{} + keys = []primitives.Slot{} assert.DeepEqual(t, smm.keys, keys, "Unexpected keys") assert.Equal(t, 0, len(smm.machines), "Expected empty list") } @@ -305,7 +305,7 @@ func TestStateMachineManager_findStateMachine(t *testing.T) { if fsm, ok := smm.findStateMachine(512); !ok || fsm.start != 512 { t.Errorf("unexpected start slot: %v, want: %v", fsm.start, 512) } - keys := []types.Slot{64, 128, 196, 256, 512} + keys := []primitives.Slot{64, 128, 196, 256, 512} assert.DeepEqual(t, smm.keys, keys, "Keys not sorted") } @@ -318,11 +318,11 @@ func TestStateMachineManager_highestStartSlot(t *testing.T) { smm.addStateMachine(196) start, err := smm.highestStartSlot() assert.NoError(t, err) - assert.Equal(t, types.Slot(196), start, "Incorrect highest start slot") + assert.Equal(t, primitives.Slot(196), start, "Incorrect highest start slot") assert.NoError(t, smm.removeStateMachine(196)) start, err = smm.highestStartSlot() assert.NoError(t, err) - assert.Equal(t, types.Slot(128), start, "Incorrect highest start slot") + assert.Equal(t, primitives.Slot(128), start, "Incorrect highest start slot") } func TestStateMachineManager_allMachinesInState(t *testing.T) { @@ -458,6 +458,6 @@ func TestStateMachine_isFirstLast(t *testing.T) { checkFirst(m5, true) checkLast(m5, false) - keys := []types.Slot{32, 64, 128, 196, 512} + keys := []primitives.Slot{32, 64, 128, 196, 512} assert.DeepEqual(t, smm.keys, keys, "Keys not sorted") } diff --git a/beacon-chain/sync/initial-sync/initial_sync_test.go b/beacon-chain/sync/initial-sync/initial_sync_test.go index c7b20819cc..167d5d2952 100644 --- a/beacon-chain/sync/initial-sync/initial_sync_test.go +++ b/beacon-chain/sync/initial-sync/initial_sync_test.go @@ -22,7 +22,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/features" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -37,17 +37,17 @@ import ( type testCache struct { sync.RWMutex - rootCache map[types.Slot][32]byte - parentSlotCache map[types.Slot]types.Slot + rootCache map[primitives.Slot][32]byte + parentSlotCache map[primitives.Slot]primitives.Slot } var cache = &testCache{} type peerData struct { - blocks []types.Slot // slots that peer has blocks - finalizedEpoch types.Epoch - headSlot types.Slot - failureSlots []types.Slot // slots at which the peer will return an error + blocks []primitives.Slot // slots that peer has blocks + finalizedEpoch primitives.Epoch + headSlot primitives.Slot + failureSlots []primitives.Slot // slots at which the peer will return an error forkedPeer bool } @@ -72,7 +72,7 @@ func TestMain(m *testing.M) { m.Run() } -func initializeTestServices(t *testing.T, slots []types.Slot, peers []*peerData) (*mock.ChainService, *p2pt.TestP2P, db.Database) { +func initializeTestServices(t *testing.T, slots []primitives.Slot, peers []*peerData) (*mock.ChainService, *p2pt.TestP2P, db.Database) { cache.initializeRootCache(slots, t) beaconDB := dbtest.SetupDB(t) @@ -100,36 +100,36 @@ func initializeTestServices(t *testing.T, slots []types.Slot, peers []*peerData) } // makeGenesisTime where now is the current slot. -func makeGenesisTime(currentSlot types.Slot) time.Time { +func makeGenesisTime(currentSlot primitives.Slot) time.Time { return prysmTime.Now().Add(-1 * time.Second * time.Duration(currentSlot) * time.Duration(params.BeaconConfig().SecondsPerSlot)) } // sanity test on helper function func TestMakeGenesisTime(t *testing.T) { - currentSlot := types.Slot(64) + currentSlot := primitives.Slot(64) gt := makeGenesisTime(currentSlot) require.Equal(t, currentSlot, slots.Since(gt)) } // helper function for sequences of block slots -func makeSequence(start, end types.Slot) []types.Slot { +func makeSequence(start, end primitives.Slot) []primitives.Slot { if end < start { panic("cannot make sequence where end is before start") } - seq := make([]types.Slot, 0, end-start+1) + seq := make([]primitives.Slot, 0, end-start+1) for i := start; i <= end; i++ { seq = append(seq, i) } return seq } -func (c *testCache) initializeRootCache(reqSlots []types.Slot, t *testing.T) { +func (c *testCache) initializeRootCache(reqSlots []primitives.Slot, t *testing.T) { c.Lock() defer c.Unlock() - c.rootCache = make(map[types.Slot][32]byte) - c.parentSlotCache = make(map[types.Slot]types.Slot) - parentSlot := types.Slot(0) + c.rootCache = make(map[primitives.Slot][32]byte) + c.parentSlotCache = make(map[primitives.Slot]primitives.Slot) + parentSlot := primitives.Slot(0) genesisBlock := util.NewBeaconBlock().Block genesisRoot, err := genesisBlock.HashTreeRoot() @@ -151,7 +151,7 @@ func (c *testCache) initializeRootCache(reqSlots []types.Slot, t *testing.T) { // sanity test on helper function func TestMakeSequence(t *testing.T) { got := makeSequence(3, 5) - want := []types.Slot{3, 4, 5} + want := []primitives.Slot{3, 4, 5} require.DeepEqual(t, want, got) } @@ -257,7 +257,7 @@ func extendBlockSequence(t *testing.T, inSeq []*ethpb.SignedBeaconBlock, size in // Extend block chain sequentially. for slot := startSlot; slot < len(outSeq); slot++ { outSeq[slot] = util.NewBeaconBlock() - outSeq[slot].Block.Slot = types.Slot(slot) + outSeq[slot].Block.Slot = primitives.Slot(slot) parentRoot, err := outSeq[slot-1].Block.HashTreeRoot() require.NoError(t, err) outSeq[slot].Block.ParentRoot = parentRoot[:] @@ -271,7 +271,7 @@ func extendBlockSequence(t *testing.T, inSeq []*ethpb.SignedBeaconBlock, size in // connectPeerHavingBlocks connect host with a peer having provided blocks. func connectPeerHavingBlocks( - t *testing.T, host *p2pt.TestP2P, blks []*ethpb.SignedBeaconBlock, finalizedSlot types.Slot, + t *testing.T, host *p2pt.TestP2P, blks []*ethpb.SignedBeaconBlock, finalizedSlot primitives.Slot, peerStatus *peers.Status, ) peer.ID { p := p2pt.NewTestP2P(t) @@ -285,7 +285,7 @@ func connectPeerHavingBlocks( req := ðpb.BeaconBlocksByRangeRequest{} assert.NoError(t, p.Encoding().DecodeWithMaxLength(stream, req)) - for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += primitives.Slot(req.Step) { if uint64(i) >= uint64(len(blks)) { break } diff --git a/beacon-chain/sync/initial-sync/round_robin.go b/beacon-chain/sync/initial-sync/round_robin.go index 3dd8a97069..a15872a242 100644 --- a/beacon-chain/sync/initial-sync/round_robin.go +++ b/beacon-chain/sync/initial-sync/round_robin.go @@ -11,7 +11,7 @@ import ( "github.com/paulbellamy/ratecounter" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/time/slots" "github.com/sirupsen/logrus" ) @@ -124,7 +124,7 @@ func (s *Service) syncToNonFinalizedEpoch(ctx context.Context, genesis time.Time // processFetchedData processes data received from queue. func (s *Service) processFetchedData( - ctx context.Context, genesis time.Time, startSlot types.Slot, data *blocksQueueFetchedData) { + ctx context.Context, genesis time.Time, startSlot primitives.Slot, data *blocksQueueFetchedData) { defer s.updatePeerScorerStats(data.pid, startSlot) // Use Batch Block Verify to process and verify batches directly. @@ -135,7 +135,7 @@ func (s *Service) processFetchedData( // processFetchedData processes data received from queue. func (s *Service) processFetchedDataRegSync( - ctx context.Context, genesis time.Time, startSlot types.Slot, data *blocksQueueFetchedData) { + ctx context.Context, genesis time.Time, startSlot primitives.Slot, data *blocksQueueFetchedData) { defer s.updatePeerScorerStats(data.pid, startSlot) blockReceiver := s.cfg.Chain.ReceiveBlock @@ -171,8 +171,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() types.Epoch { - highest := types.Epoch(0) +func (s *Service) highestFinalizedEpoch() primitives.Epoch { + highest := primitives.Epoch(0) for _, pid := range s.cfg.P2P.Peers().Connected() { peerChainState, err := s.cfg.P2P.Peers().ChainState(pid) if err == nil && peerChainState != nil && peerChainState.FinalizedEpoch > highest { @@ -289,7 +289,7 @@ func (s *Service) processBatchedBlocks(ctx context.Context, genesis time.Time, } // updatePeerScorerStats adjusts monitored metrics for a peer. -func (s *Service) updatePeerScorerStats(pid peer.ID, startSlot types.Slot) { +func (s *Service) updatePeerScorerStats(pid peer.ID, startSlot primitives.Slot) { if pid == "" { return } diff --git a/beacon-chain/sync/initial-sync/round_robin_test.go b/beacon-chain/sync/initial-sync/round_robin_test.go index 146d31c98c..44b7506847 100644 --- a/beacon-chain/sync/initial-sync/round_robin_test.go +++ b/beacon-chain/sync/initial-sync/round_robin_test.go @@ -12,7 +12,7 @@ import ( p2pt "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/testing" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -29,9 +29,9 @@ func TestService_roundRobinSync(t *testing.T) { }() tests := []struct { name string - currentSlot types.Slot - availableBlockSlots []types.Slot - expectedBlockSlots []types.Slot + currentSlot primitives.Slot + availableBlockSlots []primitives.Slot + expectedBlockSlots []primitives.Slot peers []*peerData }{ { @@ -313,7 +313,7 @@ func TestService_roundRobinSync(t *testing.T) { t.Errorf("Head slot (%d) is less than expected currentSlot (%d)", s.cfg.Chain.HeadSlot(), tt.currentSlot) } assert.Equal(t, true, len(tt.expectedBlockSlots) <= len(mc.BlocksReceived), "Processes wrong number of blocks") - var receivedBlockSlots []types.Slot + var receivedBlockSlots []primitives.Slot for _, blk := range mc.BlocksReceived { receivedBlockSlots = append(receivedBlockSlots, blk.Block().Slot()) } @@ -389,7 +389,7 @@ func TestService_processBlock(t *testing.T) { return nil }) assert.NoError(t, err) - assert.Equal(t, types.Slot(2), s.cfg.Chain.HeadSlot(), "Unexpected head slot") + assert.Equal(t, primitives.Slot(2), s.cfg.Chain.HeadSlot(), "Unexpected head slot") }) } @@ -420,7 +420,7 @@ func TestService_processBlockBatch(t *testing.T) { t.Run("process non-linear batch", func(t *testing.T) { var batch []interfaces.SignedBeaconBlock currBlockRoot := genesisBlkRoot - for i := types.Slot(1); i < 10; i++ { + for i := primitives.Slot(1); i < 10; i++ { parentRoot := currBlockRoot blk1 := util.NewBeaconBlock() blk1.Block.Slot = i @@ -435,7 +435,7 @@ func TestService_processBlockBatch(t *testing.T) { } var batch2 []interfaces.SignedBeaconBlock - for i := types.Slot(10); i < 20; i++ { + for i := primitives.Slot(10); i < 20; i++ { parentRoot := currBlockRoot blk1 := util.NewBeaconBlock() blk1.Block.Slot = i @@ -488,7 +488,7 @@ func TestService_processBlockBatch(t *testing.T) { return nil }) assert.NoError(t, err) - assert.Equal(t, types.Slot(19), s.cfg.Chain.HeadSlot(), "Unexpected head slot") + assert.Equal(t, primitives.Slot(19), s.cfg.Chain.HeadSlot(), "Unexpected head slot") }) } @@ -506,13 +506,13 @@ func TestService_blockProviderScoring(t *testing.T) { peerData := []*peerData{ { // The slowest peer, only a single block in couple of epochs. - blocks: []types.Slot{1, 65, 129}, + blocks: []primitives.Slot{1, 65, 129}, finalizedEpoch: 5, headSlot: 160, }, { // A relatively slow peer, still should perform better than the slowest peer. - blocks: append([]types.Slot{1, 2, 3, 4, 65, 66, 67, 68, 129, 130}, makeSequence(131, 160)...), + blocks: append([]primitives.Slot{1, 2, 3, 4, 65, 66, 67, 68, 129, 130}, makeSequence(131, 160)...), finalizedEpoch: 5, headSlot: 160, }, @@ -556,7 +556,7 @@ func TestService_blockProviderScoring(t *testing.T) { } scorer := s.cfg.P2P.Peers().Scorers().BlockProviderScorer() expectedBlockSlots := makeSequence(1, 160) - currentSlot := types.Slot(160) + currentSlot := primitives.Slot(160) assert.Equal(t, scorer.MaxScore(), scorer.Score(peer1)) assert.Equal(t, scorer.MaxScore(), scorer.Score(peer2)) @@ -567,7 +567,7 @@ func TestService_blockProviderScoring(t *testing.T) { t.Errorf("Head slot (%d) is less than expected currentSlot (%d)", s.cfg.Chain.HeadSlot(), currentSlot) } assert.Equal(t, true, len(expectedBlockSlots) <= len(mc.BlocksReceived), "Processes wrong number of blocks") - var receivedBlockSlots []types.Slot + var receivedBlockSlots []primitives.Slot for _, blk := range mc.BlocksReceived { receivedBlockSlots = append(receivedBlockSlots, blk.Block().Slot()) } @@ -620,7 +620,7 @@ func TestService_syncToFinalizedEpoch(t *testing.T) { counter: ratecounter.NewRateCounter(counterSeconds * time.Second), } expectedBlockSlots := makeSequence(1, 191) - currentSlot := types.Slot(191) + currentSlot := primitives.Slot(191) // Sync to finalized epoch. hook := logTest.NewGlobal() @@ -635,7 +635,7 @@ func TestService_syncToFinalizedEpoch(t *testing.T) { t.Errorf("Head slot (%d) is less than expected currentSlot (%d)", s.cfg.Chain.HeadSlot(), currentSlot) } assert.Equal(t, true, len(expectedBlockSlots) <= len(mc.BlocksReceived), "Processes wrong number of blocks") - var receivedBlockSlots []types.Slot + var receivedBlockSlots []primitives.Slot for _, blk := range mc.BlocksReceived { receivedBlockSlots = append(receivedBlockSlots, blk.Block().Slot()) } diff --git a/beacon-chain/sync/initial-sync/service_test.go b/beacon-chain/sync/initial-sync/service_test.go index 10a7eda138..ec17e2d444 100644 --- a/beacon-chain/sync/initial-sync/service_test.go +++ b/beacon-chain/sync/initial-sync/service_test.go @@ -16,7 +16,7 @@ import ( p2pt "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/testing" "github.com/prysmaticlabs/prysm/v3/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -113,7 +113,7 @@ func TestService_InitStartStop(t *testing.T) { // Set to some future slot, and then make sure that current head matches it. st, err := util.NewBeaconState() require.NoError(t, err) - futureSlot := types.Slot(27354) + futureSlot := primitives.Slot(27354) require.NoError(t, st.SetSlot(futureSlot)) return &mock.ChainService{ State: st, @@ -125,7 +125,7 @@ func TestService_InitStartStop(t *testing.T) { } }, methodRuns: func(fd *event.Feed) { - futureSlot := types.Slot(27354) + futureSlot := primitives.Slot(27354) // Send valid event. fd.Send(&feed.Event{ Type: statefeed.Initialized, @@ -398,7 +398,7 @@ func TestService_Resync(t *testing.T) { chainService: func() *mock.ChainService { st, err := util.NewBeaconState() require.NoError(t, err) - futureSlot := types.Slot(160) + futureSlot := primitives.Slot(160) require.NoError(t, st.SetGenesisTime(uint64(makeGenesisTime(futureSlot).Unix()))) return &mock.ChainService{ State: st, @@ -413,7 +413,7 @@ func TestService_Resync(t *testing.T) { }, assert: func(s *Service) { assert.LogsContain(t, hook, "Resync attempt complete") - assert.Equal(t, types.Slot(160), s.cfg.Chain.HeadSlot()) + assert.Equal(t, primitives.Slot(160), s.cfg.Chain.HeadSlot()) }, }, } @@ -434,7 +434,7 @@ func TestService_Resync(t *testing.T) { StateNotifier: mc.StateNotifier(), }) assert.NotNil(t, s) - assert.Equal(t, types.Slot(0), s.cfg.Chain.HeadSlot()) + assert.Equal(t, primitives.Slot(0), s.cfg.Chain.HeadSlot()) err := s.Resync() if tt.wantedErr != "" { assert.ErrorContains(t, tt.wantedErr, err) diff --git a/beacon-chain/sync/pending_attestations_queue.go b/beacon-chain/sync/pending_attestations_queue.go index 40101da5e0..a3770e1ae0 100644 --- a/beacon-chain/sync/pending_attestations_queue.go +++ b/beacon-chain/sync/pending_attestations_queue.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/async" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/rand" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -183,7 +183,7 @@ func (s *Service) savePendingAtt(att *ethpb.SignedAggregateAttestationAndProof) // If not valid, a node will remove it in the queue in place. The validity // check specifies the pending attestation could not fall one epoch behind // of the current slot. -func (s *Service) validatePendingAtts(ctx context.Context, slot types.Slot) { +func (s *Service) validatePendingAtts(ctx context.Context, slot primitives.Slot) { ctx, span := trace.StartSpan(ctx, "validatePendingAtts") defer span.End() diff --git a/beacon-chain/sync/pending_attestations_queue_test.go b/beacon-chain/sync/pending_attestations_queue_test.go index 3dbe5bb464..3a044fe735 100644 --- a/beacon-chain/sync/pending_attestations_queue_test.go +++ b/beacon-chain/sync/pending_attestations_queue_test.go @@ -19,7 +19,7 @@ import ( lruwrpr "github.com/prysmaticlabs/prysm/v3/cache/lru" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -92,7 +92,7 @@ func TestProcessPendingAtts_HasBlockSaveUnAggregatedAtt(t *testing.T) { // Arbitrary aggregator index for testing purposes. aggregatorIndex := committee[0] - sszUint := types.SSZUint64(att.Data.Slot) + sszUint := primitives.SSZUint64(att.Data.Slot) sig, err := signing.ComputeDomainAndSign(beaconState, 0, &sszUint, params.BeaconConfig().DomainSelectionProof, privKeys[aggregatorIndex]) require.NoError(t, err) aggregateAndProof := ðpb.AggregateAttestationAndProof{ @@ -208,7 +208,7 @@ func TestProcessPendingAtts_NoBroadcastWithBadSignature(t *testing.T) { // Arbitrary aggregator index for testing purposes. aggregatorIndex := committee[0] - sszSlot := types.SSZUint64(att.Data.Slot) + sszSlot := primitives.SSZUint64(att.Data.Slot) sig, err := signing.ComputeDomainAndSign(s, 0, &sszSlot, params.BeaconConfig().DomainSelectionProof, privKeys[aggregatorIndex]) require.NoError(t, err) aggregateAndProof := ðpb.AggregateAttestationAndProof{ @@ -289,7 +289,7 @@ func TestProcessPendingAtts_HasBlockSaveAggregatedAtt(t *testing.T) { // Arbitrary aggregator index for testing purposes. aggregatorIndex := committee[0] - sszUint := types.SSZUint64(att.Data.Slot) + sszUint := primitives.SSZUint64(att.Data.Slot) sig, err := signing.ComputeDomainAndSign(beaconState, 0, &sszUint, params.BeaconConfig().DomainSelectionProof, privKeys[aggregatorIndex]) require.NoError(t, err) aggregateAndProof := ðpb.AggregateAttestationAndProof{ @@ -348,20 +348,20 @@ func TestValidatePendingAtts_CanPruneOldAtts(t *testing.T) { r2 := [32]byte{'B'} r3 := [32]byte{'C'} - for i := types.Slot(0); i < 100; i++ { + for i := primitives.Slot(0); i < 100; i++ { s.savePendingAtt(ðpb.SignedAggregateAttestationAndProof{ Message: ðpb.AggregateAttestationAndProof{ - AggregatorIndex: types.ValidatorIndex(i), + AggregatorIndex: primitives.ValidatorIndex(i), Aggregate: ðpb.Attestation{ Data: ðpb.AttestationData{Slot: i, BeaconBlockRoot: r1[:]}}}}) s.savePendingAtt(ðpb.SignedAggregateAttestationAndProof{ Message: ðpb.AggregateAttestationAndProof{ - AggregatorIndex: types.ValidatorIndex(i*2 + i), + AggregatorIndex: primitives.ValidatorIndex(i*2 + i), Aggregate: ðpb.Attestation{ Data: ðpb.AttestationData{Slot: i, BeaconBlockRoot: r2[:]}}}}) s.savePendingAtt(ðpb.SignedAggregateAttestationAndProof{ Message: ðpb.AggregateAttestationAndProof{ - AggregatorIndex: types.ValidatorIndex(i*3 + i), + AggregatorIndex: primitives.ValidatorIndex(i*3 + i), Aggregate: ðpb.Attestation{ Data: ðpb.AttestationData{Slot: i, BeaconBlockRoot: r3[:]}}}}) } diff --git a/beacon-chain/sync/pending_blocks_queue.go b/beacon-chain/sync/pending_blocks_queue.go index 655dd8390b..b1784f5e8b 100644 --- a/beacon-chain/sync/pending_blocks_queue.go +++ b/beacon-chain/sync/pending_blocks_queue.go @@ -14,7 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/rand" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/encoding/ssz/equality" @@ -210,7 +210,7 @@ func (s *Service) processPendingBlocks(ctx context.Context) error { func (s *Service) checkIfBlockIsBad( ctx context.Context, span *trace.Span, - slot types.Slot, + slot primitives.Slot, b interfaces.SignedBeaconBlock, blkRoot [32]byte, ) (keepProcessing bool, err error) { @@ -280,13 +280,13 @@ func (s *Service) sendBatchRootRequest(ctx context.Context, roots [][32]byte, ra return nil } -func (s *Service) sortedPendingSlots() []types.Slot { +func (s *Service) sortedPendingSlots() []primitives.Slot { s.pendingQueueLock.RLock() defer s.pendingQueueLock.RUnlock() items := s.slotToPendingBlocks.Items() - ss := make([]types.Slot, 0, len(items)) + ss := make([]primitives.Slot, 0, len(items)) for k := range items { slot := cacheKeyToSlot(k) ss = append(ss, slot) @@ -353,7 +353,7 @@ func (s *Service) clearPendingSlots() { // Delete block from the list from the pending queue using the slot as key. // Note: this helper is not thread safe. -func (s *Service) deleteBlockFromPendingQueue(slot types.Slot, b interfaces.SignedBeaconBlock, r [32]byte) error { +func (s *Service) deleteBlockFromPendingQueue(slot primitives.Slot, b interfaces.SignedBeaconBlock, r [32]byte) error { mutexasserts.AssertRWMutexLocked(&s.pendingQueueLock) blks := s.pendingBlocksInCache(slot) @@ -398,7 +398,7 @@ func (s *Service) deleteBlockFromPendingQueue(slot types.Slot, b interfaces.Sign // Insert block to the list in the pending queue using the slot as key. // Note: this helper is not thread safe. -func (s *Service) insertBlockToPendingQueue(_ types.Slot, b interfaces.SignedBeaconBlock, r [32]byte) error { +func (s *Service) insertBlockToPendingQueue(_ primitives.Slot, b interfaces.SignedBeaconBlock, r [32]byte) error { mutexasserts.AssertRWMutexLocked(&s.pendingQueueLock) if s.seenPendingBlocks[r] { @@ -414,7 +414,7 @@ func (s *Service) insertBlockToPendingQueue(_ types.Slot, b interfaces.SignedBea } // This returns signed beacon blocks given input key from slotToPendingBlocks. -func (s *Service) pendingBlocksInCache(slot types.Slot) []interfaces.SignedBeaconBlock { +func (s *Service) pendingBlocksInCache(slot primitives.Slot) []interfaces.SignedBeaconBlock { k := slotToCacheKey(slot) value, ok := s.slotToPendingBlocks.Get(k) if !ok { @@ -452,13 +452,13 @@ func (s *Service) isGenesisTimeSet() bool { } // This converts input string to slot. -func cacheKeyToSlot(s string) types.Slot { +func cacheKeyToSlot(s string) primitives.Slot { b := []byte(s) return bytesutil.BytesToSlotBigEndian(b) } // This converts input slot to a key to be used for slotToPendingBlocks cache. -func slotToCacheKey(s types.Slot) string { +func slotToCacheKey(s primitives.Slot) string { b := bytesutil.SlotToBytesBigEndian(s) return string(b) } diff --git a/beacon-chain/sync/pending_blocks_queue_test.go b/beacon-chain/sync/pending_blocks_queue_test.go index 653cc8eb5f..cc76bb597d 100644 --- a/beacon-chain/sync/pending_blocks_queue_test.go +++ b/beacon-chain/sync/pending_blocks_queue_test.go @@ -23,7 +23,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/rand" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -557,7 +557,7 @@ func TestService_sortedPendingSlots(t *testing.T) { seenPendingBlocks: make(map[[32]byte]bool), } - var lastSlot types.Slot = math.MaxUint64 + var lastSlot primitives.Slot = math.MaxUint64 wsb, err := blocks.NewSignedBeaconBlock(util.HydrateSignedBeaconBlock(ðpb.SignedBeaconBlock{Block: ðpb.BeaconBlock{Slot: lastSlot}})) require.NoError(t, err) require.NoError(t, r.insertBlockToPendingQueue(lastSlot, wsb, [32]byte{1})) @@ -571,7 +571,7 @@ func TestService_sortedPendingSlots(t *testing.T) { require.NoError(t, err) require.NoError(t, r.insertBlockToPendingQueue(lastSlot-2, wsb, [32]byte{4})) - want := []types.Slot{lastSlot - 5, lastSlot - 3, lastSlot - 2, lastSlot} + want := []primitives.Slot{lastSlot - 5, lastSlot - 3, lastSlot - 2, lastSlot} assert.DeepEqual(t, want, r.sortedPendingSlots(), "Unexpected pending slots list") } diff --git a/beacon-chain/sync/rpc_beacon_blocks_by_range.go b/beacon-chain/sync/rpc_beacon_blocks_by_range.go index a7dd28e460..3e4fbee807 100644 --- a/beacon-chain/sync/rpc_beacon_blocks_by_range.go +++ b/beacon-chain/sync/rpc_beacon_blocks_by_range.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "go.opencensus.io/trace" @@ -120,7 +120,7 @@ func (s *Service) beaconBlocksByRangeRPCHandler(ctx context.Context, msg interfa return nil } -func (s *Service) writeBlockRangeToStream(ctx context.Context, startSlot, endSlot types.Slot, step uint64, +func (s *Service) writeBlockRangeToStream(ctx context.Context, startSlot, endSlot primitives.Slot, step uint64, prevRoot *[32]byte, stream libp2pcore.Stream) error { ctx, span := trace.StartSpan(ctx, "sync.WriteBlockRangeToStream") defer span.End() @@ -234,7 +234,7 @@ func (s *Service) validateRangeRequest(r *pb.BeaconBlocksByRangeRequest) error { // filters all the provided blocks to ensure they are canonical // and are strictly linear. func (s *Service) filterBlocks(ctx context.Context, blks []interfaces.SignedBeaconBlock, roots [][32]byte, prevRoot *[32]byte, - step uint64, startSlot types.Slot) ([]interfaces.SignedBeaconBlock, error) { + step uint64, startSlot primitives.Slot) ([]interfaces.SignedBeaconBlock, error) { if len(blks) != len(roots) { return nil, errors.New("input blks and roots are diff lengths") } diff --git a/beacon-chain/sync/rpc_beacon_blocks_by_range_test.go b/beacon-chain/sync/rpc_beacon_blocks_by_range_test.go index f25bcc7a93..ab588f3801 100644 --- a/beacon-chain/sync/rpc_beacon_blocks_by_range_test.go +++ b/beacon-chain/sync/rpc_beacon_blocks_by_range_test.go @@ -26,7 +26,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" leakybucket "github.com/prysmaticlabs/prysm/v3/container/leaky-bucket" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" @@ -54,7 +54,7 @@ func TestRPCBeaconBlocksByRange_RPCHandlerReturnsBlocks(t *testing.T) { // Populate the database with blocks that would match the request. var prevRoot [32]byte var err error - for i := req.StartSlot; i < req.StartSlot.Add(req.Count); i += types.Slot(1) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count); i += primitives.Slot(1) { blk := util.NewBeaconBlock() blk.Block.Slot = i copy(blk.Block.ParentRoot, prevRoot[:]) @@ -72,7 +72,7 @@ func TestRPCBeaconBlocksByRange_RPCHandlerReturnsBlocks(t *testing.T) { wg.Add(1) p2.BHost.SetStreamHandler(pcl, func(stream network.Stream) { defer wg.Done() - for i := req.StartSlot; i < req.StartSlot.Add(req.Count); i += types.Slot(1) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count); i += primitives.Slot(1) { expectSuccess(t, stream) res := util.NewBeaconBlock() assert.NoError(t, r.cfg.p2p.Encoding().DecodeWithMaxLength(stream, res)) @@ -113,7 +113,7 @@ func TestRPCBeaconBlocksByRange_ReturnCorrectNumberBack(t *testing.T) { var genRoot [32]byte // Populate the database with blocks that would match the request. - for i := req.StartSlot; i < req.StartSlot.Add(req.Step*req.Count); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Step*req.Count); i += primitives.Slot(req.Step) { blk := util.NewBeaconBlock() blk.Block.Slot = i if i == 0 { @@ -138,7 +138,7 @@ func TestRPCBeaconBlocksByRange_ReturnCorrectNumberBack(t *testing.T) { p2.BHost.SetStreamHandler(pcl, func(stream network.Stream) { defer wg.Done() - for i := newReq.StartSlot; i < newReq.StartSlot.Add(newReq.Count*newReq.Step); i += types.Slot(newReq.Step) { + for i := newReq.StartSlot; i < newReq.StartSlot.Add(newReq.Count*newReq.Step); i += primitives.Slot(newReq.Step) { expectSuccess(t, stream) res := util.NewBeaconBlock() assert.NoError(t, r.cfg.p2p.Encoding().DecodeWithMaxLength(stream, res)) @@ -221,7 +221,7 @@ func TestRPCBeaconBlocksByRange_ReconstructsPayloads(t *testing.T) { var genRoot [32]byte // Populate the database with blocks that would match the request. - for i := req.StartSlot; i < req.StartSlot.Add(req.Step*req.Count); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Step*req.Count); i += primitives.Slot(req.Step) { blk := util.NewBlindedBeaconBlockBellatrix() blk.Block.Slot = i blk.Block.Body.ExecutionPayloadHeader = header @@ -255,7 +255,7 @@ func TestRPCBeaconBlocksByRange_ReconstructsPayloads(t *testing.T) { p2.BHost.SetStreamHandler(pcl, func(stream network.Stream) { defer wg.Done() - for i := newReq.StartSlot; i < newReq.StartSlot.Add(newReq.Count*newReq.Step); i += types.Slot(newReq.Step) { + for i := newReq.StartSlot; i < newReq.StartSlot.Add(newReq.Count*newReq.Step); i += primitives.Slot(newReq.Step) { expectSuccess(t, stream) res := util.NewBeaconBlockBellatrix() assert.NoError(t, r.cfg.p2p.Encoding().DecodeWithMaxLength(stream, res)) @@ -320,9 +320,9 @@ func TestRPCBeaconBlocksByRange_RPCHandlerReturnsSortedBlocks(t *testing.T) { wg.Add(1) p2.BHost.SetStreamHandler(pcl, func(stream network.Stream) { defer wg.Done() - prevSlot := types.Slot(0) + prevSlot := primitives.Slot(0) require.Equal(t, uint64(len(expectedRoots)), req.Count, "Number of roots not expected") - for i, j := req.StartSlot, 0; i < req.StartSlot.Add(req.Count); i += types.Slot(1) { + for i, j := req.StartSlot, 0; i < req.StartSlot.Add(req.Count); i += primitives.Slot(1) { expectSuccess(t, stream) res := ðpb.SignedBeaconBlock{} assert.NoError(t, r.cfg.p2p.Encoding().DecodeWithMaxLength(stream, res)) @@ -389,8 +389,8 @@ func TestRPCBeaconBlocksByRange_ReturnsGenesisBlock(t *testing.T) { expectSuccess(t, stream) res := ðpb.SignedBeaconBlock{} assert.NoError(t, r.cfg.p2p.Encoding().DecodeWithMaxLength(stream, res)) - assert.Equal(t, types.Slot(0), res.Block.Slot, "genesis block was not returned") - for i := req.StartSlot.Add(req.Step); i < types.Slot(req.Count*req.Step); i += types.Slot(req.Step) { + assert.Equal(t, primitives.Slot(0), res.Block.Slot, "genesis block was not returned") + for i := req.StartSlot.Add(req.Step); i < primitives.Slot(req.Count*req.Step); i += primitives.Slot(req.Step) { expectSuccess(t, stream) res := ðpb.SignedBeaconBlock{} assert.NoError(t, r.cfg.p2p.Encoding().DecodeWithMaxLength(stream, res)) @@ -413,7 +413,7 @@ func TestRPCBeaconBlocksByRange_RPCHandlerRateLimitOverflow(t *testing.T) { var parentRoot [32]byte // Default to 1 to be inline with the spec. req.Step = 1 - for i := req.StartSlot; i < req.StartSlot.Add(req.Step*req.Count); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Step*req.Count); i += primitives.Slot(req.Step) { block := util.NewBeaconBlock() block.Block.Slot = i if req.Step == 1 { @@ -437,7 +437,7 @@ func TestRPCBeaconBlocksByRange_RPCHandlerRateLimitOverflow(t *testing.T) { } // Use a step of 1 to be inline with our specs. req.Step = 1 - for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += primitives.Slot(req.Step) { if !success { continue } @@ -552,7 +552,7 @@ func TestRPCBeaconBlocksByRange_RPCHandlerRateLimitOverflow(t *testing.T) { } func TestRPCBeaconBlocksByRange_validateRangeRequest(t *testing.T) { - slotsSinceGenesis := types.Slot(1000) + slotsSinceGenesis := primitives.Slot(1000) offset := int64(slotsSinceGenesis.Mul(params.BeaconConfig().SecondsPerSlot)) r := &Service{ cfg: &config{ @@ -676,7 +676,7 @@ func TestRPCBeaconBlocksByRange_EnforceResponseInvariants(t *testing.T) { saveBlocks := func(req *ethpb.BeaconBlocksByRangeRequest) { // Populate the database with blocks that would match the request. var parentRoot [32]byte - for i := req.StartSlot; i < req.StartSlot.Add(req.Step*req.Count); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Step*req.Count); i += primitives.Slot(req.Step) { block := util.NewBeaconBlock() block.Block.Slot = i block.Block.ParentRoot = parentRoot[:] @@ -694,7 +694,7 @@ func TestRPCBeaconBlocksByRange_EnforceResponseInvariants(t *testing.T) { p2.BHost.SetStreamHandler(pcl, func(stream network.Stream) { defer wg.Done() blocks := make([]*ethpb.SignedBeaconBlock, 0, req.Count) - for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += primitives.Slot(req.Step) { expectSuccess(t, stream) blk := util.NewBeaconBlock() assert.NoError(t, r.cfg.p2p.Encoding().DecodeWithMaxLength(stream, blk)) @@ -759,7 +759,7 @@ func TestRPCBeaconBlocksByRange_FilterBlocks(t *testing.T) { require.NoError(t, d.SaveGenesisBlockRoot(context.Background(), previousRoot)) blks := make([]*ethpb.SignedBeaconBlock, req.Count) // Populate the database with blocks that would match the request. - for i, j := req.StartSlot, 0; i < req.StartSlot.Add(req.Step*req.Count); i += types.Slot(req.Step) { + for i, j := req.StartSlot, 0; i < req.StartSlot.Add(req.Step*req.Count); i += primitives.Slot(req.Step) { parentRoot := make([]byte, fieldparams.RootLength) copy(parentRoot, previousRoot[:]) blks[j] = util.NewBeaconBlock() @@ -807,7 +807,7 @@ func TestRPCBeaconBlocksByRange_FilterBlocks(t *testing.T) { require.NoError(t, d.SaveGenesisBlockRoot(context.Background(), previousRoot)) blks := make([]*ethpb.SignedBeaconBlock, req.Count) // Populate the database with blocks with non linear roots. - for i, j := req.StartSlot, 0; i < req.StartSlot.Add(req.Step*req.Count); i += types.Slot(req.Step) { + for i, j := req.StartSlot, 0; i < req.StartSlot.Add(req.Step*req.Count); i += primitives.Slot(req.Step) { parentRoot := make([]byte, fieldparams.RootLength) copy(parentRoot, previousRoot[:]) blks[j] = util.NewBeaconBlock() @@ -854,7 +854,7 @@ func TestRPCBeaconBlocksByRange_FilterBlocks(t *testing.T) { p2.BHost.SetStreamHandler(pcl, func(stream network.Stream) { defer wg.Done() blocks := make([]*ethpb.SignedBeaconBlock, 0, req.Count) - for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += primitives.Slot(req.Step) { code, _, err := ReadStatusCode(stream, &encoder.SszNetworkEncoder{}) if err != nil && err != io.EOF { t.Fatal(err) @@ -1085,7 +1085,7 @@ func TestRPCBeaconBlocksByRange_FilterBlocks_PreviousRoot(t *testing.T) { var err error blks := []interfaces.SignedBeaconBlock{} var roots [][32]byte - for i := req.StartSlot; i < req.StartSlot.Add(req.Count); i += types.Slot(1) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count); i += primitives.Slot(1) { blk := util.NewBeaconBlock() blk.Block.Slot = i copy(blk.Block.ParentRoot, prevRoot[:]) diff --git a/beacon-chain/sync/rpc_beacon_blocks_by_root_test.go b/beacon-chain/sync/rpc_beacon_blocks_by_root_test.go index f3691c8056..e3cf583b70 100644 --- a/beacon-chain/sync/rpc_beacon_blocks_by_root_test.go +++ b/beacon-chain/sync/rpc_beacon_blocks_by_root_test.go @@ -22,7 +22,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" leakybucket "github.com/prysmaticlabs/prysm/v3/container/leaky-bucket" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" @@ -41,7 +41,7 @@ func TestRecentBeaconBlocksRPCHandler_ReturnsBlocks(t *testing.T) { var blkRoots p2pTypes.BeaconBlockByRootsReq // Populate the database with blocks that would match the request. - for i := types.Slot(1); i < 11; i++ { + for i := primitives.Slot(1); i < 11; i++ { blk := util.NewBeaconBlock() blk.Block.Slot = i root, err := blk.Block.HashTreeRoot() @@ -127,7 +127,7 @@ func TestRecentBeaconBlocksRPCHandler_ReturnsBlocks_ReconstructsPayload(t *testi var blkRoots p2pTypes.BeaconBlockByRootsReq // Populate the database with blocks that would match the request. - for i := types.Slot(1); i < 11; i++ { + for i := primitives.Slot(1); i < 11; i++ { blk := util.NewBlindedBeaconBlockBellatrix() blk.Block.Body.ExecutionPayloadHeader = header blk.Block.Slot = i diff --git a/beacon-chain/sync/rpc_goodbye.go b/beacon-chain/sync/rpc_goodbye.go index 163da36a60..c62017f863 100644 --- a/beacon-chain/sync/rpc_goodbye.go +++ b/beacon-chain/sync/rpc_goodbye.go @@ -11,12 +11,12 @@ import ( "github.com/prysmaticlabs/prysm/v3/async" "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p" p2ptypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/time/slots" "github.com/sirupsen/logrus" ) -var backOffTime = map[types.SSZUint64]time.Duration{ +var backOffTime = map[primitives.SSZUint64]time.Duration{ // Do not dial peers which are from a different/unverifiable // network. p2ptypes.GoodbyeCodeWrongNetwork: 24 * time.Hour, @@ -37,7 +37,7 @@ var backOffTime = map[types.SSZUint64]time.Duration{ func (s *Service) goodbyeRPCHandler(_ context.Context, msg interface{}, stream libp2pcore.Stream) error { SetRPCStreamDeadlines(stream) - m, ok := msg.(*types.SSZUint64) + m, ok := msg.(*primitives.SSZUint64) if !ok { return fmt.Errorf("wrong message type for goodbye, got %T, wanted *uint64", msg) } diff --git a/beacon-chain/sync/rpc_goodbye_test.go b/beacon-chain/sync/rpc_goodbye_test.go index 29838c6455..26d6a46aaa 100644 --- a/beacon-chain/sync/rpc_goodbye_test.go +++ b/beacon-chain/sync/rpc_goodbye_test.go @@ -13,7 +13,7 @@ import ( p2ptest "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/testing" p2ptypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" leakybucket "github.com/prysmaticlabs/prysm/v3/container/leaky-bucket" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -171,7 +171,7 @@ func TestSendGoodbye_SendsMessage(t *testing.T) { wg.Add(1) p2.BHost.SetStreamHandler(pcl, func(stream network.Stream) { defer wg.Done() - out := new(types.SSZUint64) + out := new(primitives.SSZUint64) assert.NoError(t, r.cfg.p2p.Encoding().DecodeWithMaxLength(stream, out)) assert.Equal(t, failureCode, *out) assert.NoError(t, stream.Close()) @@ -216,7 +216,7 @@ func TestSendGoodbye_DisconnectWithPeer(t *testing.T) { wg.Add(1) p2.BHost.SetStreamHandler(pcl, func(stream network.Stream) { defer wg.Done() - out := new(types.SSZUint64) + out := new(primitives.SSZUint64) assert.NoError(t, r.cfg.p2p.Encoding().DecodeWithMaxLength(stream, out)) assert.Equal(t, failureCode, *out) assert.NoError(t, stream.Close()) diff --git a/beacon-chain/sync/rpc_ping.go b/beacon-chain/sync/rpc_ping.go index 7db7c27823..9cd1aec4fa 100644 --- a/beacon-chain/sync/rpc_ping.go +++ b/beacon-chain/sync/rpc_ping.go @@ -10,7 +10,7 @@ import ( "github.com/libp2p/go-libp2p/core/peer" "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p" p2ptypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/time" "github.com/prysmaticlabs/prysm/v3/time/slots" ) @@ -19,7 +19,7 @@ import ( func (s *Service) pingHandler(_ context.Context, msg interface{}, stream libp2pcore.Stream) error { SetRPCStreamDeadlines(stream) - m, ok := msg.(*types.SSZUint64) + m, ok := msg.(*primitives.SSZUint64) if !ok { return fmt.Errorf("wrong message type for ping, got %T, wanted *uint64", msg) } @@ -39,7 +39,7 @@ func (s *Service) pingHandler(_ context.Context, msg interface{}, stream libp2pc if _, err := stream.Write([]byte{responseCodeSuccess}); err != nil { return err } - sq := types.SSZUint64(s.cfg.p2p.MetadataSeq()) + sq := primitives.SSZUint64(s.cfg.p2p.MetadataSeq()) if _, err := s.cfg.p2p.Encoding().EncodeWithMaxLength(stream, &sq); err != nil { return err } @@ -77,7 +77,7 @@ func (s *Service) sendPingRequest(ctx context.Context, id peer.ID) error { ctx, cancel := context.WithTimeout(ctx, respTimeout) defer cancel() - metadataSeq := types.SSZUint64(s.cfg.p2p.MetadataSeq()) + metadataSeq := primitives.SSZUint64(s.cfg.p2p.MetadataSeq()) topic, err := p2p.TopicFromMessage(p2p.PingMessageName, slots.ToEpoch(s.cfg.chain.CurrentSlot())) if err != nil { return err @@ -100,7 +100,7 @@ func (s *Service) sendPingRequest(ctx context.Context, id peer.ID) error { s.cfg.p2p.Peers().Scorers().BadResponsesScorer().Increment(stream.Conn().RemotePeer()) return errors.New(errMsg) } - msg := new(types.SSZUint64) + msg := new(primitives.SSZUint64) if err := s.cfg.p2p.Encoding().DecodeWithMaxLength(stream, msg); err != nil { return err } @@ -126,7 +126,7 @@ func (s *Service) sendPingRequest(ctx context.Context, id peer.ID) error { } // validates the peer's sequence number. -func (s *Service) validateSequenceNum(seq types.SSZUint64, id peer.ID) (bool, error) { +func (s *Service) validateSequenceNum(seq primitives.SSZUint64, id peer.ID) (bool, error) { md, err := s.cfg.p2p.Peers().Metadata(id) if err != nil { return false, err diff --git a/beacon-chain/sync/rpc_ping_test.go b/beacon-chain/sync/rpc_ping_test.go index a604b45736..a3770bff62 100644 --- a/beacon-chain/sync/rpc_ping_test.go +++ b/beacon-chain/sync/rpc_ping_test.go @@ -14,7 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p" p2ptest "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/testing" p2ptypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/types" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/consensus-types/wrapper" leakybucket "github.com/prysmaticlabs/prysm/v3/container/leaky-bucket" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -60,13 +60,13 @@ func TestPingRPCHandler_ReceivesPing(t *testing.T) { p2.BHost.SetStreamHandler(pcl, func(stream network.Stream) { defer wg.Done() expectSuccess(t, stream) - out := new(types.SSZUint64) + out := new(primitives.SSZUint64) assert.NoError(t, r.cfg.p2p.Encoding().DecodeWithMaxLength(stream, out)) assert.Equal(t, uint64(2), uint64(*out)) }) stream1, err := p1.BHost.NewStream(context.Background(), p2.BHost.ID(), pcl) require.NoError(t, err) - seqNumber := types.SSZUint64(2) + seqNumber := primitives.SSZUint64(2) assert.NoError(t, r.pingHandler(context.Background(), &seqNumber, stream1)) @@ -129,7 +129,7 @@ func TestPingRPCHandler_SendsPing(t *testing.T) { wg.Add(1) p2.BHost.SetStreamHandler(pcl, func(stream network.Stream) { defer wg.Done() - out := new(types.SSZUint64) + out := new(primitives.SSZUint64) assert.NoError(t, r2.cfg.p2p.Encoding().DecodeWithMaxLength(stream, out)) assert.Equal(t, uint64(2), uint64(*out)) assert.NoError(t, r2.pingHandler(context.Background(), out, stream)) @@ -194,7 +194,7 @@ func TestPingRPCHandler_BadSequenceNumber(t *testing.T) { stream1, err := p1.BHost.NewStream(context.Background(), p2.BHost.ID(), pcl) require.NoError(t, err) - wantedSeq := types.SSZUint64(p2.LocalMetadata.SequenceNumber()) + wantedSeq := primitives.SSZUint64(p2.LocalMetadata.SequenceNumber()) err = r.pingHandler(context.Background(), &wantedSeq, stream1) assert.ErrorContains(t, p2ptypes.ErrInvalidSequenceNum.Error(), err) diff --git a/beacon-chain/sync/rpc_send_request.go b/beacon-chain/sync/rpc_send_request.go index a51b8e1af2..39b3bb7648 100644 --- a/beacon-chain/sync/rpc_send_request.go +++ b/beacon-chain/sync/rpc_send_request.go @@ -11,7 +11,7 @@ import ( p2ptypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" ) @@ -47,7 +47,7 @@ func SendBeaconBlocksByRangeRequest( } return nil } - var prevSlot types.Slot + var prevSlot primitives.Slot for i := uint64(0); ; i++ { isFirstChunk := i == 0 blk, err := ReadChunkedBlock(stream, chain, p2pProvider, isFirstChunk) diff --git a/beacon-chain/sync/rpc_send_request_test.go b/beacon-chain/sync/rpc_send_request_test.go index e43485f77e..40982674e8 100644 --- a/beacon-chain/sync/rpc_send_request_test.go +++ b/beacon-chain/sync/rpc_send_request_test.go @@ -16,7 +16,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -47,7 +47,7 @@ func TestSendRequest_SendBeaconBlocksByRangeRequest(t *testing.T) { parentRoot := genesisBlkRoot for i := 0; i < 255; i++ { blk := util.NewBeaconBlock() - blk.Block.Slot = types.Slot(i) + blk.Block.Slot = primitives.Slot(i) blk.Block.ParentRoot = parentRoot[:] knownBlocks = append(knownBlocks, blk) parentRoot, err = blk.Block.HashTreeRoot() @@ -63,7 +63,7 @@ func TestSendRequest_SendBeaconBlocksByRangeRequest(t *testing.T) { req := ðpb.BeaconBlocksByRangeRequest{} assert.NoError(t, p2pProvider.Encoding().DecodeWithMaxLength(stream, req)) - for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += primitives.Slot(req.Step) { if processor != nil { wsb, err := blocks.NewSignedBeaconBlock(knownBlocks[i]) require.NoError(t, err) @@ -234,7 +234,7 @@ func TestSendRequest_SendBeaconBlocksByRangeRequest(t *testing.T) { req := ðpb.BeaconBlocksByRangeRequest{} assert.NoError(t, p2.Encoding().DecodeWithMaxLength(stream, req)) - for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += primitives.Slot(req.Step) { if uint64(i) >= uint64(len(knownBlocks)) { break } @@ -278,7 +278,7 @@ func TestSendRequest_SendBeaconBlocksByRangeRequest(t *testing.T) { req := ðpb.BeaconBlocksByRangeRequest{} assert.NoError(t, p2.Encoding().DecodeWithMaxLength(stream, req)) - for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += types.Slot(req.Step) { + for i := req.StartSlot; i < req.StartSlot.Add(req.Count*req.Step); i += primitives.Slot(req.Step) { if uint64(i) >= uint64(len(knownBlocks)) { break } diff --git a/beacon-chain/sync/rpc_status.go b/beacon-chain/sync/rpc_status.go index c0babe5969..d5b02ca657 100644 --- a/beacon-chain/sync/rpc_status.go +++ b/beacon-chain/sync/rpc_status.go @@ -17,7 +17,7 @@ import ( p2ptypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/v3/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" prysmTime "github.com/prysmaticlabs/prysm/v3/time" @@ -111,7 +111,7 @@ func (s *Service) resyncIfBehind() { func (s *Service) shouldReSync() bool { syncedEpoch := slots.ToEpoch(s.cfg.chain.HeadSlot()) currentEpoch := slots.ToEpoch(s.cfg.chain.CurrentSlot()) - prevEpoch := types.Epoch(0) + prevEpoch := primitives.Epoch(0) if currentEpoch > 1 { prevEpoch = currentEpoch - 1 } @@ -294,7 +294,7 @@ func (s *Service) validateStatusMessage(ctx context.Context, msg *pb.Status) err maxEpoch := slots.EpochsSinceGenesis(genesis) // It would take a minimum of 2 epochs to finalize a // previous epoch - maxFinalizedEpoch := types.Epoch(0) + maxFinalizedEpoch := primitives.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 226c326251..9dcf0e4a48 100644 --- a/beacon-chain/sync/rpc_status_test.go +++ b/beacon-chain/sync/rpc_status_test.go @@ -22,7 +22,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/consensus-types/wrapper" leakybucket "github.com/prysmaticlabs/prysm/v3/container/leaky-bucket" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -82,7 +82,7 @@ func TestStatusRPCHandler_Disconnects_OnForkVersionMismatch(t *testing.T) { wg2.Add(1) p2.BHost.SetStreamHandler(pcl2, func(stream network.Stream) { defer wg2.Done() - msg := new(types.SSZUint64) + msg := new(primitives.SSZUint64) assert.NoError(t, r.cfg.p2p.Encoding().DecodeWithMaxLength(stream, msg)) assert.Equal(t, p2ptypes.GoodbyeCodeWrongNetwork, *msg) assert.NoError(t, stream.Close()) @@ -344,7 +344,7 @@ func TestHandshakeHandlers_Roundtrip(t *testing.T) { wg2.Add(1) p2.BHost.SetStreamHandler(pcl, func(stream network.Stream) { defer wg2.Done() - out := new(types.SSZUint64) + out := new(primitives.SSZUint64) assert.NoError(t, r.cfg.p2p.Encoding().DecodeWithMaxLength(stream, out)) assert.Equal(t, uint64(2), uint64(*out)) assert.NoError(t, r2.pingHandler(context.Background(), out, stream)) @@ -591,19 +591,19 @@ func TestStatusRPCRequest_FinalizedBlockSkippedSlots(t *testing.T) { } require.NoError(t, db.SaveStateSummaries(context.Background(), stateSummaries)) - rootFetcher := func(slot types.Slot) [32]byte { + rootFetcher := func(slot primitives.Slot) [32]byte { rt, err := blocksTillHead[slot-1].Block().HashTreeRoot() require.NoError(t, err) return rt } tests := []struct { name string - expectedFinalizedEpoch types.Epoch + expectedFinalizedEpoch primitives.Epoch expectedFinalizedRoot [32]byte - headSlot types.Slot - remoteFinalizedEpoch types.Epoch + headSlot primitives.Slot + remoteFinalizedEpoch primitives.Epoch remoteFinalizedRoot [32]byte - remoteHeadSlot types.Slot + remoteHeadSlot primitives.Slot expectError bool }{ { @@ -884,7 +884,7 @@ func TestShouldResync(t *testing.T) { type args struct { genesis time.Time syncing bool - headSlot types.Slot + headSlot primitives.Slot } tests := []struct { name string @@ -957,7 +957,7 @@ func makeBlocks(t *testing.T, i, n uint64, previousRoot [32]byte) []interfaces.S parentRoot := make([]byte, 32) copy(parentRoot, previousRoot[:]) blocks[j-i] = util.NewBeaconBlock() - blocks[j-i].Block.Slot = types.Slot(j + 1) + blocks[j-i].Block.Slot = primitives.Slot(j + 1) blocks[j-i].Block.ParentRoot = parentRoot var err error previousRoot, err = blocks[j-i].Block.HashTreeRoot() diff --git a/beacon-chain/sync/subscriber.go b/beacon-chain/sync/subscriber.go index 3e69291b23..0185b2b4da 100644 --- a/beacon-chain/sync/subscriber.go +++ b/beacon-chain/sync/subscriber.go @@ -18,7 +18,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/cmd/beacon-chain/flags" "github.com/prysmaticlabs/prysm/v3/config/features" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" "github.com/prysmaticlabs/prysm/v3/network/forks" @@ -50,7 +50,7 @@ func (s *Service) noopValidator(_ context.Context, _ peer.ID, msg *pubsub.Messag } // Register PubSub subscribers -func (s *Service) registerSubscribers(epoch types.Epoch, digest [4]byte) { +func (s *Service) registerSubscribers(epoch primitives.Epoch, digest [4]byte) { s.subscribe( p2p.BlockSubnetTopicFormat, s.validateBeaconBlockPubSub, @@ -659,7 +659,7 @@ func (s *Service) validPeersExist(subnetTopic string) bool { return len(numOfPeers) >= flags.Get().MinimumPeersPerSubnet } -func (s *Service) retrievePersistentSubs(currSlot types.Slot) []uint64 { +func (s *Service) retrievePersistentSubs(currSlot primitives.Slot) []uint64 { // Persistent subscriptions from validators persistentSubs := s.persistentSubnetIndices() // Update desired topic indices for aggregator @@ -669,7 +669,7 @@ func (s *Service) retrievePersistentSubs(currSlot types.Slot) []uint64 { return slice.SetUint64(append(persistentSubs, wantedSubs...)) } -func (_ *Service) retrieveActiveSyncSubnets(currEpoch types.Epoch) []uint64 { +func (_ *Service) retrieveActiveSyncSubnets(currEpoch primitives.Epoch) []uint64 { subs := cache.SyncSubnetIDs.GetAllSubnets(currEpoch) return slice.SetUint64(subs) } diff --git a/beacon-chain/sync/subscriber_beacon_attestation.go b/beacon-chain/sync/subscriber_beacon_attestation.go index 0bc2dcc15c..ee5cce822f 100644 --- a/beacon-chain/sync/subscriber_beacon_attestation.go +++ b/beacon-chain/sync/subscriber_beacon_attestation.go @@ -7,7 +7,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/cache" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -40,7 +40,7 @@ func (_ *Service) persistentSubnetIndices() []uint64 { return cache.SubnetIDs.GetAllSubnets() } -func (_ *Service) aggregatorSubnetIndices(currentSlot types.Slot) []uint64 { +func (_ *Service) aggregatorSubnetIndices(currentSlot primitives.Slot) []uint64 { endEpoch := slots.ToEpoch(currentSlot) + 1 endSlot := params.BeaconConfig().SlotsPerEpoch.Mul(uint64(endEpoch)) var commIds []uint64 @@ -50,7 +50,7 @@ func (_ *Service) aggregatorSubnetIndices(currentSlot types.Slot) []uint64 { return slice.SetUint64(commIds) } -func (_ *Service) attesterSubnetIndices(currentSlot types.Slot) []uint64 { +func (_ *Service) attesterSubnetIndices(currentSlot primitives.Slot) []uint64 { endEpoch := slots.ToEpoch(currentSlot) + 1 endSlot := params.BeaconConfig().SlotsPerEpoch.Mul(uint64(endEpoch)) var commIds []uint64 diff --git a/beacon-chain/sync/subscriber_test.go b/beacon-chain/sync/subscriber_test.go index ad85064622..8d693f576f 100644 --- a/beacon-chain/sync/subscriber_test.go +++ b/beacon-chain/sync/subscriber_test.go @@ -25,7 +25,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/cmd/beacon-chain/flags" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/network/forks" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -452,7 +452,7 @@ func TestFilterSubnetPeers(t *testing.T) { defer flags.Init(new(flags.GlobalFlags)) p := p2ptest.NewTestP2P(t) ctx, cancel := context.WithCancel(context.Background()) - currSlot := types.Slot(100) + currSlot := primitives.Slot(100) r := Service{ ctx: ctx, cfg: &config{ @@ -522,7 +522,7 @@ func TestSubscribeWithSyncSubnets_StaticOK(t *testing.T) { p := p2ptest.NewTestP2P(t) ctx, cancel := context.WithCancel(context.Background()) - currSlot := types.Slot(100) + currSlot := primitives.Slot(100) r := Service{ ctx: ctx, cfg: &config{ @@ -553,7 +553,7 @@ func TestSubscribeWithSyncSubnets_DynamicOK(t *testing.T) { p := p2ptest.NewTestP2P(t) ctx, cancel := context.WithCancel(context.Background()) - currSlot := types.Slot(100) + currSlot := primitives.Slot(100) r := Service{ ctx: ctx, cfg: &config{ @@ -598,7 +598,7 @@ func TestSubscribeWithSyncSubnets_StaticSwitchFork(t *testing.T) { params.OverrideBeaconConfig(cfg) params.BeaconConfig().InitializeForkSchedule() ctx, cancel := context.WithCancel(context.Background()) - currSlot := types.Slot(100) + currSlot := primitives.Slot(100) r := Service{ ctx: ctx, cfg: &config{ @@ -637,7 +637,7 @@ func TestSubscribeWithSyncSubnets_DynamicSwitchFork(t *testing.T) { params.OverrideBeaconConfig(cfg) params.BeaconConfig().InitializeForkSchedule() ctx, cancel := context.WithCancel(context.Background()) - currSlot := types.Slot(100) + currSlot := primitives.Slot(100) r := Service{ ctx: ctx, cfg: &config{ diff --git a/beacon-chain/sync/utils_test.go b/beacon-chain/sync/utils_test.go index d24416ef1e..f1fcd8ae81 100644 --- a/beacon-chain/sync/utils_test.go +++ b/beacon-chain/sync/utils_test.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -22,7 +22,7 @@ func TestSortedObj_SortBlocksRoots(t *testing.T) { } for i := 0; i < 10; i++ { - slot := types.Slot(randFunc()) + slot := primitives.Slot(randFunc()) newBlk, err := blocks.NewSignedBeaconBlock(ðpb.SignedBeaconBlock{Block: ðpb.BeaconBlock{Slot: slot, Body: ðpb.BeaconBlockBody{}}}) require.NoError(t, err) blks = append(blks, newBlk) @@ -34,7 +34,7 @@ func TestSortedObj_SortBlocksRoots(t *testing.T) { newBlks, newRoots := r.sortBlocksAndRoots(blks, roots) - previousSlot := types.Slot(0) + previousSlot := primitives.Slot(0) for i, b := range newBlks { if b.Block().Slot() < previousSlot { t.Errorf("Block list is not sorted as %d is smaller than previousSlot %d", b.Block().Slot(), previousSlot) @@ -56,7 +56,7 @@ func TestSortedObj_NoDuplicates(t *testing.T) { } for i := 0; i < 10; i++ { - slot := types.Slot(randFunc()) + slot := primitives.Slot(randFunc()) newBlk := ðpb.SignedBeaconBlock{Block: ðpb.BeaconBlock{Slot: slot, Body: ðpb.BeaconBlockBody{}}} // append twice wsb, err := blocks.NewSignedBeaconBlock(newBlk) diff --git a/beacon-chain/sync/validate_aggregate_proof.go b/beacon-chain/sync/validate_aggregate_proof.go index a24969f6d7..5a56b9a4f7 100644 --- a/beacon-chain/sync/validate_aggregate_proof.go +++ b/beacon-chain/sync/validate_aggregate_proof.go @@ -15,7 +15,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" @@ -214,7 +214,7 @@ func (s *Service) validateBlockInAttestation(ctx context.Context, satt *ethpb.Si } // Returns true if the node has received aggregate for the aggregator with index and target epoch. -func (s *Service) hasSeenAggregatorIndexEpoch(epoch types.Epoch, aggregatorIndex types.ValidatorIndex) bool { +func (s *Service) hasSeenAggregatorIndexEpoch(epoch primitives.Epoch, aggregatorIndex primitives.ValidatorIndex) bool { s.seenAggregatedAttestationLock.RLock() defer s.seenAggregatedAttestationLock.RUnlock() b := append(bytesutil.Bytes32(uint64(epoch)), bytesutil.Bytes32(uint64(aggregatorIndex))...) @@ -223,7 +223,7 @@ func (s *Service) hasSeenAggregatorIndexEpoch(epoch types.Epoch, aggregatorIndex } // Set aggregate's aggregator index target epoch as seen. -func (s *Service) setAggregatorIndexEpochSeen(epoch types.Epoch, aggregatorIndex types.ValidatorIndex) { +func (s *Service) setAggregatorIndexEpochSeen(epoch primitives.Epoch, aggregatorIndex primitives.ValidatorIndex) { s.seenAggregatedAttestationLock.Lock() defer s.seenAggregatedAttestationLock.Unlock() b := append(bytesutil.Bytes32(uint64(epoch)), bytesutil.Bytes32(uint64(aggregatorIndex))...) @@ -231,7 +231,7 @@ func (s *Service) setAggregatorIndexEpochSeen(epoch types.Epoch, aggregatorIndex } // This validates the aggregator's index in state is within the beacon committee. -func validateIndexInCommittee(ctx context.Context, bs state.ReadOnlyBeaconState, a *ethpb.Attestation, validatorIndex types.ValidatorIndex) error { +func validateIndexInCommittee(ctx context.Context, bs state.ReadOnlyBeaconState, a *ethpb.Attestation, validatorIndex primitives.ValidatorIndex) error { ctx, span := trace.StartSpan(ctx, "sync.validateIndexInCommittee") defer span.End() @@ -259,7 +259,7 @@ func validateSelectionIndex( ctx context.Context, bs state.ReadOnlyBeaconState, data *ethpb.AttestationData, - validatorIndex types.ValidatorIndex, + validatorIndex primitives.ValidatorIndex, proof []byte, ) (*bls.SignatureBatch, error) { ctx, span := trace.StartSpan(ctx, "sync.validateSelectionIndex") @@ -293,7 +293,7 @@ func validateSelectionIndex( if err != nil { return nil, err } - sszUint := types.SSZUint64(data.Slot) + sszUint := primitives.SSZUint64(data.Slot) root, err := signing.ComputeSigningRoot(&sszUint, d) if err != nil { return nil, err diff --git a/beacon-chain/sync/validate_aggregate_proof_test.go b/beacon-chain/sync/validate_aggregate_proof_test.go index 7bf2b62356..f314f245a8 100644 --- a/beacon-chain/sync/validate_aggregate_proof_test.go +++ b/beacon-chain/sync/validate_aggregate_proof_test.go @@ -21,7 +21,7 @@ import ( lruwrpr "github.com/prysmaticlabs/prysm/v3/cache/lru" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -50,7 +50,7 @@ func TestVerifyIndexInCommittee_CanVerify(t *testing.T) { assert.NoError(t, err) indices, err := attestation.AttestingIndices(att.AggregationBits, committee) require.NoError(t, err) - require.NoError(t, validateIndexInCommittee(ctx, s, att, types.ValidatorIndex(indices[0]))) + require.NoError(t, validateIndexInCommittee(ctx, s, att, primitives.ValidatorIndex(indices[0]))) wanted := "validator index 1000 is not within the committee" assert.ErrorContains(t, wanted, validateIndexInCommittee(ctx, s, att, 1000)) @@ -340,7 +340,7 @@ func TestValidateAggregateAndProof_CanValidate(t *testing.T) { } att.Signature = bls.AggregateSignatures(sigs).Marshal() ai := committee[0] - sszUint := types.SSZUint64(att.Data.Slot) + sszUint := primitives.SSZUint64(att.Data.Slot) sig, err := signing.ComputeDomainAndSign(beaconState, 0, &sszUint, params.BeaconConfig().DomainSelectionProof, privKeys[ai]) require.NoError(t, err) aggregateAndProof := ðpb.AggregateAttestationAndProof{ @@ -441,7 +441,7 @@ func TestVerifyIndexInCommittee_SeenAggregatorEpoch(t *testing.T) { } att.Signature = bls.AggregateSignatures(sigs).Marshal() ai := committee[0] - sszUint := types.SSZUint64(att.Data.Slot) + sszUint := primitives.SSZUint64(att.Data.Slot) sig, err := signing.ComputeDomainAndSign(beaconState, 0, &sszUint, params.BeaconConfig().DomainSelectionProof, privKeys[ai]) require.NoError(t, err) aggregateAndProof := ðpb.AggregateAttestationAndProof{ @@ -560,7 +560,7 @@ func TestValidateAggregateAndProof_BadBlock(t *testing.T) { } att.Signature = bls.AggregateSignatures(sigs).Marshal() ai := committee[0] - sszUint := types.SSZUint64(att.Data.Slot) + sszUint := primitives.SSZUint64(att.Data.Slot) sig, err := signing.ComputeDomainAndSign(beaconState, 0, &sszUint, params.BeaconConfig().DomainSelectionProof, privKeys[ai]) require.NoError(t, err) @@ -651,7 +651,7 @@ func TestValidateAggregateAndProof_RejectWhenAttEpochDoesntEqualTargetEpoch(t *t } att.Signature = bls.AggregateSignatures(sigs).Marshal() ai := committee[0] - sszUint := types.SSZUint64(att.Data.Slot) + sszUint := primitives.SSZUint64(att.Data.Slot) sig, err := signing.ComputeDomainAndSign(beaconState, 0, &sszUint, params.BeaconConfig().DomainSelectionProof, privKeys[ai]) require.NoError(t, err) aggregateAndProof := ðpb.AggregateAttestationAndProof{ diff --git a/beacon-chain/sync/validate_attester_slashing_test.go b/beacon-chain/sync/validate_attester_slashing_test.go index 5f14487160..9c5dbd9178 100644 --- a/beacon-chain/sync/validate_attester_slashing_test.go +++ b/beacon-chain/sync/validate_attester_slashing_test.go @@ -17,7 +17,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" mockSync "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -29,7 +29,7 @@ func setupValidAttesterSlashing(t *testing.T) (*ethpb.AttesterSlashing, state.Be s, privKeys := util.DeterministicGenesisState(t, 5) vals := s.Validators() for _, vv := range vals { - vv.WithdrawableEpoch = types.Epoch(1 * params.BeaconConfig().SlotsPerEpoch) + vv.WithdrawableEpoch = primitives.Epoch(1 * params.BeaconConfig().SlotsPerEpoch) } require.NoError(t, s.SetValidators(vals)) diff --git a/beacon-chain/sync/validate_beacon_attestation.go b/beacon-chain/sync/validate_beacon_attestation.go index 357e9b9b66..2334d30820 100644 --- a/beacon-chain/sync/validate_beacon_attestation.go +++ b/beacon-chain/sync/validate_beacon_attestation.go @@ -16,7 +16,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/features" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -231,7 +231,7 @@ func (s *Service) validateUnaggregatedAttWithState(ctx context.Context, a *eth.A } // Returns true if the attestation was already seen for the participating validator for the slot. -func (s *Service) hasSeenCommitteeIndicesSlot(slot types.Slot, committeeID types.CommitteeIndex, aggregateBits []byte) bool { +func (s *Service) hasSeenCommitteeIndicesSlot(slot primitives.Slot, committeeID primitives.CommitteeIndex, aggregateBits []byte) bool { s.seenUnAggregatedAttestationLock.RLock() defer s.seenUnAggregatedAttestationLock.RUnlock() b := append(bytesutil.Bytes32(uint64(slot)), bytesutil.Bytes32(uint64(committeeID))...) @@ -241,7 +241,7 @@ func (s *Service) hasSeenCommitteeIndicesSlot(slot types.Slot, committeeID types } // Set committee's indices and slot as seen for incoming attestations. -func (s *Service) setSeenCommitteeIndicesSlot(slot types.Slot, committeeID types.CommitteeIndex, aggregateBits []byte) { +func (s *Service) setSeenCommitteeIndicesSlot(slot primitives.Slot, committeeID primitives.CommitteeIndex, aggregateBits []byte) { s.seenUnAggregatedAttestationLock.Lock() defer s.seenUnAggregatedAttestationLock.Unlock() b := append(bytesutil.Bytes32(uint64(slot)), bytesutil.Bytes32(uint64(committeeID))...) diff --git a/beacon-chain/sync/validate_beacon_blocks.go b/beacon-chain/sync/validate_beacon_blocks.go index de012a04e6..3b9cf83880 100644 --- a/beacon-chain/sync/validate_beacon_blocks.go +++ b/beacon-chain/sync/validate_beacon_blocks.go @@ -18,7 +18,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" prysmTime "github.com/prysmaticlabs/prysm/v3/time" @@ -309,7 +309,7 @@ func (s *Service) validateBellatrixBeaconBlock(ctx context.Context, parentState } // Returns true if the block is not the first block proposed for the proposer for the slot. -func (s *Service) hasSeenBlockIndexSlot(slot types.Slot, proposerIdx types.ValidatorIndex) bool { +func (s *Service) hasSeenBlockIndexSlot(slot primitives.Slot, proposerIdx primitives.ValidatorIndex) bool { s.seenBlockLock.RLock() defer s.seenBlockLock.RUnlock() b := append(bytesutil.Bytes32(uint64(slot)), bytesutil.Bytes32(uint64(proposerIdx))...) @@ -318,7 +318,7 @@ func (s *Service) hasSeenBlockIndexSlot(slot types.Slot, proposerIdx types.Valid } // Set block proposer index and slot as seen for incoming blocks. -func (s *Service) setSeenBlockIndexSlot(slot types.Slot, proposerIdx types.ValidatorIndex) { +func (s *Service) setSeenBlockIndexSlot(slot primitives.Slot, proposerIdx primitives.ValidatorIndex) { s.seenBlockLock.Lock() defer s.seenBlockLock.Unlock() b := append(bytesutil.Bytes32(uint64(slot)), bytesutil.Bytes32(uint64(proposerIdx))...) @@ -345,7 +345,7 @@ func (s *Service) setBadBlock(ctx context.Context, root [32]byte) { } // This captures metrics for block arrival time by subtracts slot start time. -func captureArrivalTimeMetric(genesisTime uint64, currentSlot types.Slot) error { +func captureArrivalTimeMetric(genesisTime uint64, currentSlot primitives.Slot) error { startTime, err := slots.ToTime(genesisTime, currentSlot) if err != nil { return err @@ -360,7 +360,7 @@ func captureArrivalTimeMetric(genesisTime uint64, currentSlot types.Slot) error // current_time + MAXIMUM_GOSSIP_CLOCK_DISPARITY. in short, this function // returns true if the corresponding block should be queued and false if // the block should be processed immediately. -func isBlockQueueable(genesisTime uint64, slot types.Slot, receivedTime time.Time) bool { +func isBlockQueueable(genesisTime uint64, slot primitives.Slot, receivedTime time.Time) bool { slotTime, err := slots.ToTime(genesisTime, slot) if err != nil { return false diff --git a/beacon-chain/sync/validate_beacon_blocks_test.go b/beacon-chain/sync/validate_beacon_blocks_test.go index 02534c774a..88f5e0d5c1 100644 --- a/beacon-chain/sync/validate_beacon_blocks_test.go +++ b/beacon-chain/sync/validate_beacon_blocks_test.go @@ -28,7 +28,7 @@ import ( lruwrpr "github.com/prysmaticlabs/prysm/v3/cache/lru" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -995,7 +995,7 @@ func TestValidateBeaconBlockPubSub_RejectBlocksFromBadParent(t *testing.T) { perSlot := params.BeaconConfig().SecondsPerSlot // current slot time - slotsSinceGenesis := types.Slot(1000) + slotsSinceGenesis := primitives.Slot(1000) // max uint, divided by slot time. But avoid losing precision too much. overflowBase := (1 << 63) / (perSlot >> 1) msg.Block.Slot = slotsSinceGenesis.Add(overflowBase) @@ -1064,7 +1064,7 @@ func TestService_setBadBlock_DoesntSetWithContextErr(t *testing.T) { func TestService_isBlockQueueable(t *testing.T) { currentTime := time.Now().Round(time.Second) genesisTime := uint64(currentTime.Unix() - int64(params.BeaconConfig().SecondsPerSlot)) - blockSlot := types.Slot(1) + blockSlot := primitives.Slot(1) // slot time within MAXIMUM_GOSSIP_CLOCK_DISPARITY, so don't queue the block. receivedTime := currentTime.Add(-400 * time.Millisecond) diff --git a/beacon-chain/sync/validate_proposer_slashing.go b/beacon-chain/sync/validate_proposer_slashing.go index ebe0d65b68..6cadd3adf3 100644 --- a/beacon-chain/sync/validate_proposer_slashing.go +++ b/beacon-chain/sync/validate_proposer_slashing.go @@ -6,7 +6,7 @@ import ( pubsub "github.com/libp2p/go-libp2p-pubsub" "github.com/libp2p/go-libp2p/core/peer" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "go.opencensus.io/trace" @@ -60,7 +60,7 @@ func (s *Service) validateProposerSlashing(ctx context.Context, pid peer.ID, msg } // Returns true if the node has already received a valid proposer slashing received for the proposer with index -func (s *Service) hasSeenProposerSlashingIndex(i types.ValidatorIndex) bool { +func (s *Service) hasSeenProposerSlashingIndex(i primitives.ValidatorIndex) bool { s.seenProposerSlashingLock.RLock() defer s.seenProposerSlashingLock.RUnlock() _, seen := s.seenProposerSlashingCache.Get(i) @@ -68,7 +68,7 @@ func (s *Service) hasSeenProposerSlashingIndex(i types.ValidatorIndex) bool { } // Set proposer slashing index in proposer slashing cache. -func (s *Service) setProposerSlashingIndexSeen(i types.ValidatorIndex) { +func (s *Service) setProposerSlashingIndexSeen(i primitives.ValidatorIndex) { s.seenProposerSlashingLock.Lock() defer s.seenProposerSlashingLock.Unlock() s.seenProposerSlashingCache.Add(i, true) diff --git a/beacon-chain/sync/validate_proposer_slashing_test.go b/beacon-chain/sync/validate_proposer_slashing_test.go index 254ee3840d..39f70a3e9c 100644 --- a/beacon-chain/sync/validate_proposer_slashing_test.go +++ b/beacon-chain/sync/validate_proposer_slashing_test.go @@ -21,7 +21,7 @@ import ( mockSync "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" lruwrpr "github.com/prysmaticlabs/prysm/v3/cache/lru" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -44,7 +44,7 @@ func setupValidProposerSlashing(t *testing.T) (*ethpb.ProposerSlashing, state.Be validatorBalances[i] = params.BeaconConfig().MaxEffectiveBalance } - currentSlot := types.Slot(0) + currentSlot := primitives.Slot(0) st, err := state_native.InitializeFromProtoPhase0(ðpb.BeaconState{ Validators: validators, Slot: currentSlot, diff --git a/beacon-chain/sync/validate_sync_committee_message.go b/beacon-chain/sync/validate_sync_committee_message.go index 8fcf4dacfe..6cc28df9a8 100644 --- a/beacon-chain/sync/validate_sync_committee_message.go +++ b/beacon-chain/sync/validate_sync_committee_message.go @@ -14,7 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p" p2ptypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" @@ -119,7 +119,7 @@ func (s *Service) readSyncCommitteeMessage(msg *pubsub.Message) (*ethpb.SyncComm } // Mark all a slot and validator index as seen for every index in a committee and subnet. -func (s *Service) markSyncCommitteeMessagesSeen(committeeIndices []types.CommitteeIndex, m *ethpb.SyncCommitteeMessage) { +func (s *Service) markSyncCommitteeMessagesSeen(committeeIndices []primitives.CommitteeIndex, m *ethpb.SyncCommitteeMessage) { subCommitteeSize := params.BeaconConfig().SyncCommitteeSize / params.BeaconConfig().SyncCommitteeSubnetCount for _, idx := range committeeIndices { subnet := uint64(idx) / subCommitteeSize @@ -128,7 +128,7 @@ func (s *Service) markSyncCommitteeMessagesSeen(committeeIndices []types.Committ } // Returns true if the node has received sync committee for the validator with index and slot. -func (s *Service) hasSeenSyncMessageIndexSlot(slot types.Slot, valIndex types.ValidatorIndex, subCommitteeIndex uint64) bool { +func (s *Service) hasSeenSyncMessageIndexSlot(slot primitives.Slot, valIndex primitives.ValidatorIndex, subCommitteeIndex uint64) bool { s.seenSyncMessageLock.RLock() defer s.seenSyncMessageLock.RUnlock() _, seen := s.seenSyncMessageCache.Get(seenSyncCommitteeKey(slot, valIndex, subCommitteeIndex)) @@ -136,7 +136,7 @@ func (s *Service) hasSeenSyncMessageIndexSlot(slot types.Slot, valIndex types.Va } // Set sync committee message validator index and slot as seen. -func (s *Service) setSeenSyncMessageIndexSlot(slot types.Slot, valIndex types.ValidatorIndex, subCommitteeIndex uint64) { +func (s *Service) setSeenSyncMessageIndexSlot(slot primitives.Slot, valIndex primitives.ValidatorIndex, subCommitteeIndex uint64) { s.seenSyncMessageLock.Lock() defer s.seenSyncMessageLock.Unlock() key := seenSyncCommitteeKey(slot, valIndex, subCommitteeIndex) @@ -152,7 +152,7 @@ func (s *Service) setSeenSyncMessageIndexSlot(slot types.Slot, valIndex types.Va // message and broadcasts it into subnet 2, we need to make sure that whatever committee index and // resultant subnet that the validator has is valid for this particular topic. func (s *Service) rejectIncorrectSyncCommittee( - committeeIndices []types.CommitteeIndex, topic string, + committeeIndices []primitives.CommitteeIndex, topic string, ) validationFn { return func(ctx context.Context) (pubsub.ValidationResult, error) { ctx, span := trace.StartSpan(ctx, "sync.rejectIncorrectSyncCommittee") @@ -185,7 +185,7 @@ func (s *Service) rejectIncorrectSyncCommittee( // and `subcommittee_index`. In the event of `validator_index` belongs to multiple subnets, as long // as one subnet has not been seen, we should let it in. func (s *Service) ignoreHasSeenSyncMsg( - m *ethpb.SyncCommitteeMessage, committeeIndices []types.CommitteeIndex, + m *ethpb.SyncCommitteeMessage, committeeIndices []primitives.CommitteeIndex, ) validationFn { return func(ctx context.Context) (pubsub.ValidationResult, error) { var isValid bool @@ -252,7 +252,7 @@ func (s *Service) rejectInvalidSyncCommitteeSignature(m *ethpb.SyncCommitteeMess } } -func ignoreEmptyCommittee(indices []types.CommitteeIndex) validationFn { +func ignoreEmptyCommittee(indices []primitives.CommitteeIndex) validationFn { return func(ctx context.Context) (pubsub.ValidationResult, error) { if len(indices) == 0 { return pubsub.ValidationIgnore, nil @@ -261,7 +261,7 @@ func ignoreEmptyCommittee(indices []types.CommitteeIndex) validationFn { } } -func seenSyncCommitteeKey(slot types.Slot, valIndex types.ValidatorIndex, subCommitteeIndex uint64) string { +func seenSyncCommitteeKey(slot primitives.Slot, valIndex primitives.ValidatorIndex, subCommitteeIndex uint64) string { b := append(bytesutil.Bytes32(uint64(slot)), bytesutil.Bytes32(uint64(valIndex))...) b = append(b, bytesutil.Bytes32(subCommitteeIndex)...) return string(b) diff --git a/beacon-chain/sync/validate_sync_committee_message_test.go b/beacon-chain/sync/validate_sync_committee_message_test.go index 40eaeba899..a9c36158e7 100644 --- a/beacon-chain/sync/validate_sync_committee_message_test.go +++ b/beacon-chain/sync/validate_sync_committee_message_test.go @@ -22,7 +22,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" mockSync "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -217,7 +217,7 @@ func TestService_ValidateSyncCommitteeMessage(t *testing.T) { hState, err := beaconDB.State(context.Background(), headRoot) assert.NoError(t, err) s.cfg.chain = &mockChain.ChainService{ - SyncCommitteeIndices: []types.CommitteeIndex{0}, + SyncCommitteeIndices: []primitives.CommitteeIndex{0}, ValidatorsRoot: [32]byte{'A'}, Genesis: time.Now().Add(-time.Second * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Duration(hState.Slot()-1)), } @@ -226,7 +226,7 @@ func TestService_ValidateSyncCommitteeMessage(t *testing.T) { chosenVal := numOfVals - 10 msg.Signature = emptySig[:] msg.BlockRoot = headRoot[:] - msg.ValidatorIndex = types.ValidatorIndex(chosenVal) + msg.ValidatorIndex = primitives.ValidatorIndex(chosenVal) msg.Slot = slots.PrevSlot(hState.Slot()) // Set Bad Topic and Subnet @@ -274,7 +274,7 @@ func TestService_ValidateSyncCommitteeMessage(t *testing.T) { chosenVal := numOfVals + 10 msg.Signature = emptySig[:] msg.BlockRoot = headRoot[:] - msg.ValidatorIndex = types.ValidatorIndex(chosenVal) + msg.ValidatorIndex = primitives.ValidatorIndex(chosenVal) msg.Slot = slots.PrevSlot(hState.Slot()) digest, err := s.currentForkDigest() @@ -317,14 +317,14 @@ func TestService_ValidateSyncCommitteeMessage(t *testing.T) { chosenVal := numOfVals - 10 msg.Signature = emptySig[:] msg.BlockRoot = headRoot[:] - msg.ValidatorIndex = types.ValidatorIndex(chosenVal) + msg.ValidatorIndex = primitives.ValidatorIndex(chosenVal) msg.Slot = slots.PrevSlot(hState.Slot()) d, err := signing.Domain(hState.Fork(), slots.ToEpoch(hState.Slot()), params.BeaconConfig().DomainSyncCommittee, hState.GenesisValidatorsRoot()) assert.NoError(t, err) subCommitteeSize := params.BeaconConfig().SyncCommitteeSize / params.BeaconConfig().SyncCommitteeSubnetCount s.cfg.chain = &mockChain.ChainService{ - SyncCommitteeIndices: []types.CommitteeIndex{types.CommitteeIndex(subCommitteeSize)}, + SyncCommitteeIndices: []primitives.CommitteeIndex{primitives.CommitteeIndex(subCommitteeSize)}, ValidatorsRoot: [32]byte{'A'}, Genesis: time.Now().Add(-time.Second * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Duration(hState.Slot()-1)), SyncCommitteeDomain: d, @@ -378,7 +378,7 @@ func TestService_ValidateSyncCommitteeMessage(t *testing.T) { assert.NoError(t, err) s.cfg.chain = &mockChain.ChainService{ - SyncCommitteeIndices: []types.CommitteeIndex{types.CommitteeIndex(subCommitteeSize)}, + SyncCommitteeIndices: []primitives.CommitteeIndex{primitives.CommitteeIndex(subCommitteeSize)}, ValidatorsRoot: [32]byte{'A'}, Genesis: time.Now().Add(-time.Second * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Duration(hState.Slot()-1)), SyncCommitteeDomain: d, @@ -387,7 +387,7 @@ func TestService_ValidateSyncCommitteeMessage(t *testing.T) { msg.Signature = keys[chosenVal].Sign(sigRoot[:]).Marshal() msg.BlockRoot = headRoot[:] - msg.ValidatorIndex = types.ValidatorIndex(chosenVal) + msg.ValidatorIndex = primitives.ValidatorIndex(chosenVal) msg.Slot = slots.PrevSlot(hState.Slot()) // Set Topic and Subnet @@ -437,7 +437,7 @@ func TestService_ignoreHasSeenSyncMsg(t *testing.T) { name string setupSvc func(s *Service, msg *ethpb.SyncCommitteeMessage, topic string) (*Service, string) msg *ethpb.SyncCommitteeMessage - committee []types.CommitteeIndex + committee []primitives.CommitteeIndex want pubsub.ValidationResult }{ { @@ -448,7 +448,7 @@ func TestService_ignoreHasSeenSyncMsg(t *testing.T) { return s, "" }, msg: ðpb.SyncCommitteeMessage{ValidatorIndex: 0, Slot: 1}, - committee: []types.CommitteeIndex{1, 2, 3}, + committee: []primitives.CommitteeIndex{1, 2, 3}, want: pubsub.ValidationIgnore, }, { @@ -459,7 +459,7 @@ func TestService_ignoreHasSeenSyncMsg(t *testing.T) { return s, "" }, msg: ðpb.SyncCommitteeMessage{ValidatorIndex: 1, Slot: 1}, - committee: []types.CommitteeIndex{1, 2, 3}, + committee: []primitives.CommitteeIndex{1, 2, 3}, want: pubsub.ValidationAccept, }, } @@ -480,7 +480,7 @@ func TestService_rejectIncorrectSyncCommittee(t *testing.T) { name string cfg *config setupTopic func(s *Service) string - committeeIndices []types.CommitteeIndex + committeeIndices []primitives.CommitteeIndex want pubsub.ValidationResult }{ { @@ -491,7 +491,7 @@ func TestService_rejectIncorrectSyncCommittee(t *testing.T) { ValidatorsRoot: [32]byte{1}, }, }, - committeeIndices: []types.CommitteeIndex{0}, + committeeIndices: []primitives.CommitteeIndex{0}, setupTopic: func(_ *Service) string { return "foobar" }, @@ -505,7 +505,7 @@ func TestService_rejectIncorrectSyncCommittee(t *testing.T) { ValidatorsRoot: [32]byte{1}, }, }, - committeeIndices: []types.CommitteeIndex{0}, + committeeIndices: []primitives.CommitteeIndex{0}, setupTopic: func(s *Service) string { format := p2p.GossipTypeMapping[reflect.TypeOf(ðpb.SyncCommitteeMessage{})] digest, err := s.currentForkDigest() @@ -534,7 +534,7 @@ func TestService_rejectIncorrectSyncCommittee(t *testing.T) { func Test_ignoreEmptyCommittee(t *testing.T) { tests := []struct { name string - committee []types.CommitteeIndex + committee []primitives.CommitteeIndex want pubsub.ValidationResult }{ { @@ -544,12 +544,12 @@ func Test_ignoreEmptyCommittee(t *testing.T) { }, { name: "empty", - committee: []types.CommitteeIndex{}, + committee: []primitives.CommitteeIndex{}, want: pubsub.ValidationIgnore, }, { name: "non-empty", - committee: []types.CommitteeIndex{1}, + committee: []primitives.CommitteeIndex{1}, want: pubsub.ValidationAccept, }, } diff --git a/beacon-chain/sync/validate_sync_contribution_proof.go b/beacon-chain/sync/validate_sync_contribution_proof.go index 03610b1dce..9299f8468a 100644 --- a/beacon-chain/sync/validate_sync_contribution_proof.go +++ b/beacon-chain/sync/validate_sync_contribution_proof.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" p2ptypes "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/types" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" @@ -82,7 +82,7 @@ func (s *Service) validateSyncContributionAndProof(ctx context.Context, pid peer if err := s.setSyncContributionBits(con); err != nil { return pubsub.ValidationIgnore, err } - s.setSyncContributionIndexSlotSeen(con.Slot, m.Message.AggregatorIndex, types.CommitteeIndex(con.SubcommitteeIndex)) + s.setSyncContributionIndexSlotSeen(con.Slot, m.Message.AggregatorIndex, primitives.CommitteeIndex(con.SubcommitteeIndex)) msg.ValidatorData = m @@ -151,7 +151,7 @@ func (s *Service) ignoreSeenSyncContribution(m *ethpb.SignedContributionAndProof if seen { return pubsub.ValidationIgnore, nil } - seen = s.hasSeenSyncContributionIndexSlot(c.Slot, m.Message.AggregatorIndex, types.CommitteeIndex(c.SubcommitteeIndex)) + seen = s.hasSeenSyncContributionIndexSlot(c.Slot, m.Message.AggregatorIndex, primitives.CommitteeIndex(c.SubcommitteeIndex)) if seen { return pubsub.ValidationIgnore, nil } @@ -253,7 +253,7 @@ func (s *Service) rejectInvalidSyncAggregateSignature(m *ethpb.SignedContributio // derived from the participation info in `aggregation_bits` for the subcommittee specified by the `contribution.subcommittee_index`. var activePubkeys []bls.PublicKey var activeRawPubkeys [][]byte - syncPubkeys, err := s.cfg.chain.HeadSyncCommitteePubKeys(ctx, m.Message.Contribution.Slot, types.CommitteeIndex(m.Message.Contribution.SubcommitteeIndex)) + syncPubkeys, err := s.cfg.chain.HeadSyncCommitteePubKeys(ctx, m.Message.Contribution.Slot, primitives.CommitteeIndex(m.Message.Contribution.SubcommitteeIndex)) if err != nil { return pubsub.ValidationIgnore, err } @@ -303,7 +303,7 @@ func (s *Service) rejectInvalidSyncAggregateSignature(m *ethpb.SignedContributio } // Returns true if the node has received sync contribution for the aggregator with index, slot and subcommittee index. -func (s *Service) hasSeenSyncContributionIndexSlot(slot types.Slot, aggregatorIndex types.ValidatorIndex, subComIdx types.CommitteeIndex) bool { +func (s *Service) hasSeenSyncContributionIndexSlot(slot primitives.Slot, aggregatorIndex primitives.ValidatorIndex, subComIdx primitives.CommitteeIndex) bool { s.seenSyncContributionLock.RLock() defer s.seenSyncContributionLock.RUnlock() @@ -314,7 +314,7 @@ func (s *Service) hasSeenSyncContributionIndexSlot(slot types.Slot, aggregatorIn } // Set sync contributor's aggregate index, slot and subcommittee index as seen. -func (s *Service) setSyncContributionIndexSlotSeen(slot types.Slot, aggregatorIndex types.ValidatorIndex, subComIdx types.CommitteeIndex) { +func (s *Service) setSyncContributionIndexSlotSeen(slot primitives.Slot, aggregatorIndex primitives.ValidatorIndex, subComIdx primitives.CommitteeIndex) { s.seenSyncContributionLock.Lock() defer s.seenSyncContributionLock.Unlock() b := append(bytesutil.Bytes32(uint64(aggregatorIndex)), bytesutil.Bytes32(uint64(slot))...) diff --git a/beacon-chain/sync/validate_sync_contribution_proof_test.go b/beacon-chain/sync/validate_sync_contribution_proof_test.go index 4715b32e01..2a35787edb 100644 --- a/beacon-chain/sync/validate_sync_contribution_proof_test.go +++ b/beacon-chain/sync/validate_sync_contribution_proof_test.go @@ -29,7 +29,7 @@ import ( mockSync "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -323,12 +323,12 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { sc, err := hState.CurrentSyncCommittee() assert.NoError(t, err) for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSubnetCount; i++ { - coms, err := altair.SyncSubCommitteePubkeys(sc, types.CommitteeIndex(i)) + coms, err := altair.SyncSubCommitteePubkeys(sc, primitives.CommitteeIndex(i)) assert.NoError(t, err) for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), primitives.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -380,12 +380,12 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { sc, err := hState.CurrentSyncCommittee() assert.NoError(t, err) for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSubnetCount; i++ { - coms, err := altair.SyncSubCommitteePubkeys(sc, types.CommitteeIndex(i)) + coms, err := altair.SyncSubCommitteePubkeys(sc, primitives.CommitteeIndex(i)) assert.NoError(t, err) for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), primitives.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -400,7 +400,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { s.cfg.chain = &mockChain.ChainService{ ValidatorsRoot: [32]byte{'A'}, Genesis: time.Now().Add(-time.Second * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Duration(msg.Message.Contribution.Slot)), - SyncCommitteeIndices: []types.CommitteeIndex{types.CommitteeIndex(msg.Message.Contribution.SubcommitteeIndex * subCommitteeSize)}, + SyncCommitteeIndices: []primitives.CommitteeIndex{primitives.CommitteeIndex(msg.Message.Contribution.SubcommitteeIndex * subCommitteeSize)}, } msg.Message.Contribution.AggregationBits.SetBitAt(1, true) @@ -447,12 +447,12 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { assert.NoError(t, err) var pubkey []byte for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSubnetCount; i++ { - coms, err := altair.SyncSubCommitteePubkeys(sc, types.CommitteeIndex(i)) + coms, err := altair.SyncSubCommitteePubkeys(sc, primitives.CommitteeIndex(i)) assert.NoError(t, err) for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), primitives.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -479,7 +479,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { s.cfg.chain = &mockChain.ChainService{ ValidatorsRoot: [32]byte{'A'}, Genesis: time.Now().Add(-time.Second * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Duration(msg.Message.Contribution.Slot)), - SyncCommitteeIndices: []types.CommitteeIndex{types.CommitteeIndex(msg.Message.Contribution.SubcommitteeIndex * subCommitteeSize)}, + SyncCommitteeIndices: []primitives.CommitteeIndex{primitives.CommitteeIndex(msg.Message.Contribution.SubcommitteeIndex * subCommitteeSize)}, PublicKey: bytesutil.ToBytes48(pubkey), SyncSelectionProofDomain: d, } @@ -525,12 +525,12 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { sc, err := hState.CurrentSyncCommittee() assert.NoError(t, err) for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSubnetCount; i++ { - coms, err := altair.SyncSubCommitteePubkeys(sc, types.CommitteeIndex(i)) + coms, err := altair.SyncSubCommitteePubkeys(sc, primitives.CommitteeIndex(i)) assert.NoError(t, err) for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), primitives.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -563,7 +563,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { s.cfg.chain = &mockChain.ChainService{ ValidatorsRoot: [32]byte{'A'}, Genesis: time.Now().Add(-time.Second * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Duration(msg.Message.Contribution.Slot)), - SyncCommitteeIndices: []types.CommitteeIndex{1}, + SyncCommitteeIndices: []primitives.CommitteeIndex{1}, } s.initCaches() @@ -609,12 +609,12 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { cd, err := signing.Domain(hState.Fork(), slots.ToEpoch(slots.PrevSlot(hState.Slot())), params.BeaconConfig().DomainContributionAndProof, hState.GenesisValidatorsRoot()) assert.NoError(t, err) for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSubnetCount; i++ { - coms, err := altair.SyncSubCommitteePubkeys(sc, types.CommitteeIndex(i)) + coms, err := altair.SyncSubCommitteePubkeys(sc, primitives.CommitteeIndex(i)) assert.NoError(t, err) for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), primitives.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -644,7 +644,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { s.cfg.chain = &mockChain.ChainService{ ValidatorsRoot: [32]byte{'A'}, Genesis: time.Now().Add(-time.Second * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Duration(msg.Message.Contribution.Slot)), - SyncCommitteeIndices: []types.CommitteeIndex{types.CommitteeIndex(msg.Message.Contribution.SubcommitteeIndex * subCommitteeSize)}, + SyncCommitteeIndices: []primitives.CommitteeIndex{primitives.CommitteeIndex(msg.Message.Contribution.SubcommitteeIndex * subCommitteeSize)}, PublicKey: bytesutil.ToBytes48(keys[msg.Message.AggregatorIndex].PublicKey().Marshal()), SyncSelectionProofDomain: d, SyncContributionProofDomain: cd, @@ -696,13 +696,13 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { assert.NoError(t, err) var pubkeys [][]byte for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSubnetCount; i++ { - coms, err := altair.SyncSubCommitteePubkeys(sc, types.CommitteeIndex(i)) + coms, err := altair.SyncSubCommitteePubkeys(sc, primitives.CommitteeIndex(i)) pubkeys = coms assert.NoError(t, err) for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), primitives.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -739,7 +739,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { s.cfg.chain = &mockChain.ChainService{ ValidatorsRoot: [32]byte{'A'}, Genesis: time.Now().Add(-time.Second * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Duration(msg.Message.Contribution.Slot)), - SyncCommitteeIndices: []types.CommitteeIndex{types.CommitteeIndex(msg.Message.Contribution.SubcommitteeIndex * subCommitteeSize)}, + SyncCommitteeIndices: []primitives.CommitteeIndex{primitives.CommitteeIndex(msg.Message.Contribution.SubcommitteeIndex * subCommitteeSize)}, PublicKey: bytesutil.ToBytes48(keys[msg.Message.AggregatorIndex].PublicKey().Marshal()), SyncSelectionProofDomain: pd, SyncContributionProofDomain: cd, @@ -792,13 +792,13 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { assert.NoError(t, err) var pubkeys [][]byte for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSubnetCount; i++ { - coms, err := altair.SyncSubCommitteePubkeys(sc, types.CommitteeIndex(i)) + coms, err := altair.SyncSubCommitteePubkeys(sc, primitives.CommitteeIndex(i)) pubkeys = coms assert.NoError(t, err) for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), primitives.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -837,7 +837,7 @@ func TestService_ValidateSyncContributionAndProof(t *testing.T) { s.cfg.chain = &mockChain.ChainService{ ValidatorsRoot: [32]byte{'A'}, Genesis: time.Now().Add(-time.Second * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Duration(msg.Message.Contribution.Slot)), - SyncCommitteeIndices: []types.CommitteeIndex{types.CommitteeIndex(msg.Message.Contribution.SubcommitteeIndex * subCommitteeSize)}, + SyncCommitteeIndices: []primitives.CommitteeIndex{primitives.CommitteeIndex(msg.Message.Contribution.SubcommitteeIndex * subCommitteeSize)}, PublicKey: bytesutil.ToBytes48(keys[msg.Message.AggregatorIndex].PublicKey().Marshal()), SyncSelectionProofDomain: pd, SyncContributionProofDomain: cd, @@ -939,13 +939,13 @@ func TestValidateSyncContributionAndProof(t *testing.T) { assert.NoError(t, err) var pubkeys [][]byte for i := uint64(0); i < params.BeaconConfig().SyncCommitteeSubnetCount; i++ { - coms, err := altair.SyncSubCommitteePubkeys(sc, types.CommitteeIndex(i)) + coms, err := altair.SyncSubCommitteePubkeys(sc, primitives.CommitteeIndex(i)) pubkeys = coms assert.NoError(t, err) for _, p := range coms { idx, ok := hState.ValidatorIndexByPubkey(bytesutil.ToBytes48(p)) assert.Equal(t, true, ok) - rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), types.CommitteeIndex(i)) + rt, err := syncSelectionProofSigningRoot(hState, slots.PrevSlot(hState.Slot()), primitives.CommitteeIndex(i)) assert.NoError(t, err) sig := keys[idx].Sign(rt[:]) isAggregator, err := altair.IsSyncCommitteeAggregator(sig.Marshal()) @@ -982,7 +982,7 @@ func TestValidateSyncContributionAndProof(t *testing.T) { s.cfg.chain = &mockChain.ChainService{ ValidatorsRoot: [32]byte{'A'}, Genesis: time.Now().Add(-time.Second * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Duration(msg.Message.Contribution.Slot)), - SyncCommitteeIndices: []types.CommitteeIndex{types.CommitteeIndex(msg.Message.Contribution.SubcommitteeIndex * subCommitteeSize)}, + SyncCommitteeIndices: []primitives.CommitteeIndex{primitives.CommitteeIndex(msg.Message.Contribution.SubcommitteeIndex * subCommitteeSize)}, PublicKey: bytesutil.ToBytes48(keys[msg.Message.AggregatorIndex].PublicKey().Marshal()), SyncSelectionProofDomain: pd, SyncContributionProofDomain: cd, @@ -1037,7 +1037,7 @@ func fillUpBlocksAndState(ctx context.Context, t *testing.T, beaconDB db.Databas testState := gs.Copy() var hRoot [32]byte - for i := types.Slot(1); i <= params.BeaconConfig().SlotsPerEpoch; i++ { + for i := primitives.Slot(1); i <= params.BeaconConfig().SlotsPerEpoch; i++ { blk, err := util.GenerateFullBlockAltair(testState, keys, util.DefaultBlockGenConfig(), i) require.NoError(t, err) r, err := blk.Block.HashTreeRoot() @@ -1055,7 +1055,7 @@ func fillUpBlocksAndState(ctx context.Context, t *testing.T, beaconDB db.Databas return hRoot, keys } -func syncSelectionProofSigningRoot(st state.BeaconState, slot types.Slot, comIdx types.CommitteeIndex) ([32]byte, error) { +func syncSelectionProofSigningRoot(st state.BeaconState, slot primitives.Slot, comIdx primitives.CommitteeIndex) ([32]byte, error) { dom, err := signing.Domain(st.Fork(), slots.ToEpoch(slot), params.BeaconConfig().DomainSyncCommitteeSelectionProof, st.GenesisValidatorsRoot()) if err != nil { return [32]byte{}, err diff --git a/beacon-chain/sync/validate_voluntary_exit.go b/beacon-chain/sync/validate_voluntary_exit.go index b13f431af1..ca49d41486 100644 --- a/beacon-chain/sync/validate_voluntary_exit.go +++ b/beacon-chain/sync/validate_voluntary_exit.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/feed" opfeed "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/feed/operation" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "go.opencensus.io/trace" @@ -81,7 +81,7 @@ func (s *Service) validateVoluntaryExit(ctx context.Context, pid peer.ID, msg *p } // Returns true if the node has already received a valid exit request for the validator with index `i`. -func (s *Service) hasSeenExitIndex(i types.ValidatorIndex) bool { +func (s *Service) hasSeenExitIndex(i primitives.ValidatorIndex) bool { s.seenExitLock.RLock() defer s.seenExitLock.RUnlock() _, seen := s.seenExitCache.Get(i) @@ -89,7 +89,7 @@ func (s *Service) hasSeenExitIndex(i types.ValidatorIndex) bool { } // Set exit request index `i` in seen exit request cache. -func (s *Service) setExitIndexSeen(i types.ValidatorIndex) { +func (s *Service) setExitIndexSeen(i primitives.ValidatorIndex) { s.seenExitLock.Lock() defer s.seenExitLock.Unlock() s.seenExitCache.Add(i, true) diff --git a/cmd/prysmctl/p2p/handshake.go b/cmd/prysmctl/p2p/handshake.go index d88961515f..1403268e5e 100644 --- a/cmd/prysmctl/p2p/handshake.go +++ b/cmd/prysmctl/p2p/handshake.go @@ -5,7 +5,7 @@ import ( libp2pcore "github.com/libp2p/go-libp2p/core" "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/network/forks" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -27,7 +27,7 @@ func (c *client) pingHandler(_ context.Context, _ interface{}, stream libp2pcore if _, err := stream.Write([]byte{responseCodeSuccess}); err != nil { return err } - sq := types.SSZUint64(c.MetadataSeq()) + sq := primitives.SSZUint64(c.MetadataSeq()) if _, err := c.Encoding().EncodeWithMaxLength(stream, &sq); err != nil { return err } diff --git a/cmd/prysmctl/p2p/mock_chain.go b/cmd/prysmctl/p2p/mock_chain.go index ae10c22358..33dab78a86 100644 --- a/cmd/prysmctl/p2p/mock_chain.go +++ b/cmd/prysmctl/p2p/mock_chain.go @@ -4,7 +4,7 @@ import ( "time" "github.com/prysmaticlabs/prysm/v3/beacon-chain/forkchoice" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" ) @@ -31,6 +31,6 @@ func (m *mockChain) GenesisTime() time.Time { return m.genesisTime } -func (m *mockChain) CurrentSlot() types.Slot { +func (m *mockChain) CurrentSlot() primitives.Slot { return slots.SinceGenesis(m.genesisTime) } diff --git a/cmd/prysmctl/p2p/request_blocks.go b/cmd/prysmctl/p2p/request_blocks.go index af05e5a77d..f830f9e801 100644 --- a/cmd/prysmctl/p2p/request_blocks.go +++ b/cmd/prysmctl/p2p/request_blocks.go @@ -14,7 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/cmd" "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" "github.com/sirupsen/logrus" @@ -139,8 +139,8 @@ func cliActionRequestBlocks(cliCtx *cli.Context) error { return err } - startSlot := types.Slot(requestBlocksFlags.StartSlot) - var headSlot *types.Slot + startSlot := primitives.Slot(requestBlocksFlags.StartSlot) + var headSlot *primitives.Slot if startSlot == 0 { headResp, err := c.beaconClient.GetChainHead(ctx, &emptypb.Empty{}) if err != nil { diff --git a/config/params/config.go b/config/params/config.go index 5085e2bdce..b662ddcc1d 100644 --- a/config/params/config.go +++ b/config/params/config.go @@ -6,20 +6,20 @@ import ( "github.com/ethereum/go-ethereum/common" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ) // BeaconChainConfig contains constant configs for node to participate in beacon chain. type BeaconChainConfig struct { // Constants (non-configurable) - GenesisSlot types.Slot `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 epoch for validators. - FarFutureSlot types.Slot `yaml:"FAR_FUTURE_SLOT"` // FarFutureSlot represents a slot extremely far away in the future. - 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 primitives.Slot `yaml:"GENESIS_SLOT"` // GenesisSlot represents the first canonical slot number of the beacon chain. + GenesisEpoch primitives.Epoch `yaml:"GENESIS_EPOCH"` // GenesisEpoch represents the first canonical epoch number of the beacon chain. + FarFutureEpoch primitives.Epoch `yaml:"FAR_FUTURE_EPOCH"` // FarFutureEpoch represents a epoch extremely far away in the future used as the default penalization epoch for validators. + FarFutureSlot primitives.Slot `yaml:"FAR_FUTURE_SLOT"` // FarFutureSlot represents a slot extremely far away in the future. + 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. PresetBase string `yaml:"PRESET_BASE" spec:"true"` // PresetBase represents the underlying spec preset this config is based on. @@ -49,22 +49,22 @@ 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 Ethereum Beacon Chain genesis. Must be at least 1 second. - MinAttestationInclusionDelay types.Slot `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 types.Slot `yaml:"SLOTS_PER_EPOCH" spec:"true"` // SlotsPerEpoch is the number of slots in an epoch. - SqrRootSlotsPerEpoch types.Slot // SqrRootSlotsPerEpoch is a hard coded value where we take the square root of `SlotsPerEpoch` and round down. - 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 types.Slot `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 types.Slot `yaml:"SAFE_SLOTS_TO_UPDATE_JUSTIFIED" spec:"true"` // SafeSlotsToUpdateJustified is the minimal slots needed to update justified check point. - DeprecatedSafeSlotsToImportOptimistically types.Slot `yaml:"SAFE_SLOTS_TO_IMPORT_OPTIMISTICALLY" spec:"true"` // SafeSlotsToImportOptimistically is the minimal number of slots to wait before importing optimistically a pre-merge block - 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 Ethereum Beacon Chain genesis. Must be at least 1 second. + MinAttestationInclusionDelay primitives.Slot `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 primitives.Slot `yaml:"SLOTS_PER_EPOCH" spec:"true"` // SlotsPerEpoch is the number of slots in an epoch. + SqrRootSlotsPerEpoch primitives.Slot // SqrRootSlotsPerEpoch is a hard coded value where we take the square root of `SlotsPerEpoch` and round down. + MinSeedLookahead primitives.Epoch `yaml:"MIN_SEED_LOOKAHEAD" spec:"true"` // MinSeedLookahead is the duration of randao look ahead seed. + MaxSeedLookahead primitives.Epoch `yaml:"MAX_SEED_LOOKAHEAD" spec:"true"` // MaxSeedLookahead is the duration a validator has to wait for entry and exit in epoch. + EpochsPerEth1VotingPeriod primitives.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 primitives.Slot `yaml:"SLOTS_PER_HISTORICAL_ROOT" spec:"true"` // SlotsPerHistoricalRoot defines how often the historical root is saved. + MinValidatorWithdrawabilityDelay primitives.Epoch `yaml:"MIN_VALIDATOR_WITHDRAWABILITY_DELAY" spec:"true"` // MinValidatorWithdrawabilityDelay is the shortest amount of time a validator has to wait to withdraw. + ShardCommitteePeriod primitives.Epoch `yaml:"SHARD_COMMITTEE_PERIOD" spec:"true"` // ShardCommitteePeriod is the minimum amount of epochs a validator must participate before exiting. + MinEpochsToInactivityPenalty primitives.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 primitives.Slot `yaml:"SAFE_SLOTS_TO_UPDATE_JUSTIFIED" spec:"true"` // SafeSlotsToUpdateJustified is the minimal slots needed to update justified check point. + DeprecatedSafeSlotsToImportOptimistically primitives.Slot `yaml:"SAFE_SLOTS_TO_IMPORT_OPTIMISTICALLY" spec:"true"` // SafeSlotsToImportOptimistically is the minimal number of slots to wait before importing optimistically a pre-merge block + SecondsPerETH1Block uint64 `yaml:"SECONDS_PER_ETH1_BLOCK" spec:"true"` // SecondsPerETH1Block is the approximate time for a single eth1 block to be produced. // Fork choice algorithm constants. ProposerScoreBoost uint64 `yaml:"PROPOSER_SCORE_BOOST" spec:"true"` // ProposerScoreBoost defines a value that is a % of the committee weight for fork-choice boosting. @@ -80,10 +80,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 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. + EpochsPerHistoricalVector primitives.Epoch `yaml:"EPOCHS_PER_HISTORICAL_VECTOR" spec:"true"` // EpochsPerHistoricalVector defines max length in epoch to store old historical stats in beacon state. + EpochsPerSlashingsVector primitives.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. @@ -119,41 +119,41 @@ type BeaconChainConfig struct { DomainBLSToExecutionChange [4]byte // DomainBLSToExecutionChange defines the BLS signature domain to change withdrawal addresses to ETH1 prefix // Prysm constants. - GweiPerEth uint64 // GweiPerEth is the amount of gwei corresponding to 1 eth. - BLSSecretKeyLength int // BLSSecretKeyLength defines the expected length of BLS secret keys in bytes. - BLSPubkeyLength int // BLSPubkeyLength defines the expected length of BLS public keys in bytes. - DefaultBufferSize int // DefaultBufferSize for channels across the Prysm repository. - ValidatorPrivkeyFileName string // ValidatorPrivKeyFileName specifies the string name of a validator private key file. - WithdrawalPrivkeyFileName string // WithdrawalPrivKeyFileName specifies the string name of a withdrawal private key file. - RPCSyncCheck time.Duration // Number of seconds to query the sync service, to find out if the node is synced or not. - EmptySignature [96]byte // EmptySignature is used to represent a zeroed out BLS Signature. - DefaultPageSize int // DefaultPageSize defines the default page size for RPC server request. - MaxPeersToSync int // MaxPeersToSync describes the limit for number of peers in round robin sync. - SlotsPerArchivedPoint types.Slot // SlotsPerArchivedPoint defines the number of slots per one archived point. - GenesisCountdownInterval time.Duration // How often to log the countdown until the genesis time is reached. - BeaconStateFieldCount int // BeaconStateFieldCount defines how many fields are in the Phase0 beacon state. - BeaconStateAltairFieldCount int // BeaconStateAltairFieldCount defines how many fields are in the beacon state post upgrade to Altair. - BeaconStateBellatrixFieldCount int // BeaconStateBellatrixFieldCount defines how many fields are in beacon state post upgrade to Bellatrix. - BeaconStateCapellaFieldCount int // BeaconStateCapellaFieldCount defines how many fields are in beacon state post upgrade to Capella. + GweiPerEth uint64 // GweiPerEth is the amount of gwei corresponding to 1 eth. + BLSSecretKeyLength int // BLSSecretKeyLength defines the expected length of BLS secret keys in bytes. + BLSPubkeyLength int // BLSPubkeyLength defines the expected length of BLS public keys in bytes. + DefaultBufferSize int // DefaultBufferSize for channels across the Prysm repository. + ValidatorPrivkeyFileName string // ValidatorPrivKeyFileName specifies the string name of a validator private key file. + WithdrawalPrivkeyFileName string // WithdrawalPrivKeyFileName specifies the string name of a withdrawal private key file. + RPCSyncCheck time.Duration // Number of seconds to query the sync service, to find out if the node is synced or not. + EmptySignature [96]byte // EmptySignature is used to represent a zeroed out BLS Signature. + DefaultPageSize int // DefaultPageSize defines the default page size for RPC server request. + MaxPeersToSync int // MaxPeersToSync describes the limit for number of peers in round robin sync. + SlotsPerArchivedPoint primitives.Slot // SlotsPerArchivedPoint defines the number of slots per one archived point. + GenesisCountdownInterval time.Duration // How often to log the countdown until the genesis time is reached. + BeaconStateFieldCount int // BeaconStateFieldCount defines how many fields are in the Phase0 beacon state. + BeaconStateAltairFieldCount int // BeaconStateAltairFieldCount defines how many fields are in the beacon state post upgrade to Altair. + BeaconStateBellatrixFieldCount int // BeaconStateBellatrixFieldCount defines how many fields are in beacon state post upgrade to Bellatrix. + BeaconStateCapellaFieldCount int // BeaconStateCapellaFieldCount defines how many fields are in beacon state post upgrade to Capella. // Slasher constants. - 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. + WeakSubjectivityPeriod primitives.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 primitives.Epoch // PruneSlasherStoragePeriod defines the time period expressed in number of epochs were proof of stake network should prune attestation and block header store. // Slashing protection constants. - SlashingProtectionPruningEpochs types.Epoch // SlashingProtectionPruningEpochs defines a period after which all prior epochs are pruned in the validator database. + SlashingProtectionPruningEpochs primitives.Epoch // SlashingProtectionPruningEpochs defines a period after which all prior epochs are pruned in the validator database. // Fork-related values. - GenesisForkVersion []byte `yaml:"GENESIS_FORK_VERSION" spec:"true"` // GenesisForkVersion is used to track fork version between state transitions. - AltairForkVersion []byte `yaml:"ALTAIR_FORK_VERSION" spec:"true"` // AltairForkVersion is used to represent the fork version for altair. - AltairForkEpoch types.Epoch `yaml:"ALTAIR_FORK_EPOCH" spec:"true"` // AltairForkEpoch is used to represent the assigned fork epoch for altair. - BellatrixForkVersion []byte `yaml:"BELLATRIX_FORK_VERSION" spec:"true"` // BellatrixForkVersion is used to represent the fork version for bellatrix. - BellatrixForkEpoch types.Epoch `yaml:"BELLATRIX_FORK_EPOCH" spec:"true"` // BellatrixForkEpoch is used to represent the assigned fork epoch for bellatrix. - CapellaForkVersion []byte `yaml:"CAPELLA_FORK_VERSION" spec:"true"` // CapellaForkVersion is used to represent the fork version for capella. - CapellaForkEpoch types.Epoch `yaml:"CAPELLA_FORK_EPOCH" spec:"true"` // CapellaForkEpoch is used to represent the assigned fork epoch for capella. + GenesisForkVersion []byte `yaml:"GENESIS_FORK_VERSION" spec:"true"` // GenesisForkVersion is used to track fork version between state transitions. + AltairForkVersion []byte `yaml:"ALTAIR_FORK_VERSION" spec:"true"` // AltairForkVersion is used to represent the fork version for altair. + AltairForkEpoch primitives.Epoch `yaml:"ALTAIR_FORK_EPOCH" spec:"true"` // AltairForkEpoch is used to represent the assigned fork epoch for altair. + BellatrixForkVersion []byte `yaml:"BELLATRIX_FORK_VERSION" spec:"true"` // BellatrixForkVersion is used to represent the fork version for bellatrix. + BellatrixForkEpoch primitives.Epoch `yaml:"BELLATRIX_FORK_EPOCH" spec:"true"` // BellatrixForkEpoch is used to represent the assigned fork epoch for bellatrix. + CapellaForkVersion []byte `yaml:"CAPELLA_FORK_VERSION" spec:"true"` // CapellaForkVersion is used to represent the fork version for capella. + CapellaForkEpoch primitives.Epoch `yaml:"CAPELLA_FORK_EPOCH" spec:"true"` // CapellaForkEpoch is used to represent the assigned fork epoch for capella. - ForkVersionSchedule map[[fieldparams.VersionLength]byte]types.Epoch // Schedule of fork epochs by version. - ForkVersionNames map[[fieldparams.VersionLength]byte]string // Human-readable names of fork versions. + ForkVersionSchedule map[[fieldparams.VersionLength]byte]primitives.Epoch // Schedule of fork epochs by version. + ForkVersionNames map[[fieldparams.VersionLength]byte]string // Human-readable names of fork versions. // Weak subjectivity values. SafetyDecay uint64 // SafetyDecay is defined as the loss in the 1/3 consensus safety margin of the casper FFG mechanism. @@ -177,10 +177,10 @@ type BeaconChainConfig struct { SyncCommitteeSubnetCount uint64 `yaml:"SYNC_COMMITTEE_SUBNET_COUNT" spec:"true"` // SyncCommitteeSubnetCount for sync committee subnet count. // Misc. - SyncCommitteeSize uint64 `yaml:"SYNC_COMMITTEE_SIZE" spec:"true"` // SyncCommitteeSize for light client sync committee size. - InactivityScoreBias uint64 `yaml:"INACTIVITY_SCORE_BIAS" spec:"true"` // InactivityScoreBias for calculating score bias penalties during inactivity - InactivityScoreRecoveryRate uint64 `yaml:"INACTIVITY_SCORE_RECOVERY_RATE" spec:"true"` // InactivityScoreRecoveryRate for recovering score bias penalties during inactivity. - EpochsPerSyncCommitteePeriod types.Epoch `yaml:"EPOCHS_PER_SYNC_COMMITTEE_PERIOD" spec:"true"` // EpochsPerSyncCommitteePeriod defines how many epochs per sync committee period. + SyncCommitteeSize uint64 `yaml:"SYNC_COMMITTEE_SIZE" spec:"true"` // SyncCommitteeSize for light client sync committee size. + InactivityScoreBias uint64 `yaml:"INACTIVITY_SCORE_BIAS" spec:"true"` // InactivityScoreBias for calculating score bias penalties during inactivity + InactivityScoreRecoveryRate uint64 `yaml:"INACTIVITY_SCORE_RECOVERY_RATE" spec:"true"` // InactivityScoreRecoveryRate for recovering score bias penalties during inactivity. + EpochsPerSyncCommitteePeriod primitives.Epoch `yaml:"EPOCHS_PER_SYNC_COMMITTEE_PERIOD" spec:"true"` // EpochsPerSyncCommitteePeriod defines how many epochs per sync committee period. // Updated penalty values. This moves penalty parameters toward their final, maximum security values. // Note: We do not override previous configuration values but instead creates new values and replaces usage throughout. @@ -195,16 +195,16 @@ type BeaconChainConfig struct { MinSyncCommitteeParticipants uint64 `yaml:"MIN_SYNC_COMMITTEE_PARTICIPANTS" spec:"true"` // MinSyncCommitteeParticipants defines the minimum amount of sync committee participants for which the light client acknowledges the signature. // Bellatrix - TerminalBlockHash common.Hash `yaml:"TERMINAL_BLOCK_HASH" spec:"true"` // TerminalBlockHash of beacon chain. - TerminalBlockHashActivationEpoch types.Epoch `yaml:"TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH" spec:"true"` // TerminalBlockHashActivationEpoch of beacon chain. - TerminalTotalDifficulty string `yaml:"TERMINAL_TOTAL_DIFFICULTY" spec:"true"` // TerminalTotalDifficulty is part of the experimental Bellatrix spec. This value is type is currently TBD. - DefaultFeeRecipient common.Address // DefaultFeeRecipient where the transaction fee goes to. - EthBurnAddressHex string // EthBurnAddressHex is the constant eth address written in hex format to burn fees in that network. the default is 0x0 - DefaultBuilderGasLimit uint64 // DefaultBuilderGasLimit is the default used to set the gaslimit for the Builder APIs, typically at around 30M wei. + TerminalBlockHash common.Hash `yaml:"TERMINAL_BLOCK_HASH" spec:"true"` // TerminalBlockHash of beacon chain. + TerminalBlockHashActivationEpoch primitives.Epoch `yaml:"TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH" spec:"true"` // TerminalBlockHashActivationEpoch of beacon chain. + TerminalTotalDifficulty string `yaml:"TERMINAL_TOTAL_DIFFICULTY" spec:"true"` // TerminalTotalDifficulty is part of the experimental Bellatrix spec. This value is type is currently TBD. + DefaultFeeRecipient common.Address // DefaultFeeRecipient where the transaction fee goes to. + EthBurnAddressHex string // EthBurnAddressHex is the constant eth address written in hex format to burn fees in that network. the default is 0x0 + DefaultBuilderGasLimit uint64 // DefaultBuilderGasLimit is the default used to set the gaslimit for the Builder APIs, typically at around 30M wei. // Mev-boost circuit breaker - MaxBuilderConsecutiveMissedSlots types.Slot // MaxBuilderConsecutiveMissedSlots defines the number of consecutive skip slot to fallback from using relay/builder to local execution engine for block construction. - MaxBuilderEpochMissedSlots types.Slot // MaxBuilderEpochMissedSlots is defines the number of total skip slot (per epoch rolling windows) to fallback from using relay/builder to local execution engine for block construction. + MaxBuilderConsecutiveMissedSlots primitives.Slot // MaxBuilderConsecutiveMissedSlots defines the number of consecutive skip slot to fallback from using relay/builder to local execution engine for block construction. + MaxBuilderEpochMissedSlots primitives.Slot // MaxBuilderEpochMissedSlots is defines the number of total skip slot (per epoch rolling windows) to fallback from using relay/builder to local execution engine for block construction. // Execution engine timeout value ExecutionEngineTimeoutValue uint64 // ExecutionEngineTimeoutValue defines the seconds to wait before timing out engine endpoints with execution payload execution semantics (newPayload, forkchoiceUpdated). @@ -217,8 +217,8 @@ func (b *BeaconChainConfig) InitializeForkSchedule() { b.ForkVersionNames = configForkNames(b) } -func configForkSchedule(b *BeaconChainConfig) map[[fieldparams.VersionLength]byte]types.Epoch { - fvs := map[[fieldparams.VersionLength]byte]types.Epoch{} +func configForkSchedule(b *BeaconChainConfig) map[[fieldparams.VersionLength]byte]primitives.Epoch { + fvs := map[[fieldparams.VersionLength]byte]primitives.Epoch{} fvs[bytesutil.ToBytes4(b.GenesisForkVersion)] = b.GenesisEpoch fvs[bytesutil.ToBytes4(b.AltairForkVersion)] = b.AltairForkEpoch fvs[bytesutil.ToBytes4(b.BellatrixForkVersion)] = b.BellatrixForkEpoch diff --git a/config/params/loader.go b/config/params/loader.go index 9ba8902993..599d021632 100644 --- a/config/params/loader.go +++ b/config/params/loader.go @@ -7,7 +7,7 @@ import ( "strings" "github.com/pkg/errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/math" log "github.com/sirupsen/logrus" "gopkg.in/yaml.v2" @@ -63,7 +63,7 @@ func UnmarshalConfig(yamlFile []byte, conf *BeaconChainConfig) (*BeaconChainConf conf.ConfigName = DevnetName } // recompute SqrRootSlotsPerEpoch constant to handle non-standard values of SlotsPerEpoch - conf.SqrRootSlotsPerEpoch = types.Slot(math.IntegerSquareRoot(uint64(conf.SlotsPerEpoch))) + conf.SqrRootSlotsPerEpoch = primitives.Slot(math.IntegerSquareRoot(uint64(conf.SlotsPerEpoch))) log.Debugf("Config file values: %+v", conf) return conf, nil } diff --git a/config/params/network_config.go b/config/params/network_config.go index a4e1d9af09..88c421b846 100644 --- a/config/params/network_config.go +++ b/config/params/network_config.go @@ -4,23 +4,23 @@ import ( "time" "github.com/mohae/deepcopy" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // NetworkConfig defines the spec based network parameters. type NetworkConfig struct { - GossipMaxSize uint64 `yaml:"GOSSIP_MAX_SIZE"` // GossipMaxSize is the maximum allowed size of uncompressed gossip messages. - GossipMaxSizeBellatrix uint64 `yaml:"GOSSIP_MAX_SIZE_BELLATRIX"` // GossipMaxSizeBellatrix is the maximum allowed size of uncompressed gossip messages after the bellatrix epoch. - MaxChunkSize uint64 `yaml:"MAX_CHUNK_SIZE"` // MaxChunkSize is the maximum allowed size of uncompressed req/resp chunked responses. - MaxChunkSizeBellatrix uint64 `yaml:"MAX_CHUNK_SIZE_BELLATRIX"` // MaxChunkSizeBellatrix is the maximum allowed size of uncompressed req/resp chunked responses after the bellatrix epoch. - AttestationSubnetCount uint64 `yaml:"ATTESTATION_SUBNET_COUNT"` // AttestationSubnetCount is the number of attestation subnets used in the gossipsub protocol. - AttestationPropagationSlotRange types.Slot `yaml:"ATTESTATION_PROPAGATION_SLOT_RANGE"` // AttestationPropagationSlotRange is the maximum number of slots during which an attestation can be propagated. - MaxRequestBlocks uint64 `yaml:"MAX_REQUEST_BLOCKS"` // MaxRequestBlocks is the maximum number of blocks in a single request. - TtfbTimeout time.Duration `yaml:"TTFB_TIMEOUT"` // TtfbTimeout is the maximum time to wait for first byte of request response (time-to-first-byte). - RespTimeout time.Duration `yaml:"RESP_TIMEOUT"` // RespTimeout is the maximum time for complete response transfer. - MaximumGossipClockDisparity time.Duration `yaml:"MAXIMUM_GOSSIP_CLOCK_DISPARITY"` // MaximumGossipClockDisparity is the maximum milliseconds of clock disparity assumed between honest nodes. - MessageDomainInvalidSnappy [4]byte `yaml:"MESSAGE_DOMAIN_INVALID_SNAPPY"` // MessageDomainInvalidSnappy is the 4-byte domain for gossip message-id isolation of invalid snappy messages. - MessageDomainValidSnappy [4]byte `yaml:"MESSAGE_DOMAIN_VALID_SNAPPY"` // MessageDomainValidSnappy is the 4-byte domain for gossip message-id isolation of valid snappy messages. + GossipMaxSize uint64 `yaml:"GOSSIP_MAX_SIZE"` // GossipMaxSize is the maximum allowed size of uncompressed gossip messages. + GossipMaxSizeBellatrix uint64 `yaml:"GOSSIP_MAX_SIZE_BELLATRIX"` // GossipMaxSizeBellatrix is the maximum allowed size of uncompressed gossip messages after the bellatrix epoch. + MaxChunkSize uint64 `yaml:"MAX_CHUNK_SIZE"` // MaxChunkSize is the maximum allowed size of uncompressed req/resp chunked responses. + MaxChunkSizeBellatrix uint64 `yaml:"MAX_CHUNK_SIZE_BELLATRIX"` // MaxChunkSizeBellatrix is the maximum allowed size of uncompressed req/resp chunked responses after the bellatrix epoch. + AttestationSubnetCount uint64 `yaml:"ATTESTATION_SUBNET_COUNT"` // AttestationSubnetCount is the number of attestation subnets used in the gossipsub protocol. + AttestationPropagationSlotRange primitives.Slot `yaml:"ATTESTATION_PROPAGATION_SLOT_RANGE"` // AttestationPropagationSlotRange is the maximum number of slots during which an attestation can be propagated. + MaxRequestBlocks uint64 `yaml:"MAX_REQUEST_BLOCKS"` // MaxRequestBlocks is the maximum number of blocks in a single request. + TtfbTimeout time.Duration `yaml:"TTFB_TIMEOUT"` // TtfbTimeout is the maximum time to wait for first byte of request response (time-to-first-byte). + RespTimeout time.Duration `yaml:"RESP_TIMEOUT"` // RespTimeout is the maximum time for complete response transfer. + MaximumGossipClockDisparity time.Duration `yaml:"MAXIMUM_GOSSIP_CLOCK_DISPARITY"` // MaximumGossipClockDisparity is the maximum milliseconds of clock disparity assumed between honest nodes. + MessageDomainInvalidSnappy [4]byte `yaml:"MESSAGE_DOMAIN_INVALID_SNAPPY"` // MessageDomainInvalidSnappy is the 4-byte domain for gossip message-id isolation of invalid snappy messages. + MessageDomainValidSnappy [4]byte `yaml:"MESSAGE_DOMAIN_VALID_SNAPPY"` // MessageDomainValidSnappy is the 4-byte domain for gossip message-id isolation of valid snappy messages. // DiscoveryV5 Config ETH2Key string // ETH2Key is the ENR key of the Ethereum consensus object in an enr. diff --git a/consensus-types/blocks/getters.go b/consensus-types/blocks/getters.go index 6804a4499a..3b69d66239 100644 --- a/consensus-types/blocks/getters.go +++ b/consensus-types/blocks/getters.go @@ -7,7 +7,7 @@ import ( ssz "github.com/prysmaticlabs/fastssz" field_params "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" validatorpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/validator-client" @@ -454,12 +454,12 @@ func (b *SignedBeaconBlock) UnmarshalSSZ(buf []byte) error { } // Slot returns the respective slot of the block. -func (b *BeaconBlock) Slot() types.Slot { +func (b *BeaconBlock) Slot() primitives.Slot { return b.slot } // ProposerIndex returns the proposer index of the beacon block. -func (b *BeaconBlock) ProposerIndex() types.ValidatorIndex { +func (b *BeaconBlock) ProposerIndex() primitives.ValidatorIndex { return b.proposerIndex } diff --git a/consensus-types/blocks/getters_test.go b/consensus-types/blocks/getters_test.go index ad8dbd3825..07e2592234 100644 --- a/consensus-types/blocks/getters_test.go +++ b/consensus-types/blocks/getters_test.go @@ -6,7 +6,7 @@ import ( ssz "github.com/prysmaticlabs/fastssz" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" pb "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -142,13 +142,13 @@ func Test_SignedBeaconBlock_UnmarshalSSZ(t *testing.T) { func Test_BeaconBlock_Slot(t *testing.T) { b := &BeaconBlock{} b.SetSlot(128) - assert.Equal(t, types.Slot(128), b.Slot()) + assert.Equal(t, primitives.Slot(128), b.Slot()) } func Test_BeaconBlock_ProposerIndex(t *testing.T) { b := &BeaconBlock{} b.SetProposerIndex(128) - assert.Equal(t, types.ValidatorIndex(128), b.ProposerIndex()) + assert.Equal(t, primitives.ValidatorIndex(128), b.ProposerIndex()) } func Test_BeaconBlock_ParentRoot(t *testing.T) { diff --git a/consensus-types/blocks/setters.go b/consensus-types/blocks/setters.go index f4e3c6d19a..656a0ab7ea 100644 --- a/consensus-types/blocks/setters.go +++ b/consensus-types/blocks/setters.go @@ -2,7 +2,7 @@ package blocks import ( "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" ) @@ -15,13 +15,13 @@ func (b *SignedBeaconBlock) SetSignature(sig []byte) { // SetSlot sets the respective slot of the block. // This function is not thread safe, it is only used during block creation. -func (b *BeaconBlock) SetSlot(slot types.Slot) { +func (b *BeaconBlock) SetSlot(slot primitives.Slot) { b.slot = slot } // SetProposerIndex sets the proposer index of the beacon block. // This function is not thread safe, it is only used during block creation. -func (b *BeaconBlock) SetProposerIndex(proposerIndex types.ValidatorIndex) { +func (b *BeaconBlock) SetProposerIndex(proposerIndex primitives.ValidatorIndex) { b.proposerIndex = proposerIndex } diff --git a/consensus-types/blocks/testing/mutator.go b/consensus-types/blocks/testing/mutator.go index 31c23c1217..23da634a07 100644 --- a/consensus-types/blocks/testing/mutator.go +++ b/consensus-types/blocks/testing/mutator.go @@ -3,7 +3,7 @@ package testing import ( "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" ) @@ -71,7 +71,7 @@ func SetBlockParentRoot(b interfaces.SignedBeaconBlock, pr [32]byte) (interfaces } // SetBlockSlot modifies the block's slot. -func SetBlockSlot(b interfaces.SignedBeaconBlock, s types.Slot) (interfaces.SignedBeaconBlock, error) { +func SetBlockSlot(b interfaces.SignedBeaconBlock, s primitives.Slot) (interfaces.SignedBeaconBlock, error) { return blockMutator{ Phase0: func(bb *eth.SignedBeaconBlock) { bb.Block.Slot = s }, Altair: func(bb *eth.SignedBeaconBlockAltair) { bb.Block.Slot = s }, @@ -81,7 +81,7 @@ func SetBlockSlot(b interfaces.SignedBeaconBlock, s types.Slot) (interfaces.Sign } // SetProposerIndex modifies the block's proposer index. -func SetProposerIndex(b interfaces.SignedBeaconBlock, idx types.ValidatorIndex) (interfaces.SignedBeaconBlock, error) { +func SetProposerIndex(b interfaces.SignedBeaconBlock, idx primitives.ValidatorIndex) (interfaces.SignedBeaconBlock, error) { return blockMutator{ Phase0: func(bb *eth.SignedBeaconBlock) { bb.Block.ProposerIndex = idx }, Altair: func(bb *eth.SignedBeaconBlockAltair) { bb.Block.ProposerIndex = idx }, diff --git a/consensus-types/blocks/types.go b/consensus-types/blocks/types.go index fe8f70a9a5..cb8dfd356f 100644 --- a/consensus-types/blocks/types.go +++ b/consensus-types/blocks/types.go @@ -6,7 +6,7 @@ import ( "github.com/pkg/errors" field_params "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" ) @@ -61,8 +61,8 @@ type BeaconBlockBody struct { // BeaconBlock is the main beacon block structure. It can represent any block type. type BeaconBlock struct { version int - slot types.Slot - proposerIndex types.ValidatorIndex + slot primitives.Slot + proposerIndex primitives.ValidatorIndex parentRoot [field_params.RootLength]byte stateRoot [field_params.RootLength]byte body *BeaconBlockBody diff --git a/consensus-types/interfaces/beacon_block.go b/consensus-types/interfaces/beacon_block.go index 4b582c00e7..fbf860ec8b 100644 --- a/consensus-types/interfaces/beacon_block.go +++ b/consensus-types/interfaces/beacon_block.go @@ -3,7 +3,7 @@ package interfaces import ( ssz "github.com/prysmaticlabs/fastssz" field_params "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" validatorpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/validator-client" @@ -37,10 +37,10 @@ type SignedBeaconBlock interface { // BeaconBlock describes an interface which states the methods // employed by an object that is a beacon block. type BeaconBlock interface { - Slot() types.Slot - SetSlot(slot types.Slot) - ProposerIndex() types.ValidatorIndex - SetProposerIndex(idx types.ValidatorIndex) + Slot() primitives.Slot + SetSlot(slot primitives.Slot) + ProposerIndex() primitives.ValidatorIndex + SetProposerIndex(idx primitives.ValidatorIndex) ParentRoot() [field_params.RootLength]byte SetParentRoot([]byte) StateRoot() [field_params.RootLength]byte diff --git a/consensus-types/mock/block.go b/consensus-types/mock/block.go index 8f701a318e..a0c34dab93 100644 --- a/consensus-types/mock/block.go +++ b/consensus-types/mock/block.go @@ -4,7 +4,7 @@ import ( ssz "github.com/prysmaticlabs/fastssz" field_params "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" validatorpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/validator-client" "google.golang.org/protobuf/proto" @@ -102,7 +102,7 @@ type BeaconBlock struct { Htr [field_params.RootLength]byte HtrErr error BeaconBlockBody interfaces.BeaconBlockBody - BlockSlot types.Slot + BlockSlot primitives.Slot } func (BeaconBlock) AsSignRequestObject() (validatorpb.SignRequestObject, error) { @@ -113,11 +113,11 @@ func (m BeaconBlock) HashTreeRoot() ([field_params.RootLength]byte, error) { return m.Htr, m.HtrErr } -func (m BeaconBlock) Slot() types.Slot { +func (m BeaconBlock) Slot() primitives.Slot { return m.BlockSlot } -func (BeaconBlock) ProposerIndex() types.ValidatorIndex { +func (BeaconBlock) ProposerIndex() primitives.ValidatorIndex { panic("implement me") } @@ -173,11 +173,11 @@ func (BeaconBlock) ToBlinded() (interfaces.BeaconBlock, error) { panic("implement me") } -func (BeaconBlock) SetSlot(_ types.Slot) { +func (BeaconBlock) SetSlot(_ primitives.Slot) { panic("implement me") } -func (BeaconBlock) SetProposerIndex(_ types.ValidatorIndex) { +func (BeaconBlock) SetProposerIndex(_ primitives.ValidatorIndex) { panic("implement me") } diff --git a/consensus-types/primitives/committee_index.go b/consensus-types/primitives/committee_index.go index a20adc21f1..28abfde83f 100644 --- a/consensus-types/primitives/committee_index.go +++ b/consensus-types/primitives/committee_index.go @@ -1,4 +1,4 @@ -package types +package primitives import ( "fmt" diff --git a/consensus-types/primitives/committee_index_test.go b/consensus-types/primitives/committee_index_test.go index 6ef20b0d9a..c96bd5c2ae 100644 --- a/consensus-types/primitives/committee_index_test.go +++ b/consensus-types/primitives/committee_index_test.go @@ -1,4 +1,4 @@ -package types +package primitives import ( "testing" diff --git a/consensus-types/primitives/domain.go b/consensus-types/primitives/domain.go index bcb6a84bb7..e3263009eb 100644 --- a/consensus-types/primitives/domain.go +++ b/consensus-types/primitives/domain.go @@ -1,4 +1,4 @@ -package types +package primitives import ( "fmt" diff --git a/consensus-types/primitives/domain_test.go b/consensus-types/primitives/domain_test.go index ebe3f82a6d..97e4599254 100644 --- a/consensus-types/primitives/domain_test.go +++ b/consensus-types/primitives/domain_test.go @@ -1,4 +1,4 @@ -package types +package primitives import ( "reflect" diff --git a/consensus-types/primitives/epoch.go b/consensus-types/primitives/epoch.go index d2b6985c0e..0318e8059d 100644 --- a/consensus-types/primitives/epoch.go +++ b/consensus-types/primitives/epoch.go @@ -1,4 +1,4 @@ -package types +package primitives import ( "fmt" diff --git a/consensus-types/primitives/epoch_test.go b/consensus-types/primitives/epoch_test.go index de94cadb40..69d0e202b2 100644 --- a/consensus-types/primitives/epoch_test.go +++ b/consensus-types/primitives/epoch_test.go @@ -1,26 +1,26 @@ -package types_test +package primitives_test import ( "fmt" "math" "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" mathprysm "github.com/prysmaticlabs/prysm/v3/math" "github.com/prysmaticlabs/prysm/v3/testing/require" ) func TestMaxEpoch(t *testing.T) { - require.Equal(t, types.Epoch(0), types.MaxEpoch(0, 0)) - require.Equal(t, types.Epoch(1), types.MaxEpoch(1, 0)) - require.Equal(t, types.Epoch(1), types.MaxEpoch(0, 1)) - require.Equal(t, types.Epoch(1000), types.MaxEpoch(100, 1000)) + require.Equal(t, primitives.Epoch(0), primitives.MaxEpoch(0, 0)) + require.Equal(t, primitives.Epoch(1), primitives.MaxEpoch(1, 0)) + require.Equal(t, primitives.Epoch(1), primitives.MaxEpoch(0, 1)) + require.Equal(t, primitives.Epoch(1000), primitives.MaxEpoch(100, 1000)) } func TestEpoch_Mul(t *testing.T) { tests := []struct { a, b uint64 - res types.Epoch + res primitives.Epoch panicMsg string }{ {a: 0, b: 1, res: 0}, @@ -36,13 +36,13 @@ func TestEpoch_Mul(t *testing.T) { for _, tt := range tests { t.Run(fmt.Sprintf("Epoch(%v).Mul(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Epoch + var res primitives.Epoch if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Epoch(tt.a).Mul(tt.b) + res = primitives.Epoch(tt.a).Mul(tt.b) }) } else { - res = types.Epoch(tt.a).Mul(tt.b) + res = primitives.Epoch(tt.a).Mul(tt.b) } if tt.res != res { t.Errorf("Epoch.Mul() = %v, want %v", res, tt.res) @@ -54,7 +54,7 @@ func TestEpoch_Mul(t *testing.T) { func TestEpoch_Div(t *testing.T) { tests := []struct { a, b uint64 - res types.Epoch + res primitives.Epoch panicMsg string }{ {a: 0, b: 1, res: 0}, @@ -69,13 +69,13 @@ func TestEpoch_Div(t *testing.T) { for _, tt := range tests { t.Run(fmt.Sprintf("Epoch(%v).Div(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Epoch + var res primitives.Epoch if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Epoch(tt.a).Div(tt.b) + res = primitives.Epoch(tt.a).Div(tt.b) }) } else { - res = types.Epoch(tt.a).Div(tt.b) + res = primitives.Epoch(tt.a).Div(tt.b) } if tt.res != res { t.Errorf("Epoch.Div() = %v, want %v", res, tt.res) @@ -87,7 +87,7 @@ func TestEpoch_Div(t *testing.T) { func TestEpoch_Add(t *testing.T) { tests := []struct { a, b uint64 - res types.Epoch + res primitives.Epoch panicMsg string }{ {a: 0, b: 1, res: 1}, @@ -103,26 +103,26 @@ func TestEpoch_Add(t *testing.T) { for _, tt := range tests { t.Run(fmt.Sprintf("Epoch(%v).Add(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Epoch + var res primitives.Epoch if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Epoch(tt.a).Add(tt.b) + res = primitives.Epoch(tt.a).Add(tt.b) }) } else { - res = types.Epoch(tt.a).Add(tt.b) + res = primitives.Epoch(tt.a).Add(tt.b) } if tt.res != res { t.Errorf("Epoch.Add() = %v, want %v", res, tt.res) } }) t.Run(fmt.Sprintf("Epoch(%v).AddEpoch(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Epoch + var res primitives.Epoch if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Epoch(tt.a).AddEpoch(types.Epoch(tt.b)) + res = primitives.Epoch(tt.a).AddEpoch(primitives.Epoch(tt.b)) }) } else { - res = types.Epoch(tt.a).AddEpoch(types.Epoch(tt.b)) + res = primitives.Epoch(tt.a).AddEpoch(primitives.Epoch(tt.b)) } if tt.res != res { t.Errorf("Epoch.AddEpoch() = %v, want %v", res, tt.res) @@ -134,7 +134,7 @@ func TestEpoch_Add(t *testing.T) { func TestEpoch_Sub(t *testing.T) { tests := []struct { a, b uint64 - res types.Epoch + res primitives.Epoch panicMsg string }{ {a: 1, b: 0, res: 1}, @@ -152,13 +152,13 @@ func TestEpoch_Sub(t *testing.T) { for _, tt := range tests { t.Run(fmt.Sprintf("Epoch(%v).Sub(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Epoch + var res primitives.Epoch if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Epoch(tt.a).Sub(tt.b) + res = primitives.Epoch(tt.a).Sub(tt.b) }) } else { - res = types.Epoch(tt.a).Sub(tt.b) + res = primitives.Epoch(tt.a).Sub(tt.b) } if tt.res != res { t.Errorf("Epoch.Sub() = %v, want %v", res, tt.res) @@ -170,7 +170,7 @@ func TestEpoch_Sub(t *testing.T) { func TestEpoch_Mod(t *testing.T) { tests := []struct { a, b uint64 - res types.Epoch + res primitives.Epoch panicMsg string }{ {a: 1, b: 0, res: 0, panicMsg: mathprysm.ErrDivByZero.Error()}, @@ -190,13 +190,13 @@ func TestEpoch_Mod(t *testing.T) { for _, tt := range tests { t.Run(fmt.Sprintf("Epoch(%v).Mod(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Epoch + var res primitives.Epoch if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Epoch(tt.a).Mod(tt.b) + res = primitives.Epoch(tt.a).Mod(tt.b) }) } else { - res = types.Epoch(tt.a).Mod(tt.b) + res = primitives.Epoch(tt.a).Mod(tt.b) } if tt.res != res { t.Errorf("Epoch.Mod() = %v, want %v", res, tt.res) diff --git a/consensus-types/primitives/slot.go b/consensus-types/primitives/slot.go index 56da70f3d9..c4ff9d9ae5 100644 --- a/consensus-types/primitives/slot.go +++ b/consensus-types/primitives/slot.go @@ -1,4 +1,4 @@ -package types +package primitives import ( "fmt" diff --git a/consensus-types/primitives/slot_test.go b/consensus-types/primitives/slot_test.go index e70bc6b41f..ed129268ce 100644 --- a/consensus-types/primitives/slot_test.go +++ b/consensus-types/primitives/slot_test.go @@ -1,4 +1,4 @@ -package types_test +package primitives_test import ( "fmt" @@ -6,12 +6,12 @@ import ( "testing" "time" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" mathprysm "github.com/prysmaticlabs/prysm/v3/math" ) func TestSlot_Casting(t *testing.T) { - slot := types.Slot(42) + slot := primitives.Slot(42) t.Run("time.Duration", func(t *testing.T) { if uint64(time.Duration(slot)) != uint64(slot) { @@ -21,20 +21,20 @@ func TestSlot_Casting(t *testing.T) { t.Run("floats", func(t *testing.T) { var x1 float32 = 42.2 - if types.Slot(x1) != slot { - t.Errorf("Unequal: %v = %v", types.Slot(x1), slot) + if primitives.Slot(x1) != slot { + t.Errorf("Unequal: %v = %v", primitives.Slot(x1), slot) } var x2 = 42.2 - if types.Slot(x2) != slot { - t.Errorf("Unequal: %v = %v", types.Slot(x2), slot) + if primitives.Slot(x2) != slot { + t.Errorf("Unequal: %v = %v", primitives.Slot(x2), slot) } }) t.Run("int", func(t *testing.T) { var x = 42 - if types.Slot(x) != slot { - t.Errorf("Unequal: %v = %v", types.Slot(x), slot) + if primitives.Slot(x) != slot { + t.Errorf("Unequal: %v = %v", primitives.Slot(x), slot) } }) } @@ -42,7 +42,7 @@ func TestSlot_Casting(t *testing.T) { func TestSlot_Mul(t *testing.T) { tests := []struct { a, b uint64 - res types.Slot + res primitives.Slot panicMsg string }{ {a: 0, b: 1, res: 0}, @@ -58,33 +58,33 @@ func TestSlot_Mul(t *testing.T) { for _, tt := range tests { t.Run(fmt.Sprintf("Slot(%v).Mul(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Slot + var res primitives.Slot if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Slot(tt.a).Mul(tt.b) + res = primitives.Slot(tt.a).Mul(tt.b) }) } else { - res = types.Slot(tt.a).Mul(tt.b) + res = primitives.Slot(tt.a).Mul(tt.b) } if tt.res != res { t.Errorf("Slot.Mul() = %v, want %v", res, tt.res) } }) t.Run(fmt.Sprintf("Slot(%v).MulSlot(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Slot + var res primitives.Slot if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Slot(tt.a).MulSlot(types.Slot(tt.b)) + res = primitives.Slot(tt.a).MulSlot(primitives.Slot(tt.b)) }) } else { - res = types.Slot(tt.a).MulSlot(types.Slot(tt.b)) + res = primitives.Slot(tt.a).MulSlot(primitives.Slot(tt.b)) } if tt.res != res { t.Errorf("Slot.MulSlot() = %v, want %v", res, tt.res) } }) t.Run(fmt.Sprintf("Slot(%v).SafeMulSlot(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - res, err := types.Slot(tt.a).SafeMulSlot(types.Slot(tt.b)) + res, err := primitives.Slot(tt.a).SafeMulSlot(primitives.Slot(tt.b)) if tt.panicMsg != "" && (err == nil || err.Error() != tt.panicMsg) { t.Errorf("Expected error not thrown, wanted: %v, got: %v", tt.panicMsg, err) return @@ -99,7 +99,7 @@ func TestSlot_Mul(t *testing.T) { func TestSlot_Div(t *testing.T) { tests := []struct { a, b uint64 - res types.Slot + res primitives.Slot panicMsg string }{ {a: 0, b: 1, res: 0}, @@ -114,33 +114,33 @@ func TestSlot_Div(t *testing.T) { for _, tt := range tests { t.Run(fmt.Sprintf("Slot(%v).Div(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Slot + var res primitives.Slot if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Slot(tt.a).Div(tt.b) + res = primitives.Slot(tt.a).Div(tt.b) }) } else { - res = types.Slot(tt.a).Div(tt.b) + res = primitives.Slot(tt.a).Div(tt.b) } if tt.res != res { t.Errorf("Slot.Div() = %v, want %v", res, tt.res) } }) t.Run(fmt.Sprintf("Slot(%v).DivSlot(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Slot + var res primitives.Slot if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Slot(tt.a).DivSlot(types.Slot(tt.b)) + res = primitives.Slot(tt.a).DivSlot(primitives.Slot(tt.b)) }) } else { - res = types.Slot(tt.a).DivSlot(types.Slot(tt.b)) + res = primitives.Slot(tt.a).DivSlot(primitives.Slot(tt.b)) } if tt.res != res { t.Errorf("Slot.DivSlot() = %v, want %v", res, tt.res) } }) t.Run(fmt.Sprintf("Slot(%v).SafeDivSlot(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - res, err := types.Slot(tt.a).SafeDivSlot(types.Slot(tt.b)) + res, err := primitives.Slot(tt.a).SafeDivSlot(primitives.Slot(tt.b)) if tt.panicMsg != "" && (err == nil || err.Error() != tt.panicMsg) { t.Errorf("Expected error not thrown, wanted: %v, got: %v", tt.panicMsg, err) return @@ -155,7 +155,7 @@ func TestSlot_Div(t *testing.T) { func TestSlot_Add(t *testing.T) { tests := []struct { a, b uint64 - res types.Slot + res primitives.Slot panicMsg string }{ {a: 0, b: 1, res: 1}, @@ -171,33 +171,33 @@ func TestSlot_Add(t *testing.T) { for _, tt := range tests { t.Run(fmt.Sprintf("Slot(%v).Add(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Slot + var res primitives.Slot if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Slot(tt.a).Add(tt.b) + res = primitives.Slot(tt.a).Add(tt.b) }) } else { - res = types.Slot(tt.a).Add(tt.b) + res = primitives.Slot(tt.a).Add(tt.b) } if tt.res != res { t.Errorf("Slot.Add() = %v, want %v", res, tt.res) } }) t.Run(fmt.Sprintf("Slot(%v).AddSlot(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Slot + var res primitives.Slot if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Slot(tt.a).AddSlot(types.Slot(tt.b)) + res = primitives.Slot(tt.a).AddSlot(primitives.Slot(tt.b)) }) } else { - res = types.Slot(tt.a).AddSlot(types.Slot(tt.b)) + res = primitives.Slot(tt.a).AddSlot(primitives.Slot(tt.b)) } if tt.res != res { t.Errorf("Slot.AddSlot() = %v, want %v", res, tt.res) } }) t.Run(fmt.Sprintf("Slot(%v).SafeAddSlot(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - res, err := types.Slot(tt.a).SafeAddSlot(types.Slot(tt.b)) + res, err := primitives.Slot(tt.a).SafeAddSlot(primitives.Slot(tt.b)) if tt.panicMsg != "" && (err == nil || err.Error() != tt.panicMsg) { t.Errorf("Expected error not thrown, wanted: %v, got: %v", tt.panicMsg, err) return @@ -212,7 +212,7 @@ func TestSlot_Add(t *testing.T) { func TestSlot_Sub(t *testing.T) { tests := []struct { a, b uint64 - res types.Slot + res primitives.Slot panicMsg string }{ {a: 1, b: 0, res: 1}, @@ -230,33 +230,33 @@ func TestSlot_Sub(t *testing.T) { for _, tt := range tests { t.Run(fmt.Sprintf("Slot(%v).Sub(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Slot + var res primitives.Slot if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Slot(tt.a).Sub(tt.b) + res = primitives.Slot(tt.a).Sub(tt.b) }) } else { - res = types.Slot(tt.a).Sub(tt.b) + res = primitives.Slot(tt.a).Sub(tt.b) } if tt.res != res { t.Errorf("Slot.Sub() = %v, want %v", res, tt.res) } }) t.Run(fmt.Sprintf("Slot(%v).SubSlot(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Slot + var res primitives.Slot if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Slot(tt.a).SubSlot(types.Slot(tt.b)) + res = primitives.Slot(tt.a).SubSlot(primitives.Slot(tt.b)) }) } else { - res = types.Slot(tt.a).SubSlot(types.Slot(tt.b)) + res = primitives.Slot(tt.a).SubSlot(primitives.Slot(tt.b)) } if tt.res != res { t.Errorf("Slot.SubSlot() = %v, want %v", res, tt.res) } }) t.Run(fmt.Sprintf("Slot(%v).SafeSubSlot(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - res, err := types.Slot(tt.a).SafeSubSlot(types.Slot(tt.b)) + res, err := primitives.Slot(tt.a).SafeSubSlot(primitives.Slot(tt.b)) if tt.panicMsg != "" && (err == nil || err.Error() != tt.panicMsg) { t.Errorf("Expected error not thrown, wanted: %v, got: %v", tt.panicMsg, err) return @@ -271,7 +271,7 @@ func TestSlot_Sub(t *testing.T) { func TestSlot_Mod(t *testing.T) { tests := []struct { a, b uint64 - res types.Slot + res primitives.Slot panicMsg string }{ {a: 1, b: 0, res: 0, panicMsg: mathprysm.ErrDivByZero.Error()}, @@ -291,33 +291,33 @@ func TestSlot_Mod(t *testing.T) { for _, tt := range tests { t.Run(fmt.Sprintf("Slot(%v).Mod(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Slot + var res primitives.Slot if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Slot(tt.a).Mod(tt.b) + res = primitives.Slot(tt.a).Mod(tt.b) }) } else { - res = types.Slot(tt.a).Mod(tt.b) + res = primitives.Slot(tt.a).Mod(tt.b) } if tt.res != res { t.Errorf("Slot.Mod() = %v, want %v", res, tt.res) } }) t.Run(fmt.Sprintf("Slot(%v).ModSlot(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - var res types.Slot + var res primitives.Slot if tt.panicMsg != "" { assertPanic(t, tt.panicMsg, func() { - res = types.Slot(tt.a).ModSlot(types.Slot(tt.b)) + res = primitives.Slot(tt.a).ModSlot(primitives.Slot(tt.b)) }) } else { - res = types.Slot(tt.a).ModSlot(types.Slot(tt.b)) + res = primitives.Slot(tt.a).ModSlot(primitives.Slot(tt.b)) } if tt.res != res { t.Errorf("Slot.Mod() = %v, want %v", res, tt.res) } }) t.Run(fmt.Sprintf("Slot(%v).SafeModSlot(%v) = %v", tt.a, tt.b, tt.res), func(t *testing.T) { - res, err := types.Slot(tt.a).SafeModSlot(types.Slot(tt.b)) + res, err := primitives.Slot(tt.a).SafeModSlot(primitives.Slot(tt.b)) if tt.panicMsg != "" && (err == nil || err.Error() != tt.panicMsg) { t.Errorf("Expected error not thrown, wanted: %v, got: %v", tt.panicMsg, err) return diff --git a/consensus-types/primitives/sszbytes.go b/consensus-types/primitives/sszbytes.go index d451af3313..7e37586dd4 100644 --- a/consensus-types/primitives/sszbytes.go +++ b/consensus-types/primitives/sszbytes.go @@ -1,4 +1,4 @@ -package types +package primitives import ( fssz "github.com/prysmaticlabs/fastssz" diff --git a/consensus-types/primitives/sszbytes_test.go b/consensus-types/primitives/sszbytes_test.go index 3e320b36b2..5ea8accd54 100644 --- a/consensus-types/primitives/sszbytes_test.go +++ b/consensus-types/primitives/sszbytes_test.go @@ -1,11 +1,11 @@ -package types_test +package primitives_test import ( "encoding/hex" "reflect" "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) func TestSSZBytes_HashTreeRoot(t *testing.T) { @@ -36,7 +36,7 @@ func TestSSZBytes_HashTreeRoot(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - s := types.SSZBytes(tt.actualValue) + s := primitives.SSZBytes(tt.actualValue) htr, err := s.HashTreeRoot() if err != nil { t.Errorf("SSZBytes.HashTreeRoot() unexpected error = %v", err) diff --git a/consensus-types/primitives/sszuint64.go b/consensus-types/primitives/sszuint64.go index 829c8d0f50..dfd733d280 100644 --- a/consensus-types/primitives/sszuint64.go +++ b/consensus-types/primitives/sszuint64.go @@ -1,4 +1,4 @@ -package types +package primitives import ( "encoding/binary" diff --git a/consensus-types/primitives/sszuint64_test.go b/consensus-types/primitives/sszuint64_test.go index 5a16c86492..bfae28545e 100644 --- a/consensus-types/primitives/sszuint64_test.go +++ b/consensus-types/primitives/sszuint64_test.go @@ -1,15 +1,15 @@ -package types_test +package primitives_test import ( "reflect" "strings" "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) func TestSSZUint64_Limit(t *testing.T) { - sszType := types.SSZUint64(0) + sszType := primitives.SSZUint64(0) var serializedObj [7]byte err := sszType.UnmarshalSSZ(serializedObj[:]) if err == nil || !strings.Contains(err.Error(), "expected buffer of length") { @@ -19,13 +19,13 @@ func TestSSZUint64_Limit(t *testing.T) { func TestSSZUint64_RoundTrip(t *testing.T) { fixedVal := uint64(8) - sszVal := types.SSZUint64(fixedVal) + sszVal := primitives.SSZUint64(fixedVal) marshalledObj, err := sszVal.MarshalSSZ() if err != nil { t.Errorf("Unexpected error: %v", err) } - newVal := types.SSZUint64(0) + newVal := primitives.SSZUint64(0) err = newVal.UnmarshalSSZ(marshalledObj) if err != nil { @@ -68,7 +68,7 @@ func TestSSZUint64(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - var s types.SSZUint64 + var s primitives.SSZUint64 if err := s.UnmarshalSSZ(tt.serializedBytes); (err != nil) != tt.wantErr { t.Errorf("SSZUint64.UnmarshalSSZ() error = %v, wantErr %v", err, tt.wantErr) } diff --git a/consensus-types/primitives/validator.go b/consensus-types/primitives/validator.go index d107ad41cd..73fc6e68ea 100644 --- a/consensus-types/primitives/validator.go +++ b/consensus-types/primitives/validator.go @@ -1,4 +1,4 @@ -package types +package primitives import ( "fmt" diff --git a/consensus-types/primitives/validator_test.go b/consensus-types/primitives/validator_test.go index 548c10b23b..9c7d4aeab0 100644 --- a/consensus-types/primitives/validator_test.go +++ b/consensus-types/primitives/validator_test.go @@ -1,4 +1,4 @@ -package types +package primitives import ( "testing" diff --git a/container/slice/slice.go b/container/slice/slice.go index dab8dcfb76..3daba64209 100644 --- a/container/slice/slice.go +++ b/container/slice/slice.go @@ -3,7 +3,7 @@ package slice import ( "strings" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // SubsetUint64 returns true if the first array is @@ -310,15 +310,15 @@ func SplitOffset(listSize, chunks, index uint64) uint64 { // complexity of approximately O(n) leveraging a map to // check for element existence off by a constant factor // of underlying map efficiency. -func IntersectionSlot(s ...[]types.Slot) []types.Slot { +func IntersectionSlot(s ...[]primitives.Slot) []primitives.Slot { if len(s) == 0 { - return []types.Slot{} + return []primitives.Slot{} } if len(s) == 1 { return s[0] } - intersect := make([]types.Slot, 0) - m := make(map[types.Slot]int) + intersect := make([]primitives.Slot, 0) + m := make(map[primitives.Slot]int) for _, k := range s[0] { m[k] = 1 } @@ -340,9 +340,9 @@ func IntersectionSlot(s ...[]types.Slot) []types.Slot { // not in slice a with time complexity of approximately // O(n) leveraging a map to check for element existence // off by a constant factor of underlying map efficiency. -func NotSlot(a, b []types.Slot) []types.Slot { - set := make([]types.Slot, 0) - m := make(map[types.Slot]bool) +func NotSlot(a, b []primitives.Slot) []primitives.Slot { + set := make([]primitives.Slot, 0) + m := make(map[primitives.Slot]bool) for i := 0; i < len(a); i++ { m[a[i]] = true @@ -356,7 +356,7 @@ func NotSlot(a, b []types.Slot) []types.Slot { } // IsInSlots returns true if a is in b and False otherwise. -func IsInSlots(a types.Slot, b []types.Slot) bool { +func IsInSlots(a primitives.Slot, b []primitives.Slot) bool { for _, v := range b { if a == v { return true diff --git a/container/slice/slice_test.go b/container/slice/slice_test.go index 0e4eb9d24a..d3e5731f1f 100644 --- a/container/slice/slice_test.go +++ b/container/slice/slice_test.go @@ -5,7 +5,7 @@ import ( "sort" "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -503,31 +503,31 @@ func TestSplitOffset_OK(t *testing.T) { func TestIntersectionSlot(t *testing.T) { testCases := []struct { - setA []types.Slot - setB []types.Slot - setC []types.Slot - out []types.Slot + setA []primitives.Slot + setB []primitives.Slot + setC []primitives.Slot + out []primitives.Slot }{ - {[]types.Slot{2, 3, 5}, []types.Slot{3}, []types.Slot{3}, []types.Slot{3}}, - {[]types.Slot{2, 3, 5}, []types.Slot{3, 5}, []types.Slot{5}, []types.Slot{5}}, - {[]types.Slot{2, 3, 5}, []types.Slot{3, 5}, []types.Slot{3, 5}, []types.Slot{3, 5}}, - {[]types.Slot{2, 3, 5}, []types.Slot{5, 3, 2}, []types.Slot{3, 2, 5}, []types.Slot{2, 3, 5}}, - {[]types.Slot{3, 2, 5}, []types.Slot{5, 3, 2}, []types.Slot{3, 2, 5}, []types.Slot{2, 3, 5}}, - {[]types.Slot{3, 3, 5}, []types.Slot{5, 3, 2}, []types.Slot{3, 2, 5}, []types.Slot{3, 5}}, - {[]types.Slot{2, 3, 5}, []types.Slot{2, 3, 5}, []types.Slot{2, 3, 5}, []types.Slot{2, 3, 5}}, - {[]types.Slot{2, 3, 5}, []types.Slot{}, []types.Slot{}, []types.Slot{}}, - {[]types.Slot{2, 3, 5}, []types.Slot{2, 3, 5}, []types.Slot{}, []types.Slot{}}, - {[]types.Slot{2, 3}, []types.Slot{2, 3, 5}, []types.Slot{5}, []types.Slot{}}, - {[]types.Slot{2, 2, 2}, []types.Slot{2, 2, 2}, []types.Slot{}, []types.Slot{}}, - {[]types.Slot{}, []types.Slot{2, 3, 5}, []types.Slot{}, []types.Slot{}}, - {[]types.Slot{}, []types.Slot{}, []types.Slot{}, []types.Slot{}}, - {[]types.Slot{1}, []types.Slot{1}, []types.Slot{}, []types.Slot{}}, - {[]types.Slot{1, 1, 1}, []types.Slot{1, 1}, []types.Slot{1, 2, 3}, []types.Slot{1}}, + {[]primitives.Slot{2, 3, 5}, []primitives.Slot{3}, []primitives.Slot{3}, []primitives.Slot{3}}, + {[]primitives.Slot{2, 3, 5}, []primitives.Slot{3, 5}, []primitives.Slot{5}, []primitives.Slot{5}}, + {[]primitives.Slot{2, 3, 5}, []primitives.Slot{3, 5}, []primitives.Slot{3, 5}, []primitives.Slot{3, 5}}, + {[]primitives.Slot{2, 3, 5}, []primitives.Slot{5, 3, 2}, []primitives.Slot{3, 2, 5}, []primitives.Slot{2, 3, 5}}, + {[]primitives.Slot{3, 2, 5}, []primitives.Slot{5, 3, 2}, []primitives.Slot{3, 2, 5}, []primitives.Slot{2, 3, 5}}, + {[]primitives.Slot{3, 3, 5}, []primitives.Slot{5, 3, 2}, []primitives.Slot{3, 2, 5}, []primitives.Slot{3, 5}}, + {[]primitives.Slot{2, 3, 5}, []primitives.Slot{2, 3, 5}, []primitives.Slot{2, 3, 5}, []primitives.Slot{2, 3, 5}}, + {[]primitives.Slot{2, 3, 5}, []primitives.Slot{}, []primitives.Slot{}, []primitives.Slot{}}, + {[]primitives.Slot{2, 3, 5}, []primitives.Slot{2, 3, 5}, []primitives.Slot{}, []primitives.Slot{}}, + {[]primitives.Slot{2, 3}, []primitives.Slot{2, 3, 5}, []primitives.Slot{5}, []primitives.Slot{}}, + {[]primitives.Slot{2, 2, 2}, []primitives.Slot{2, 2, 2}, []primitives.Slot{}, []primitives.Slot{}}, + {[]primitives.Slot{}, []primitives.Slot{2, 3, 5}, []primitives.Slot{}, []primitives.Slot{}}, + {[]primitives.Slot{}, []primitives.Slot{}, []primitives.Slot{}, []primitives.Slot{}}, + {[]primitives.Slot{1}, []primitives.Slot{1}, []primitives.Slot{}, []primitives.Slot{}}, + {[]primitives.Slot{1, 1, 1}, []primitives.Slot{1, 1}, []primitives.Slot{1, 2, 3}, []primitives.Slot{1}}, } for _, tt := range testCases { - setA := append([]types.Slot{}, tt.setA...) - setB := append([]types.Slot{}, tt.setB...) - setC := append([]types.Slot{}, tt.setC...) + setA := append([]primitives.Slot{}, tt.setA...) + setB := append([]primitives.Slot{}, tt.setB...) + setC := append([]primitives.Slot{}, tt.setC...) result := slice.IntersectionSlot(setA, setB, setC) sort.Slice(result, func(i, j int) bool { return result[i] < result[j] @@ -549,17 +549,17 @@ func TestIntersectionSlot(t *testing.T) { func TestNotSlot(t *testing.T) { testCases := []struct { - setA []types.Slot - setB []types.Slot - out []types.Slot + setA []primitives.Slot + setB []primitives.Slot + out []primitives.Slot }{ - {[]types.Slot{4, 6}, []types.Slot{2, 3, 5, 4, 6}, []types.Slot{2, 3, 5}}, - {[]types.Slot{3, 5}, []types.Slot{2, 3, 5}, []types.Slot{2}}, - {[]types.Slot{2, 3, 5}, []types.Slot{2, 3, 5}, []types.Slot{}}, - {[]types.Slot{2}, []types.Slot{2, 3, 5}, []types.Slot{3, 5}}, - {[]types.Slot{}, []types.Slot{2, 3, 5}, []types.Slot{2, 3, 5}}, - {[]types.Slot{}, []types.Slot{}, []types.Slot{}}, - {[]types.Slot{1}, []types.Slot{1}, []types.Slot{}}, + {[]primitives.Slot{4, 6}, []primitives.Slot{2, 3, 5, 4, 6}, []primitives.Slot{2, 3, 5}}, + {[]primitives.Slot{3, 5}, []primitives.Slot{2, 3, 5}, []primitives.Slot{2}}, + {[]primitives.Slot{2, 3, 5}, []primitives.Slot{2, 3, 5}, []primitives.Slot{}}, + {[]primitives.Slot{2}, []primitives.Slot{2, 3, 5}, []primitives.Slot{3, 5}}, + {[]primitives.Slot{}, []primitives.Slot{2, 3, 5}, []primitives.Slot{2, 3, 5}}, + {[]primitives.Slot{}, []primitives.Slot{}, []primitives.Slot{}}, + {[]primitives.Slot{1}, []primitives.Slot{1}, []primitives.Slot{}}, } for _, tt := range testCases { result := slice.NotSlot(tt.setA, tt.setB) @@ -571,14 +571,14 @@ func TestNotSlot(t *testing.T) { func TestIsInSlots(t *testing.T) { testCases := []struct { - a types.Slot - b []types.Slot + a primitives.Slot + b []primitives.Slot result bool }{ - {0, []types.Slot{}, false}, - {0, []types.Slot{0}, true}, - {4, []types.Slot{2, 3, 5, 4, 6}, true}, - {100, []types.Slot{2, 3, 5, 4, 6}, false}, + {0, []primitives.Slot{}, false}, + {0, []primitives.Slot{0}, true}, + {4, []primitives.Slot{2, 3, 5, 4, 6}, true}, + {100, []primitives.Slot{2, 3, 5, 4, 6}, false}, } for _, tt := range testCases { result := slice.IsInSlots(tt.a, tt.b) diff --git a/encoding/bytesutil/eth_types.go b/encoding/bytesutil/eth_types.go index 3ce2615e55..a8534458de 100644 --- a/encoding/bytesutil/eth_types.go +++ b/encoding/bytesutil/eth_types.go @@ -2,32 +2,32 @@ package bytesutil import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // EpochToBytesLittleEndian conversion. -func EpochToBytesLittleEndian(i types.Epoch) []byte { +func EpochToBytesLittleEndian(i primitives.Epoch) []byte { return Uint64ToBytesLittleEndian(uint64(i)) } // EpochToBytesBigEndian conversion. -func EpochToBytesBigEndian(i types.Epoch) []byte { +func EpochToBytesBigEndian(i primitives.Epoch) []byte { return Uint64ToBytesBigEndian(uint64(i)) } // BytesToEpochBigEndian conversion. -func BytesToEpochBigEndian(b []byte) types.Epoch { - return types.Epoch(BytesToUint64BigEndian(b)) +func BytesToEpochBigEndian(b []byte) primitives.Epoch { + return primitives.Epoch(BytesToUint64BigEndian(b)) } // SlotToBytesBigEndian conversion. -func SlotToBytesBigEndian(i types.Slot) []byte { +func SlotToBytesBigEndian(i primitives.Slot) []byte { return Uint64ToBytesBigEndian(uint64(i)) } // BytesToSlotBigEndian conversion. -func BytesToSlotBigEndian(b []byte) types.Slot { - return types.Slot(BytesToUint64BigEndian(b)) +func BytesToSlotBigEndian(b []byte) primitives.Slot { + return primitives.Slot(BytesToUint64BigEndian(b)) } // ZeroRoot returns whether or not a root is of proper length and non-zero hash. diff --git a/encoding/ssz/detect/configfork.go b/encoding/ssz/detect/configfork.go index 7f907e4e33..9a8c5063d2 100644 --- a/encoding/ssz/detect/configfork.go +++ b/encoding/ssz/detect/configfork.go @@ -14,7 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -138,12 +138,12 @@ var beaconBlockSlot = fieldSpec{ t: typeUint64, } -func slotFromBlock(marshaled []byte) (types.Slot, error) { +func slotFromBlock(marshaled []byte) (primitives.Slot, error) { slot, err := beaconBlockSlot.uint64(marshaled) if err != nil { return 0, err } - return types.Slot(slot), nil + return primitives.Slot(slot), nil } var errBlockForkMismatch = errors.New("fork or config detected in unmarshaler is different than block") @@ -212,7 +212,7 @@ func (cf *VersionedUnmarshaler) UnmarshalBlindedBeaconBlock(marshaled []byte) (i // Heuristic to make sure block is from the same version as the VersionedUnmarshaler. // Look up the version for the epoch that the block is from, then ensure that it matches the Version in the // VersionedUnmarshaler. -func (cf *VersionedUnmarshaler) validateVersion(slot types.Slot) error { +func (cf *VersionedUnmarshaler) validateVersion(slot primitives.Slot) error { epoch := slots.ToEpoch(slot) fs := forks.NewOrderedSchedule(cf.Config) ver, err := fs.VersionForEpoch(epoch) diff --git a/encoding/ssz/detect/configfork_test.go b/encoding/ssz/detect/configfork_test.go index 02e13f1285..70f37864e8 100644 --- a/encoding/ssz/detect/configfork_test.go +++ b/encoding/ssz/detect/configfork_test.go @@ -15,14 +15,14 @@ import ( "github.com/prysmaticlabs/prysm/v3/testing/util" "github.com/prysmaticlabs/prysm/v3/time/slots" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" ) func TestSlotFromBlock(t *testing.T) { b := util.NewBeaconBlock() - var slot types.Slot = 3 + var slot primitives.Slot = 3 b.Block.Slot = slot bb, err := b.MarshalSSZ() require.NoError(t, err) @@ -63,7 +63,7 @@ func TestByState(t *testing.T) { cases := []struct { name string version int - slot types.Slot + slot primitives.Slot forkversion [4]byte }{ { @@ -139,7 +139,7 @@ func TestUnmarshalState(t *testing.T) { cases := []struct { name string version int - slot types.Slot + slot primitives.Slot forkversion [4]byte }{ { @@ -208,10 +208,10 @@ func TestUnmarshalBlock(t *testing.T) { bellaS, err := slots.EpochStart(params.BeaconConfig().BellatrixForkEpoch) require.NoError(t, err) cases := []struct { - b func(*testing.T, types.Slot) interfaces.SignedBeaconBlock + b func(*testing.T, primitives.Slot) interfaces.SignedBeaconBlock name string version [4]byte - slot types.Slot + slot primitives.Slot err error }{ { @@ -299,10 +299,10 @@ func TestUnmarshalBlindedBlock(t *testing.T) { bellaS, err := slots.EpochStart(params.BeaconConfig().BellatrixForkEpoch) require.NoError(t, err) cases := []struct { - b func(*testing.T, types.Slot) interfaces.SignedBeaconBlock + b func(*testing.T, primitives.Slot) interfaces.SignedBeaconBlock name string version [4]byte - slot types.Slot + slot primitives.Slot err error }{ { @@ -377,7 +377,7 @@ func TestUnmarshalBlindedBlock(t *testing.T) { } } -func signedTestBlockGenesis(t *testing.T, slot types.Slot) interfaces.SignedBeaconBlock { +func signedTestBlockGenesis(t *testing.T, slot primitives.Slot) interfaces.SignedBeaconBlock { b := util.NewBeaconBlock() b.Block.Slot = slot s, err := blocks.NewSignedBeaconBlock(b) @@ -385,7 +385,7 @@ func signedTestBlockGenesis(t *testing.T, slot types.Slot) interfaces.SignedBeac return s } -func signedTestBlockAltair(t *testing.T, slot types.Slot) interfaces.SignedBeaconBlock { +func signedTestBlockAltair(t *testing.T, slot primitives.Slot) interfaces.SignedBeaconBlock { b := util.NewBeaconBlockAltair() b.Block.Slot = slot s, err := blocks.NewSignedBeaconBlock(b) @@ -393,7 +393,7 @@ func signedTestBlockAltair(t *testing.T, slot types.Slot) interfaces.SignedBeaco return s } -func signedTestBlockBellatrix(t *testing.T, slot types.Slot) interfaces.SignedBeaconBlock { +func signedTestBlockBellatrix(t *testing.T, slot primitives.Slot) interfaces.SignedBeaconBlock { b := util.NewBeaconBlockBellatrix() b.Block.Slot = slot s, err := blocks.NewSignedBeaconBlock(b) @@ -401,7 +401,7 @@ func signedTestBlockBellatrix(t *testing.T, slot types.Slot) interfaces.SignedBe return s } -func signedTestBlindedBlockBellatrix(t *testing.T, slot types.Slot) interfaces.SignedBeaconBlock { +func signedTestBlindedBlockBellatrix(t *testing.T, slot primitives.Slot) interfaces.SignedBeaconBlock { b := util.NewBlindedBeaconBlockBellatrix() b.Block.Slot = slot s, err := blocks.NewSignedBeaconBlock(b) diff --git a/encoding/ssz/equality/deep_equal.go b/encoding/ssz/equality/deep_equal.go index 7dcbf6ba96..40be690ff3 100644 --- a/encoding/ssz/equality/deep_equal.go +++ b/encoding/ssz/equality/deep_equal.go @@ -4,7 +4,7 @@ import ( "reflect" "unsafe" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "google.golang.org/protobuf/proto" ) @@ -223,13 +223,13 @@ func deepValueBaseTypeEqual(v1, v2 reflect.Value) bool { case reflect.Uint64: switch v1.Type().Name() { case "Epoch": - return v1.Interface().(types.Epoch) == v2.Interface().(types.Epoch) + return v1.Interface().(primitives.Epoch) == v2.Interface().(primitives.Epoch) case "Slot": - return v1.Interface().(types.Slot) == v2.Interface().(types.Slot) + return v1.Interface().(primitives.Slot) == v2.Interface().(primitives.Slot) case "ValidatorIndex": - return v1.Interface().(types.ValidatorIndex) == v2.Interface().(types.ValidatorIndex) + return v1.Interface().(primitives.ValidatorIndex) == v2.Interface().(primitives.ValidatorIndex) case "CommitteeIndex": - return v1.Interface().(types.CommitteeIndex) == v2.Interface().(types.CommitteeIndex) + return v1.Interface().(primitives.CommitteeIndex) == v2.Interface().(primitives.CommitteeIndex) } return v1.Interface().(uint64) == v2.Interface().(uint64) case reflect.Uint32: diff --git a/network/forks/fork.go b/network/forks/fork.go index 58dfd126d3..245be7666a 100644 --- a/network/forks/fork.go +++ b/network/forks/fork.go @@ -10,7 +10,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -41,7 +41,7 @@ func IsForkNextEpoch(genesisTime time.Time, genesisValidatorsRoot []byte) (bool, // ForkDigestFromEpoch retrieves the fork digest from the current schedule determined // by the provided epoch. -func ForkDigestFromEpoch(currentEpoch types.Epoch, genesisValidatorsRoot []byte) ([4]byte, error) { +func ForkDigestFromEpoch(currentEpoch primitives.Epoch, genesisValidatorsRoot []byte) ([4]byte, error) { if len(genesisValidatorsRoot) == 0 { return [4]byte{}, errors.New("genesis validators root is not set") } @@ -83,13 +83,13 @@ func CreateForkDigest( // Fork given a target epoch, // returns the active fork version during this epoch. func Fork( - targetEpoch types.Epoch, + targetEpoch primitives.Epoch, ) (*ethpb.Fork, error) { currentForkVersion := bytesutil.ToBytes4(params.BeaconConfig().GenesisForkVersion) previousForkVersion := bytesutil.ToBytes4(params.BeaconConfig().GenesisForkVersion) fSchedule := params.BeaconConfig().ForkVersionSchedule sortedForkVersions := SortedForkVersions(fSchedule) - forkEpoch := types.Epoch(0) + forkEpoch := primitives.Epoch(0) for _, forkVersion := range sortedForkVersions { epoch, ok := fSchedule[forkVersion] if !ok { @@ -110,7 +110,7 @@ func Fork( // RetrieveForkDataFromDigest performs the inverse, where it tries to determine the fork version // and epoch from a provided digest by looping through our current fork schedule. -func RetrieveForkDataFromDigest(digest [4]byte, genesisValidatorsRoot []byte) ([4]byte, types.Epoch, error) { +func RetrieveForkDataFromDigest(digest [4]byte, genesisValidatorsRoot []byte) ([4]byte, primitives.Epoch, error) { fSchedule := params.BeaconConfig().ForkVersionSchedule for v, e := range fSchedule { rDigest, err := signing.ComputeForkDigest(v[:], genesisValidatorsRoot) @@ -126,10 +126,10 @@ func RetrieveForkDataFromDigest(digest [4]byte, genesisValidatorsRoot []byte) ([ // NextForkData retrieves the next fork data according to the // provided current epoch. -func NextForkData(currEpoch types.Epoch) ([4]byte, types.Epoch, error) { +func NextForkData(currEpoch primitives.Epoch) ([4]byte, primitives.Epoch, error) { fSchedule := params.BeaconConfig().ForkVersionSchedule sortedForkVersions := SortedForkVersions(fSchedule) - nextForkEpoch := types.Epoch(math.MaxUint64) + nextForkEpoch := primitives.Epoch(math.MaxUint64) var nextForkVersion [4]byte for _, forkVersion := range sortedForkVersions { epoch, ok := fSchedule[forkVersion] @@ -158,7 +158,7 @@ func NextForkData(currEpoch types.Epoch) ([4]byte, types.Epoch, error) { // SortedForkVersions sorts the provided fork schedule in ascending order // by epoch. -func SortedForkVersions(forkSchedule map[[4]byte]types.Epoch) [][4]byte { +func SortedForkVersions(forkSchedule map[[4]byte]primitives.Epoch) [][4]byte { sortedVersions := make([][4]byte, len(forkSchedule)) i := 0 for k := range forkSchedule { diff --git a/network/forks/fork_test.go b/network/forks/fork_test.go index 5788e38a05..07751fda8f 100644 --- a/network/forks/fork_test.go +++ b/network/forks/fork_test.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" ) @@ -19,7 +19,7 @@ func TestFork(t *testing.T) { tests := []struct { name string - targetEpoch types.Epoch + targetEpoch primitives.Epoch want *ethpb.Fork wantErr bool setConfg func() @@ -36,7 +36,7 @@ func TestFork(t *testing.T) { setConfg: func() { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{} + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{} params.OverrideBeaconConfig(cfg) }, }, @@ -52,7 +52,7 @@ func TestFork(t *testing.T) { setConfg: func() { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, } params.OverrideBeaconConfig(cfg) @@ -71,7 +71,7 @@ func TestFork(t *testing.T) { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} cfg.AltairForkVersion = []byte{'A', 'B', 'C', 'F'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, {'A', 'B', 'C', 'F'}: 10, } @@ -91,7 +91,7 @@ func TestFork(t *testing.T) { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} cfg.AltairForkVersion = []byte{'A', 'B', 'C', 'F'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, {'A', 'B', 'C', 'F'}: 10, } @@ -112,7 +112,7 @@ func TestFork(t *testing.T) { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} cfg.AltairForkVersion = []byte{'A', 'B', 'C', 'F'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, {'A', 'B', 'C', 'F'}: 10, } @@ -132,7 +132,7 @@ func TestFork(t *testing.T) { setConfg: func() { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, {'A', 'B', 'C', 'F'}: 10, {'A', 'B', 'C', 'Z'}: 100, @@ -152,7 +152,7 @@ func TestFork(t *testing.T) { setConfg: func() { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, {'A', 'B', 'C', 'F'}: 10, {'A', 'B', 'C', 'Z'}: 100, @@ -194,7 +194,7 @@ func TestRetrieveForkDataFromDigest(t *testing.T) { version, epoch, err := RetrieveForkDataFromDigest(digest, genValRoot[:]) assert.NoError(t, err) assert.Equal(t, [4]byte{'A', 'B', 'C', 'F'}, version) - assert.Equal(t, epoch, types.Epoch(10)) + assert.Equal(t, epoch, primitives.Epoch(10)) digest, err = signing.ComputeForkDigest([]byte{'A', 'B', 'C', 'Z'}, genValRoot[:]) assert.NoError(t, err) @@ -202,20 +202,20 @@ func TestRetrieveForkDataFromDigest(t *testing.T) { version, epoch, err = RetrieveForkDataFromDigest(digest, genValRoot[:]) assert.NoError(t, err) assert.Equal(t, [4]byte{'A', 'B', 'C', 'Z'}, version) - assert.Equal(t, epoch, types.Epoch(100)) + assert.Equal(t, epoch, primitives.Epoch(100)) } func TestIsForkNextEpoch(t *testing.T) { params.SetupTestConfigCleanup(t) cfg := params.BeaconConfig().Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, {'A', 'B', 'C', 'F'}: 10, {'A', 'B', 'C', 'Z'}: 100, } params.OverrideBeaconConfig(cfg) - genTimeCreator := func(epoch types.Epoch) time.Time { + genTimeCreator := func(epoch primitives.Epoch) time.Time { return time.Now().Add(-time.Duration(uint64(params.BeaconConfig().SlotsPerEpoch)*uint64(epoch)*params.BeaconConfig().SecondsPerSlot) * time.Second) } // Is at Fork Epoch @@ -254,9 +254,9 @@ func TestNextForkData(t *testing.T) { tests := []struct { name string setConfg func() - currEpoch types.Epoch + currEpoch primitives.Epoch wantedForkVerison [4]byte - wantedEpoch types.Epoch + wantedEpoch primitives.Epoch }{ { name: "genesis fork", @@ -266,7 +266,7 @@ func TestNextForkData(t *testing.T) { setConfg: func() { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, } params.OverrideBeaconConfig(cfg) @@ -281,7 +281,7 @@ func TestNextForkData(t *testing.T) { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} cfg.AltairForkVersion = []byte{'A', 'B', 'C', 'F'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, {'A', 'B', 'C', 'F'}: 10, } @@ -297,7 +297,7 @@ func TestNextForkData(t *testing.T) { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} cfg.AltairForkVersion = []byte{'A', 'B', 'C', 'F'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, {'A', 'B', 'C', 'F'}: 10, } @@ -314,7 +314,7 @@ func TestNextForkData(t *testing.T) { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} cfg.AltairForkVersion = []byte{'A', 'B', 'C', 'F'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, {'A', 'B', 'C', 'F'}: 10, } @@ -330,7 +330,7 @@ func TestNextForkData(t *testing.T) { setConfg: func() { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, {'A', 'B', 'C', 'F'}: 10, {'A', 'B', 'C', 'Z'}: 100, @@ -346,7 +346,7 @@ func TestNextForkData(t *testing.T) { setConfg: func() { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, {'A', 'B', 'C', 'F'}: 10, {'A', 'B', 'C', 'Z'}: 100, @@ -362,7 +362,7 @@ func TestNextForkData(t *testing.T) { setConfg: func() { cfg = cfg.Copy() cfg.GenesisForkVersion = []byte{'A', 'B', 'C', 'D'} - cfg.ForkVersionSchedule = map[[4]byte]types.Epoch{ + cfg.ForkVersionSchedule = map[[4]byte]primitives.Epoch{ {'A', 'B', 'C', 'D'}: 0, {'A', 'B', 'C', 'F'}: 10, {'A', 'B', 'C', 'Z'}: 100, diff --git a/network/forks/ordered.go b/network/forks/ordered.go index 9a50fcdbb4..c55c2cf0eb 100644 --- a/network/forks/ordered.go +++ b/network/forks/ordered.go @@ -8,13 +8,13 @@ import ( "github.com/pkg/errors" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // ForkScheduleEntry is a Version+Epoch tuple for sorted storage in an OrderedSchedule type ForkScheduleEntry struct { Version [fieldparams.VersionLength]byte - Epoch types.Epoch + Epoch primitives.Epoch Name string } @@ -37,7 +37,7 @@ func (o OrderedSchedule) Less(i, j int) bool { } // VersionForEpoch finds the Version with the highest epoch <= the given epoch -func (o OrderedSchedule) VersionForEpoch(epoch types.Epoch) ([fieldparams.VersionLength]byte, error) { +func (o OrderedSchedule) VersionForEpoch(epoch primitives.Epoch) ([fieldparams.VersionLength]byte, error) { for i := len(o) - 1; i >= 0; i-- { if o[i].Epoch <= epoch { return o[i].Version, nil diff --git a/network/forks/ordered_test.go b/network/forks/ordered_test.go index 8063f36043..16586a75d6 100644 --- a/network/forks/ordered_test.go +++ b/network/forks/ordered_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" ) @@ -16,7 +16,7 @@ func TestOrderedConfigSchedule(t *testing.T) { prevVersion := [4]byte{0, 0, 0, 0} // epoch 0 is genesis, and it's a uint so can't make it -1 // so we use a pointer to detect the boundary condition and skip it - var prevEpoch *types.Epoch + var prevEpoch *primitives.Epoch for _, fse := range NewOrderedSchedule(cfg) { // copy loop variable so we can take the address of fields f := fse @@ -37,8 +37,8 @@ func TestOrderedConfigSchedule(t *testing.T) { bc := testForkVersionBCC() ofs := NewOrderedSchedule(bc) for i := range ofs { - if ofs[i].Epoch != types.Epoch(math.Pow(2, float64(i))) { - t.Errorf("expected %dth element of list w/ epoch=%d, got=%d. list=%v", i, types.Epoch(2^i), ofs[i].Epoch, ofs) + if ofs[i].Epoch != primitives.Epoch(math.Pow(2, float64(i))) { + t.Errorf("expected %dth element of list w/ epoch=%d, got=%d. list=%v", i, primitives.Epoch(2^i), ofs[i].Epoch, ofs) } } } @@ -49,32 +49,32 @@ func TestVersionForEpoch(t *testing.T) { testCases := []struct { name string version [4]byte - epoch types.Epoch + epoch primitives.Epoch err error }{ { name: "found between versions", version: [4]byte{2, 1, 2, 3}, - epoch: types.Epoch(7), + epoch: primitives.Epoch(7), }, { name: "found at end", version: [4]byte{4, 1, 2, 3}, - epoch: types.Epoch(100), + epoch: primitives.Epoch(100), }, { name: "found at start", version: [4]byte{0, 1, 2, 3}, - epoch: types.Epoch(1), + epoch: primitives.Epoch(1), }, { name: "found at boundary", version: [4]byte{1, 1, 2, 3}, - epoch: types.Epoch(2), + epoch: primitives.Epoch(2), }, { name: "not found before", - epoch: types.Epoch(0), + epoch: primitives.Epoch(0), err: ErrVersionNotFound, }, } @@ -131,12 +131,12 @@ func TestVersionForName(t *testing.T) { func testForkVersionBCC() *params.BeaconChainConfig { return ¶ms.BeaconChainConfig{ - ForkVersionSchedule: map[[4]byte]types.Epoch{ - {1, 1, 2, 3}: types.Epoch(2), - {0, 1, 2, 3}: types.Epoch(1), - {4, 1, 2, 3}: types.Epoch(16), - {3, 1, 2, 3}: types.Epoch(8), - {2, 1, 2, 3}: types.Epoch(4), + ForkVersionSchedule: map[[4]byte]primitives.Epoch{ + {1, 1, 2, 3}: primitives.Epoch(2), + {0, 1, 2, 3}: primitives.Epoch(1), + {4, 1, 2, 3}: primitives.Epoch(16), + {3, 1, 2, 3}: primitives.Epoch(8), + {2, 1, 2, 3}: primitives.Epoch(4), }, ForkVersionNames: map[[4]byte]string{ {1, 1, 2, 3}: "second", diff --git a/proto/engine/v1/json_marshal_unmarshal.go b/proto/engine/v1/json_marshal_unmarshal.go index bf8700a6cb..fa2a46fc24 100644 --- a/proto/engine/v1/json_marshal_unmarshal.go +++ b/proto/engine/v1/json_marshal_unmarshal.go @@ -11,7 +11,7 @@ import ( gethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/pkg/errors" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/runtime/version" ) @@ -191,7 +191,7 @@ func (w *Withdrawal) UnmarshalJSON(enc []byte) error { } *w = Withdrawal{} w.Index = uint64(*dec.Index) - w.ValidatorIndex = types.ValidatorIndex(*dec.Validator) + w.ValidatorIndex = primitives.ValidatorIndex(*dec.Validator) w.Amount = uint64(*dec.Amount) w.Address = dec.Address.Bytes() return nil diff --git a/proto/engine/v1/json_marshal_unmarshal_test.go b/proto/engine/v1/json_marshal_unmarshal_test.go index 92a7b3a263..8669c2f437 100644 --- a/proto/engine/v1/json_marshal_unmarshal_test.go +++ b/proto/engine/v1/json_marshal_unmarshal_test.go @@ -12,7 +12,7 @@ import ( "github.com/holiman/uint256" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -201,7 +201,7 @@ func TestJsonMarshalUnmarshal(t *testing.T) { require.Equal(t, 1, len(payloadPb.Withdrawals)) withdrawal := payloadPb.Withdrawals[0] require.Equal(t, uint64(1), withdrawal.Index) - require.Equal(t, types.ValidatorIndex(1), withdrawal.ValidatorIndex) + require.Equal(t, primitives.ValidatorIndex(1), withdrawal.ValidatorIndex) require.DeepEqual(t, bytesutil.PadTo([]byte("address"), 20), withdrawal.Address) require.Equal(t, uint64(1), withdrawal.Amount) }) @@ -466,11 +466,11 @@ func TestJsonMarshalUnmarshal(t *testing.T) { require.DeepEqual(t, want.Nonce, payloadPb.Nonce) require.Equal(t, 2, len(payloadPb.Withdrawals)) require.Equal(t, uint64(1), payloadPb.Withdrawals[0].Index) - require.Equal(t, types.ValidatorIndex(1), payloadPb.Withdrawals[0].ValidatorIndex) + require.Equal(t, primitives.ValidatorIndex(1), payloadPb.Withdrawals[0].ValidatorIndex) require.DeepEqual(t, bytesutil.PadTo([]byte("address1"), 20), payloadPb.Withdrawals[0].Address) require.Equal(t, uint64(100), payloadPb.Withdrawals[0].Amount) require.Equal(t, uint64(2), payloadPb.Withdrawals[1].Index) - require.Equal(t, types.ValidatorIndex(2), payloadPb.Withdrawals[1].ValidatorIndex) + require.Equal(t, primitives.ValidatorIndex(2), payloadPb.Withdrawals[1].ValidatorIndex) require.DeepEqual(t, bytesutil.PadTo([]byte("address2"), 20), payloadPb.Withdrawals[1].Address) require.Equal(t, uint64(200), payloadPb.Withdrawals[1].Amount) }) diff --git a/proto/migration/v1alpha1_to_v1_test.go b/proto/migration/v1alpha1_to_v1_test.go index 9ee22cd0ba..089a2c3110 100644 --- a/proto/migration/v1alpha1_to_v1_test.go +++ b/proto/migration/v1alpha1_to_v1_test.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/go-bitfield" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpbv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ethpbalpha "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -16,10 +16,10 @@ import ( ) var ( - slot = types.Slot(1) - epoch = types.Epoch(1) - validatorIndex = types.ValidatorIndex(1) - committeeIndex = types.CommitteeIndex(1) + slot = primitives.Slot(1) + epoch = primitives.Epoch(1) + validatorIndex = primitives.ValidatorIndex(1) + committeeIndex = primitives.CommitteeIndex(1) depositCount = uint64(2) attestingIndices = []uint64{1, 2} blockNumber = uint64(10) @@ -83,7 +83,7 @@ func Test_V1Alpha1AggregateAttAndProofToV1(t *testing.T) { SelectionProof: proof[:], } v1 := V1Alpha1AggregateAttAndProofToV1(alpha) - assert.Equal(t, v1.AggregatorIndex, types.ValidatorIndex(1)) + assert.Equal(t, v1.AggregatorIndex, primitives.ValidatorIndex(1)) assert.DeepSSZEqual(t, v1.Aggregate.Data.Slot, att.Data.Slot) assert.DeepEqual(t, v1.SelectionProof, proof[:]) } @@ -394,10 +394,10 @@ func Test_V1Alpha1ValidatorToV1(t *testing.T) { assert.DeepEqual(t, []byte("withdraw"), v1Validator.WithdrawalCredentials) assert.Equal(t, uint64(99), v1Validator.EffectiveBalance) assert.Equal(t, true, v1Validator.Slashed) - assert.Equal(t, types.Epoch(1), v1Validator.ActivationEligibilityEpoch) - assert.Equal(t, types.Epoch(11), v1Validator.ActivationEpoch) - assert.Equal(t, types.Epoch(111), v1Validator.ExitEpoch) - assert.Equal(t, types.Epoch(1111), v1Validator.WithdrawableEpoch) + assert.Equal(t, primitives.Epoch(1), v1Validator.ActivationEligibilityEpoch) + assert.Equal(t, primitives.Epoch(11), v1Validator.ActivationEpoch) + assert.Equal(t, primitives.Epoch(111), v1Validator.ExitEpoch) + assert.Equal(t, primitives.Epoch(1111), v1Validator.WithdrawableEpoch) } func Test_V1ValidatorToV1Alpha1(t *testing.T) { @@ -418,10 +418,10 @@ func Test_V1ValidatorToV1Alpha1(t *testing.T) { assert.DeepEqual(t, []byte("withdraw"), v1Alpha1Validator.WithdrawalCredentials) assert.Equal(t, uint64(99), v1Alpha1Validator.EffectiveBalance) assert.Equal(t, true, v1Alpha1Validator.Slashed) - assert.Equal(t, types.Epoch(1), v1Alpha1Validator.ActivationEligibilityEpoch) - assert.Equal(t, types.Epoch(11), v1Alpha1Validator.ActivationEpoch) - assert.Equal(t, types.Epoch(111), v1Alpha1Validator.ExitEpoch) - assert.Equal(t, types.Epoch(1111), v1Alpha1Validator.WithdrawableEpoch) + assert.Equal(t, primitives.Epoch(1), v1Alpha1Validator.ActivationEligibilityEpoch) + assert.Equal(t, primitives.Epoch(11), v1Alpha1Validator.ActivationEpoch) + assert.Equal(t, primitives.Epoch(111), v1Alpha1Validator.ExitEpoch) + assert.Equal(t, primitives.Epoch(1111), v1Alpha1Validator.WithdrawableEpoch) } func Test_V1SignedAggregateAttAndProofToV1Alpha1(t *testing.T) { @@ -554,16 +554,16 @@ func TestBeaconStateToProto(t *testing.T) { require.NotNil(t, result) assert.Equal(t, uint64(1), result.GenesisTime) assert.DeepEqual(t, bytesutil.PadTo([]byte("genesisvalidatorsroot"), 32), result.GenesisValidatorsRoot) - assert.Equal(t, types.Slot(2), result.Slot) + assert.Equal(t, primitives.Slot(2), result.Slot) resultFork := result.Fork require.NotNil(t, resultFork) assert.DeepEqual(t, bytesutil.PadTo([]byte("123"), 4), resultFork.PreviousVersion) assert.DeepEqual(t, bytesutil.PadTo([]byte("456"), 4), resultFork.CurrentVersion) - assert.Equal(t, types.Epoch(3), resultFork.Epoch) + assert.Equal(t, primitives.Epoch(3), resultFork.Epoch) resultLatestBlockHeader := result.LatestBlockHeader require.NotNil(t, resultLatestBlockHeader) - assert.Equal(t, types.Slot(4), resultLatestBlockHeader.Slot) - assert.Equal(t, types.ValidatorIndex(5), resultLatestBlockHeader.ProposerIndex) + assert.Equal(t, primitives.Slot(4), resultLatestBlockHeader.Slot) + assert.Equal(t, primitives.ValidatorIndex(5), resultLatestBlockHeader.ProposerIndex) assert.DeepEqual(t, bytesutil.PadTo([]byte("lbhparentroot"), 32), resultLatestBlockHeader.ParentRoot) assert.DeepEqual(t, bytesutil.PadTo([]byte("lbhstateroot"), 32), resultLatestBlockHeader.StateRoot) assert.DeepEqual(t, bytesutil.PadTo([]byte("lbhbodyroot"), 32), resultLatestBlockHeader.BodyRoot) @@ -592,10 +592,10 @@ func TestBeaconStateToProto(t *testing.T) { assert.DeepEqual(t, bytesutil.PadTo([]byte("withdrawalcredentials"), 32), resultValidator.WithdrawalCredentials) assert.Equal(t, uint64(9), resultValidator.EffectiveBalance) assert.Equal(t, true, resultValidator.Slashed) - assert.Equal(t, types.Epoch(10), resultValidator.ActivationEligibilityEpoch) - assert.Equal(t, types.Epoch(11), resultValidator.ActivationEpoch) - assert.Equal(t, types.Epoch(12), resultValidator.ExitEpoch) - assert.Equal(t, types.Epoch(13), resultValidator.WithdrawableEpoch) + assert.Equal(t, primitives.Epoch(10), resultValidator.ActivationEligibilityEpoch) + assert.Equal(t, primitives.Epoch(11), resultValidator.ActivationEpoch) + assert.Equal(t, primitives.Epoch(12), resultValidator.ExitEpoch) + assert.Equal(t, primitives.Epoch(13), resultValidator.WithdrawableEpoch) assert.DeepEqual(t, []uint64{14}, result.Balances) assert.Equal(t, 65536, len(result.RandaoMixes)) assert.DeepEqual(t, bytesutil.PadTo([]byte("randaomixes"), 32), result.RandaoMixes[0]) @@ -606,48 +606,48 @@ func TestBeaconStateToProto(t *testing.T) { assert.DeepEqual(t, bitfield.Bitlist{16}, resultPrevEpochAtt.AggregationBits) resultPrevEpochAttData := resultPrevEpochAtt.Data require.NotNil(t, resultPrevEpochAttData) - assert.Equal(t, types.Slot(17), resultPrevEpochAttData.Slot) - assert.Equal(t, types.CommitteeIndex(18), resultPrevEpochAttData.Index) + assert.Equal(t, primitives.Slot(17), resultPrevEpochAttData.Slot) + assert.Equal(t, primitives.CommitteeIndex(18), resultPrevEpochAttData.Index) assert.DeepEqual(t, bytesutil.PadTo([]byte("peabeaconblockroot"), 32), resultPrevEpochAttData.BeaconBlockRoot) resultPrevEpochAttSource := resultPrevEpochAttData.Source require.NotNil(t, resultPrevEpochAttSource) - assert.Equal(t, types.Epoch(19), resultPrevEpochAttSource.Epoch) + assert.Equal(t, primitives.Epoch(19), resultPrevEpochAttSource.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("peasroot"), 32), resultPrevEpochAttSource.Root) resultPrevEpochAttTarget := resultPrevEpochAttData.Target require.NotNil(t, resultPrevEpochAttTarget) - assert.Equal(t, types.Epoch(20), resultPrevEpochAttTarget.Epoch) + assert.Equal(t, primitives.Epoch(20), resultPrevEpochAttTarget.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("peatroot"), 32), resultPrevEpochAttTarget.Root) - assert.Equal(t, types.Slot(21), resultPrevEpochAtt.InclusionDelay) - assert.Equal(t, types.ValidatorIndex(22), resultPrevEpochAtt.ProposerIndex) + assert.Equal(t, primitives.Slot(21), resultPrevEpochAtt.InclusionDelay) + assert.Equal(t, primitives.ValidatorIndex(22), resultPrevEpochAtt.ProposerIndex) resultCurrEpochAtt := result.CurrentEpochAttestations[0] require.NotNil(t, resultCurrEpochAtt) assert.DeepEqual(t, bitfield.Bitlist{23}, resultCurrEpochAtt.AggregationBits) resultCurrEpochAttData := resultCurrEpochAtt.Data require.NotNil(t, resultCurrEpochAttData) - assert.Equal(t, types.Slot(24), resultCurrEpochAttData.Slot) - assert.Equal(t, types.CommitteeIndex(25), resultCurrEpochAttData.Index) + assert.Equal(t, primitives.Slot(24), resultCurrEpochAttData.Slot) + assert.Equal(t, primitives.CommitteeIndex(25), resultCurrEpochAttData.Index) assert.DeepEqual(t, bytesutil.PadTo([]byte("ceabeaconblockroot"), 32), resultCurrEpochAttData.BeaconBlockRoot) resultCurrEpochAttSource := resultCurrEpochAttData.Source require.NotNil(t, resultCurrEpochAttSource) - assert.Equal(t, types.Epoch(26), resultCurrEpochAttSource.Epoch) + assert.Equal(t, primitives.Epoch(26), resultCurrEpochAttSource.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("ceasroot"), 32), resultCurrEpochAttSource.Root) resultCurrEpochAttTarget := resultCurrEpochAttData.Target require.NotNil(t, resultCurrEpochAttTarget) - assert.Equal(t, types.Epoch(27), resultCurrEpochAttTarget.Epoch) + assert.Equal(t, primitives.Epoch(27), resultCurrEpochAttTarget.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("ceatroot"), 32), resultCurrEpochAttTarget.Root) - assert.Equal(t, types.Slot(28), resultCurrEpochAtt.InclusionDelay) - assert.Equal(t, types.ValidatorIndex(29), resultCurrEpochAtt.ProposerIndex) + assert.Equal(t, primitives.Slot(28), resultCurrEpochAtt.InclusionDelay) + assert.Equal(t, primitives.ValidatorIndex(29), resultCurrEpochAtt.ProposerIndex) assert.DeepEqual(t, bitfield.Bitvector4{1}, result.JustificationBits) resultPrevJustifiedCheckpoint := result.PreviousJustifiedCheckpoint require.NotNil(t, resultPrevJustifiedCheckpoint) - assert.Equal(t, types.Epoch(30), resultPrevJustifiedCheckpoint.Epoch) + assert.Equal(t, primitives.Epoch(30), resultPrevJustifiedCheckpoint.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("pjcroot"), 32), resultPrevJustifiedCheckpoint.Root) resultCurrJustifiedCheckpoint := result.CurrentJustifiedCheckpoint require.NotNil(t, resultCurrJustifiedCheckpoint) - assert.Equal(t, types.Epoch(31), resultCurrJustifiedCheckpoint.Epoch) + assert.Equal(t, primitives.Epoch(31), resultCurrJustifiedCheckpoint.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("cjcroot"), 32), resultCurrJustifiedCheckpoint.Root) resultFinalizedCheckpoint := result.FinalizedCheckpoint require.NotNil(t, resultFinalizedCheckpoint) - assert.Equal(t, types.Epoch(32), resultFinalizedCheckpoint.Epoch) + assert.Equal(t, primitives.Epoch(32), resultFinalizedCheckpoint.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("fcroot"), 32), resultFinalizedCheckpoint.Root) } diff --git a/proto/migration/v1alpha1_to_v2_test.go b/proto/migration/v1alpha1_to_v2_test.go index 4ca7e07061..263dc0584a 100644 --- a/proto/migration/v1alpha1_to_v2_test.go +++ b/proto/migration/v1alpha1_to_v2_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/prysmaticlabs/go-bitfield" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpbv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" @@ -327,16 +327,16 @@ func TestBeaconStateAltairToProto(t *testing.T) { require.NotNil(t, result) assert.Equal(t, uint64(1), result.GenesisTime) assert.DeepEqual(t, bytesutil.PadTo([]byte("genesisvalidatorsroot"), 32), result.GenesisValidatorsRoot) - assert.Equal(t, types.Slot(2), result.Slot) + assert.Equal(t, primitives.Slot(2), result.Slot) resultFork := result.Fork require.NotNil(t, resultFork) assert.DeepEqual(t, bytesutil.PadTo([]byte("123"), 4), resultFork.PreviousVersion) assert.DeepEqual(t, bytesutil.PadTo([]byte("456"), 4), resultFork.CurrentVersion) - assert.Equal(t, types.Epoch(3), resultFork.Epoch) + assert.Equal(t, primitives.Epoch(3), resultFork.Epoch) resultLatestBlockHeader := result.LatestBlockHeader require.NotNil(t, resultLatestBlockHeader) - assert.Equal(t, types.Slot(4), resultLatestBlockHeader.Slot) - assert.Equal(t, types.ValidatorIndex(5), resultLatestBlockHeader.ProposerIndex) + assert.Equal(t, primitives.Slot(4), resultLatestBlockHeader.Slot) + assert.Equal(t, primitives.ValidatorIndex(5), resultLatestBlockHeader.ProposerIndex) assert.DeepEqual(t, bytesutil.PadTo([]byte("lbhparentroot"), 32), resultLatestBlockHeader.ParentRoot) assert.DeepEqual(t, bytesutil.PadTo([]byte("lbhstateroot"), 32), resultLatestBlockHeader.StateRoot) assert.DeepEqual(t, bytesutil.PadTo([]byte("lbhbodyroot"), 32), resultLatestBlockHeader.BodyRoot) @@ -365,10 +365,10 @@ func TestBeaconStateAltairToProto(t *testing.T) { assert.DeepEqual(t, bytesutil.PadTo([]byte("withdrawalcredentials"), 32), resultValidator.WithdrawalCredentials) assert.Equal(t, uint64(9), resultValidator.EffectiveBalance) assert.Equal(t, true, resultValidator.Slashed) - assert.Equal(t, types.Epoch(10), resultValidator.ActivationEligibilityEpoch) - assert.Equal(t, types.Epoch(11), resultValidator.ActivationEpoch) - assert.Equal(t, types.Epoch(12), resultValidator.ExitEpoch) - assert.Equal(t, types.Epoch(13), resultValidator.WithdrawableEpoch) + assert.Equal(t, primitives.Epoch(10), resultValidator.ActivationEligibilityEpoch) + assert.Equal(t, primitives.Epoch(11), resultValidator.ActivationEpoch) + assert.Equal(t, primitives.Epoch(12), resultValidator.ExitEpoch) + assert.Equal(t, primitives.Epoch(13), resultValidator.WithdrawableEpoch) assert.DeepEqual(t, []uint64{14}, result.Balances) assert.Equal(t, 65536, len(result.RandaoMixes)) assert.DeepEqual(t, bytesutil.PadTo([]byte("randaomixes"), 32), result.RandaoMixes[0]) @@ -376,15 +376,15 @@ func TestBeaconStateAltairToProto(t *testing.T) { assert.DeepEqual(t, bitfield.Bitvector4{1}, result.JustificationBits) resultPrevJustifiedCheckpoint := result.PreviousJustifiedCheckpoint require.NotNil(t, resultPrevJustifiedCheckpoint) - assert.Equal(t, types.Epoch(30), resultPrevJustifiedCheckpoint.Epoch) + assert.Equal(t, primitives.Epoch(30), resultPrevJustifiedCheckpoint.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("pjcroot"), 32), resultPrevJustifiedCheckpoint.Root) resultCurrJustifiedCheckpoint := result.CurrentJustifiedCheckpoint require.NotNil(t, resultCurrJustifiedCheckpoint) - assert.Equal(t, types.Epoch(31), resultCurrJustifiedCheckpoint.Epoch) + assert.Equal(t, primitives.Epoch(31), resultCurrJustifiedCheckpoint.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("cjcroot"), 32), resultCurrJustifiedCheckpoint.Root) resultFinalizedCheckpoint := result.FinalizedCheckpoint require.NotNil(t, resultFinalizedCheckpoint) - assert.Equal(t, types.Epoch(32), resultFinalizedCheckpoint.Epoch) + assert.Equal(t, primitives.Epoch(32), resultFinalizedCheckpoint.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("fcroot"), 32), resultFinalizedCheckpoint.Root) assert.DeepEqual(t, []byte("previousepochparticipation"), result.PreviousEpochParticipation) assert.DeepEqual(t, []byte("currentepochparticipation"), result.CurrentEpochParticipation) @@ -490,16 +490,16 @@ func TestBeaconStateBellatrixToProto(t *testing.T) { require.NotNil(t, result) assert.Equal(t, uint64(1), result.GenesisTime) assert.DeepEqual(t, bytesutil.PadTo([]byte("genesisvalidatorsroot"), 32), result.GenesisValidatorsRoot) - assert.Equal(t, types.Slot(2), result.Slot) + assert.Equal(t, primitives.Slot(2), result.Slot) resultFork := result.Fork require.NotNil(t, resultFork) assert.DeepEqual(t, bytesutil.PadTo([]byte("123"), 4), resultFork.PreviousVersion) assert.DeepEqual(t, bytesutil.PadTo([]byte("456"), 4), resultFork.CurrentVersion) - assert.Equal(t, types.Epoch(3), resultFork.Epoch) + assert.Equal(t, primitives.Epoch(3), resultFork.Epoch) resultLatestBlockHeader := result.LatestBlockHeader require.NotNil(t, resultLatestBlockHeader) - assert.Equal(t, types.Slot(4), resultLatestBlockHeader.Slot) - assert.Equal(t, types.ValidatorIndex(5), resultLatestBlockHeader.ProposerIndex) + assert.Equal(t, primitives.Slot(4), resultLatestBlockHeader.Slot) + assert.Equal(t, primitives.ValidatorIndex(5), resultLatestBlockHeader.ProposerIndex) assert.DeepEqual(t, bytesutil.PadTo([]byte("lbhparentroot"), 32), resultLatestBlockHeader.ParentRoot) assert.DeepEqual(t, bytesutil.PadTo([]byte("lbhstateroot"), 32), resultLatestBlockHeader.StateRoot) assert.DeepEqual(t, bytesutil.PadTo([]byte("lbhbodyroot"), 32), resultLatestBlockHeader.BodyRoot) @@ -528,10 +528,10 @@ func TestBeaconStateBellatrixToProto(t *testing.T) { assert.DeepEqual(t, bytesutil.PadTo([]byte("withdrawalcredentials"), 32), resultValidator.WithdrawalCredentials) assert.Equal(t, uint64(9), resultValidator.EffectiveBalance) assert.Equal(t, true, resultValidator.Slashed) - assert.Equal(t, types.Epoch(10), resultValidator.ActivationEligibilityEpoch) - assert.Equal(t, types.Epoch(11), resultValidator.ActivationEpoch) - assert.Equal(t, types.Epoch(12), resultValidator.ExitEpoch) - assert.Equal(t, types.Epoch(13), resultValidator.WithdrawableEpoch) + assert.Equal(t, primitives.Epoch(10), resultValidator.ActivationEligibilityEpoch) + assert.Equal(t, primitives.Epoch(11), resultValidator.ActivationEpoch) + assert.Equal(t, primitives.Epoch(12), resultValidator.ExitEpoch) + assert.Equal(t, primitives.Epoch(13), resultValidator.WithdrawableEpoch) assert.DeepEqual(t, []uint64{14}, result.Balances) assert.Equal(t, 65536, len(result.RandaoMixes)) assert.DeepEqual(t, bytesutil.PadTo([]byte("randaomixes"), 32), result.RandaoMixes[0]) @@ -539,15 +539,15 @@ func TestBeaconStateBellatrixToProto(t *testing.T) { assert.DeepEqual(t, bitfield.Bitvector4{1}, result.JustificationBits) resultPrevJustifiedCheckpoint := result.PreviousJustifiedCheckpoint require.NotNil(t, resultPrevJustifiedCheckpoint) - assert.Equal(t, types.Epoch(30), resultPrevJustifiedCheckpoint.Epoch) + assert.Equal(t, primitives.Epoch(30), resultPrevJustifiedCheckpoint.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("pjcroot"), 32), resultPrevJustifiedCheckpoint.Root) resultCurrJustifiedCheckpoint := result.CurrentJustifiedCheckpoint require.NotNil(t, resultCurrJustifiedCheckpoint) - assert.Equal(t, types.Epoch(31), resultCurrJustifiedCheckpoint.Epoch) + assert.Equal(t, primitives.Epoch(31), resultCurrJustifiedCheckpoint.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("cjcroot"), 32), resultCurrJustifiedCheckpoint.Root) resultFinalizedCheckpoint := result.FinalizedCheckpoint require.NotNil(t, resultFinalizedCheckpoint) - assert.Equal(t, types.Epoch(32), resultFinalizedCheckpoint.Epoch) + assert.Equal(t, primitives.Epoch(32), resultFinalizedCheckpoint.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("fcroot"), 32), resultFinalizedCheckpoint.Root) assert.DeepEqual(t, []byte("previousepochparticipation"), result.PreviousEpochParticipation) assert.DeepEqual(t, []byte("currentepochparticipation"), result.CurrentEpochParticipation) @@ -681,16 +681,16 @@ func TestBeaconStateCapellaToProto(t *testing.T) { require.NotNil(t, result) assert.Equal(t, uint64(1), result.GenesisTime) assert.DeepEqual(t, bytesutil.PadTo([]byte("genesisvalidatorsroot"), 32), result.GenesisValidatorsRoot) - assert.Equal(t, types.Slot(2), result.Slot) + assert.Equal(t, primitives.Slot(2), result.Slot) resultFork := result.Fork require.NotNil(t, resultFork) assert.DeepEqual(t, bytesutil.PadTo([]byte("123"), 4), resultFork.PreviousVersion) assert.DeepEqual(t, bytesutil.PadTo([]byte("456"), 4), resultFork.CurrentVersion) - assert.Equal(t, types.Epoch(3), resultFork.Epoch) + assert.Equal(t, primitives.Epoch(3), resultFork.Epoch) resultLatestBlockHeader := result.LatestBlockHeader require.NotNil(t, resultLatestBlockHeader) - assert.Equal(t, types.Slot(4), resultLatestBlockHeader.Slot) - assert.Equal(t, types.ValidatorIndex(5), resultLatestBlockHeader.ProposerIndex) + assert.Equal(t, primitives.Slot(4), resultLatestBlockHeader.Slot) + assert.Equal(t, primitives.ValidatorIndex(5), resultLatestBlockHeader.ProposerIndex) assert.DeepEqual(t, bytesutil.PadTo([]byte("lbhparentroot"), 32), resultLatestBlockHeader.ParentRoot) assert.DeepEqual(t, bytesutil.PadTo([]byte("lbhstateroot"), 32), resultLatestBlockHeader.StateRoot) assert.DeepEqual(t, bytesutil.PadTo([]byte("lbhbodyroot"), 32), resultLatestBlockHeader.BodyRoot) @@ -717,10 +717,10 @@ func TestBeaconStateCapellaToProto(t *testing.T) { assert.DeepEqual(t, bytesutil.PadTo([]byte("withdrawalcredentials"), 32), resultValidator.WithdrawalCredentials) assert.Equal(t, uint64(9), resultValidator.EffectiveBalance) assert.Equal(t, true, resultValidator.Slashed) - assert.Equal(t, types.Epoch(10), resultValidator.ActivationEligibilityEpoch) - assert.Equal(t, types.Epoch(11), resultValidator.ActivationEpoch) - assert.Equal(t, types.Epoch(12), resultValidator.ExitEpoch) - assert.Equal(t, types.Epoch(13), resultValidator.WithdrawableEpoch) + assert.Equal(t, primitives.Epoch(10), resultValidator.ActivationEligibilityEpoch) + assert.Equal(t, primitives.Epoch(11), resultValidator.ActivationEpoch) + assert.Equal(t, primitives.Epoch(12), resultValidator.ExitEpoch) + assert.Equal(t, primitives.Epoch(13), resultValidator.WithdrawableEpoch) assert.DeepEqual(t, []uint64{14}, result.Balances) assert.Equal(t, 65536, len(result.RandaoMixes)) assert.DeepEqual(t, bytesutil.PadTo([]byte("randaomixes"), 32), result.RandaoMixes[0]) @@ -728,15 +728,15 @@ func TestBeaconStateCapellaToProto(t *testing.T) { assert.DeepEqual(t, bitfield.Bitvector4{1}, result.JustificationBits) resultPrevJustifiedCheckpoint := result.PreviousJustifiedCheckpoint require.NotNil(t, resultPrevJustifiedCheckpoint) - assert.Equal(t, types.Epoch(30), resultPrevJustifiedCheckpoint.Epoch) + assert.Equal(t, primitives.Epoch(30), resultPrevJustifiedCheckpoint.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("pjcroot"), 32), resultPrevJustifiedCheckpoint.Root) resultCurrJustifiedCheckpoint := result.CurrentJustifiedCheckpoint require.NotNil(t, resultCurrJustifiedCheckpoint) - assert.Equal(t, types.Epoch(31), resultCurrJustifiedCheckpoint.Epoch) + assert.Equal(t, primitives.Epoch(31), resultCurrJustifiedCheckpoint.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("cjcroot"), 32), resultCurrJustifiedCheckpoint.Root) resultFinalizedCheckpoint := result.FinalizedCheckpoint require.NotNil(t, resultFinalizedCheckpoint) - assert.Equal(t, types.Epoch(32), resultFinalizedCheckpoint.Epoch) + assert.Equal(t, primitives.Epoch(32), resultFinalizedCheckpoint.Epoch) assert.DeepEqual(t, bytesutil.PadTo([]byte("fcroot"), 32), resultFinalizedCheckpoint.Root) assert.DeepEqual(t, []byte("previousepochparticipation"), result.PreviousEpochParticipation) assert.DeepEqual(t, []byte("currentepochparticipation"), result.CurrentEpochParticipation) @@ -765,7 +765,7 @@ func TestBeaconStateCapellaToProto(t *testing.T) { assert.DeepEqual(t, bytesutil.PadTo([]byte("transactionsroot"), 32), resultLatestExecutionPayloadHeader.TransactionsRoot) assert.DeepEqual(t, bytesutil.PadTo([]byte("withdrawalsroot"), 32), resultLatestExecutionPayloadHeader.WithdrawalsRoot) assert.Equal(t, uint64(123), result.NextWithdrawalIndex) - assert.Equal(t, types.ValidatorIndex(123), result.NextWithdrawalValidatorIndex) + assert.Equal(t, primitives.ValidatorIndex(123), result.NextWithdrawalValidatorIndex) assert.DeepEqual(t, bytesutil.PadTo([]byte("blocksummaryroot"), 32), result.HistoricalSummaries[0].BlockSummaryRoot) assert.DeepEqual(t, bytesutil.PadTo([]byte("statesummaryroot"), 32), result.HistoricalSummaries[0].StateSummaryRoot) assert.DeepEqual(t, bytesutil.PadTo([]byte("blocksummaryroot2"), 32), result.HistoricalSummaries[1].BlockSummaryRoot) diff --git a/proto/prysm/v1alpha1/attestation/aggregation/testing/bitlistutils.go b/proto/prysm/v1alpha1/attestation/aggregation/testing/bitlistutils.go index a50effa7ad..b2c7553c7c 100644 --- a/proto/prysm/v1alpha1/attestation/aggregation/testing/bitlistutils.go +++ b/proto/prysm/v1alpha1/attestation/aggregation/testing/bitlistutils.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/prysmaticlabs/go-bitfield" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time" @@ -97,7 +97,7 @@ func MakeSyncContributionsFromBitVector(bl []bitfield.Bitvector128) []*ethpb.Syn c := make([]*ethpb.SyncCommitteeContribution, len(bl)) for i, b := range bl { c[i] = ðpb.SyncCommitteeContribution{ - Slot: types.Slot(1), + Slot: primitives.Slot(1), SubcommitteeIndex: 2, AggregationBits: b, Signature: bls.NewAggregateSignature().Marshal(), diff --git a/proto/prysm/v1alpha1/attestation/attestation_utils.go b/proto/prysm/v1alpha1/attestation/attestation_utils.go index d57fb59ef8..0970eb355f 100644 --- a/proto/prysm/v1alpha1/attestation/attestation_utils.go +++ b/proto/prysm/v1alpha1/attestation/attestation_utils.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "go.opencensus.io/trace" @@ -37,7 +37,7 @@ import ( // data=attestation.data, // signature=attestation.signature, // ) -func ConvertToIndexed(ctx context.Context, attestation *ethpb.Attestation, committee []types.ValidatorIndex) (*ethpb.IndexedAttestation, error) { +func ConvertToIndexed(ctx context.Context, attestation *ethpb.Attestation, committee []primitives.ValidatorIndex) (*ethpb.IndexedAttestation, error) { ctx, span := trace.StartSpan(ctx, "attestationutil.ConvertToIndexed") defer span.End() @@ -71,7 +71,7 @@ func ConvertToIndexed(ctx context.Context, attestation *ethpb.Attestation, commi // """ // committee = get_beacon_committee(state, data.slot, data.index) // return set(index for i, index in enumerate(committee) if bits[i]) -func AttestingIndices(bf bitfield.Bitfield, committee []types.ValidatorIndex) ([]uint64, error) { +func AttestingIndices(bf bitfield.Bitfield, committee []primitives.ValidatorIndex) ([]uint64, error) { if bf.Len() != uint64(len(committee)) { return nil, fmt.Errorf("bitfield length %d is not equal to committee length %d", bf.Len(), len(committee)) } diff --git a/proto/prysm/v1alpha1/attestation/attestation_utils_test.go b/proto/prysm/v1alpha1/attestation/attestation_utils_test.go index 3882c6de2f..53cb165043 100644 --- a/proto/prysm/v1alpha1/attestation/attestation_utils_test.go +++ b/proto/prysm/v1alpha1/attestation/attestation_utils_test.go @@ -7,7 +7,7 @@ import ( "github.com/prysmaticlabs/go-bitfield" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/attestation" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -17,7 +17,7 @@ import ( func TestAttestingIndices(t *testing.T) { type args struct { bf bitfield.Bitfield - committee []types.ValidatorIndex + committee []primitives.ValidatorIndex } tests := []struct { name string @@ -29,7 +29,7 @@ func TestAttestingIndices(t *testing.T) { name: "Full committee attested", args: args{ bf: bitfield.Bitlist{0b1111}, - committee: []types.ValidatorIndex{0, 1, 2}, + committee: []primitives.ValidatorIndex{0, 1, 2}, }, want: []uint64{0, 1, 2}, }, @@ -37,7 +37,7 @@ func TestAttestingIndices(t *testing.T) { name: "Partial committee attested", args: args{ bf: bitfield.Bitlist{0b1101}, - committee: []types.ValidatorIndex{0, 1, 2}, + committee: []primitives.ValidatorIndex{0, 1, 2}, }, want: []uint64{0, 2}, }, @@ -45,7 +45,7 @@ func TestAttestingIndices(t *testing.T) { name: "Invalid bit length", args: args{ bf: bitfield.Bitlist{0b11111}, - committee: []types.ValidatorIndex{0, 1, 2}, + committee: []primitives.ValidatorIndex{0, 1, 2}, }, err: "bitfield length 4 is not equal to committee length 3", }, @@ -157,7 +157,7 @@ func TestIsValidAttestationIndices(t *testing.T) { func BenchmarkAttestingIndices_PartialCommittee(b *testing.B) { bf := bitfield.Bitlist{0b11111111, 0b11111111, 0b10000111, 0b11111111, 0b100} - committee := []types.ValidatorIndex{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34} + committee := []primitives.ValidatorIndex{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34} b.ResetTimer() for i := 0; i < b.N; i++ { diff --git a/proto/prysm/v1alpha1/slashings/surround_votes_test.go b/proto/prysm/v1alpha1/slashings/surround_votes_test.go index 940e8641ad..b005940620 100644 --- a/proto/prysm/v1alpha1/slashings/surround_votes_test.go +++ b/proto/prysm/v1alpha1/slashings/surround_votes_test.go @@ -3,7 +3,7 @@ package slashings import ( "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -83,7 +83,7 @@ func TestIsSurround(t *testing.T) { } } -func createAttestation(source, target types.Epoch) *ethpb.IndexedAttestation { +func createAttestation(source, target primitives.Epoch) *ethpb.IndexedAttestation { return ðpb.IndexedAttestation{ Data: ðpb.AttestationData{ Source: ðpb.Checkpoint{Epoch: source}, diff --git a/testing/endtoend/endtoend_test.go b/testing/endtoend/endtoend_test.go index ce5060cd01..e1622c91ee 100644 --- a/testing/endtoend/endtoend_test.go +++ b/testing/endtoend/endtoend_test.go @@ -27,7 +27,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/transition" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/endtoend/components" @@ -127,7 +127,7 @@ func (r *testRunner) scenarioRunner() { r.runBase([]runEvent{r.scenarioRun}) } -func (r *testRunner) waitExtra(ctx context.Context, e types.Epoch, conn *grpc.ClientConn, extra types.Epoch) error { +func (r *testRunner) waitExtra(ctx context.Context, e primitives.Epoch, conn *grpc.ClientConn, extra primitives.Epoch) error { spe := uint64(params.BeaconConfig().SlotsPerEpoch.Mul(params.BeaconConfig().SecondsPerSlot)) dl := time.Now().Add(time.Second * time.Duration(uint64(extra)*spe)) @@ -520,7 +520,7 @@ func (r *testRunner) defaultEndToEndRun() error { } if config.ExtraEpochs > 0 { - if err := r.waitExtra(ctx, types.Epoch(config.EpochsToRun+config.ExtraEpochs), conns[0], types.Epoch(config.ExtraEpochs)); err != nil { + if err := r.waitExtra(ctx, primitives.Epoch(config.EpochsToRun+config.ExtraEpochs), conns[0], primitives.Epoch(config.ExtraEpochs)); err != nil { return errors.Wrap(err, "error while waiting for ExtraEpochs") } syncEvaluators := []e2etypes.Evaluator{ev.FinishedSyncing, ev.AllNodesHaveSameHead} @@ -591,7 +591,7 @@ func (r *testRunner) executeProvidedEvaluators(ec *e2etypes.EvaluationContext, c // in a separate goroutine. evaluator := eval // Only run if the policy says so. - if !evaluator.Policy(types.Epoch(currentEpoch)) { + if !evaluator.Policy(primitives.Epoch(currentEpoch)) { continue } wg.Add(1) diff --git a/testing/endtoend/evaluators/api_middleware.go b/testing/endtoend/evaluators/api_middleware.go index b8e5d036f2..215c6ccdb9 100644 --- a/testing/endtoend/evaluators/api_middleware.go +++ b/testing/endtoend/evaluators/api_middleware.go @@ -11,7 +11,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/pkg/errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/proto/eth/service" ethpbv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ethpbv2 "github.com/prysmaticlabs/prysm/v3/proto/eth/v2" @@ -208,7 +208,7 @@ func withCompareAttesterDuties(beaconNodeIdx int, conn *grpc.ClientConn) error { validatorClient := service.NewBeaconValidatorClient(conn) resp, err := validatorClient.GetAttesterDuties(ctx, ðpbv1.AttesterDutiesRequest{ Epoch: helpers.AltairE2EForkEpoch, - Index: []types.ValidatorIndex{0}, + Index: []primitives.ValidatorIndex{0}, }) if err != nil { return err diff --git a/testing/endtoend/evaluators/beaconapi_evaluators/beacon_api.go b/testing/endtoend/evaluators/beaconapi_evaluators/beacon_api.go index ff3d3989ee..bcd506ae9f 100644 --- a/testing/endtoend/evaluators/beaconapi_evaluators/beacon_api.go +++ b/testing/endtoend/evaluators/beaconapi_evaluators/beacon_api.go @@ -9,27 +9,23 @@ import ( "strconv" "strings" - v1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" - "github.com/prysmaticlabs/prysm/v3/testing/endtoend/helpers" - - "github.com/prysmaticlabs/prysm/v3/config/params" - - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" - - "github.com/golang/protobuf/ptypes/empty" - "github.com/prysmaticlabs/prysm/v3/proto/eth/service" - "github.com/prysmaticlabs/prysm/v3/time/slots" - "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/golang/protobuf/ptypes/empty" "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" + "github.com/prysmaticlabs/prysm/v3/config/params" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/proto/eth/service" + v1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/v3/testing/endtoend/helpers" + "github.com/prysmaticlabs/prysm/v3/time/slots" "google.golang.org/grpc" ) type metadata struct { basepath string - params func(encoding string, currentEpoch types.Epoch) []string + params func(encoding string, currentEpoch primitives.Epoch) []string prysmResps map[string]interface{} lighthouseResps map[string]interface{} customEvaluation func(interface{}, interface{}) error @@ -38,7 +34,7 @@ type metadata struct { var beaconPathsAndObjects = map[string]metadata{ "/beacon/genesis": { basepath: v1MiddlewarePathTemplate, - params: func(_ string, _ types.Epoch) []string { + params: func(_ string, _ primitives.Epoch) []string { return []string{} }, prysmResps: map[string]interface{}{ @@ -50,7 +46,7 @@ var beaconPathsAndObjects = map[string]metadata{ }, "/beacon/states/{param1}/root": { basepath: v1MiddlewarePathTemplate, - params: func(_ string, _ types.Epoch) []string { + params: func(_ string, _ primitives.Epoch) []string { return []string{"head"} }, prysmResps: map[string]interface{}{ @@ -62,7 +58,7 @@ var beaconPathsAndObjects = map[string]metadata{ }, "/beacon/states/{param1}/finality_checkpoints": { basepath: v1MiddlewarePathTemplate, - params: func(_ string, _ types.Epoch) []string { + params: func(_ string, _ primitives.Epoch) []string { return []string{"head"} }, prysmResps: map[string]interface{}{ @@ -74,7 +70,7 @@ var beaconPathsAndObjects = map[string]metadata{ }, "/beacon/blocks/{param1}": { basepath: v2MiddlewarePathTemplate, - params: func(t string, e types.Epoch) []string { + params: func(t string, e primitives.Epoch) []string { if t == "ssz" { if e < 4 { return []string{"genesis"} @@ -95,7 +91,7 @@ var beaconPathsAndObjects = map[string]metadata{ }, "/beacon/states/{param1}/fork": { basepath: v1MiddlewarePathTemplate, - params: func(_ string, _ types.Epoch) []string { + params: func(_ string, _ primitives.Epoch) []string { return []string{"finalized"} }, prysmResps: map[string]interface{}{ @@ -107,7 +103,7 @@ var beaconPathsAndObjects = map[string]metadata{ }, "/debug/beacon/states/{param1}": { basepath: v2MiddlewarePathTemplate, - params: func(_ string, e types.Epoch) []string { + params: func(_ string, e primitives.Epoch) []string { return []string{"head"} }, prysmResps: map[string]interface{}{ @@ -119,7 +115,7 @@ var beaconPathsAndObjects = map[string]metadata{ }, "/validator/duties/proposer/{param1}": { basepath: v1MiddlewarePathTemplate, - params: func(_ string, e types.Epoch) []string { + params: func(_ string, e primitives.Epoch) []string { return []string{fmt.Sprintf("%v", e)} }, prysmResps: map[string]interface{}{ @@ -143,7 +139,7 @@ var beaconPathsAndObjects = map[string]metadata{ }, "/beacon/headers/{param1}": { basepath: v1MiddlewarePathTemplate, - params: func(_ string, e types.Epoch) []string { + params: func(_ string, e primitives.Epoch) []string { slot := uint64(0) if e > 0 { slot = (uint64(e) * uint64(params.BeaconConfig().SlotsPerEpoch)) - 1 @@ -159,7 +155,7 @@ var beaconPathsAndObjects = map[string]metadata{ }, "/node/identity": { basepath: v1MiddlewarePathTemplate, - params: func(_ string, _ types.Epoch) []string { + params: func(_ string, _ primitives.Epoch) []string { return []string{} }, prysmResps: map[string]interface{}{ @@ -188,7 +184,7 @@ var beaconPathsAndObjects = map[string]metadata{ }, "/node/peers": { basepath: v1MiddlewarePathTemplate, - params: func(_ string, _ types.Epoch) []string { + params: func(_ string, _ primitives.Epoch) []string { return []string{} }, prysmResps: map[string]interface{}{ diff --git a/testing/endtoend/evaluators/data.go b/testing/endtoend/evaluators/data.go index 7261cecfb0..7cf697d130 100644 --- a/testing/endtoend/evaluators/data.go +++ b/testing/endtoend/evaluators/data.go @@ -4,7 +4,7 @@ import ( "context" "errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" e2etypes "github.com/prysmaticlabs/prysm/v3/testing/endtoend/types" "google.golang.org/grpc" @@ -15,7 +15,7 @@ const epochToCheck = 50 // must be more than 46 (32 hot states + 16 chkpt interv // ColdStateCheckpoint checks data from the database using cold state storage. var ColdStateCheckpoint = e2etypes.Evaluator{ Name: "cold_state_assignments_from_epoch_%d", - Policy: func(currentEpoch types.Epoch) bool { + Policy: func(currentEpoch primitives.Epoch) bool { return currentEpoch == epochToCheck }, Evaluation: checkColdStateCheckpoint, @@ -26,7 +26,7 @@ func checkColdStateCheckpoint(_ *e2etypes.EvaluationContext, conns ...*grpc.Clie ctx := context.Background() client := eth.NewBeaconChainClient(conns[0]) - for i := types.Epoch(0); i < epochToCheck; i++ { + for i := primitives.Epoch(0); i < epochToCheck; i++ { res, err := client.ListValidatorAssignments(ctx, ð.ListValidatorAssignmentsRequest{ QueryFilter: ð.ListValidatorAssignmentsRequest_Epoch{Epoch: i}, }) diff --git a/testing/endtoend/evaluators/execution_engine.go b/testing/endtoend/evaluators/execution_engine.go index f21843e6dc..8c9e82fa85 100644 --- a/testing/endtoend/evaluators/execution_engine.go +++ b/testing/endtoend/evaluators/execution_engine.go @@ -5,7 +5,7 @@ import ( "strconv" "github.com/pkg/errors" - ctypes "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" mathutil "github.com/prysmaticlabs/prysm/v3/math" "github.com/prysmaticlabs/prysm/v3/proto/eth/service" v2 "github.com/prysmaticlabs/prysm/v3/proto/eth/v2" @@ -40,13 +40,13 @@ func optimisticSyncEnabled(_ *types.EvaluationContext, conns ...*grpc.ClientConn default: return errors.New("no valid block type retrieved") } - currEpoch := slots.ToEpoch(ctypes.Slot(headSlot)) + currEpoch := slots.ToEpoch(primitives.Slot(headSlot)) startSlot, err := slots.EpochStart(currEpoch) if err != nil { return err } isOptimistic := false - for i := startSlot; i <= ctypes.Slot(headSlot); i++ { + for i := startSlot; i <= primitives.Slot(headSlot); i++ { castI, err := mathutil.Int(uint64(i)) if err != nil { return err diff --git a/testing/endtoend/evaluators/finality.go b/testing/endtoend/evaluators/finality.go index 4e1869ff47..6c6279c0bc 100644 --- a/testing/endtoend/evaluators/finality.go +++ b/testing/endtoend/evaluators/finality.go @@ -5,7 +5,7 @@ import ( "fmt" "github.com/pkg/errors" - ethtypes "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/endtoend/policies" "github.com/prysmaticlabs/prysm/v3/testing/endtoend/types" @@ -15,7 +15,7 @@ import ( // FinalizationOccurs is an evaluator to make sure finalization is performing as it should. // Requires to be run after at least 4 epochs have passed. -var FinalizationOccurs = func(epoch ethtypes.Epoch) types.Evaluator { +var FinalizationOccurs = func(epoch primitives.Epoch) types.Evaluator { return types.Evaluator{ Name: "finalizes_at_epoch_%d", Policy: policies.AfterNthEpoch(epoch), diff --git a/testing/endtoend/evaluators/fork.go b/testing/endtoend/evaluators/fork.go index 2bde30b6bc..840ff4d64f 100644 --- a/testing/endtoend/evaluators/fork.go +++ b/testing/endtoend/evaluators/fork.go @@ -6,7 +6,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - ptypes "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" "github.com/prysmaticlabs/prysm/v3/testing/endtoend/helpers" @@ -22,7 +22,7 @@ var startingFork = version.Bellatrix // AltairForkTransition ensures that the Altair hard fork has occurred successfully. var AltairForkTransition = types.Evaluator{ Name: "altair_fork_transition_%d", - Policy: func(e ptypes.Epoch) bool { + Policy: func(e primitives.Epoch) bool { altair := policies.OnEpoch(helpers.AltairE2EForkEpoch) // TODO (11750): modify policies to take an end to end config if startingFork == version.Phase0 { diff --git a/testing/endtoend/evaluators/node.go b/testing/endtoend/evaluators/node.go index f6e941967f..c38fe970e6 100644 --- a/testing/endtoend/evaluators/node.go +++ b/testing/endtoend/evaluators/node.go @@ -11,7 +11,7 @@ import ( "time" "github.com/pkg/errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" e2e "github.com/prysmaticlabs/prysm/v3/testing/endtoend/params" "github.com/prysmaticlabs/prysm/v3/testing/endtoend/policies" @@ -128,7 +128,7 @@ func finishedSyncing(_ *e2etypes.EvaluationContext, conns ...*grpc.ClientConn) e } func allNodesHaveSameHead(_ *e2etypes.EvaluationContext, conns ...*grpc.ClientConn) error { - headEpochs := make([]types.Epoch, len(conns)) + headEpochs := make([]primitives.Epoch, len(conns)) justifiedRoots := make([][]byte, len(conns)) prevJustifiedRoots := make([][]byte, len(conns)) finalizedRoots := make([][]byte, len(conns)) diff --git a/testing/endtoend/evaluators/operations.go b/testing/endtoend/evaluators/operations.go index ca9b7e69fb..bd6ef0fab8 100644 --- a/testing/endtoend/evaluators/operations.go +++ b/testing/endtoend/evaluators/operations.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/endtoend/helpers" @@ -34,7 +34,7 @@ var depositsInBlockStart = params.E2ETestConfig().EpochsPerEth1VotingPeriod * 2 // deposits included + finalization + MaxSeedLookahead for activation. var depositActivationStartEpoch = depositsInBlockStart + 2 + params.E2ETestConfig().MaxSeedLookahead -var depositEndEpoch = depositActivationStartEpoch + types.Epoch(math.Ceil(float64(depositValCount)/float64(churnLimit))) +var depositEndEpoch = depositActivationStartEpoch + primitives.Epoch(math.Ceil(float64(depositValCount)/float64(churnLimit))) // ProcessesDepositsInBlocks ensures the expected amount of deposits are accepted into blocks. var ProcessesDepositsInBlocks = e2etypes.Evaluator{ @@ -324,7 +324,7 @@ func proposeVoluntaryExit(ec *e2etypes.EvaluationContext, conns ...*grpc.ClientC return err } - exitedIndex := types.ValidatorIndex(rand.Uint64() % params.BeaconConfig().MinGenesisActiveValidatorCount) + exitedIndex := primitives.ValidatorIndex(rand.Uint64() % params.BeaconConfig().MinGenesisActiveValidatorCount) voluntaryExit := ðpb.VoluntaryExit{ Epoch: chainHead.HeadEpoch, @@ -398,7 +398,7 @@ func validatorsVoteWithTheMajority(ec *e2etypes.EvaluationContext, conns ...*grp slotsPerVotingPeriod := params.E2ETestConfig().SlotsPerEpoch.Mul(uint64(params.E2ETestConfig().EpochsPerEth1VotingPeriod)) for _, blk := range blks.BlockContainers { - var slot types.Slot + var slot primitives.Slot var vote []byte switch blk.Block.(type) { case *ethpb.BeaconBlockContainer_Phase0Block: @@ -441,7 +441,7 @@ func validatorsVoteWithTheMajority(ec *e2etypes.EvaluationContext, conns ...*grp } if !bytes.Equal(vote, ec.ExpectedEth1DataVote) { - for i := types.Slot(0); i < slot; i++ { + for i := primitives.Slot(0); i < slot; i++ { v, ok := ec.SeenVotes[i] if ok { fmt.Printf("vote at slot=%d = %#x\n", i, v) diff --git a/testing/endtoend/evaluators/slashing.go b/testing/endtoend/evaluators/slashing.go index 7c75ccf2a1..ba743c0315 100644 --- a/testing/endtoend/evaluators/slashing.go +++ b/testing/endtoend/evaluators/slashing.go @@ -10,7 +10,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/container/slice" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -23,7 +23,7 @@ import ( ) // InjectDoubleVoteOnEpoch broadcasts a double vote into the beacon node pool for the slasher to detect. -var InjectDoubleVoteOnEpoch = func(n types.Epoch) e2eTypes.Evaluator { +var InjectDoubleVoteOnEpoch = func(n primitives.Epoch) e2eTypes.Evaluator { return e2eTypes.Evaluator{ Name: "inject_double_vote_%d", Policy: policies.OnEpoch(n), @@ -32,7 +32,7 @@ var InjectDoubleVoteOnEpoch = func(n types.Epoch) e2eTypes.Evaluator { } // InjectDoubleBlockOnEpoch proposes a double block to the beacon node for the slasher to detect. -var InjectDoubleBlockOnEpoch = func(n types.Epoch) e2eTypes.Evaluator { +var InjectDoubleBlockOnEpoch = func(n primitives.Epoch) e2eTypes.Evaluator { return e2eTypes.Evaluator{ Name: "inject_double_block_%d", Policy: policies.OnEpoch(n), @@ -41,7 +41,7 @@ var InjectDoubleBlockOnEpoch = func(n types.Epoch) e2eTypes.Evaluator { } // ValidatorsSlashedAfterEpoch ensures the expected amount of validators are slashed. -var ValidatorsSlashedAfterEpoch = func(n types.Epoch) e2eTypes.Evaluator { +var ValidatorsSlashedAfterEpoch = func(n primitives.Epoch) e2eTypes.Evaluator { return e2eTypes.Evaluator{ Name: "validators_slashed_epoch_%d", Policy: policies.AfterNthEpoch(n), @@ -50,7 +50,7 @@ var ValidatorsSlashedAfterEpoch = func(n types.Epoch) e2eTypes.Evaluator { } // SlashedValidatorsLoseBalanceAfterEpoch checks if the validators slashed lose the right balance. -var SlashedValidatorsLoseBalanceAfterEpoch = func(n types.Epoch) e2eTypes.Evaluator { +var SlashedValidatorsLoseBalanceAfterEpoch = func(n primitives.Epoch) e2eTypes.Evaluator { return e2eTypes.Evaluator{ Name: "slashed_validators_lose_valance_epoch_%d", Policy: policies.AfterNthEpoch(n), @@ -83,7 +83,7 @@ func validatorsLoseBalance(_ *e2eTypes.EvaluationContext, conns ...*grpc.ClientC for i, slashedIndex := range slashedIndices { req := ð.GetValidatorRequest{ QueryFilter: ð.GetValidatorRequest_Index{ - Index: types.ValidatorIndex(slashedIndex), + Index: primitives.ValidatorIndex(slashedIndex), }, } valResp, err := client.GetValidator(ctx, req) @@ -133,8 +133,8 @@ func insertDoubleAttestationIntoPool(_ *e2eTypes.EvaluationContext, conns ...*gr return errors.Wrap(err, "could not get duties") } - var committeeIndex types.CommitteeIndex - var committee []types.ValidatorIndex + var committeeIndex primitives.CommitteeIndex + var committee []primitives.ValidatorIndex for _, duty := range duties.Duties { if duty.AttesterSlot == chainHead.HeadSlot-1 { committeeIndex = duty.CommitteeIndex @@ -220,10 +220,10 @@ func proposeDoubleBlock(_ *e2eTypes.EvaluationContext, conns ...*grpc.ClientConn return errors.Wrap(err, "could not get duties") } - var proposerIndex types.ValidatorIndex + var proposerIndex primitives.ValidatorIndex for i, duty := range duties.CurrentEpochDuties { if slice.IsInSlots(chainHead.HeadSlot-1, duty.ProposerSlots) { - proposerIndex = types.ValidatorIndex(i) + proposerIndex = primitives.ValidatorIndex(i) break } } @@ -237,7 +237,7 @@ func proposeDoubleBlock(_ *e2eTypes.EvaluationContext, conns ...*grpc.ClientConn // If the proposer index is in the second validator client, we connect to // the corresponding beacon node instead. - if proposerIndex >= types.ValidatorIndex(uint64(validatorsPerNode)) { + if proposerIndex >= primitives.ValidatorIndex(uint64(validatorsPerNode)) { valClient = eth.NewBeaconNodeValidatorClient(conns[1]) } diff --git a/testing/endtoend/evaluators/validator.go b/testing/endtoend/evaluators/validator.go index 231fc14e8c..4f8a762d90 100644 --- a/testing/endtoend/evaluators/validator.go +++ b/testing/endtoend/evaluators/validator.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - ethtypes "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpbservice "github.com/prysmaticlabs/prysm/v3/proto/eth/service" "github.com/prysmaticlabs/prysm/v3/proto/eth/v2" @@ -37,7 +37,7 @@ var ValidatorsAreActive = types.Evaluator{ } // ValidatorsParticipatingAtEpoch ensures the expected amount of validators are participating. -var ValidatorsParticipatingAtEpoch = func(epoch ethtypes.Epoch) types.Evaluator { +var ValidatorsParticipatingAtEpoch = func(epoch primitives.Epoch) types.Evaluator { return types.Evaluator{ Name: "validators_participating_epoch_%d", Policy: policies.AfterNthEpoch(epoch), diff --git a/testing/endtoend/policies/policies.go b/testing/endtoend/policies/policies.go index 78e50db089..8785a29d5a 100644 --- a/testing/endtoend/policies/policies.go +++ b/testing/endtoend/policies/policies.go @@ -1,29 +1,29 @@ package policies -import types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" +import "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" // AfterNthEpoch runs for every epoch after the provided epoch. -func AfterNthEpoch(afterEpoch types.Epoch) func(epoch types.Epoch) bool { - return func(currentEpoch types.Epoch) bool { +func AfterNthEpoch(afterEpoch primitives.Epoch) func(epoch primitives.Epoch) bool { + return func(currentEpoch primitives.Epoch) bool { return currentEpoch > afterEpoch } } // AllEpochs runs for all epochs. -func AllEpochs(_ types.Epoch) bool { +func AllEpochs(_ primitives.Epoch) bool { return true } // OnEpoch runs only for the provided epoch. -func OnEpoch(epoch types.Epoch) func(types.Epoch) bool { - return func(currentEpoch types.Epoch) bool { +func OnEpoch(epoch primitives.Epoch) func(primitives.Epoch) bool { + return func(currentEpoch primitives.Epoch) bool { return currentEpoch == epoch } } // BetweenEpochs runs for every epoch that is between the provided epochs. -func BetweenEpochs(fromEpoch, toEpoch types.Epoch) func(types.Epoch) bool { - return func(currentEpoch types.Epoch) bool { +func BetweenEpochs(fromEpoch, toEpoch primitives.Epoch) func(primitives.Epoch) bool { + return func(currentEpoch primitives.Epoch) bool { return fromEpoch < currentEpoch && currentEpoch < toEpoch } } diff --git a/testing/endtoend/slasher_simulator_e2e_test.go b/testing/endtoend/slasher_simulator_e2e_test.go index 5b7280827f..a383486b72 100644 --- a/testing/endtoend/slasher_simulator_e2e_test.go +++ b/testing/endtoend/slasher_simulator_e2e_test.go @@ -11,7 +11,7 @@ import ( mockslashings "github.com/prysmaticlabs/prysm/v3/beacon-chain/operations/slashings/mock" mockstategen "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen/mock" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -70,11 +70,11 @@ func TestEndToEnd_SlasherSimulator(t *testing.T) { // We setup validators in the beacon state along with their // private keys used to generate valid signatures in generated objects. validators := make([]*ethpb.Validator, simulatorParams.NumValidators) - privKeys := make(map[types.ValidatorIndex]bls.SecretKey) + privKeys := make(map[primitives.ValidatorIndex]bls.SecretKey) for valIdx := range validators { privKey, err := bls.RandKey() require.NoError(t, err) - privKeys[types.ValidatorIndex(valIdx)] = privKey + privKeys[primitives.ValidatorIndex(valIdx)] = privKey validators[valIdx] = ðpb.Validator{ PublicKey: privKey.PublicKey().Marshal(), WithdrawalCredentials: make([]byte, 32), diff --git a/testing/endtoend/types/types.go b/testing/endtoend/types/types.go index cafb04879f..ba5afa58fd 100644 --- a/testing/endtoend/types/types.go +++ b/testing/endtoend/types/types.go @@ -7,7 +7,7 @@ import ( "os" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/runtime/version" "google.golang.org/grpc" ) @@ -85,7 +85,7 @@ func GenesisFork() int { // conduct the current beacon state during the E2E. type Evaluator struct { Name string - Policy func(currentEpoch types.Epoch) bool + Policy func(currentEpoch primitives.Epoch) bool // Evaluation accepts one or many/all conns, depending on what is needed by the set of evaluators. Evaluation func(ec *EvaluationContext, conn ...*grpc.ClientConn) error } @@ -112,7 +112,7 @@ type DepositBalancer interface { type EvaluationContext struct { DepositBalancer ExitedVals map[[48]byte]bool - SeenVotes map[types.Slot][]byte + SeenVotes map[primitives.Slot][]byte ExpectedEth1DataVote []byte } @@ -121,7 +121,7 @@ func NewEvaluationContext(d DepositBalancer) *EvaluationContext { return &EvaluationContext{ DepositBalancer: d, ExitedVals: make(map[[48]byte]bool), - SeenVotes: make(map[types.Slot][]byte), + SeenVotes: make(map[primitives.Slot][]byte), } } diff --git a/testing/slasher/simulator/attestation_generator.go b/testing/slasher/simulator/attestation_generator.go index 82929946e1..e2d9ba8013 100644 --- a/testing/slasher/simulator/attestation_generator.go +++ b/testing/slasher/simulator/attestation_generator.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/rand" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -18,7 +18,7 @@ import ( ) func (s *Simulator) generateAttestationsForSlot( - ctx context.Context, slot types.Slot, + ctx context.Context, slot primitives.Slot, ) ([]*ethpb.IndexedAttestation, []*ethpb.AttesterSlashing, error) { attestations := make([]*ethpb.IndexedAttestation, 0) slashings := make([]*ethpb.AttesterSlashing, 0) @@ -37,7 +37,7 @@ func (s *Simulator) generateAttestationsForSlot( var slashedIndices []uint64 startIdx := valsPerSlot * uint64(slot%s.srvConfig.Params.SlotsPerEpoch) endIdx := startIdx + valsPerCommittee - for c := types.CommitteeIndex(0); uint64(c) < committeesPerSlot; c++ { + for c := primitives.CommitteeIndex(0); uint64(c) < committeesPerSlot; c++ { attData := ðpb.AttestationData{ Slot: slot, CommitteeIndex: c, @@ -125,7 +125,7 @@ func (s *Simulator) aggregateSigForAttestation( } sigs := make([]bls.Signature, len(att.AttestingIndices)) for i, validatorIndex := range att.AttestingIndices { - privKey := s.srvConfig.PrivateKeysByValidatorIndex[types.ValidatorIndex(validatorIndex)] + privKey := s.srvConfig.PrivateKeysByValidatorIndex[primitives.ValidatorIndex(validatorIndex)] sigs[i] = privKey.Sign(signingRoot[:]) } return bls.AggregateSignatures(sigs), nil diff --git a/testing/slasher/simulator/block_generator.go b/testing/slasher/simulator/block_generator.go index 452a1d2e7e..2d83a52999 100644 --- a/testing/slasher/simulator/block_generator.go +++ b/testing/slasher/simulator/block_generator.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/rand" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -14,7 +14,7 @@ import ( ) func (s *Simulator) generateBlockHeadersForSlot( - ctx context.Context, slot types.Slot, + ctx context.Context, slot primitives.Slot, ) ([]*ethpb.SignedBeaconBlockHeader, []*ethpb.ProposerSlashing, error) { blocks := make([]*ethpb.SignedBeaconBlockHeader, 0) slashings := make([]*ethpb.ProposerSlashing, 0) @@ -28,7 +28,7 @@ func (s *Simulator) generateBlockHeadersForSlot( block := ðpb.SignedBeaconBlockHeader{ Header: ðpb.BeaconBlockHeader{ Slot: slot, - ProposerIndex: types.ValidatorIndex(proposer), + ProposerIndex: primitives.ValidatorIndex(proposer), ParentRoot: bytesutil.PadTo([]byte{}, 32), StateRoot: bytesutil.PadTo([]byte{}, 32), BodyRoot: bytesutil.PadTo([]byte("good block"), 32), @@ -46,7 +46,7 @@ func (s *Simulator) generateBlockHeadersForSlot( slashableBlock := ðpb.SignedBeaconBlockHeader{ Header: ðpb.BeaconBlockHeader{ Slot: slot, - ProposerIndex: types.ValidatorIndex(proposer), + ProposerIndex: primitives.ValidatorIndex(proposer), ParentRoot: bytesutil.PadTo([]byte{}, 32), StateRoot: bytesutil.PadTo([]byte{}, 32), BodyRoot: bytesutil.PadTo([]byte("bad block"), 32), diff --git a/testing/slasher/simulator/simulator.go b/testing/slasher/simulator/simulator.go index c3d8dcf8b6..0624cd215e 100644 --- a/testing/slasher/simulator/simulator.go +++ b/testing/slasher/simulator/simulator.go @@ -15,7 +15,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -33,14 +33,14 @@ type ServiceConfig struct { HeadStateFetcher blockchain.HeadFetcher StateGen stategen.StateManager SlashingsPool slashings.PoolManager - PrivateKeysByValidatorIndex map[types.ValidatorIndex]bls.SecretKey + PrivateKeysByValidatorIndex map[primitives.ValidatorIndex]bls.SecretKey SyncChecker sync.Checker } // Parameters for a slasher simulator. type Parameters struct { SecondsPerSlot uint64 - SlotsPerEpoch types.Slot + SlotsPerEpoch primitives.Slot AggregationPercent float64 ProposerSlashingProbab float64 AttesterSlashingProbab float64 @@ -168,7 +168,7 @@ func (s *Simulator) simulateBlocksAndAttestations(ctx context.Context) { select { case slot := <-ticker.C(): // We only run the simulator for a specified number of epochs. - totalEpochs := types.Epoch(s.srvConfig.Params.NumEpochs) + totalEpochs := primitives.Epoch(s.srvConfig.Params.NumEpochs) if slots.ToEpoch(slot) >= totalEpochs { return } diff --git a/testing/slasher/simulator/simulator_test.go b/testing/slasher/simulator/simulator_test.go index 7d85cf0401..3f653c9dde 100644 --- a/testing/slasher/simulator/simulator_test.go +++ b/testing/slasher/simulator/simulator_test.go @@ -6,7 +6,7 @@ import ( mock "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain/testing" dbtest "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" mockstategen "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen/mock" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -21,11 +21,11 @@ func setupService(t *testing.T, params *Parameters) *Simulator { // We setup validators in the beacon state along with their // private keys used to generate valid signatures in generated objects. validators := make([]*ethpb.Validator, params.NumValidators) - privKeys := make(map[types.ValidatorIndex]bls.SecretKey) + privKeys := make(map[primitives.ValidatorIndex]bls.SecretKey) for valIdx := range validators { privKey, err := bls.RandKey() require.NoError(t, err) - privKeys[types.ValidatorIndex(valIdx)] = privKey + privKeys[primitives.ValidatorIndex(valIdx)] = privKey validators[valIdx] = ðpb.Validator{ PublicKey: privKey.PublicKey().Marshal(), WithdrawalCredentials: make([]byte, 32), diff --git a/testing/spectest/shared/altair/fork/transition.go b/testing/spectest/shared/altair/fork/transition.go index 09af1a4583..97abcdd51e 100644 --- a/testing/spectest/shared/altair/fork/transition.go +++ b/testing/spectest/shared/altair/fork/transition.go @@ -11,7 +11,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/spectest/utils" @@ -96,7 +96,7 @@ func RunForkTransitionTest(t *testing.T, config string) { require.NoError(t, err) bc := params.BeaconConfig().Copy() - bc.AltairForkEpoch = types.Epoch(config.ForkEpoch) + bc.AltairForkEpoch = primitives.Epoch(config.ForkEpoch) params.OverrideBeaconConfig(bc) ctx := context.Background() diff --git a/testing/spectest/shared/bellatrix/fork/transition.go b/testing/spectest/shared/bellatrix/fork/transition.go index 36cc0a0a8c..3aec6900fc 100644 --- a/testing/spectest/shared/bellatrix/fork/transition.go +++ b/testing/spectest/shared/bellatrix/fork/transition.go @@ -11,7 +11,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/spectest/utils" @@ -90,7 +90,7 @@ func RunForkTransitionTest(t *testing.T, config string) { require.NoError(t, err) bc := params.BeaconConfig().Copy() - bc.BellatrixForkEpoch = types.Epoch(config.ForkEpoch) + bc.BellatrixForkEpoch = primitives.Epoch(config.ForkEpoch) params.OverrideBeaconConfig(bc) ctx := context.Background() diff --git a/testing/spectest/shared/capella/fork/transition.go b/testing/spectest/shared/capella/fork/transition.go index 2808829caa..1830c4a262 100644 --- a/testing/spectest/shared/capella/fork/transition.go +++ b/testing/spectest/shared/capella/fork/transition.go @@ -11,7 +11,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/spectest/utils" @@ -90,7 +90,7 @@ func RunForkTransitionTest(t *testing.T, config string) { require.NoError(t, err) bc := params.BeaconConfig().Copy() - bc.CapellaForkEpoch = types.Epoch(config.ForkEpoch) + bc.CapellaForkEpoch = primitives.Epoch(config.ForkEpoch) params.OverrideBeaconConfig(bc) ctx := context.Background() diff --git a/testing/spectest/shared/common/forkchoice/builder.go b/testing/spectest/shared/common/forkchoice/builder.go index 2c01c3de0c..b334192da8 100644 --- a/testing/spectest/shared/common/forkchoice/builder.go +++ b/testing/spectest/shared/common/forkchoice/builder.go @@ -13,7 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -44,7 +44,7 @@ func (bb *Builder) Tick(t testing.TB, tick int64) { for lastSlot < currentSlot { lastSlot++ bb.service.ForkChoicer().SetGenesisTime(uint64(time.Now().Unix() - int64(params.BeaconConfig().SecondsPerSlot*lastSlot))) - require.NoError(t, bb.service.ForkChoicer().NewSlot(context.TODO(), types.Slot(lastSlot))) + require.NoError(t, bb.service.ForkChoicer().NewSlot(context.TODO(), primitives.Slot(lastSlot))) } if tick > int64(params.BeaconConfig().SecondsPerSlot*lastSlot) { bb.service.ForkChoicer().SetGenesisTime(uint64(time.Now().Unix() - tick)) @@ -124,11 +124,11 @@ func (bb *Builder) Check(t testing.TB, c *Check) { r, err := bb.service.HeadRoot(ctx) require.NoError(t, err) require.DeepEqual(t, common.FromHex(c.Head.Root), r) - require.Equal(t, types.Slot(c.Head.Slot), bb.service.HeadSlot()) + require.Equal(t, primitives.Slot(c.Head.Slot), bb.service.HeadSlot()) } if c.JustifiedCheckPoint != nil { cp := ðpb.Checkpoint{ - Epoch: types.Epoch(c.JustifiedCheckPoint.Epoch), + Epoch: primitives.Epoch(c.JustifiedCheckPoint.Epoch), Root: common.FromHex(c.JustifiedCheckPoint.Root), } got := bb.service.CurrentJustifiedCheckpt() @@ -136,7 +136,7 @@ func (bb *Builder) Check(t testing.TB, c *Check) { } if c.BestJustifiedCheckPoint != nil { cp := ðpb.Checkpoint{ - Epoch: types.Epoch(c.BestJustifiedCheckPoint.Epoch), + Epoch: primitives.Epoch(c.BestJustifiedCheckPoint.Epoch), Root: common.FromHex(c.BestJustifiedCheckPoint.Root), } got := bb.service.BestJustifiedCheckpt() @@ -144,7 +144,7 @@ func (bb *Builder) Check(t testing.TB, c *Check) { } if c.FinalizedCheckPoint != nil { cp := ðpb.Checkpoint{ - Epoch: types.Epoch(c.FinalizedCheckPoint.Epoch), + Epoch: primitives.Epoch(c.FinalizedCheckPoint.Epoch), Root: common.FromHex(c.FinalizedCheckPoint.Root), } got := bb.service.FinalizedCheckpt() diff --git a/testing/spectest/shared/common/forkchoice/service.go b/testing/spectest/shared/common/forkchoice/service.go index 60860ca295..2c92493a72 100644 --- a/testing/spectest/shared/common/forkchoice/service.go +++ b/testing/spectest/shared/common/forkchoice/service.go @@ -19,7 +19,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" payloadattribute "github.com/prysmaticlabs/prysm/v3/consensus-types/payload-attribute" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" pb "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -78,7 +78,7 @@ type engineMock struct { payloadStatus error } -func (m *engineMock) GetPayload(context.Context, [8]byte, types.Slot) (interfaces.ExecutionData, error) { +func (m *engineMock) GetPayload(context.Context, [8]byte, primitives.Slot) (interfaces.ExecutionData, error) { return nil, nil } diff --git a/testing/spectest/shared/phase0/shuffling/core/shuffle/shuffle.go b/testing/spectest/shared/phase0/shuffling/core/shuffle/shuffle.go index 1aba0ccdf7..22603da949 100644 --- a/testing/spectest/shared/phase0/shuffling/core/shuffle/shuffle.go +++ b/testing/spectest/shared/phase0/shuffling/core/shuffle/shuffle.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/go-yaml/yaml" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/spectest/utils" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -45,12 +45,12 @@ func runShuffleTest(t *testing.T, testCase *ShuffleTestCase) error { } seed := common.BytesToHash(baseSeed) - testIndices := make([]types.ValidatorIndex, testCase.Count) - for i := types.ValidatorIndex(0); uint64(i) < testCase.Count; i++ { + testIndices := make([]primitives.ValidatorIndex, testCase.Count) + for i := primitives.ValidatorIndex(0); uint64(i) < testCase.Count; i++ { testIndices[i] = i } - shuffledList := make([]types.ValidatorIndex, testCase.Count) - for i := types.ValidatorIndex(0); uint64(i) < testCase.Count; i++ { + shuffledList := make([]primitives.ValidatorIndex, testCase.Count) + for i := primitives.ValidatorIndex(0); uint64(i) < testCase.Count; i++ { si, err := helpers.ShuffledIndex(i, testCase.Count, seed) if err != nil { return err diff --git a/testing/spectest/shared/phase0/shuffling/core/shuffle/shuffle_test_format.go b/testing/spectest/shared/phase0/shuffling/core/shuffle/shuffle_test_format.go index df3844b908..967f219a8f 100644 --- a/testing/spectest/shared/phase0/shuffling/core/shuffle/shuffle_test_format.go +++ b/testing/spectest/shared/phase0/shuffling/core/shuffle/shuffle_test_format.go @@ -1,10 +1,10 @@ package shuffle -import types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" +import "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" // ShuffleTestCase -- type ShuffleTestCase struct { - Seed string `yaml:"seed"` - Count uint64 `yaml:"count"` - Mapping []types.ValidatorIndex `yaml:"mapping"` + Seed string `yaml:"seed"` + Count uint64 `yaml:"count"` + Mapping []primitives.ValidatorIndex `yaml:"mapping"` } diff --git a/testing/spectest/utils/config_test.go b/testing/spectest/utils/config_test.go index cf2ff11e4f..cc2444e978 100644 --- a/testing/spectest/utils/config_test.go +++ b/testing/spectest/utils/config_test.go @@ -4,13 +4,13 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/require" ) func TestConfig(t *testing.T) { require.NoError(t, SetConfig(t, "minimal")) - require.Equal(t, types.Slot(8), params.BeaconConfig().SlotsPerEpoch) + require.Equal(t, primitives.Slot(8), params.BeaconConfig().SlotsPerEpoch) require.NoError(t, SetConfig(t, "mainnet")) - require.Equal(t, types.Slot(32), params.BeaconConfig().SlotsPerEpoch) + require.Equal(t, primitives.Slot(32), params.BeaconConfig().SlotsPerEpoch) } diff --git a/testing/util/altair.go b/testing/util/altair.go index fcf987c070..a655651667 100644 --- a/testing/util/altair.go +++ b/testing/util/altair.go @@ -19,7 +19,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" consensusblocks "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -319,7 +319,7 @@ func GenerateFullBlockAltair( bState state.BeaconState, privs []bls.SecretKey, conf *BlockGenConfig, - slot types.Slot, + slot primitives.Slot, ) (*ethpb.SignedBeaconBlockAltair, error) { ctx := context.Background() currentSlot := bState.Slot() diff --git a/testing/util/attestation.go b/testing/util/attestation.go index ca92fecf38..8611007f59 100644 --- a/testing/util/attestation.go +++ b/testing/util/attestation.go @@ -14,7 +14,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/rand" attv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" @@ -49,7 +49,7 @@ func NewAttestation() *ethpb.Attestation { // // If you request 4 attestations, but there are 8 committees, you will get 4 fully aggregated attestations. func GenerateAttestations( - bState state.BeaconState, privs []bls.SecretKey, numToGen uint64, slot types.Slot, randomRoot bool, + bState state.BeaconState, privs []bls.SecretKey, numToGen uint64, slot primitives.Slot, randomRoot bool, ) ([]*ethpb.Attestation, error) { var attestations []*ethpb.Attestation generateHeadState := false @@ -174,7 +174,7 @@ func GenerateAttestations( if err != nil { return nil, err } - for c := types.CommitteeIndex(0); uint64(c) < committeesPerSlot && uint64(c) < numToGen; c++ { + for c := primitives.CommitteeIndex(0); uint64(c) < committeesPerSlot && uint64(c) < numToGen; c++ { committee, err := helpers.BeaconCommitteeFromState(context.Background(), bState, slot, c) if err != nil { return nil, err diff --git a/testing/util/bellatrix.go b/testing/util/bellatrix.go index ae160348f8..d8d8a9e861 100644 --- a/testing/util/bellatrix.go +++ b/testing/util/bellatrix.go @@ -13,7 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -30,7 +30,7 @@ func GenerateFullBlockBellatrix( bState state.BeaconState, privs []bls.SecretKey, conf *BlockGenConfig, - slot types.Slot, + slot primitives.Slot, ) (*ethpb.SignedBeaconBlockBellatrix, error) { ctx := context.Background() currentSlot := bState.Slot() diff --git a/testing/util/block.go b/testing/util/block.go index f475768bab..759aba9942 100644 --- a/testing/util/block.go +++ b/testing/util/block.go @@ -14,7 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/rand" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -83,7 +83,7 @@ func GenerateFullBlock( bState state.BeaconState, privs []bls.SecretKey, conf *BlockGenConfig, - slot types.Slot, + slot primitives.Slot, ) (*ethpb.SignedBeaconBlock, error) { ctx := context.Background() currentSlot := bState.Slot() @@ -204,7 +204,7 @@ func GenerateFullBlock( func GenerateProposerSlashingForValidator( bState state.BeaconState, priv bls.SecretKey, - idx types.ValidatorIndex, + idx primitives.ValidatorIndex, ) (*ethpb.ProposerSlashing, error) { header1 := HydrateSignedBeaconHeader(ðpb.SignedBeaconBlockHeader{ Header: ðpb.BeaconBlockHeader{ @@ -264,7 +264,7 @@ func generateProposerSlashings( func GenerateAttesterSlashingForValidator( bState state.BeaconState, priv bls.SecretKey, - idx types.ValidatorIndex, + idx primitives.ValidatorIndex, ) (*ethpb.AttesterSlashing, error) { currentEpoch := time.CurrentEpoch(bState) @@ -326,7 +326,7 @@ func generateAttesterSlashings( randGen := rand.NewDeterministicGenerator() for i := uint64(0); i < numSlashings; i++ { committeeIndex := randGen.Uint64() % helpers.SlotCommitteeCount(uint64(bState.NumValidators())) - committee, err := helpers.BeaconCommitteeFromState(context.Background(), bState, bState.Slot(), types.CommitteeIndex(committeeIndex)) + committee, err := helpers.BeaconCommitteeFromState(context.Background(), bState, bState.Slot(), primitives.CommitteeIndex(committeeIndex)) if err != nil { return nil, err } @@ -361,7 +361,7 @@ func generateDepositsAndEth1Data( return currentDeposits[previousDepsLen:], eth1Data, nil } -func GenerateVoluntaryExits(bState state.BeaconState, k bls.SecretKey, idx types.ValidatorIndex) (*ethpb.SignedVoluntaryExit, error) { +func GenerateVoluntaryExits(bState state.BeaconState, k bls.SecretKey, idx primitives.ValidatorIndex) (*ethpb.SignedVoluntaryExit, error) { currentEpoch := time.CurrentEpoch(bState) exit := ðpb.SignedVoluntaryExit{ Exit: ðpb.VoluntaryExit{ @@ -405,12 +405,12 @@ func generateVoluntaryExits( return voluntaryExits, nil } -func randValIndex(bState state.BeaconState) (types.ValidatorIndex, error) { +func randValIndex(bState state.BeaconState) (primitives.ValidatorIndex, error) { activeCount, err := helpers.ActiveValidatorCount(context.Background(), bState, time.CurrentEpoch(bState)) if err != nil { return 0, err } - return types.ValidatorIndex(rand.NewGenerator().Uint64() % activeCount), nil + return primitives.ValidatorIndex(rand.NewGenerator().Uint64() % activeCount), nil } // HydrateSignedBeaconHeader hydrates a signed beacon block header with correct field length sizes diff --git a/testing/util/block_test.go b/testing/util/block_test.go index d4d3434c9e..7dc5a4ac4a 100644 --- a/testing/util/block_test.go +++ b/testing/util/block_test.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/transition/stateutils" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpbv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ethpbv2 "github.com/prysmaticlabs/prysm/v3/proto/eth/v2" @@ -113,7 +113,7 @@ func TestGenerateFullBlock_ValidAttesterSlashings(t *testing.T) { require.NoError(t, err) slashableIndices := block.Block.Body.AttesterSlashings[0].Attestation_1.AttestingIndices - if val, err := beaconState.ValidatorAtIndexReadOnly(types.ValidatorIndex(slashableIndices[0])); err != nil || !val.Slashed() { + if val, err := beaconState.ValidatorAtIndexReadOnly(primitives.ValidatorIndex(slashableIndices[0])); err != nil || !val.Slashed() { require.NoError(t, err) t.Fatal("expected validator to be slashed") } diff --git a/testing/util/capella_block.go b/testing/util/capella_block.go index 90365c06b5..5d1896ed94 100644 --- a/testing/util/capella_block.go +++ b/testing/util/capella_block.go @@ -13,7 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" v1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" @@ -29,7 +29,7 @@ func GenerateFullBlockCapella( bState state.BeaconState, privs []bls.SecretKey, conf *BlockGenConfig, - slot types.Slot, + slot primitives.Slot, ) (*ethpb.SignedBeaconBlockCapella, error) { ctx := context.Background() currentSlot := bState.Slot() @@ -174,7 +174,7 @@ func GenerateFullBlockCapella( changes := make([]*ethpb.SignedBLSToExecutionChange, conf.NumBLSChanges) for i := uint64(0); i < conf.NumBLSChanges; i++ { - changes[i], err = GenerateBLSToExecutionChange(bState, privs[i+1], types.ValidatorIndex(i)) + changes[i], err = GenerateBLSToExecutionChange(bState, privs[i+1], primitives.ValidatorIndex(i)) if err != nil { return nil, err } @@ -209,7 +209,7 @@ func GenerateFullBlockCapella( } // GenerateBLSToExecutionChange generates a valid bls to exec changae for validator `val` and its private key `priv` with the given beacon state `st`. -func GenerateBLSToExecutionChange(st state.BeaconState, priv bls.SecretKey, val types.ValidatorIndex) (*ethpb.SignedBLSToExecutionChange, error) { +func GenerateBLSToExecutionChange(st state.BeaconState, priv bls.SecretKey, val primitives.ValidatorIndex) (*ethpb.SignedBLSToExecutionChange, error) { cred := indexToHash(uint64(val)) pubkey := priv.PublicKey().Marshal() message := ðpb.BLSToExecutionChange{ diff --git a/testing/util/helpers.go b/testing/util/helpers.go index ec7b7ce1d6..1b4f7f9b5b 100644 --- a/testing/util/helpers.go +++ b/testing/util/helpers.go @@ -14,14 +14,14 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/rand" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) // RandaoReveal returns a signature of the requested epoch using the beacon proposer private key. -func RandaoReveal(beaconState state.ReadOnlyBeaconState, epoch types.Epoch, privKeys []bls.SecretKey) ([]byte, error) { +func RandaoReveal(beaconState state.ReadOnlyBeaconState, epoch primitives.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(context.Background(), beaconState) if err != nil { @@ -31,7 +31,7 @@ func RandaoReveal(beaconState state.ReadOnlyBeaconState, epoch types.Epoch, priv binary.LittleEndian.PutUint64(buf, uint64(epoch)) // We make the previous validator's index sign the message instead of the proposer. - sszEpoch := types.SSZUint64(epoch) + sszEpoch := primitives.SSZUint64(epoch) return signing.ComputeDomainAndSign(beaconState, epoch, &sszEpoch, params.BeaconConfig().DomainRandao, privKeys[proposerIdx]) } @@ -78,7 +78,7 @@ func BlockSignature( // Temporarily increasing the beacon state slot here since BeaconProposerIndex is a // function deterministic on beacon state slot. - var blockSlot types.Slot + var blockSlot primitives.Slot switch b := block.(type) { case *ethpb.BeaconBlock: blockSlot = b.Slot diff --git a/testing/util/helpers_test.go b/testing/util/helpers_test.go index f39db8a531..4df089590f 100644 --- a/testing/util/helpers_test.go +++ b/testing/util/helpers_test.go @@ -11,7 +11,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/time" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -51,7 +51,7 @@ func TestRandaoReveal(t *testing.T) { buf := make([]byte, fieldparams.RootLength) binary.LittleEndian.PutUint64(buf, uint64(epoch)) // We make the previous validator's index sign the message instead of the proposer. - sszUint := types.SSZUint64(epoch) + sszUint := primitives.SSZUint64(epoch) epochSignature, err := signing.ComputeDomainAndSign(beaconState, epoch, &sszUint, params.BeaconConfig().DomainRandao, privKeys[proposerIdx]) require.NoError(t, err) diff --git a/time/slots/slotticker.go b/time/slots/slotticker.go index f0afaa2080..f6eea0d3df 100644 --- a/time/slots/slotticker.go +++ b/time/slots/slotticker.go @@ -4,14 +4,14 @@ package slots import ( "time" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" prysmTime "github.com/prysmaticlabs/prysm/v3/time" ) // The Ticker interface defines a type which can expose a // receive-only channel firing slot events. type Ticker interface { - C() <-chan types.Slot + C() <-chan primitives.Slot Done() } @@ -22,13 +22,13 @@ type Ticker interface { // multiple of the slot duration. // In addition, the channel returns the new slot number. type SlotTicker struct { - c chan types.Slot + c chan primitives.Slot done chan struct{} } // C returns the ticker channel. Call Cancel afterwards to ensure // that the goroutine exits cleanly. -func (s *SlotTicker) C() <-chan types.Slot { +func (s *SlotTicker) C() <-chan primitives.Slot { return s.c } @@ -45,7 +45,7 @@ func NewSlotTicker(genesisTime time.Time, secondsPerSlot uint64) *SlotTicker { panic("zero genesis time") } ticker := &SlotTicker{ - c: make(chan types.Slot), + c: make(chan primitives.Slot), done: make(chan struct{}), } ticker.start(genesisTime, secondsPerSlot, prysmTime.Since, prysmTime.Until, time.After) @@ -62,7 +62,7 @@ func NewSlotTickerWithOffset(genesisTime time.Time, offset time.Duration, second panic("invalid ticker offset") } ticker := &SlotTicker{ - c: make(chan types.Slot), + c: make(chan primitives.Slot), done: make(chan struct{}), } ticker.start(genesisTime.Add(offset), secondsPerSlot, prysmTime.Since, prysmTime.Until, time.After) @@ -81,7 +81,7 @@ func (s *SlotTicker) start( sinceGenesis := since(genesisTime) var nextTickTime time.Time - var slot types.Slot + var slot primitives.Slot if sinceGenesis < d { // Handle when the current time is before the genesis time. nextTickTime = genesisTime @@ -89,7 +89,7 @@ func (s *SlotTicker) start( } else { nextTick := sinceGenesis.Truncate(d) + d nextTickTime = genesisTime.Add(nextTick) - slot = types.Slot(nextTick / d) + slot = primitives.Slot(nextTick / d) } for { diff --git a/time/slots/slotticker_test.go b/time/slots/slotticker_test.go index 5a230e6487..f096b61124 100644 --- a/time/slots/slotticker_test.go +++ b/time/slots/slotticker_test.go @@ -4,14 +4,14 @@ import ( "testing" "time" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) var _ Ticker = (*SlotTicker)(nil) func TestSlotTicker(t *testing.T) { ticker := &SlotTicker{ - c: make(chan types.Slot), + c: make(chan primitives.Slot), done: make(chan struct{}), } defer ticker.Done() @@ -66,7 +66,7 @@ func TestSlotTicker(t *testing.T) { func TestSlotTickerGenesis(t *testing.T) { ticker := &SlotTicker{ - c: make(chan types.Slot), + c: make(chan primitives.Slot), done: make(chan struct{}), } defer ticker.Done() diff --git a/time/slots/slottime.go b/time/slots/slottime.go index 06d085e919..df653f55fc 100644 --- a/time/slots/slottime.go +++ b/time/slots/slottime.go @@ -7,7 +7,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" mathutil "github.com/prysmaticlabs/prysm/v3/math" prysmTime "github.com/prysmaticlabs/prysm/v3/time" ) @@ -18,7 +18,7 @@ const MaxSlotBuffer = uint64(1 << 7) // StartTime returns the start time in terms of its unix epoch // value. -func StartTime(genesis uint64, slot types.Slot) time.Time { +func StartTime(genesis uint64, slot primitives.Slot) time.Time { duration := time.Second * time.Duration(slot.Mul(params.BeaconConfig().SecondsPerSlot)) startTime := time.Unix(int64(genesis), 0).Add(duration) // lint:ignore uintcast -- Genesis timestamp will not exceed int64 in your lifetime. return startTime @@ -26,17 +26,17 @@ func StartTime(genesis uint64, slot types.Slot) time.Time { // SinceGenesis returns the number of slots since // the provided genesis time. -func SinceGenesis(genesis time.Time) types.Slot { +func SinceGenesis(genesis time.Time) primitives.Slot { if genesis.After(prysmTime.Now()) { // Genesis has not occurred yet. return 0 } - return types.Slot(uint64(prysmTime.Since(genesis).Seconds()) / params.BeaconConfig().SecondsPerSlot) + return primitives.Slot(uint64(prysmTime.Since(genesis).Seconds()) / params.BeaconConfig().SecondsPerSlot) } // EpochsSinceGenesis returns the number of epochs since // the provided genesis time. -func EpochsSinceGenesis(genesis time.Time) types.Epoch { - return types.Epoch(SinceGenesis(genesis) / params.BeaconConfig().SlotsPerEpoch) +func EpochsSinceGenesis(genesis time.Time) primitives.Epoch { + return primitives.Epoch(SinceGenesis(genesis) / params.BeaconConfig().SlotsPerEpoch) } // DivideSlotBy divides the SECONDS_PER_SLOT configuration @@ -55,7 +55,7 @@ func MultiplySlotBy(times int64) time.Duration { } // AbsoluteValueSlotDifference between two slots. -func AbsoluteValueSlotDifference(x, y types.Slot) uint64 { +func AbsoluteValueSlotDifference(x, y primitives.Slot) uint64 { if x > y { return uint64(x.SubSlot(y)) } @@ -71,8 +71,8 @@ func AbsoluteValueSlotDifference(x, y types.Slot) uint64 { // Return the epoch number at ``slot``. // """ // return Epoch(slot // SLOTS_PER_EPOCH) -func ToEpoch(slot types.Slot) types.Epoch { - return types.Epoch(slot.DivSlot(params.BeaconConfig().SlotsPerEpoch)) +func ToEpoch(slot primitives.Slot) primitives.Epoch { + return primitives.Epoch(slot.DivSlot(params.BeaconConfig().SlotsPerEpoch)) } // EpochStart returns the first slot number of the @@ -85,7 +85,7 @@ func ToEpoch(slot types.Slot) types.Epoch { // Return the start slot of ``epoch``. // """ // return Slot(epoch * SLOTS_PER_EPOCH) -func EpochStart(epoch types.Epoch) (types.Slot, error) { +func EpochStart(epoch primitives.Epoch) (primitives.Slot, error) { slot, err := params.BeaconConfig().SlotsPerEpoch.SafeMul(uint64(epoch)) if err != nil { return slot, errors.Errorf("start slot calculation overflows: %v", err) @@ -95,7 +95,7 @@ func EpochStart(epoch types.Epoch) (types.Slot, error) { // EpochEnd returns the last slot number of the // current epoch. -func EpochEnd(epoch types.Epoch) (types.Slot, error) { +func EpochEnd(epoch primitives.Epoch) (primitives.Slot, error) { if epoch == math.MaxUint64 { return 0, errors.New("start slot calculation overflows") } @@ -108,23 +108,23 @@ func EpochEnd(epoch types.Epoch) (types.Slot, error) { // IsEpochStart returns true if the given slot number is an epoch starting slot // number. -func IsEpochStart(slot types.Slot) bool { +func IsEpochStart(slot primitives.Slot) bool { return slot%params.BeaconConfig().SlotsPerEpoch == 0 } // IsEpochEnd returns true if the given slot number is an epoch ending slot // number. -func IsEpochEnd(slot types.Slot) bool { +func IsEpochEnd(slot primitives.Slot) bool { return IsEpochStart(slot + 1) } // SinceEpochStarts returns number of slots since the start of the epoch. -func SinceEpochStarts(slot types.Slot) types.Slot { +func SinceEpochStarts(slot primitives.Slot) primitives.Slot { return slot % params.BeaconConfig().SlotsPerEpoch } // VerifyTime validates the input slot is not from the future. -func VerifyTime(genesisTime uint64, slot types.Slot, timeTolerance time.Duration) error { +func VerifyTime(genesisTime uint64, slot primitives.Slot, timeTolerance time.Duration) error { slotTime, err := ToTime(genesisTime, slot) if err != nil { return err @@ -146,7 +146,7 @@ func VerifyTime(genesisTime uint64, slot types.Slot, timeTolerance time.Duration } // ToTime takes the given slot and genesis time to determine the start time of the slot. -func ToTime(genesisTimeSec uint64, slot types.Slot) (time.Time, error) { +func ToTime(genesisTimeSec uint64, slot primitives.Slot) (time.Time, error) { timeSinceGenesis, err := slot.SafeMul(params.BeaconConfig().SecondsPerSlot) if err != nil { return time.Unix(0, 0), fmt.Errorf("slot (%d) is in the far distant future: %w", slot, err) @@ -159,24 +159,24 @@ func ToTime(genesisTimeSec uint64, slot types.Slot) (time.Time, error) { } // Since computes the number of time slots that have occurred since the given timestamp. -func Since(time time.Time) types.Slot { +func Since(time time.Time) primitives.Slot { return CurrentSlot(uint64(time.Unix())) } // CurrentSlot returns the current slot as determined by the local clock and // provided genesis time. -func CurrentSlot(genesisTimeSec uint64) types.Slot { +func CurrentSlot(genesisTimeSec uint64) primitives.Slot { now := uint64(prysmTime.Now().Unix()) if now < genesisTimeSec { return 0 } - return types.Slot((now - genesisTimeSec) / params.BeaconConfig().SecondsPerSlot) + return primitives.Slot((now - genesisTimeSec) / params.BeaconConfig().SecondsPerSlot) } // ValidateClock validates a provided slot against the local // clock to ensure slots that are unreasonable are returned with // an error. -func ValidateClock(slot types.Slot, genesisTimeSec uint64) error { +func ValidateClock(slot primitives.Slot, genesisTimeSec uint64) error { maxPossibleSlot := CurrentSlot(genesisTimeSec).Add(MaxSlotBuffer) // Defensive check to ensure that we only process slots up to a hard limit // from our local clock. @@ -187,7 +187,7 @@ func ValidateClock(slot types.Slot, genesisTimeSec uint64) error { } // RoundUpToNearestEpoch rounds up the provided slot value to the nearest epoch. -func RoundUpToNearestEpoch(slot types.Slot) types.Slot { +func RoundUpToNearestEpoch(slot primitives.Slot) primitives.Slot { if slot%params.BeaconConfig().SlotsPerEpoch != 0 { slot -= slot % params.BeaconConfig().SlotsPerEpoch slot += params.BeaconConfig().SlotsPerEpoch @@ -197,14 +197,14 @@ func RoundUpToNearestEpoch(slot types.Slot) types.Slot { // VotingPeriodStartTime returns the current voting period's start time // depending on the provided genesis and current slot. -func VotingPeriodStartTime(genesis uint64, slot types.Slot) uint64 { +func VotingPeriodStartTime(genesis uint64, slot primitives.Slot) uint64 { slots := params.BeaconConfig().SlotsPerEpoch.Mul(uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod)) startTime := uint64((slot - slot.ModSlot(slots)).Mul(params.BeaconConfig().SecondsPerSlot)) return genesis + startTime } // PrevSlot returns previous slot, with an exception in slot 0 to prevent underflow. -func PrevSlot(slot types.Slot) types.Slot { +func PrevSlot(slot primitives.Slot) primitives.Slot { if slot > 0 { return slot.Sub(1) } @@ -217,16 +217,16 @@ func PrevSlot(slot types.Slot) types.Slot { // def compute_sync_committee_period(epoch: Epoch) -> uint64: // // return epoch // EPOCHS_PER_SYNC_COMMITTEE_PERIOD -func SyncCommitteePeriod(e types.Epoch) uint64 { +func SyncCommitteePeriod(e primitives.Epoch) uint64 { return uint64(e / params.BeaconConfig().EpochsPerSyncCommitteePeriod) } // SyncCommitteePeriodStartEpoch returns the start epoch of a sync committee period. -func SyncCommitteePeriodStartEpoch(e types.Epoch) (types.Epoch, error) { +func SyncCommitteePeriodStartEpoch(e primitives.Epoch) (primitives.Epoch, error) { // Overflow is impossible here because of division of `EPOCHS_PER_SYNC_COMMITTEE_PERIOD`. startEpoch, err := mathutil.Mul64(SyncCommitteePeriod(e), uint64(params.BeaconConfig().EpochsPerSyncCommitteePeriod)) if err != nil { return 0, err } - return types.Epoch(startEpoch), nil + return primitives.Epoch(startEpoch), nil } diff --git a/time/slots/slottime_test.go b/time/slots/slottime_test.go index be9368890f..fd76a22b43 100644 --- a/time/slots/slottime_test.go +++ b/time/slots/slottime_test.go @@ -6,7 +6,7 @@ import ( "time" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" prysmTime "github.com/prysmaticlabs/prysm/v3/time" @@ -19,7 +19,7 @@ func TestSlotsSinceGenesis(t *testing.T) { tests := []struct { name string args args - want types.Slot + want primitives.Slot }{ { name: "pre-genesis", @@ -47,8 +47,8 @@ func TestSlotsSinceGenesis(t *testing.T) { func TestAbsoluteValueSlotDifference(t *testing.T) { type args struct { - x types.Slot - y types.Slot + x primitives.Slot + y primitives.Slot } tests := []struct { name string @@ -58,24 +58,24 @@ func TestAbsoluteValueSlotDifference(t *testing.T) { { name: "x_<_y", args: args{ - x: types.Slot(3), - y: types.Slot(4), + x: primitives.Slot(3), + y: primitives.Slot(4), }, want: 1, }, { name: "x_>_y", args: args{ - x: types.Slot(100), - y: types.Slot(4), + x: primitives.Slot(100), + y: primitives.Slot(4), }, want: 96, }, { name: "x_==_y", args: args{ - x: types.Slot(100), - y: types.Slot(100), + x: primitives.Slot(100), + y: primitives.Slot(100), }, want: 0, }, @@ -131,8 +131,8 @@ func TestMultiplySlotBy(t *testing.T) { func TestEpochStartSlot_OK(t *testing.T) { tests := []struct { - epoch types.Epoch - startSlot types.Slot + epoch primitives.Epoch + startSlot primitives.Slot error bool }{ {epoch: 0, startSlot: 0 * params.BeaconConfig().SlotsPerEpoch, error: false}, @@ -155,8 +155,8 @@ func TestEpochStartSlot_OK(t *testing.T) { func TestEpochEndSlot_OK(t *testing.T) { tests := []struct { - epoch types.Epoch - startSlot types.Slot + epoch primitives.Epoch + startSlot primitives.Slot error bool }{ {epoch: 0, startSlot: 1*params.BeaconConfig().SlotsPerEpoch - 1, error: false}, @@ -181,7 +181,7 @@ func TestIsEpochStart(t *testing.T) { epochLength := params.BeaconConfig().SlotsPerEpoch tests := []struct { - slot types.Slot + slot primitives.Slot result bool }{ { @@ -211,7 +211,7 @@ func TestIsEpochEnd(t *testing.T) { epochLength := params.BeaconConfig().SlotsPerEpoch tests := []struct { - slot types.Slot + slot primitives.Slot result bool }{ { @@ -235,8 +235,8 @@ func TestIsEpochEnd(t *testing.T) { func TestSlotsSinceEpochStarts(t *testing.T) { tests := []struct { - slots types.Slot - wantedSlots types.Slot + slots primitives.Slot + wantedSlots primitives.Slot }{ {slots: 0, wantedSlots: 0}, {slots: 1, wantedSlots: 1}, @@ -251,8 +251,8 @@ func TestSlotsSinceEpochStarts(t *testing.T) { func TestRoundUpToNearestEpoch_OK(t *testing.T) { tests := []struct { - startSlot types.Slot - roundedUpSlot types.Slot + startSlot primitives.Slot + roundedUpSlot primitives.Slot }{ {startSlot: 0 * params.BeaconConfig().SlotsPerEpoch, roundedUpSlot: 0}, {startSlot: 1*params.BeaconConfig().SlotsPerEpoch - 10, roundedUpSlot: 1 * params.BeaconConfig().SlotsPerEpoch}, @@ -266,7 +266,7 @@ func TestRoundUpToNearestEpoch_OK(t *testing.T) { func TestSlotToTime(t *testing.T) { type args struct { genesisTimeSec uint64 - slot types.Slot + slot primitives.Slot } tests := []struct { name string @@ -323,7 +323,7 @@ func TestSlotToTime(t *testing.T) { func TestVerifySlotTime(t *testing.T) { type args struct { genesisTime int64 - slot types.Slot + slot primitives.Slot timeTolerance time.Duration } tests := []struct { @@ -357,7 +357,7 @@ func TestVerifySlotTime(t *testing.T) { name: "max future slot", args: args{ genesisTime: prysmTime.Now().Add(-1 * 5 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second).Unix(), - slot: types.Slot(MaxSlotBuffer + 6), + slot: primitives.Slot(MaxSlotBuffer + 6), }, wantedErr: "exceeds max allowed value relative to the local clock", }, @@ -367,7 +367,7 @@ func TestVerifySlotTime(t *testing.T) { genesisTime: prysmTime.Now().Add(-1 * 24 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second).Unix(), // 24 slots in the past // Gets multiplied with slot duration, and results in an overflow. Wraps around to a valid time. // Lower than max signed int. And chosen specifically to wrap to a valid slot 24 - slot: types.Slot((^uint64(0))/params.BeaconConfig().SecondsPerSlot) + 24, + slot: primitives.Slot((^uint64(0))/params.BeaconConfig().SecondsPerSlot) + 24, }, wantedErr: "is in the far distant future", }, @@ -387,17 +387,17 @@ func TestVerifySlotTime(t *testing.T) { func TestValidateSlotClock_HandlesBadSlot(t *testing.T) { genTime := prysmTime.Now().Add(-1 * time.Duration(MaxSlotBuffer) * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second).Unix() - assert.NoError(t, ValidateClock(types.Slot(MaxSlotBuffer), uint64(genTime)), "unexpected error validating slot") - assert.NoError(t, ValidateClock(types.Slot(2*MaxSlotBuffer), uint64(genTime)), "unexpected error validating slot") - assert.ErrorContains(t, "which exceeds max allowed value relative to the local clock", ValidateClock(types.Slot(2*MaxSlotBuffer+1), uint64(genTime)), "no error from bad slot") + assert.NoError(t, ValidateClock(primitives.Slot(MaxSlotBuffer), uint64(genTime)), "unexpected error validating slot") + assert.NoError(t, ValidateClock(primitives.Slot(2*MaxSlotBuffer), uint64(genTime)), "unexpected error validating slot") + assert.ErrorContains(t, "which exceeds max allowed value relative to the local clock", ValidateClock(primitives.Slot(2*MaxSlotBuffer+1), uint64(genTime)), "no error from bad slot") assert.ErrorContains(t, "which exceeds max allowed value relative to the local clock", ValidateClock(1<<63, uint64(genTime)), "no error from bad slot") } func TestPrevSlot(t *testing.T) { tests := []struct { name string - slot types.Slot - want types.Slot + slot primitives.Slot + want primitives.Slot }{ { name: "no underflow", @@ -431,7 +431,7 @@ func TestPrevSlot(t *testing.T) { func TestSyncCommitteePeriod(t *testing.T) { tests := []struct { - epoch types.Epoch + epoch primitives.Epoch wanted uint64 }{ {epoch: 0, wanted: 0}, @@ -446,8 +446,8 @@ func TestSyncCommitteePeriod(t *testing.T) { func TestSyncCommitteePeriodStartEpoch(t *testing.T) { tests := []struct { - epoch types.Epoch - wanted types.Epoch + epoch primitives.Epoch + wanted primitives.Epoch }{ {epoch: 0, wanted: 0}, {epoch: params.BeaconConfig().EpochsPerSyncCommitteePeriod + 1, wanted: params.BeaconConfig().EpochsPerSyncCommitteePeriod}, diff --git a/time/slots/testing/mock.go b/time/slots/testing/mock.go index 117ae238ae..3b7295eff3 100644 --- a/time/slots/testing/mock.go +++ b/time/slots/testing/mock.go @@ -1,16 +1,16 @@ // Package testing includes useful mocks for slot tickers in unit tests. package testing -import types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" +import "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" // MockTicker defines a useful struct for mocking the Ticker interface // from the slotutil package. type MockTicker struct { - Channel chan types.Slot + Channel chan primitives.Slot } // C -- -func (m *MockTicker) C() <-chan types.Slot { +func (m *MockTicker) C() <-chan primitives.Slot { return m.Channel } diff --git a/tools/benchmark-files-gen/main.go b/tools/benchmark-files-gen/main.go index 6819b805f6..b07800f946 100644 --- a/tools/benchmark-files-gen/main.go +++ b/tools/benchmark-files-gen/main.go @@ -15,7 +15,7 @@ import ( state_native "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/state-native" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/io/file" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/interop" @@ -102,7 +102,7 @@ func generateMarshalledFullStateAndBlock() error { conf := &util.BlockGenConfig{} slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch // Small offset for the beacon state so we don't process a block on an epoch. - slotOffset := types.Slot(2) + slotOffset := primitives.Slot(2) block, err := util.GenerateFullBlock(beaconState, privs, conf, slotsPerEpoch+slotOffset) if err != nil { return err @@ -202,7 +202,7 @@ func generate2FullEpochState() error { NumAttestations: benchmark.AttestationsPerEpoch / uint64(params.BeaconConfig().SlotsPerEpoch), } - for i := types.Slot(0); i < params.BeaconConfig().SlotsPerEpoch*2-1; i++ { + for i := primitives.Slot(0); i < params.BeaconConfig().SlotsPerEpoch*2-1; i++ { block, err := util.GenerateFullBlock(beaconState, privs, attConfig, beaconState.Slot()) if err != nil { return err diff --git a/tools/blocktree/main.go b/tools/blocktree/main.go index 2a8796f6c3..0ed702bf62 100644 --- a/tools/blocktree/main.go +++ b/tools/blocktree/main.go @@ -18,7 +18,7 @@ import ( "github.com/emicklei/dot" "github.com/prysmaticlabs/prysm/v3/beacon-chain/db" "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/filters" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) var ( @@ -46,8 +46,8 @@ func main() { graph.Attr("rankdir", "RL") graph.Attr("labeljust", "l") - startSlot := types.Slot(*startSlot) - endSlot := types.Slot(*endSlot) + startSlot := primitives.Slot(*startSlot) + endSlot := primitives.Slot(*endSlot) filter := filters.NewFilter().SetStartSlot(startSlot).SetEndSlot(endSlot) blks, roots, err := database.Blocks(context.Background(), filter) if err != nil { diff --git a/tools/eth1voting/main.go b/tools/eth1voting/main.go index e4cb32832a..a8493aea9c 100644 --- a/tools/eth1voting/main.go +++ b/tools/eth1voting/main.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" v1alpha1 "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" "golang.org/x/sync/errgroup" @@ -48,7 +48,7 @@ func main() { } fmt.Printf("Next period starts at epoch %d (%s)\n", nextStart, time.Until(nextStartTime)) - for i := types.Epoch(0); i < current.Sub(uint64(start)); i++ { + for i := primitives.Epoch(0); i < current.Sub(uint64(start)); i++ { j := i g.Go(func() error { resp, err := c.ListBeaconBlocks(ctx, &v1alpha1.ListBlocksRequest{ diff --git a/tools/exploredb/main.go b/tools/exploredb/main.go index 76f8bb4c37..e803bf1ac8 100644 --- a/tools/exploredb/main.go +++ b/tools/exploredb/main.go @@ -21,7 +21,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/kv" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" log "github.com/sirupsen/logrus" @@ -66,7 +66,7 @@ type modifiedState struct { // used to parallelize state summary bucket processing type modifiedStateSummary struct { - slot types.Slot + slot primitives.Slot root []byte key []byte valueSize uint64 diff --git a/tools/extractor/main.go b/tools/extractor/main.go index f71a31f831..ab802a81c1 100644 --- a/tools/extractor/main.go +++ b/tools/extractor/main.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/transition/interop" "github.com/prysmaticlabs/prysm/v3/beacon-chain/db" "github.com/prysmaticlabs/prysm/v3/config/features" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) var ( @@ -28,7 +28,7 @@ func main() { panic(err) } ctx := context.Background() - slot := types.Slot(*state) + slot := primitives.Slot(*state) _, roots, err := d.BlockRootsBySlot(ctx, slot) if err != nil { panic(err) diff --git a/tools/forkchecker/forkchecker.go b/tools/forkchecker/forkchecker.go index 946fce115f..b4d0beca9c 100644 --- a/tools/forkchecker/forkchecker.go +++ b/tools/forkchecker/forkchecker.go @@ -17,7 +17,7 @@ import ( "time" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" pb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/sirupsen/logrus" "google.golang.org/grpc" @@ -108,7 +108,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: types.Epoch(head2.HeadSlot / params.BeaconConfig().SlotsPerEpoch), + Epoch: primitives.Epoch(head2.HeadSlot / params.BeaconConfig().SlotsPerEpoch), }, }) if err != nil { diff --git a/validator/accounts/accounts_list_test.go b/validator/accounts/accounts_list_test.go index c6fff5a949..fd8e7098cc 100644 --- a/validator/accounts/accounts_list_test.go +++ b/validator/accounts/accounts_list_test.go @@ -18,7 +18,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/cmd/validator/flags" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpbservice "github.com/prysmaticlabs/prysm/v3/proto/eth/service" @@ -611,7 +611,7 @@ func TestListAccounts_ListValidatorIndices(t *testing.T) { m := mock.NewMockValidatorClient(ctrl) req := ðpb.MultipleValidatorStatusRequest{PublicKeys: pks} - resp := ðpb.MultipleValidatorStatusResponse{Indices: []types.ValidatorIndex{1, math.MaxUint64, 2}} + resp := ðpb.MultipleValidatorStatusResponse{Indices: []primitives.ValidatorIndex{1, math.MaxUint64, 2}} m. EXPECT(). diff --git a/validator/accounts/testing/mock.go b/validator/accounts/testing/mock.go index a83c9058d8..9cd1c2eee2 100644 --- a/validator/accounts/testing/mock.go +++ b/validator/accounts/testing/mock.go @@ -8,7 +8,7 @@ import ( "time" validatorserviceconfig "github.com/prysmaticlabs/prysm/v3/config/validator/service" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/validator/accounts/iface" iface2 "github.com/prysmaticlabs/prysm/v3/validator/client/iface" @@ -104,47 +104,47 @@ func (_ MockValidator) WaitForActivation(_ context.Context, _ chan [][48]byte) e panic("implement me") } -func (_ MockValidator) CanonicalHeadSlot(_ context.Context) (types.Slot, error) { +func (_ MockValidator) CanonicalHeadSlot(_ context.Context) (primitives.Slot, error) { panic("implement me") } -func (_ MockValidator) NextSlot() <-chan types.Slot { +func (_ MockValidator) NextSlot() <-chan primitives.Slot { panic("implement me") } -func (_ MockValidator) SlotDeadline(_ types.Slot) time.Time { +func (_ MockValidator) SlotDeadline(_ primitives.Slot) time.Time { panic("implement me") } -func (_ MockValidator) LogValidatorGainsAndLosses(_ context.Context, _ types.Slot) error { +func (_ MockValidator) LogValidatorGainsAndLosses(_ context.Context, _ primitives.Slot) error { panic("implement me") } -func (_ MockValidator) UpdateDuties(_ context.Context, _ types.Slot) error { +func (_ MockValidator) UpdateDuties(_ context.Context, _ primitives.Slot) error { panic("implement me") } -func (_ MockValidator) RolesAt(_ context.Context, _ types.Slot) (map[[48]byte][]iface2.ValidatorRole, error) { +func (_ MockValidator) RolesAt(_ context.Context, _ primitives.Slot) (map[[48]byte][]iface2.ValidatorRole, error) { panic("implement me") } -func (_ MockValidator) SubmitAttestation(_ context.Context, _ types.Slot, _ [48]byte) { +func (_ MockValidator) SubmitAttestation(_ context.Context, _ primitives.Slot, _ [48]byte) { panic("implement me") } -func (_ MockValidator) ProposeBlock(_ context.Context, _ types.Slot, _ [48]byte) { +func (_ MockValidator) ProposeBlock(_ context.Context, _ primitives.Slot, _ [48]byte) { panic("implement me") } -func (_ MockValidator) SubmitAggregateAndProof(_ context.Context, _ types.Slot, _ [48]byte) { +func (_ MockValidator) SubmitAggregateAndProof(_ context.Context, _ primitives.Slot, _ [48]byte) { panic("implement me") } -func (_ MockValidator) SubmitSyncCommitteeMessage(_ context.Context, _ types.Slot, _ [48]byte) { +func (_ MockValidator) SubmitSyncCommitteeMessage(_ context.Context, _ primitives.Slot, _ [48]byte) { panic("implement me") } -func (_ MockValidator) SubmitSignedContributionAndProof(_ context.Context, _ types.Slot, _ [48]byte) { +func (_ MockValidator) SubmitSignedContributionAndProof(_ context.Context, _ primitives.Slot, _ [48]byte) { panic("implement me") } @@ -152,7 +152,7 @@ func (_ MockValidator) LogAttestationsSubmitted() { panic("implement me") } -func (_ MockValidator) UpdateDomainDataCaches(_ context.Context, _ types.Slot) { +func (_ MockValidator) UpdateDomainDataCaches(_ context.Context, _ primitives.Slot) { panic("implement me") } diff --git a/validator/client/aggregate.go b/validator/client/aggregate.go index b5e3e50314..bdafce93e5 100644 --- a/validator/client/aggregate.go +++ b/validator/client/aggregate.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -24,7 +24,7 @@ import ( // via gRPC. Beacon node will verify the slot signature and determine if the validator is also // an aggregator. If yes, then beacon node will broadcast aggregated signature and // proof on the validator's behalf. -func (v *validator) SubmitAggregateAndProof(ctx context.Context, slot types.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) { +func (v *validator) SubmitAggregateAndProof(ctx context.Context, slot primitives.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) { ctx, span := trace.StartSpan(ctx, "validator.SubmitAggregateAndProof") defer span.End() @@ -117,14 +117,14 @@ func (v *validator) SubmitAggregateAndProof(ctx context.Context, slot types.Slot } // Signs input slot with domain selection proof. This is used to create the signature for aggregator selection. -func (v *validator) signSlotWithSelectionProof(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, slot types.Slot) (signature []byte, err error) { +func (v *validator) signSlotWithSelectionProof(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, slot primitives.Slot) (signature []byte, err error) { domain, err := v.domainData(ctx, slots.ToEpoch(slot), params.BeaconConfig().DomainSelectionProof[:]) if err != nil { return nil, err } var sig bls.Signature - sszUint := types.SSZUint64(slot) + sszUint := primitives.SSZUint64(slot) root, err := signing.ComputeSigningRoot(&sszUint, domain.SignatureDomain) if err != nil { return nil, err @@ -146,7 +146,7 @@ func (v *validator) signSlotWithSelectionProof(ctx context.Context, pubKey [fiel // waitToSlotTwoThirds waits until two third through the current slot period // such that any attestations from this slot have time to reach the beacon node // before creating the aggregated attestation. -func (v *validator) waitToSlotTwoThirds(ctx context.Context, slot types.Slot) { +func (v *validator) waitToSlotTwoThirds(ctx context.Context, slot primitives.Slot) { ctx, span := trace.StartSpan(ctx, "validator.waitToSlotTwoThirds") defer span.End() @@ -173,7 +173,7 @@ func (v *validator) waitToSlotTwoThirds(ctx context.Context, slot types.Slot) { // This returns the signature of validator signing over aggregate and // proof object. -func (v *validator) aggregateAndProofSig(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, agg *ethpb.AggregateAttestationAndProof, slot types.Slot) ([]byte, error) { +func (v *validator) aggregateAndProofSig(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, agg *ethpb.AggregateAttestationAndProof, slot primitives.Slot) ([]byte, error) { d, err := v.domainData(ctx, slots.ToEpoch(agg.Aggregate.Data.Slot), params.BeaconConfig().DomainAggregateAndProof[:]) if err != nil { return nil, err diff --git a/validator/client/aggregate_test.go b/validator/client/aggregate_test.go index e1007ec741..36a4b123fc 100644 --- a/validator/client/aggregate_test.go +++ b/validator/client/aggregate_test.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/go-bitfield" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -120,7 +120,7 @@ func TestWaitForSlotTwoThird_WaitCorrectly(t *testing.T) { validator, _, _, finish := setup(t) defer finish() currentTime := time.Now() - numOfSlots := types.Slot(4) + numOfSlots := primitives.Slot(4) validator.genesisTime = uint64(currentTime.Unix()) - uint64(numOfSlots.Mul(params.BeaconConfig().SecondsPerSlot)) oneThird := slots.DivideSlotBy(3 /* one third of slot duration */) timeToSleep := oneThird + oneThird @@ -135,7 +135,7 @@ func TestWaitForSlotTwoThird_DoneContext_ReturnsImmediately(t *testing.T) { validator, _, _, finish := setup(t) defer finish() currentTime := time.Now() - numOfSlots := types.Slot(4) + numOfSlots := primitives.Slot(4) validator.genesisTime = uint64(currentTime.Unix()) - uint64(numOfSlots.Mul(params.BeaconConfig().SecondsPerSlot)) expectedTime := time.Now() diff --git a/validator/client/attest.go b/validator/client/attest.go index de1bb3bebd..2458ce6a9d 100644 --- a/validator/client/attest.go +++ b/validator/client/attest.go @@ -15,7 +15,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" @@ -32,7 +32,7 @@ import ( // It fetches the latest beacon block head along with the latest canonical beacon state // information in order to sign the block and include information about the validator's // participation in voting on the block. -func (v *validator) SubmitAttestation(ctx context.Context, slot types.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) { +func (v *validator) SubmitAttestation(ctx context.Context, slot primitives.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) { ctx, span := trace.StartSpan(ctx, "validator.SubmitAttestation") defer span.End() span.AddAttributes(trace.StringAttribute("validator", fmt.Sprintf("%#x", pubKey))) @@ -196,7 +196,7 @@ func (v *validator) duty(pubKey [fieldparams.BLSPubkeyLength]byte) (*ethpb.Dutie } // Given validator's public key, this function returns the signature of an attestation data and its signing root. -func (v *validator) signAtt(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, data *ethpb.AttestationData, slot types.Slot) ([]byte, [32]byte, error) { +func (v *validator) signAtt(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, data *ethpb.AttestationData, slot primitives.Slot) ([]byte, [32]byte, error) { domain, root, err := v.getDomainAndSigningRoot(ctx, data) if err != nil { return nil, [32]byte{}, err @@ -229,7 +229,7 @@ func (v *validator) getDomainAndSigningRoot(ctx context.Context, data *ethpb.Att // For logging, this saves the last submitted attester index to its attestation data. The purpose of this // is to enhance attesting logs to be readable when multiple validator keys ran in a single client. -func (v *validator) saveAttesterIndexToData(data *ethpb.AttestationData, index types.ValidatorIndex) error { +func (v *validator) saveAttesterIndexToData(data *ethpb.AttestationData, index primitives.ValidatorIndex) error { v.attLogsLock.Lock() defer v.attLogsLock.Unlock() @@ -239,9 +239,9 @@ func (v *validator) saveAttesterIndexToData(data *ethpb.AttestationData, index t } if v.attLogs[h] == nil { - v.attLogs[h] = &attSubmitted{data, []types.ValidatorIndex{}, []types.ValidatorIndex{}} + v.attLogs[h] = &attSubmitted{data, []primitives.ValidatorIndex{}, []primitives.ValidatorIndex{}} } - v.attLogs[h] = &attSubmitted{data, append(v.attLogs[h].attesterIndices, index), []types.ValidatorIndex{}} + v.attLogs[h] = &attSubmitted{data, append(v.attLogs[h].attesterIndices, index), []primitives.ValidatorIndex{}} return nil } @@ -250,7 +250,7 @@ func (v *validator) saveAttesterIndexToData(data *ethpb.AttestationData, index t // // (a) the validator has received a valid block that is the same slot as input slot // (b) one-third of the slot has transpired (SECONDS_PER_SLOT / 3 seconds after the start of slot) -func (v *validator) waitOneThirdOrValidBlock(ctx context.Context, slot types.Slot) { +func (v *validator) waitOneThirdOrValidBlock(ctx context.Context, slot primitives.Slot) { ctx, span := trace.StartSpan(ctx, "validator.waitOneThirdOrValidBlock") defer span.End() diff --git a/validator/client/attest_protect_test.go b/validator/client/attest_protect_test.go index 5e07dfbfd5..8a84734586 100644 --- a/validator/client/attest_protect_test.go +++ b/validator/client/attest_protect_test.go @@ -7,7 +7,7 @@ import ( "github.com/golang/mock/gomock" "github.com/prysmaticlabs/prysm/v3/config/features" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -110,11 +110,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, types.Epoch(4), e) + require.Equal(t, primitives.Epoch(4), e) e, exists, err = validator.db.LowestSignedTargetEpoch(context.Background(), pubKey) require.NoError(t, err) require.Equal(t, true, exists) - require.Equal(t, types.Epoch(10), e) + require.Equal(t, primitives.Epoch(10), e) } func Test_slashableAttestationCheck_OK(t *testing.T) { @@ -191,9 +191,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, types.Epoch(0), e) + require.Equal(t, primitives.Epoch(0), e) e, exists, err = validator.db.LowestSignedTargetEpoch(context.Background(), fakePubkey) require.NoError(t, err) require.Equal(t, true, exists) - require.Equal(t, types.Epoch(0), e) + require.Equal(t, primitives.Epoch(0), e) } diff --git a/validator/client/attest_test.go b/validator/client/attest_test.go index 6a7afc613f..bbddbc47e6 100644 --- a/validator/client/attest_test.go +++ b/validator/client/attest_test.go @@ -17,7 +17,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -53,7 +53,7 @@ func TestAttestToBlockHead_SubmitAttestation_EmptyCommittee(t *testing.T) { { PublicKey: validatorKey.PublicKey().Marshal(), CommitteeIndex: 0, - Committee: make([]types.ValidatorIndex, 0), + Committee: make([]primitives.ValidatorIndex, 0), ValidatorIndex: 0, }}} validator.SubmitAttestation(context.Background(), 0, pubKey) @@ -69,7 +69,7 @@ func TestAttestToBlockHead_SubmitAttestation_RequestFailure(t *testing.T) { { PublicKey: validatorKey.PublicKey().Marshal(), CommitteeIndex: 5, - Committee: make([]types.ValidatorIndex, 111), + Committee: make([]primitives.ValidatorIndex, 111), ValidatorIndex: 0, }}} m.validatorClient.EXPECT().GetAttestationData( @@ -99,8 +99,8 @@ func TestAttestToBlockHead_AttestsCorrectly(t *testing.T) { validator, m, validatorKey, finish := setup(t) defer finish() hook := logTest.NewGlobal() - validatorIndex := types.ValidatorIndex(7) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(7) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} var pubKey [fieldparams.BLSPubkeyLength]byte copy(pubKey[:], validatorKey.PublicKey().Marshal()) validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ @@ -172,8 +172,8 @@ func TestAttestToBlockHead_BlocksDoubleAtt(t *testing.T) { hook := logTest.NewGlobal() validator, m, validatorKey, finish := setup(t) defer finish() - validatorIndex := types.ValidatorIndex(7) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(7) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} var pubKey [fieldparams.BLSPubkeyLength]byte copy(pubKey[:], validatorKey.PublicKey().Marshal()) validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ @@ -224,8 +224,8 @@ func TestAttestToBlockHead_BlocksSurroundAtt(t *testing.T) { hook := logTest.NewGlobal() validator, m, validatorKey, finish := setup(t) defer finish() - validatorIndex := types.ValidatorIndex(7) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(7) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} var pubKey [fieldparams.BLSPubkeyLength]byte copy(pubKey[:], validatorKey.PublicKey().Marshal()) validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ @@ -276,10 +276,10 @@ func TestAttestToBlockHead_BlocksSurroundedAtt(t *testing.T) { hook := logTest.NewGlobal() validator, m, validatorKey, finish := setup(t) defer finish() - validatorIndex := types.ValidatorIndex(7) + validatorIndex := primitives.ValidatorIndex(7) var pubKey [fieldparams.BLSPubkeyLength]byte copy(pubKey[:], validatorKey.PublicKey().Marshal()) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ { PublicKey: validatorKey.PublicKey().Marshal(), @@ -363,8 +363,8 @@ func TestAttestToBlockHead_DoesAttestAfterDelay(t *testing.T) { defer wg.Wait() validator.genesisTime = uint64(prysmTime.Now().Unix()) - validatorIndex := types.ValidatorIndex(5) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(5) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} var pubKey [fieldparams.BLSPubkeyLength]byte copy(pubKey[:], validatorKey.PublicKey().Marshal()) validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ @@ -402,8 +402,8 @@ func TestAttestToBlockHead_DoesAttestAfterDelay(t *testing.T) { func TestAttestToBlockHead_CorrectBitfieldLength(t *testing.T) { validator, m, validatorKey, finish := setup(t) defer finish() - validatorIndex := types.ValidatorIndex(2) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(2) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} var pubKey [fieldparams.BLSPubkeyLength]byte copy(pubKey[:], validatorKey.PublicKey().Marshal()) validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ @@ -486,7 +486,7 @@ func TestSignAttestation(t *testing.T) { func TestServer_WaitToSlotOneThird_CanWait(t *testing.T) { currentTime := uint64(time.Now().Unix()) - currentSlot := types.Slot(4) + currentSlot := primitives.Slot(4) genesisTime := currentTime - uint64(currentSlot.Mul(params.BeaconConfig().SecondsPerSlot)) v := &validator{ @@ -505,7 +505,7 @@ func TestServer_WaitToSlotOneThird_CanWait(t *testing.T) { func TestServer_WaitToSlotOneThird_SameReqSlot(t *testing.T) { currentTime := uint64(time.Now().Unix()) - currentSlot := types.Slot(4) + currentSlot := primitives.Slot(4) genesisTime := currentTime - uint64(currentSlot.Mul(params.BeaconConfig().SecondsPerSlot)) v := &validator{ @@ -526,7 +526,7 @@ func TestServer_WaitToSlotOneThird_ReceiveBlockSlot(t *testing.T) { defer resetCfg() currentTime := uint64(time.Now().Unix()) - currentSlot := types.Slot(4) + currentSlot := primitives.Slot(4) genesisTime := currentTime - uint64(currentSlot.Mul(params.BeaconConfig().SecondsPerSlot)) v := &validator{ diff --git a/validator/client/beacon-api/activation.go b/validator/client/beacon-api/activation.go index dac89860a9..a6e82401fb 100644 --- a/validator/client/beacon-api/activation.go +++ b/validator/client/beacon-api/activation.go @@ -1,15 +1,14 @@ package beacon_api import ( + "context" "strconv" "time" - "context" - "github.com/ethereum/go-ethereum/common/hexutil" "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "google.golang.org/grpc" ) @@ -94,7 +93,7 @@ func (c *waitForActivationClient) Recv() (*ethpb.ValidatorActivationResponse, er statuses = append(statuses, ðpb.ValidatorActivationResponse_Status{ PublicKey: pubkey, - Index: types.ValidatorIndex(index), + Index: primitives.ValidatorIndex(index), Status: ðpb.ValidatorStatusResponse{Status: validatorStatus}, }) } @@ -108,7 +107,7 @@ func (c *waitForActivationClient) Recv() (*ethpb.ValidatorActivationResponse, er for _, missingPubKey := range missingPubKeys { statuses = append(statuses, ðpb.ValidatorActivationResponse_Status{ PublicKey: missingPubKey, - Index: types.ValidatorIndex(^uint64(0)), + Index: primitives.ValidatorIndex(^uint64(0)), Status: ðpb.ValidatorStatusResponse{Status: ethpb.ValidatorStatus_UNKNOWN_STATUS}, }) } diff --git a/validator/client/beacon-api/attestation_data.go b/validator/client/beacon-api/attestation_data.go index 39c8070b9e..12edf95746 100644 --- a/validator/client/beacon-api/attestation_data.go +++ b/validator/client/beacon-api/attestation_data.go @@ -8,14 +8,14 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/pkg/errors" rpcmiddleware "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) func (c beaconApiValidatorClient) getAttestationData( ctx context.Context, - reqSlot types.Slot, - reqCommitteeIndex types.CommitteeIndex, + reqSlot primitives.Slot, + reqCommitteeIndex primitives.CommitteeIndex, ) (*ethpb.AttestationData, error) { params := url.Values{} params.Add("slot", strconv.FormatUint(uint64(reqSlot), 10)) @@ -90,14 +90,14 @@ func (c beaconApiValidatorClient) getAttestationData( response := ðpb.AttestationData{ BeaconBlockRoot: beaconBlockRoot, - CommitteeIndex: types.CommitteeIndex(committeeIndex), - Slot: types.Slot(slot), + CommitteeIndex: primitives.CommitteeIndex(committeeIndex), + Slot: primitives.Slot(slot), Source: ðpb.Checkpoint{ - Epoch: types.Epoch(sourceEpoch), + Epoch: primitives.Epoch(sourceEpoch), Root: sourceRoot, }, Target: ðpb.Checkpoint{ - Epoch: types.Epoch(targetEpoch), + Epoch: primitives.Epoch(targetEpoch), Root: targetRoot, }, } diff --git a/validator/client/beacon-api/attestation_data_test.go b/validator/client/beacon-api/attestation_data_test.go index 84da676f34..2a470285e1 100644 --- a/validator/client/beacon-api/attestation_data_test.go +++ b/validator/client/beacon-api/attestation_data_test.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/golang/mock/gomock" rpcmiddleware "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/validator/client/beacon-api/mock" @@ -59,7 +59,7 @@ func TestGetAttestationData_ValidAttestation(t *testing.T) { ).Times(1) validatorClient := &beaconApiValidatorClient{jsonRestHandler: jsonRestHandler} - resp, err := validatorClient.getAttestationData(ctx, types.Slot(expectedSlot), types.CommitteeIndex(expectedCommitteeIndex)) + resp, err := validatorClient.getAttestationData(ctx, primitives.Slot(expectedSlot), primitives.CommitteeIndex(expectedCommitteeIndex)) assert.NoError(t, err) require.NotNil(t, resp) @@ -203,8 +203,8 @@ func TestGetAttestationData_InvalidData(t *testing.T) { } func TestGetAttestationData_JsonResponseError(t *testing.T) { - const slot = types.Slot(1) - const committeeIndex = types.CommitteeIndex(2) + const slot = primitives.Slot(1) + const committeeIndex = primitives.CommitteeIndex(2) ctx := context.Background() diff --git a/validator/client/beacon-api/beacon_api_helpers.go b/validator/client/beacon-api/beacon_api_helpers.go index 36c3f7b369..23d5fe8051 100644 --- a/validator/client/beacon-api/beacon_api_helpers.go +++ b/validator/client/beacon-api/beacon_api_helpers.go @@ -11,7 +11,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -36,7 +36,7 @@ func validRoot(root string) bool { return matchesRegex } -func uint64ToString[T uint64 | types.Slot | types.ValidatorIndex | types.CommitteeIndex | types.Epoch](val T) string { +func uint64ToString[T uint64 | primitives.Slot | primitives.ValidatorIndex | primitives.CommitteeIndex | primitives.Epoch](val T) string { return strconv.FormatUint(uint64(val), 10) } @@ -82,7 +82,7 @@ func (c *beaconApiValidatorClient) getHeaders(ctx context.Context) (*apimiddlewa return blockHeadersResponseJson, nil } -func (c *beaconApiValidatorClient) getLiveness(ctx context.Context, epoch types.Epoch, validatorIndexes []string) (*apimiddleware.LivenessResponseJson, error) { +func (c *beaconApiValidatorClient) getLiveness(ctx context.Context, epoch primitives.Epoch, validatorIndexes []string) (*apimiddleware.LivenessResponseJson, error) { const endpoint = "/eth/v1/validator/liveness/" url := endpoint + strconv.FormatUint(uint64(epoch), 10) diff --git a/validator/client/beacon-api/beacon_api_helpers_test.go b/validator/client/beacon-api/beacon_api_helpers_test.go index 092c782126..a751a947fe 100644 --- a/validator/client/beacon-api/beacon_api_helpers_test.go +++ b/validator/client/beacon-api/beacon_api_helpers_test.go @@ -11,7 +11,7 @@ import ( "github.com/golang/mock/gomock" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/helpers" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/validator/client/beacon-api/mock" @@ -67,10 +67,10 @@ func TestBeaconApiHelpers_TestUint64ToString(t *testing.T) { const val = uint64(1234) assert.Equal(t, expectedResult, uint64ToString(val)) - assert.Equal(t, expectedResult, uint64ToString(types.Slot(val))) - assert.Equal(t, expectedResult, uint64ToString(types.ValidatorIndex(val))) - assert.Equal(t, expectedResult, uint64ToString(types.CommitteeIndex(val))) - assert.Equal(t, expectedResult, uint64ToString(types.Epoch(val))) + assert.Equal(t, expectedResult, uint64ToString(primitives.Slot(val))) + assert.Equal(t, expectedResult, uint64ToString(primitives.ValidatorIndex(val))) + assert.Equal(t, expectedResult, uint64ToString(primitives.CommitteeIndex(val))) + assert.Equal(t, expectedResult, uint64ToString(primitives.Epoch(val))) } func TestBuildURL_NoParams(t *testing.T) { diff --git a/validator/client/beacon-api/beacon_api_validator_client.go b/validator/client/beacon-api/beacon_api_validator_client.go index 44a47e87a0..0419078215 100644 --- a/validator/client/beacon-api/beacon_api_validator_client.go +++ b/validator/client/beacon-api/beacon_api_validator_client.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/golang/protobuf/ptypes/empty" "github.com/pkg/errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/validator/client/iface" @@ -160,7 +160,7 @@ func (c *beaconApiValidatorClient) SubmitValidatorRegistrations(ctx context.Cont return new(empty.Empty), c.submitValidatorRegistrations(ctx, in.Messages) } -func (c *beaconApiValidatorClient) SubscribeCommitteeSubnets(ctx context.Context, in *ethpb.CommitteeSubnetsSubscribeRequest, validatorIndices []types.ValidatorIndex) (*empty.Empty, error) { +func (c *beaconApiValidatorClient) SubscribeCommitteeSubnets(ctx context.Context, in *ethpb.CommitteeSubnetsSubscribeRequest, validatorIndices []primitives.ValidatorIndex) (*empty.Empty, error) { return new(empty.Empty), c.subscribeCommitteeSubnets(ctx, in, validatorIndices) } diff --git a/validator/client/beacon-api/beacon_api_validator_client_test.go b/validator/client/beacon-api/beacon_api_validator_client_test.go index 3937622624..5d98c2ca8b 100644 --- a/validator/client/beacon-api/beacon_api_validator_client_test.go +++ b/validator/client/beacon-api/beacon_api_validator_client_test.go @@ -8,7 +8,7 @@ import ( "github.com/golang/mock/gomock" rpcmiddleware "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/prysmaticlabs/prysm/v3/config/params" @@ -20,8 +20,8 @@ import ( // Make sure that GetAttestationData() returns the same thing as the internal getAttestationData() func TestBeaconApiValidatorClient_GetAttestationDataValid(t *testing.T) { - const slot = types.Slot(1) - const committeeIndex = types.CommitteeIndex(2) + const slot = primitives.Slot(1) + const committeeIndex = primitives.CommitteeIndex(2) ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -61,8 +61,8 @@ func TestBeaconApiValidatorClient_GetAttestationDataNilInput(t *testing.T) { } func TestBeaconApiValidatorClient_GetAttestationDataError(t *testing.T) { - const slot = types.Slot(1) - const committeeIndex = types.CommitteeIndex(2) + const slot = primitives.Slot(1) + const committeeIndex = primitives.CommitteeIndex(2) ctrl := gomock.NewController(t) defer ctrl.Finish() diff --git a/validator/client/beacon-api/beacon_block_proto_helpers.go b/validator/client/beacon-api/beacon_block_proto_helpers.go index fb5e15308e..958508245c 100644 --- a/validator/client/beacon-api/beacon_block_proto_helpers.go +++ b/validator/client/beacon-api/beacon_block_proto_helpers.go @@ -6,7 +6,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -79,8 +79,8 @@ func convertProposerSlashingSignedHeaderToProto(signedHeader *apimiddleware.Sign return ðpb.SignedBeaconBlockHeader{ Header: ðpb.BeaconBlockHeader{ - Slot: types.Slot(slot), - ProposerIndex: types.ValidatorIndex(proposerIndex), + Slot: primitives.Slot(slot), + ProposerIndex: primitives.ValidatorIndex(proposerIndex), ParentRoot: parentRoot, StateRoot: stateRoot, BodyRoot: bodyRoot, @@ -165,7 +165,7 @@ func convertCheckpointToProto(jsonCheckpoint *apimiddleware.CheckpointJson) (*et } return ðpb.Checkpoint{ - Epoch: types.Epoch(epoch), + Epoch: primitives.Epoch(epoch), Root: root, }, nil } @@ -234,8 +234,8 @@ func convertAttestationDataToProto(jsonAttestationData *apimiddleware.Attestatio } return ðpb.AttestationData{ - Slot: types.Slot(slot), - CommitteeIndex: types.CommitteeIndex(committeeIndex), + Slot: primitives.Slot(slot), + CommitteeIndex: primitives.CommitteeIndex(committeeIndex), BeaconBlockRoot: beaconBlockRoot, Source: sourceCheckpoint, Target: targetCheckpoint, @@ -327,8 +327,8 @@ func convertVoluntaryExitsToProto(jsonVoluntaryExits []*apimiddleware.SignedVolu attestingIndices[index] = ðpb.SignedVoluntaryExit{ Exit: ðpb.VoluntaryExit{ - Epoch: types.Epoch(epoch), - ValidatorIndex: types.ValidatorIndex(validatorIndex), + Epoch: primitives.Epoch(epoch), + ValidatorIndex: primitives.ValidatorIndex(validatorIndex), }, Signature: signature, } @@ -382,7 +382,7 @@ func convertWithdrawalsToProto(jsonWithdrawals []*apimiddleware.WithdrawalJson) withdrawals[index] = &enginev1.Withdrawal{ Index: withdrawalIndex, - ValidatorIndex: types.ValidatorIndex(validatorIndex), + ValidatorIndex: primitives.ValidatorIndex(validatorIndex), Address: executionAddress, Amount: amount, } @@ -425,7 +425,7 @@ func convertBlsToExecutionChangesToProto(jsonSignedBlsToExecutionChanges []*apim signedBlsToExecutionChanges[index] = ðpb.SignedBLSToExecutionChange{ Message: ðpb.BLSToExecutionChange{ - ValidatorIndex: types.ValidatorIndex(validatorIndex), + ValidatorIndex: primitives.ValidatorIndex(validatorIndex), FromBlsPubkey: fromBlsPubkey, ToExecutionAddress: toExecutionAddress, }, diff --git a/validator/client/beacon-api/domain_data.go b/validator/client/beacon-api/domain_data.go index 4677400402..82ccb5fa75 100644 --- a/validator/client/beacon-api/domain_data.go +++ b/validator/client/beacon-api/domain_data.go @@ -6,12 +6,12 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/network/forks" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) -func (c beaconApiValidatorClient) getDomainData(ctx context.Context, epoch types.Epoch, domainType [4]byte) (*ethpb.DomainResponse, error) { +func (c beaconApiValidatorClient) getDomainData(ctx context.Context, epoch primitives.Epoch, domainType [4]byte) (*ethpb.DomainResponse, error) { // Get the fork version from the given epoch fork, err := forks.Fork(epoch) if err != nil { diff --git a/validator/client/beacon-api/doppelganger.go b/validator/client/beacon-api/doppelganger.go index fae3f8761c..cbf7b9cc3f 100644 --- a/validator/client/beacon-api/doppelganger.go +++ b/validator/client/beacon-api/doppelganger.go @@ -9,14 +9,14 @@ import ( "github.com/pkg/errors" "github.com/ethereum/go-ethereum/common/hexutil" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/runtime/version" "github.com/prysmaticlabs/prysm/v3/time/slots" ) type DoppelGangerInfo struct { - validatorEpoch types.Epoch + validatorEpoch primitives.Epoch response *ethpb.DoppelGangerResponse_ValidatorResponse } @@ -102,7 +102,7 @@ func (c *beaconApiValidatorClient) checkDoppelGanger(ctx context.Context, in *et return nil, errors.Wrapf(err, "failed to parse head slot") } - headSlot := types.Slot(headSlotUint64) + headSlot := primitives.Slot(headSlotUint64) currentEpoch := slots.ToEpoch(headSlot) // Extract input pubkeys we did not validate for the 2 last epochs. @@ -218,7 +218,7 @@ func buildResponse( } } -func (c *beaconApiValidatorClient) getIndexToLiveness(ctx context.Context, epoch types.Epoch, indexes []string) (map[string]bool, error) { +func (c *beaconApiValidatorClient) getIndexToLiveness(ctx context.Context, epoch primitives.Epoch, indexes []string) (map[string]bool, error) { livenessResponse, err := c.getLiveness(ctx, epoch, indexes) if err != nil || livenessResponse.Data == nil { return nil, errors.Wrapf(err, fmt.Sprintf("failed to get liveness for epoch %d", epoch)) diff --git a/validator/client/beacon-api/duties.go b/validator/client/beacon-api/duties.go index 99c223cf4e..6752aa4eec 100644 --- a/validator/client/beacon-api/duties.go +++ b/validator/client/beacon-api/duties.go @@ -11,15 +11,15 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) type dutiesProvider interface { - GetAttesterDuties(ctx context.Context, epoch types.Epoch, validatorIndices []types.ValidatorIndex) ([]*apimiddleware.AttesterDutyJson, error) - GetProposerDuties(ctx context.Context, epoch types.Epoch) ([]*apimiddleware.ProposerDutyJson, error) - GetSyncDuties(ctx context.Context, epoch types.Epoch, validatorIndices []types.ValidatorIndex) ([]*apimiddleware.SyncCommitteeDuty, error) - GetCommittees(ctx context.Context, epoch types.Epoch) ([]*apimiddleware.CommitteeJson, error) + GetAttesterDuties(ctx context.Context, epoch primitives.Epoch, validatorIndices []primitives.ValidatorIndex) ([]*apimiddleware.AttesterDutyJson, error) + GetProposerDuties(ctx context.Context, epoch primitives.Epoch) ([]*apimiddleware.ProposerDutyJson, error) + GetSyncDuties(ctx context.Context, epoch primitives.Epoch, validatorIndices []primitives.ValidatorIndex) ([]*apimiddleware.SyncCommitteeDuty, error) + GetCommittees(ctx context.Context, epoch primitives.Epoch) ([]*apimiddleware.CommitteeJson, error) } type beaconApiDutiesProvider struct { @@ -27,8 +27,8 @@ type beaconApiDutiesProvider struct { } type committeeIndexSlotPair struct { - committeeIndex types.CommitteeIndex - slot types.Slot + committeeIndex primitives.CommitteeIndex + slot primitives.Slot } func (c beaconApiValidatorClient) getDuties(ctx context.Context, in *ethpb.DutiesRequest) (*ethpb.DutiesResponse, error) { @@ -59,7 +59,7 @@ func (c beaconApiValidatorClient) getDuties(ctx context.Context, in *ethpb.Dutie func (c beaconApiValidatorClient) getDutiesForEpoch( ctx context.Context, - epoch types.Epoch, + epoch primitives.Epoch, multipleValidatorStatus *ethpb.MultipleValidatorStatusResponse, fetchSyncDuties bool, ) ([]*ethpb.DutiesResponse_Duty, error) { @@ -86,7 +86,7 @@ func (c beaconApiValidatorClient) getDutiesForEpoch( } // Mapping from a validator index to its attesting committee's index and slot - attesterDutiesMapping := make(map[types.ValidatorIndex]committeeIndexSlotPair) + attesterDutiesMapping := make(map[primitives.ValidatorIndex]committeeIndexSlotPair) for _, attesterDuty := range attesterDuties { validatorIndex, err := strconv.ParseUint(attesterDuty.ValidatorIndex, 10, 64) if err != nil { @@ -103,14 +103,14 @@ func (c beaconApiValidatorClient) getDutiesForEpoch( return nil, errors.Wrapf(err, "failed to parse attester committee index `%s`", attesterDuty.CommitteeIndex) } - attesterDutiesMapping[types.ValidatorIndex(validatorIndex)] = committeeIndexSlotPair{ - slot: types.Slot(slot), - committeeIndex: types.CommitteeIndex(committeeIndex), + attesterDutiesMapping[primitives.ValidatorIndex(validatorIndex)] = committeeIndexSlotPair{ + slot: primitives.Slot(slot), + committeeIndex: primitives.CommitteeIndex(committeeIndex), } } // Mapping from a validator index to its proposal slot - proposerDutySlots := make(map[types.ValidatorIndex][]types.Slot) + proposerDutySlots := make(map[primitives.ValidatorIndex][]primitives.Slot) for _, proposerDuty := range proposerDuties { validatorIndex, err := strconv.ParseUint(proposerDuty.ValidatorIndex, 10, 64) if err != nil { @@ -122,22 +122,22 @@ func (c beaconApiValidatorClient) getDutiesForEpoch( return nil, errors.Wrapf(err, "failed to parse proposer slot `%s`", proposerDuty.Slot) } - proposerDutySlots[types.ValidatorIndex(validatorIndex)] = append(proposerDutySlots[types.ValidatorIndex(validatorIndex)], types.Slot(slot)) + proposerDutySlots[primitives.ValidatorIndex(validatorIndex)] = append(proposerDutySlots[primitives.ValidatorIndex(validatorIndex)], primitives.Slot(slot)) } // Set containing all validator indices that are part of a sync committee for this epoch - syncDutiesMapping := make(map[types.ValidatorIndex]bool) + syncDutiesMapping := make(map[primitives.ValidatorIndex]bool) for _, syncDuty := range syncDuties { validatorIndex, err := strconv.ParseUint(syncDuty.ValidatorIndex, 10, 64) if err != nil { return nil, errors.Wrapf(err, "failed to parse sync validator index `%s`", syncDuty.ValidatorIndex) } - syncDutiesMapping[types.ValidatorIndex(validatorIndex)] = true + syncDutiesMapping[primitives.ValidatorIndex(validatorIndex)] = true } // Mapping from the {committeeIndex, slot} to each of the committee's validator indices - committeeMapping := make(map[committeeIndexSlotPair][]types.ValidatorIndex) + committeeMapping := make(map[committeeIndexSlotPair][]primitives.ValidatorIndex) for _, committee := range committees { committeeIndex, err := strconv.ParseUint(committee.Index, 10, 64) if err != nil { @@ -149,18 +149,18 @@ func (c beaconApiValidatorClient) getDutiesForEpoch( return nil, errors.Wrapf(err, "failed to parse slot `%s`", committee.Slot) } - validatorIndices := make([]types.ValidatorIndex, len(committee.Validators)) + validatorIndices := make([]primitives.ValidatorIndex, len(committee.Validators)) for index, validatorIndexString := range committee.Validators { validatorIndex, err := strconv.ParseUint(validatorIndexString, 10, 64) if err != nil { return nil, errors.Wrapf(err, "failed to parse committee validator index `%s`", validatorIndexString) } - validatorIndices[index] = types.ValidatorIndex(validatorIndex) + validatorIndices[index] = primitives.ValidatorIndex(validatorIndex) } key := committeeIndexSlotPair{ - committeeIndex: types.CommitteeIndex(committeeIndex), - slot: types.Slot(slot), + committeeIndex: primitives.CommitteeIndex(committeeIndex), + slot: primitives.Slot(slot), } committeeMapping[key] = validatorIndices } @@ -170,9 +170,9 @@ func (c beaconApiValidatorClient) getDutiesForEpoch( validatorIndex := multipleValidatorStatus.Indices[index] pubkey := multipleValidatorStatus.PublicKeys[index] - var attesterSlot types.Slot - var committeeIndex types.CommitteeIndex - var committeeValidatorIndices []types.ValidatorIndex + var attesterSlot primitives.Slot + var committeeIndex primitives.CommitteeIndex + var committeeValidatorIndices []primitives.ValidatorIndex if committeeMappingKey, ok := attesterDutiesMapping[validatorIndex]; ok { committeeIndex = committeeMappingKey.committeeIndex @@ -187,11 +187,11 @@ func (c beaconApiValidatorClient) getDutiesForEpoch( Committee: committeeValidatorIndices, CommitteeIndex: committeeIndex, AttesterSlot: attesterSlot, - ProposerSlots: proposerDutySlots[types.ValidatorIndex(validatorIndex)], + ProposerSlots: proposerDutySlots[primitives.ValidatorIndex(validatorIndex)], PublicKey: pubkey, Status: validatorStatus.Status, - ValidatorIndex: types.ValidatorIndex(validatorIndex), - IsSyncCommittee: syncDutiesMapping[types.ValidatorIndex(validatorIndex)], + ValidatorIndex: primitives.ValidatorIndex(validatorIndex), + IsSyncCommittee: syncDutiesMapping[primitives.ValidatorIndex(validatorIndex)], } } @@ -199,7 +199,7 @@ func (c beaconApiValidatorClient) getDutiesForEpoch( } // GetCommittees retrieves the committees for the given epoch -func (c beaconApiDutiesProvider) GetCommittees(ctx context.Context, epoch types.Epoch) ([]*apimiddleware.CommitteeJson, error) { +func (c beaconApiDutiesProvider) GetCommittees(ctx context.Context, epoch primitives.Epoch) ([]*apimiddleware.CommitteeJson, error) { committeeParams := url.Values{} committeeParams.Add("epoch", strconv.FormatUint(uint64(epoch), 10)) committeesRequest := buildURL("/eth/v1/beacon/states/head/committees", committeeParams) @@ -223,7 +223,7 @@ func (c beaconApiDutiesProvider) GetCommittees(ctx context.Context, epoch types. } // GetAttesterDuties retrieves the attester duties for the given epoch and validatorIndices -func (c beaconApiDutiesProvider) GetAttesterDuties(ctx context.Context, epoch types.Epoch, validatorIndices []types.ValidatorIndex) ([]*apimiddleware.AttesterDutyJson, error) { +func (c beaconApiDutiesProvider) GetAttesterDuties(ctx context.Context, epoch primitives.Epoch, validatorIndices []primitives.ValidatorIndex) ([]*apimiddleware.AttesterDutyJson, error) { jsonValidatorIndices := make([]string, len(validatorIndices)) for index, validatorIndex := range validatorIndices { @@ -250,7 +250,7 @@ func (c beaconApiDutiesProvider) GetAttesterDuties(ctx context.Context, epoch ty } // GetProposerDuties retrieves the proposer duties for the given epoch -func (c beaconApiDutiesProvider) GetProposerDuties(ctx context.Context, epoch types.Epoch) ([]*apimiddleware.ProposerDutyJson, error) { +func (c beaconApiDutiesProvider) GetProposerDuties(ctx context.Context, epoch primitives.Epoch) ([]*apimiddleware.ProposerDutyJson, error) { proposerDuties := apimiddleware.ProposerDutiesResponseJson{} if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, fmt.Sprintf("/eth/v1/validator/duties/proposer/%d", epoch), &proposerDuties); err != nil { return nil, errors.Wrapf(err, "failed to query proposer duties for epoch `%d`", epoch) @@ -270,7 +270,7 @@ func (c beaconApiDutiesProvider) GetProposerDuties(ctx context.Context, epoch ty } // GetSyncDuties retrieves the sync committee duties for the given epoch and validatorIndices -func (c beaconApiDutiesProvider) GetSyncDuties(ctx context.Context, epoch types.Epoch, validatorIndices []types.ValidatorIndex) ([]*apimiddleware.SyncCommitteeDuty, error) { +func (c beaconApiDutiesProvider) GetSyncDuties(ctx context.Context, epoch primitives.Epoch, validatorIndices []primitives.ValidatorIndex) ([]*apimiddleware.SyncCommitteeDuty, error) { jsonValidatorIndices := make([]string, len(validatorIndices)) for index, validatorIndex := range validatorIndices { jsonValidatorIndices[index] = strconv.FormatUint(uint64(validatorIndex), 10) diff --git a/validator/client/beacon-api/duties_test.go b/validator/client/beacon-api/duties_test.go index 7e2d4ef24a..8e948a4cdd 100644 --- a/validator/client/beacon-api/duties_test.go +++ b/validator/client/beacon-api/duties_test.go @@ -13,7 +13,7 @@ import ( "github.com/golang/mock/gomock" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -27,7 +27,7 @@ const getCommitteesTestEndpoint = "/eth/v1/beacon/states/head/committees" func TestGetAttesterDuties_Valid(t *testing.T) { stringValidatorIndices := []string{"2", "9"} - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) validatorIndicesBytes, err := json.Marshal(stringValidatorIndices) require.NoError(t, err) @@ -60,7 +60,7 @@ func TestGetAttesterDuties_Valid(t *testing.T) { ctx := context.Background() - validatorIndices := []types.ValidatorIndex{2, 9} + validatorIndices := []primitives.ValidatorIndex{2, 9} jsonRestHandler := mock.NewMockjsonRestHandler(ctrl) jsonRestHandler.EXPECT().PostRestJson( ctx, @@ -83,7 +83,7 @@ func TestGetAttesterDuties_Valid(t *testing.T) { } func TestGetAttesterDuties_HttpError(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -109,7 +109,7 @@ func TestGetAttesterDuties_HttpError(t *testing.T) { } func TestGetAttesterDuties_NilAttesterDuty(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -139,7 +139,7 @@ func TestGetAttesterDuties_NilAttesterDuty(t *testing.T) { } func TestGetProposerDuties_Valid(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) expectedProposerDuties := apimiddleware.ProposerDutiesResponseJson{ Data: []*apimiddleware.ProposerDutyJson{ @@ -181,7 +181,7 @@ func TestGetProposerDuties_Valid(t *testing.T) { } func TestGetProposerDuties_HttpError(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -205,7 +205,7 @@ func TestGetProposerDuties_HttpError(t *testing.T) { } func TestGetProposerDuties_NilData(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -233,7 +233,7 @@ func TestGetProposerDuties_NilData(t *testing.T) { } func TestGetProposerDuties_NilProposerDuty(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -262,7 +262,7 @@ func TestGetProposerDuties_NilProposerDuty(t *testing.T) { func TestGetSyncDuties_Valid(t *testing.T) { stringValidatorIndices := []string{"2", "6"} - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) validatorIndicesBytes, err := json.Marshal(stringValidatorIndices) require.NoError(t, err) @@ -293,7 +293,7 @@ func TestGetSyncDuties_Valid(t *testing.T) { ctx := context.Background() - validatorIndices := []types.ValidatorIndex{2, 6} + validatorIndices := []primitives.ValidatorIndex{2, 6} jsonRestHandler := mock.NewMockjsonRestHandler(ctrl) jsonRestHandler.EXPECT().PostRestJson( ctx, @@ -316,7 +316,7 @@ func TestGetSyncDuties_Valid(t *testing.T) { } func TestGetSyncDuties_HttpError(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -342,7 +342,7 @@ func TestGetSyncDuties_HttpError(t *testing.T) { } func TestGetSyncDuties_NilData(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -372,7 +372,7 @@ func TestGetSyncDuties_NilData(t *testing.T) { } func TestGetSyncDuties_NilSyncDuty(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -402,7 +402,7 @@ func TestGetSyncDuties_NilSyncDuty(t *testing.T) { } func TestGetCommittees_Valid(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) expectedCommittees := apimiddleware.StateCommitteesResponseJson{ Data: []*apimiddleware.CommitteeJson{ @@ -450,7 +450,7 @@ func TestGetCommittees_Valid(t *testing.T) { } func TestGetCommittees_HttpError(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -474,7 +474,7 @@ func TestGetCommittees_HttpError(t *testing.T) { } func TestGetCommittees_NilData(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -502,7 +502,7 @@ func TestGetCommittees_NilData(t *testing.T) { } func TestGetCommittees_NilCommittee(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -530,12 +530,12 @@ func TestGetCommittees_NilCommittee(t *testing.T) { } func TestGetDutiesForEpoch_Error(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) pubkeys := [][]byte{{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}} - validatorIndices := []types.ValidatorIndex{13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24} - committeeIndices := []types.CommitteeIndex{25, 26, 27} - committeeSlots := []types.Slot{28, 29, 30} - proposerSlots := []types.Slot{31, 32, 33, 34, 35, 36, 37, 38} + validatorIndices := []primitives.ValidatorIndex{13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24} + committeeIndices := []primitives.CommitteeIndex{25, 26, 27} + committeeSlots := []primitives.Slot{28, 29, 30} + proposerSlots := []primitives.Slot{31, 32, 33, 34, 35, 36, 37, 38} testCases := []struct { name string @@ -782,12 +782,12 @@ func TestGetDutiesForEpoch_Valid(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { - const epoch = types.Epoch(1) + const epoch = primitives.Epoch(1) pubkeys := [][]byte{{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}} - validatorIndices := []types.ValidatorIndex{13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24} - committeeIndices := []types.CommitteeIndex{25, 26, 27} - committeeSlots := []types.Slot{28, 29, 30} - proposerSlots := []types.Slot{31, 32, 33, 34, 35, 36, 37, 38} + validatorIndices := []primitives.ValidatorIndex{13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24} + committeeIndices := []primitives.CommitteeIndex{25, 26, 27} + committeeSlots := []primitives.Slot{28, 29, 30} + proposerSlots := []primitives.Slot{31, 32, 33, 34, 35, 36, 37, 38} statuses := []ethpb.ValidatorStatus{ ethpb.ValidatorStatus_UNKNOWN_STATUS, @@ -865,34 +865,34 @@ func TestGetDutiesForEpoch_Valid(t *testing.T) { ).Times(1) } - var expectedProposerSlots1 []types.Slot - var expectedProposerSlots2 []types.Slot - var expectedProposerSlots3 []types.Slot - var expectedProposerSlots4 []types.Slot + var expectedProposerSlots1 []primitives.Slot + var expectedProposerSlots2 []primitives.Slot + var expectedProposerSlots3 []primitives.Slot + var expectedProposerSlots4 []primitives.Slot - expectedProposerSlots1 = []types.Slot{ + expectedProposerSlots1 = []primitives.Slot{ proposerSlots[0], proposerSlots[1], } - expectedProposerSlots2 = []types.Slot{ + expectedProposerSlots2 = []primitives.Slot{ proposerSlots[2], proposerSlots[3], } - expectedProposerSlots3 = []types.Slot{ + expectedProposerSlots3 = []primitives.Slot{ proposerSlots[4], proposerSlots[5], } - expectedProposerSlots4 = []types.Slot{ + expectedProposerSlots4 = []primitives.Slot{ proposerSlots[6], proposerSlots[7], } expectedDuties := []*ethpb.DutiesResponse_Duty{ { - Committee: []types.ValidatorIndex{ + Committee: []primitives.ValidatorIndex{ validatorIndices[0], validatorIndices[1], }, @@ -903,7 +903,7 @@ func TestGetDutiesForEpoch_Valid(t *testing.T) { ValidatorIndex: validatorIndices[0], }, { - Committee: []types.ValidatorIndex{ + Committee: []primitives.ValidatorIndex{ validatorIndices[0], validatorIndices[1], }, @@ -914,7 +914,7 @@ func TestGetDutiesForEpoch_Valid(t *testing.T) { ValidatorIndex: validatorIndices[1], }, { - Committee: []types.ValidatorIndex{ + Committee: []primitives.ValidatorIndex{ validatorIndices[2], validatorIndices[3], }, @@ -925,7 +925,7 @@ func TestGetDutiesForEpoch_Valid(t *testing.T) { ValidatorIndex: validatorIndices[2], }, { - Committee: []types.ValidatorIndex{ + Committee: []primitives.ValidatorIndex{ validatorIndices[2], validatorIndices[3], }, @@ -936,7 +936,7 @@ func TestGetDutiesForEpoch_Valid(t *testing.T) { ValidatorIndex: validatorIndices[3], }, { - Committee: []types.ValidatorIndex{ + Committee: []primitives.ValidatorIndex{ validatorIndices[4], validatorIndices[5], }, @@ -948,7 +948,7 @@ func TestGetDutiesForEpoch_Valid(t *testing.T) { ProposerSlots: expectedProposerSlots1, }, { - Committee: []types.ValidatorIndex{ + Committee: []primitives.ValidatorIndex{ validatorIndices[4], validatorIndices[5], }, @@ -1014,7 +1014,7 @@ func TestGetDutiesForEpoch_Valid(t *testing.T) { func TestGetDuties_Valid(t *testing.T) { testCases := []struct { name string - epoch types.Epoch + epoch primitives.Epoch }{ { name: "genesis epoch", @@ -1029,10 +1029,10 @@ func TestGetDuties_Valid(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { pubkeys := [][]byte{{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}} - validatorIndices := []types.ValidatorIndex{13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24} - committeeIndices := []types.CommitteeIndex{25, 26, 27} - committeeSlots := []types.Slot{28, 29, 30} - proposerSlots := []types.Slot{31, 32, 33, 34, 35, 36, 37, 38} + validatorIndices := []primitives.ValidatorIndex{13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24} + committeeIndices := []primitives.CommitteeIndex{25, 26, 27} + committeeSlots := []primitives.Slot{28, 29, 30} + proposerSlots := []primitives.Slot{31, 32, 33, 34, 35, 36, 37, 38} statuses := []ethpb.ValidatorStatus{ ethpb.ValidatorStatus_DEPOSITED, @@ -1347,7 +1347,7 @@ func TestGetDuties_GetDutiesForEpochFailed(t *testing.T) { dutiesProvider := mock.NewMockdutiesProvider(ctrl) dutiesProvider.EXPECT().GetAttesterDuties( ctx, - types.Epoch(1), + primitives.Epoch(1), gomock.Any(), ).Return( nil, @@ -1367,7 +1367,7 @@ func TestGetDuties_GetDutiesForEpochFailed(t *testing.T) { assert.ErrorContains(t, "foo error", err) } -func generateValidCommittees(committeeIndices []types.CommitteeIndex, slots []types.Slot, validatorIndices []types.ValidatorIndex) []*apimiddleware.CommitteeJson { +func generateValidCommittees(committeeIndices []primitives.CommitteeIndex, slots []primitives.Slot, validatorIndices []primitives.ValidatorIndex) []*apimiddleware.CommitteeJson { return []*apimiddleware.CommitteeJson{ { Index: strconv.FormatUint(uint64(committeeIndices[0]), 10), @@ -1396,7 +1396,7 @@ func generateValidCommittees(committeeIndices []types.CommitteeIndex, slots []ty } } -func generateValidAttesterDuties(pubkeys [][]byte, validatorIndices []types.ValidatorIndex, committeeIndices []types.CommitteeIndex, slots []types.Slot) []*apimiddleware.AttesterDutyJson { +func generateValidAttesterDuties(pubkeys [][]byte, validatorIndices []primitives.ValidatorIndex, committeeIndices []primitives.CommitteeIndex, slots []primitives.Slot) []*apimiddleware.AttesterDutyJson { return []*apimiddleware.AttesterDutyJson{ { Pubkey: hexutil.Encode(pubkeys[0]), @@ -1437,7 +1437,7 @@ func generateValidAttesterDuties(pubkeys [][]byte, validatorIndices []types.Vali } } -func generateValidProposerDuties(pubkeys [][]byte, validatorIndices []types.ValidatorIndex, slots []types.Slot) []*apimiddleware.ProposerDutyJson { +func generateValidProposerDuties(pubkeys [][]byte, validatorIndices []primitives.ValidatorIndex, slots []primitives.Slot) []*apimiddleware.ProposerDutyJson { return []*apimiddleware.ProposerDutyJson{ { Pubkey: hexutil.Encode(pubkeys[4]), @@ -1482,7 +1482,7 @@ func generateValidProposerDuties(pubkeys [][]byte, validatorIndices []types.Vali } } -func generateValidSyncDuties(pubkeys [][]byte, validatorIndices []types.ValidatorIndex) []*apimiddleware.SyncCommitteeDuty { +func generateValidSyncDuties(pubkeys [][]byte, validatorIndices []primitives.ValidatorIndex) []*apimiddleware.SyncCommitteeDuty { return []*apimiddleware.SyncCommitteeDuty{ { Pubkey: hexutil.Encode(pubkeys[5]), diff --git a/validator/client/beacon-api/get_beacon_block.go b/validator/client/beacon-api/get_beacon_block.go index dd55874c56..cc51a37c86 100644 --- a/validator/client/beacon-api/get_beacon_block.go +++ b/validator/client/beacon-api/get_beacon_block.go @@ -12,7 +12,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -23,7 +23,7 @@ type abstractProduceBlockResponseJson struct { Data json.RawMessage `json:"data"` } -func (c beaconApiValidatorClient) getBeaconBlock(ctx context.Context, slot types.Slot, randaoReveal []byte, graffiti []byte) (*ethpb.GenericBeaconBlock, error) { +func (c beaconApiValidatorClient) getBeaconBlock(ctx context.Context, slot primitives.Slot, randaoReveal []byte, graffiti []byte) (*ethpb.GenericBeaconBlock, error) { queryParams := neturl.Values{} queryParams.Add("randao_reveal", hexutil.Encode(randaoReveal)) @@ -182,8 +182,8 @@ func convertRESTPhase0BlockToProto(block *apimiddleware.BeaconBlockJson) (*ethpb return ðpb.GenericBeaconBlock_Phase0{ Phase0: ðpb.BeaconBlock{ - Slot: types.Slot(blockSlot), - ProposerIndex: types.ValidatorIndex(blockProposerIndex), + Slot: primitives.Slot(blockSlot), + ProposerIndex: primitives.ValidatorIndex(blockProposerIndex), ParentRoot: parentRoot, StateRoot: stateRoot, Body: ðpb.BeaconBlockBody{ diff --git a/validator/client/beacon-api/get_beacon_block_altair_test.go b/validator/client/beacon-api/get_beacon_block_altair_test.go index 7c2659ba20..824d3208da 100644 --- a/validator/client/beacon-api/get_beacon_block_altair_test.go +++ b/validator/client/beacon-api/get_beacon_block_altair_test.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/golang/mock/gomock" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -25,7 +25,7 @@ func TestGetBeaconBlock_AltairValid(t *testing.T) { altairBeaconBlockBytes, err := json.Marshal(test_helpers.GenerateJsonAltairBeaconBlock()) require.NoError(t, err) - const slot = types.Slot(1) + const slot = primitives.Slot(1) randaoReveal := []byte{2} graffiti := []byte{3} diff --git a/validator/client/beacon-api/get_beacon_block_bellatrix_test.go b/validator/client/beacon-api/get_beacon_block_bellatrix_test.go index fa11415e27..855bcf13fd 100644 --- a/validator/client/beacon-api/get_beacon_block_bellatrix_test.go +++ b/validator/client/beacon-api/get_beacon_block_bellatrix_test.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/golang/mock/gomock" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -25,7 +25,7 @@ func TestGetBeaconBlock_BellatrixValid(t *testing.T) { bellatrixBeaconBlockBytes, err := json.Marshal(test_helpers.GenerateJsonBellatrixBeaconBlock()) require.NoError(t, err) - const slot = types.Slot(1) + const slot = primitives.Slot(1) randaoReveal := []byte{2} graffiti := []byte{3} diff --git a/validator/client/beacon-api/get_beacon_block_capella_test.go b/validator/client/beacon-api/get_beacon_block_capella_test.go index 728cec3b5c..841c99528a 100644 --- a/validator/client/beacon-api/get_beacon_block_capella_test.go +++ b/validator/client/beacon-api/get_beacon_block_capella_test.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/golang/mock/gomock" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -25,7 +25,7 @@ func TestGetBeaconBlock_CapellaValid(t *testing.T) { capellaBeaconBlockBytes, err := json.Marshal(test_helpers.GenerateJsonCapellaBeaconBlock()) require.NoError(t, err) - const slot = types.Slot(1) + const slot = primitives.Slot(1) randaoReveal := []byte{2} graffiti := []byte{3} diff --git a/validator/client/beacon-api/get_beacon_block_phase0_test.go b/validator/client/beacon-api/get_beacon_block_phase0_test.go index 7850d74d40..9d5422b4f6 100644 --- a/validator/client/beacon-api/get_beacon_block_phase0_test.go +++ b/validator/client/beacon-api/get_beacon_block_phase0_test.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/golang/mock/gomock" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -25,7 +25,7 @@ func TestGetBeaconBlock_Phase0Valid(t *testing.T) { phase0BeaconBlockBytes, err := json.Marshal(test_helpers.GenerateJsonPhase0BeaconBlock()) require.NoError(t, err) - const slot = types.Slot(1) + const slot = primitives.Slot(1) randaoReveal := []byte{2} graffiti := []byte{3} ctx := context.Background() diff --git a/validator/client/beacon-api/index.go b/validator/client/beacon-api/index.go index e5b6f6be4d..1943b3521b 100644 --- a/validator/client/beacon-api/index.go +++ b/validator/client/beacon-api/index.go @@ -6,7 +6,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/pkg/errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -29,5 +29,5 @@ func (c beaconApiValidatorClient) validatorIndex(ctx context.Context, in *ethpb. return nil, errors.Wrap(err, "failed to parse validator index") } - return ðpb.ValidatorIndexResponse{Index: types.ValidatorIndex(index)}, nil + return ðpb.ValidatorIndexResponse{Index: primitives.ValidatorIndex(index)}, nil } diff --git a/validator/client/beacon-api/index_test.go b/validator/client/beacon-api/index_test.go index eb734975a0..a512753e6e 100644 --- a/validator/client/beacon-api/index_test.go +++ b/validator/client/beacon-api/index_test.go @@ -9,7 +9,7 @@ import ( "github.com/golang/mock/gomock" "github.com/pkg/errors" rpcmiddleware "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -74,7 +74,7 @@ func TestIndex_Nominal(t *testing.T) { ) require.NoError(t, err) - assert.Equal(t, types.ValidatorIndex(55293), validatorIndex.Index) + assert.Equal(t, primitives.ValidatorIndex(55293), validatorIndex.Index) } func TestIndex_UnexistingValidator(t *testing.T) { diff --git a/validator/client/beacon-api/status.go b/validator/client/beacon-api/status.go index 48f871561e..a7aadca2db 100644 --- a/validator/client/beacon-api/status.go +++ b/validator/client/beacon-api/status.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -41,7 +41,7 @@ func (c *beaconApiValidatorClient) multipleValidatorStatus(ctx context.Context, func (c *beaconApiValidatorClient) getValidatorsStatusResponse(ctx context.Context, inPubKeys [][]byte, inIndexes []int64) ( [][]byte, - []types.ValidatorIndex, + []primitives.ValidatorIndex, []*ethpb.ValidatorStatusResponse, error, ) { @@ -58,7 +58,7 @@ func (c *beaconApiValidatorClient) getValidatorsStatusResponse(ctx context.Conte totalLen := len(inPubKeys) + len(inIndexes) outPubKeys := make([][]byte, totalLen) - outIndexes := make([]types.ValidatorIndex, totalLen) + outIndexes := make([]primitives.ValidatorIndex, totalLen) outValidatorsStatuses := make([]*ethpb.ValidatorStatusResponse, totalLen) for index, publicKey := range inPubKeys { @@ -96,7 +96,7 @@ func (c *beaconApiValidatorClient) getValidatorsStatusResponse(ctx context.Conte } outPubKeys[i] = pubKey - outIndexes[i] = types.ValidatorIndex(validatorIndex) + outIndexes[i] = primitives.ValidatorIndex(validatorIndex) validatorStatus := ðpb.ValidatorStatusResponse{} @@ -114,7 +114,7 @@ func (c *beaconApiValidatorClient) getValidatorsStatusResponse(ctx context.Conte return nil, nil, nil, errors.Wrapf(err, "failed to parse activation epoch %s", validatorContainer.Validator.ActivationEpoch) } - validatorStatus.ActivationEpoch = types.Epoch(activationEpoch) + validatorStatus.ActivationEpoch = primitives.Epoch(activationEpoch) // Set PositionInActivationQueue switch status { @@ -156,7 +156,7 @@ func (c *beaconApiValidatorClient) getValidatorsStatusResponse(ctx context.Conte for i, missingPubKey := range missingPubKeys { outPubKeys[nbStringRetrievedPubKeys+i] = missingPubKey - outIndexes[nbStringRetrievedPubKeys+i] = types.ValidatorIndex(^uint64(0)) + outIndexes[nbStringRetrievedPubKeys+i] = primitives.ValidatorIndex(^uint64(0)) outValidatorsStatuses[nbStringRetrievedPubKeys+i] = ðpb.ValidatorStatusResponse{ Status: ethpb.ValidatorStatus_UNKNOWN_STATUS, diff --git a/validator/client/beacon-api/status_test.go b/validator/client/beacon-api/status_test.go index 22612508b8..93e79c47d2 100644 --- a/validator/client/beacon-api/status_test.go +++ b/validator/client/beacon-api/status_test.go @@ -10,7 +10,7 @@ import ( "github.com/golang/mock/gomock" rpcmiddleware "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -151,7 +151,7 @@ func TestMultipleValidatorStatus_Nominal(t *testing.T) { expectedValidatorStatusResponse := ethpb.MultipleValidatorStatusResponse{ PublicKeys: validatorsPubKey, - Indices: []types.ValidatorIndex{ + Indices: []primitives.ValidatorIndex{ 11111, 22222, }, @@ -336,14 +336,14 @@ func TestGetValidatorsStatusResponse_Nominal_SomeActiveValidators(t *testing.T) wantedValidatorsPubKey[i] = validatorPubKey } - wantedValidatorsIndex := []types.ValidatorIndex{ + wantedValidatorsIndex := []primitives.ValidatorIndex{ 11111, 22222, 33333, 40000, 50000, - types.ValidatorIndex(^uint64(0)), - types.ValidatorIndex(^uint64(0)), + primitives.ValidatorIndex(^uint64(0)), + primitives.ValidatorIndex(^uint64(0)), } wantedValidatorsStatusResponse := []*ethpb.ValidatorStatusResponse{ @@ -433,7 +433,7 @@ func TestGetValidatorsStatusResponse_Nominal_NoActiveValidators(t *testing.T) { ).Times(1) wantedValidatorsPubKey := [][]byte{validatorPubKey} - wantedValidatorsIndex := []types.ValidatorIndex{40000} + wantedValidatorsIndex := []primitives.ValidatorIndex{40000} wantedValidatorsStatusResponse := []*ethpb.ValidatorStatusResponse{ { Status: ethpb.ValidatorStatus_PENDING, diff --git a/validator/client/beacon-api/subscribe_committee_subnets.go b/validator/client/beacon-api/subscribe_committee_subnets.go index 9baa6a584a..473199148a 100644 --- a/validator/client/beacon-api/subscribe_committee_subnets.go +++ b/validator/client/beacon-api/subscribe_committee_subnets.go @@ -8,12 +8,12 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" ) -func (c beaconApiValidatorClient) subscribeCommitteeSubnets(ctx context.Context, in *ethpb.CommitteeSubnetsSubscribeRequest, validatorIndices []types.ValidatorIndex) error { +func (c beaconApiValidatorClient) subscribeCommitteeSubnets(ctx context.Context, in *ethpb.CommitteeSubnetsSubscribeRequest, validatorIndices []primitives.ValidatorIndex) error { if in == nil { return errors.New("committee subnets subscribe request is nil") } @@ -22,7 +22,7 @@ func (c beaconApiValidatorClient) subscribeCommitteeSubnets(ctx context.Context, return errors.New("arrays `in.CommitteeIds`, `in.Slots`, `in.IsAggregator` and `validatorIndices` don't have the same length") } - slotToCommitteesAtSlotMap := make(map[types.Slot]uint64) + slotToCommitteesAtSlotMap := make(map[primitives.Slot]uint64) jsonCommitteeSubscriptions := make([]*apimiddleware.BeaconCommitteeSubscribeJson, len(in.CommitteeIds)) for index := range in.CommitteeIds { subscribeSlot := in.Slots[index] @@ -50,7 +50,7 @@ func (c beaconApiValidatorClient) subscribeCommitteeSubnets(ctx context.Context, return errors.Wrapf(err, "failed to parse CommitteesAtSlot `%s`", duty.CommitteesAtSlot) } - slotToCommitteesAtSlotMap[types.Slot(dutySlot)] = committees + slotToCommitteesAtSlotMap[primitives.Slot(dutySlot)] = committees } // If the slot still isn't in the map, we either received bad data from the beacon node or the caller of this function gave us bad data diff --git a/validator/client/beacon-api/subscribe_committee_subnets_test.go b/validator/client/beacon-api/subscribe_committee_subnets_test.go index d45c8f9fe7..c56e993dfc 100644 --- a/validator/client/beacon-api/subscribe_committee_subnets_test.go +++ b/validator/client/beacon-api/subscribe_committee_subnets_test.go @@ -10,7 +10,7 @@ import ( "github.com/golang/mock/gomock" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -21,11 +21,11 @@ import ( const subscribeCommitteeSubnetsTestEndpoint = "/eth/v1/validator/beacon_committee_subscriptions" func TestSubscribeCommitteeSubnets_Valid(t *testing.T) { - subscribeSlots := []types.Slot{0, 1, 100} - validatorIndices := []types.ValidatorIndex{2, 3, 4} + subscribeSlots := []primitives.Slot{0, 1, 100} + validatorIndices := []primitives.ValidatorIndex{2, 3, 4} committeesAtSlot := []uint64{5, 6, 7} isAggregator := []bool{false, true, false} - committeeIndices := []types.CommitteeIndex{8, 9, 10} + committeeIndices := []primitives.CommitteeIndex{8, 9, 10} ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -124,7 +124,7 @@ func TestSubscribeCommitteeSubnets_Error(t *testing.T) { testCases := []struct { name string subscribeRequest *ethpb.CommitteeSubnetsSubscribeRequest - validatorIndices []types.ValidatorIndex + validatorIndices []primitives.ValidatorIndex attesterDuty *apimiddleware.AttesterDutyJson dutiesError error expectGetDutiesQuery bool @@ -139,51 +139,51 @@ func TestSubscribeCommitteeSubnets_Error(t *testing.T) { { name: "CommitteeIds size mismatch", subscribeRequest: ðpb.CommitteeSubnetsSubscribeRequest{ - CommitteeIds: []types.CommitteeIndex{1}, - Slots: []types.Slot{1, 2}, + CommitteeIds: []primitives.CommitteeIndex{1}, + Slots: []primitives.Slot{1, 2}, IsAggregator: []bool{false, true}, }, - validatorIndices: []types.ValidatorIndex{1, 2}, + validatorIndices: []primitives.ValidatorIndex{1, 2}, expectedErrorMessage: arraySizeMismatchErrorMessage, }, { name: "Slots size mismatch", subscribeRequest: ðpb.CommitteeSubnetsSubscribeRequest{ - CommitteeIds: []types.CommitteeIndex{1, 2}, - Slots: []types.Slot{1}, + CommitteeIds: []primitives.CommitteeIndex{1, 2}, + Slots: []primitives.Slot{1}, IsAggregator: []bool{false, true}, }, - validatorIndices: []types.ValidatorIndex{1, 2}, + validatorIndices: []primitives.ValidatorIndex{1, 2}, expectedErrorMessage: arraySizeMismatchErrorMessage, }, { name: "IsAggregator size mismatch", subscribeRequest: ðpb.CommitteeSubnetsSubscribeRequest{ - CommitteeIds: []types.CommitteeIndex{1, 2}, - Slots: []types.Slot{1, 2}, + CommitteeIds: []primitives.CommitteeIndex{1, 2}, + Slots: []primitives.Slot{1, 2}, IsAggregator: []bool{false}, }, - validatorIndices: []types.ValidatorIndex{1, 2}, + validatorIndices: []primitives.ValidatorIndex{1, 2}, expectedErrorMessage: arraySizeMismatchErrorMessage, }, { name: "ValidatorIndices size mismatch", subscribeRequest: ðpb.CommitteeSubnetsSubscribeRequest{ - CommitteeIds: []types.CommitteeIndex{1, 2}, - Slots: []types.Slot{1, 2}, + CommitteeIds: []primitives.CommitteeIndex{1, 2}, + Slots: []primitives.Slot{1, 2}, IsAggregator: []bool{false, true}, }, - validatorIndices: []types.ValidatorIndex{1}, + validatorIndices: []primitives.ValidatorIndex{1}, expectedErrorMessage: arraySizeMismatchErrorMessage, }, { name: "bad duties query", subscribeRequest: ðpb.CommitteeSubnetsSubscribeRequest{ - Slots: []types.Slot{1}, - CommitteeIds: []types.CommitteeIndex{2}, + Slots: []primitives.Slot{1}, + CommitteeIds: []primitives.CommitteeIndex{2}, IsAggregator: []bool{false}, }, - validatorIndices: []types.ValidatorIndex{3}, + validatorIndices: []primitives.ValidatorIndex{3}, dutiesError: errors.New("foo error"), expectGetDutiesQuery: true, expectedErrorMessage: "failed to get duties for epoch `0`: foo error", @@ -191,11 +191,11 @@ func TestSubscribeCommitteeSubnets_Error(t *testing.T) { { name: "bad duty slot", subscribeRequest: ðpb.CommitteeSubnetsSubscribeRequest{ - Slots: []types.Slot{1}, - CommitteeIds: []types.CommitteeIndex{2}, + Slots: []primitives.Slot{1}, + CommitteeIds: []primitives.CommitteeIndex{2}, IsAggregator: []bool{false}, }, - validatorIndices: []types.ValidatorIndex{3}, + validatorIndices: []primitives.ValidatorIndex{3}, attesterDuty: &apimiddleware.AttesterDutyJson{ Slot: "foo", CommitteesAtSlot: "1", @@ -206,11 +206,11 @@ func TestSubscribeCommitteeSubnets_Error(t *testing.T) { { name: "bad duty committees at slot", subscribeRequest: ðpb.CommitteeSubnetsSubscribeRequest{ - Slots: []types.Slot{1}, - CommitteeIds: []types.CommitteeIndex{2}, + Slots: []primitives.Slot{1}, + CommitteeIds: []primitives.CommitteeIndex{2}, IsAggregator: []bool{false}, }, - validatorIndices: []types.ValidatorIndex{3}, + validatorIndices: []primitives.ValidatorIndex{3}, attesterDuty: &apimiddleware.AttesterDutyJson{ Slot: "1", CommitteesAtSlot: "foo", @@ -221,11 +221,11 @@ func TestSubscribeCommitteeSubnets_Error(t *testing.T) { { name: "missing slot in duties", subscribeRequest: ðpb.CommitteeSubnetsSubscribeRequest{ - Slots: []types.Slot{1}, - CommitteeIds: []types.CommitteeIndex{2}, + Slots: []primitives.Slot{1}, + CommitteeIds: []primitives.CommitteeIndex{2}, IsAggregator: []bool{false}, }, - validatorIndices: []types.ValidatorIndex{3}, + validatorIndices: []primitives.ValidatorIndex{3}, attesterDuty: &apimiddleware.AttesterDutyJson{ Slot: "2", CommitteesAtSlot: "3", @@ -236,11 +236,11 @@ func TestSubscribeCommitteeSubnets_Error(t *testing.T) { { name: "bad POST request", subscribeRequest: ðpb.CommitteeSubnetsSubscribeRequest{ - Slots: []types.Slot{1}, - CommitteeIds: []types.CommitteeIndex{2}, + Slots: []primitives.Slot{1}, + CommitteeIds: []primitives.CommitteeIndex{2}, IsAggregator: []bool{false}, }, - validatorIndices: []types.ValidatorIndex{3}, + validatorIndices: []primitives.ValidatorIndex{3}, attesterDuty: &apimiddleware.AttesterDutyJson{ Slot: "1", CommitteesAtSlot: "2", diff --git a/validator/client/beacon-api/sync_committee.go b/validator/client/beacon-api/sync_committee.go index 267bc5ce71..385413bde0 100644 --- a/validator/client/beacon-api/sync_committee.go +++ b/validator/client/beacon-api/sync_committee.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -119,7 +119,7 @@ func convertSyncContributionJsonToProto(contribution *apimiddleware.SyncCommitte } return ðpb.SyncCommitteeContribution{ - Slot: types.Slot(slot), + Slot: primitives.Slot(slot), BlockRoot: blockRoot, SubcommitteeIndex: subcommitteeIdx, AggregationBits: aggregationBits, diff --git a/validator/client/beacon-api/sync_committee_test.go b/validator/client/beacon-api/sync_committee_test.go index eca32beac8..39ef98f4ef 100644 --- a/validator/client/beacon-api/sync_committee_test.go +++ b/validator/client/beacon-api/sync_committee_test.go @@ -12,7 +12,7 @@ import ( "github.com/golang/protobuf/ptypes/empty" "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/apimiddleware" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -55,9 +55,9 @@ func TestSubmitSyncMessage_Valid(t *testing.T) { ).Times(1) protoSyncCommiteeMessage := ethpb.SyncCommitteeMessage{ - Slot: types.Slot(42), + Slot: primitives.Slot(42), BlockRoot: decodedBeaconBlockRoot, - ValidatorIndex: types.ValidatorIndex(12345), + ValidatorIndex: primitives.ValidatorIndex(12345), Signature: decodedSignature, } @@ -176,7 +176,7 @@ func TestGetSyncCommitteeContribution(t *testing.T) { const blockRoot = "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2" request := ðpb.SyncCommitteeContributionRequest{ - Slot: types.Slot(1), + Slot: primitives.Slot(1), PublicKey: nil, SubnetId: 1, } diff --git a/validator/client/grpc-api/grpc_validator_client.go b/validator/client/grpc-api/grpc_validator_client.go index f051bf7d57..c7e1fc7843 100644 --- a/validator/client/grpc-api/grpc_validator_client.go +++ b/validator/client/grpc-api/grpc_validator_client.go @@ -5,9 +5,9 @@ import ( "github.com/golang/protobuf/ptypes/empty" "github.com/pkg/errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" - iface "github.com/prysmaticlabs/prysm/v3/validator/client/iface" + "github.com/prysmaticlabs/prysm/v3/validator/client/iface" "google.golang.org/grpc" ) @@ -99,7 +99,7 @@ func (c *grpcValidatorClient) SubmitValidatorRegistrations(ctx context.Context, return c.beaconNodeValidatorClient.SubmitValidatorRegistrations(ctx, in) } -func (c *grpcValidatorClient) SubscribeCommitteeSubnets(ctx context.Context, in *ethpb.CommitteeSubnetsSubscribeRequest, _ []types.ValidatorIndex) (*empty.Empty, error) { +func (c *grpcValidatorClient) SubscribeCommitteeSubnets(ctx context.Context, in *ethpb.CommitteeSubnetsSubscribeRequest, _ []primitives.ValidatorIndex) (*empty.Empty, error) { return c.beaconNodeValidatorClient.SubscribeCommitteeSubnets(ctx, in) } diff --git a/validator/client/iface/validator.go b/validator/client/iface/validator.go index c219f2f6a7..9d2f9330ef 100644 --- a/validator/client/iface/validator.go +++ b/validator/client/iface/validator.go @@ -7,7 +7,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" validatorserviceconfig "github.com/prysmaticlabs/prysm/v3/config/validator/service" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" validatorpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/validator-client" @@ -41,20 +41,20 @@ type Validator interface { WaitForChainStart(ctx context.Context) error WaitForSync(ctx context.Context) error WaitForActivation(ctx context.Context, accountsChangedChan chan [][fieldparams.BLSPubkeyLength]byte) error - CanonicalHeadSlot(ctx context.Context) (types.Slot, error) - NextSlot() <-chan types.Slot - SlotDeadline(slot types.Slot) time.Time - LogValidatorGainsAndLosses(ctx context.Context, slot types.Slot) error - UpdateDuties(ctx context.Context, slot types.Slot) error - RolesAt(ctx context.Context, slot types.Slot) (map[[fieldparams.BLSPubkeyLength]byte][]ValidatorRole, error) // validator pubKey -> roles - SubmitAttestation(ctx context.Context, slot types.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) - ProposeBlock(ctx context.Context, slot types.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) - SubmitAggregateAndProof(ctx context.Context, slot types.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) - SubmitSyncCommitteeMessage(ctx context.Context, slot types.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) - SubmitSignedContributionAndProof(ctx context.Context, slot types.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) + CanonicalHeadSlot(ctx context.Context) (primitives.Slot, error) + NextSlot() <-chan primitives.Slot + SlotDeadline(slot primitives.Slot) time.Time + LogValidatorGainsAndLosses(ctx context.Context, slot primitives.Slot) error + UpdateDuties(ctx context.Context, slot primitives.Slot) error + RolesAt(ctx context.Context, slot primitives.Slot) (map[[fieldparams.BLSPubkeyLength]byte][]ValidatorRole, error) // validator pubKey -> roles + SubmitAttestation(ctx context.Context, slot primitives.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) + ProposeBlock(ctx context.Context, slot primitives.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) + SubmitAggregateAndProof(ctx context.Context, slot primitives.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) + SubmitSyncCommitteeMessage(ctx context.Context, slot primitives.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) + SubmitSignedContributionAndProof(ctx context.Context, slot primitives.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) LogAttestationsSubmitted() LogSyncCommitteeMessagesSubmitted() - UpdateDomainDataCaches(ctx context.Context, slot types.Slot) + UpdateDomainDataCaches(ctx context.Context, slot primitives.Slot) WaitForKeymanagerInitialization(ctx context.Context) error AllValidatorsAreExited(ctx context.Context) (bool, error) Keymanager() (keymanager.IKeymanager, error) diff --git a/validator/client/iface/validator_client.go b/validator/client/iface/validator_client.go index d71edc5f0f..36027deb7e 100644 --- a/validator/client/iface/validator_client.go +++ b/validator/client/iface/validator_client.go @@ -4,7 +4,7 @@ import ( "context" "github.com/golang/protobuf/ptypes/empty" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -26,7 +26,7 @@ type ValidatorClient interface { SubmitAggregateSelectionProof(ctx context.Context, in *ethpb.AggregateSelectionRequest) (*ethpb.AggregateSelectionResponse, error) SubmitSignedAggregateSelectionProof(ctx context.Context, in *ethpb.SignedAggregateSubmitRequest) (*ethpb.SignedAggregateSubmitResponse, error) ProposeExit(ctx context.Context, in *ethpb.SignedVoluntaryExit) (*ethpb.ProposeExitResponse, error) - SubscribeCommitteeSubnets(ctx context.Context, in *ethpb.CommitteeSubnetsSubscribeRequest, validatorIndices []types.ValidatorIndex) (*empty.Empty, error) + SubscribeCommitteeSubnets(ctx context.Context, in *ethpb.CommitteeSubnetsSubscribeRequest, validatorIndices []primitives.ValidatorIndex) (*empty.Empty, error) CheckDoppelGanger(ctx context.Context, in *ethpb.DoppelGangerRequest) (*ethpb.DoppelGangerResponse, error) GetSyncMessageBlockRoot(ctx context.Context, in *empty.Empty) (*ethpb.SyncMessageBlockRootResponse, error) SubmitSyncMessage(ctx context.Context, in *ethpb.SyncCommitteeMessage) (*empty.Empty, error) diff --git a/validator/client/log.go b/validator/client/log.go index 743a0e42b3..d9062fe727 100644 --- a/validator/client/log.go +++ b/validator/client/log.go @@ -4,7 +4,7 @@ import ( "fmt" "sync/atomic" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/sirupsen/logrus" @@ -14,8 +14,8 @@ var log = logrus.WithField("prefix", "validator") type attSubmitted struct { data *ethpb.AttestationData - attesterIndices []types.ValidatorIndex - aggregatorIndices []types.ValidatorIndex + attesterIndices []primitives.ValidatorIndex + aggregatorIndices []primitives.ValidatorIndex } // LogAttestationsSubmitted logs info about submitted attestations. diff --git a/validator/client/metrics.go b/validator/client/metrics.go index 693fbfdc0f..27bfdbc34a 100644 --- a/validator/client/metrics.go +++ b/validator/client/metrics.go @@ -8,7 +8,7 @@ import ( "github.com/prometheus/client_golang/prometheus/promauto" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" @@ -218,7 +218,7 @@ var ( // responsibilities throughout the beacon chain's lifecycle. It logs absolute accrued rewards // and penalties over time, percentage gain/loss, and gives the end user a better idea // of how the validator performs with respect to the rest. -func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot types.Slot) error { +func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot primitives.Slot) error { if !slots.IsEpochEnd(slot) || slot <= params.BeaconConfig().SlotsPerEpoch { // Do nothing unless we are at the end of the epoch, and not in the first epoch. return nil @@ -250,9 +250,9 @@ func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot types.S } } - prevEpoch := types.Epoch(0) + prevEpoch := primitives.Epoch(0) if slot >= params.BeaconConfig().SlotsPerEpoch { - prevEpoch = types.Epoch(slot/params.BeaconConfig().SlotsPerEpoch) - 1 + prevEpoch = primitives.Epoch(slot/params.BeaconConfig().SlotsPerEpoch) - 1 if uint64(v.voteStats.startEpoch) == ^uint64(0) { // Handles unknown first epoch. v.voteStats.startEpoch = prevEpoch } @@ -267,7 +267,7 @@ func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot types.S return nil } -func (v *validator) logForEachValidator(index int, pubKey []byte, resp *ethpb.ValidatorPerformanceResponse, slot types.Slot, prevEpoch types.Epoch) { +func (v *validator) logForEachValidator(index int, pubKey []byte, resp *ethpb.ValidatorPerformanceResponse, slot primitives.Slot, prevEpoch primitives.Epoch) { truncatedKey := fmt.Sprintf("%#x", bytesutil.Trunc(pubKey)) pubKeyBytes := bytesutil.ToBytes48(pubKey) if slot < params.BeaconConfig().SlotsPerEpoch { @@ -371,9 +371,9 @@ func (v *validator) logForEachValidator(index int, pubKey []byte, resp *ethpb.Va } // 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 types.Slot) { +func (v *validator) UpdateLogAggregateStats(resp *ethpb.ValidatorPerformanceResponse, slot primitives.Slot) { summary := &v.voteStats - currentEpoch := types.Epoch(slot / params.BeaconConfig().SlotsPerEpoch) + currentEpoch := primitives.Epoch(slot / params.BeaconConfig().SlotsPerEpoch) var attested, correctSource, correctTarget, correctHead, inactivityScore int for i := range resp.PublicKeys { diff --git a/validator/client/metrics_test.go b/validator/client/metrics_test.go index a618bb8265..18dedb6831 100644 --- a/validator/client/metrics_test.go +++ b/validator/client/metrics_test.go @@ -5,7 +5,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -76,7 +76,7 @@ func TestUpdateLogAggregateStats(t *testing.T) { if i == len(responses)-1 { // Handle last log. hook = logTest.NewGlobal() } - v.UpdateLogAggregateStats(val, params.BeaconConfig().SlotsPerEpoch*types.Slot(i+1)) + v.UpdateLogAggregateStats(val, params.BeaconConfig().SlotsPerEpoch*primitives.Slot(i+1)) } require.LogsContain(t, hook, "msg=\"Previous epoch aggregated voting summary\" attestationInclusionPct=\"67%\" "+ @@ -154,7 +154,7 @@ func TestUpdateLogAltairAggregateStats(t *testing.T) { altairStart, err := slots.EpochStart(params.BeaconConfig().AltairForkEpoch) require.NoError(t, err) - v.UpdateLogAggregateStats(val, altairStart+params.BeaconConfig().SlotsPerEpoch*types.Slot(i+1)) + v.UpdateLogAggregateStats(val, altairStart+params.BeaconConfig().SlotsPerEpoch*primitives.Slot(i+1)) } require.LogsContain(t, hook, "msg=\"Previous epoch aggregated voting summary\" attestationInclusionPct=\"67%\" "+ diff --git a/validator/client/propose.go b/validator/client/propose.go index a5510bc25c..7bbdbbceea 100644 --- a/validator/client/propose.go +++ b/validator/client/propose.go @@ -13,7 +13,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/rand" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -37,7 +37,7 @@ const signExitErr = "could not sign voluntary exit proposal" // chain node to construct the new block. The new block is then processed with // the state root computation, and finally signed by the validator before being // sent back to the beacon node for broadcasting. -func (v *validator) ProposeBlock(ctx context.Context, slot types.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) { +func (v *validator) ProposeBlock(ctx context.Context, slot primitives.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) { if slot == 0 { log.Debug("Assigned to genesis slot, skipping proposal") return @@ -54,7 +54,7 @@ func (v *validator) ProposeBlock(ctx context.Context, slot types.Slot, pubKey [f log := log.WithField("pubKey", fmt.Sprintf("%#x", bytesutil.Trunc(pubKey[:]))) // Sign randao reveal, it's used to request block from beacon node - epoch := types.Epoch(slot / params.BeaconConfig().SlotsPerEpoch) + epoch := primitives.Epoch(slot / params.BeaconConfig().SlotsPerEpoch) randaoReveal, err := v.signRandaoReveal(ctx, pubKey, epoch, slot) if err != nil { log.WithError(err).Error("Failed to sign randao reveal") @@ -214,7 +214,7 @@ func ProposeExit( return errors.Wrap(err, "gRPC call to get genesis time failed") } totalSecondsPassed := prysmTime.Now().Unix() - genesisResponse.GenesisTime.Seconds - currentEpoch := types.Epoch(uint64(totalSecondsPassed) / uint64(params.BeaconConfig().SlotsPerEpoch.Mul(params.BeaconConfig().SecondsPerSlot))) + currentEpoch := primitives.Epoch(uint64(totalSecondsPassed) / uint64(params.BeaconConfig().SlotsPerEpoch.Mul(params.BeaconConfig().SecondsPerSlot))) currentSlot := slots.CurrentSlot(uint64(genesisResponse.GenesisTime.AsTime().Unix())) exit := ðpb.VoluntaryExit{Epoch: currentEpoch, ValidatorIndex: indexResponse.Index} sig, err := signVoluntaryExit(ctx, validatorClient, signer, pubKey, exit, currentSlot) @@ -236,7 +236,7 @@ func ProposeExit( } // Sign randao reveal with randao domain and private key. -func (v *validator) signRandaoReveal(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, epoch types.Epoch, slot types.Slot) ([]byte, error) { +func (v *validator) signRandaoReveal(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, epoch primitives.Epoch, slot primitives.Slot) ([]byte, error) { domain, err := v.domainData(ctx, epoch, params.BeaconConfig().DomainRandao[:]) if err != nil { return nil, errors.Wrap(err, domainDataErr) @@ -246,7 +246,7 @@ func (v *validator) signRandaoReveal(ctx context.Context, pubKey [fieldparams.BL } var randaoReveal bls.Signature - sszUint := types.SSZUint64(epoch) + sszUint := primitives.SSZUint64(epoch) root, err := signing.ComputeSigningRoot(&sszUint, domain.SignatureDomain) if err != nil { return nil, err @@ -266,7 +266,7 @@ func (v *validator) signRandaoReveal(ctx context.Context, pubKey [fieldparams.BL // Sign block with proposer domain and private key. // Returns the signature, block signing root, and any error. -func (v *validator) signBlock(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, epoch types.Epoch, slot types.Slot, b interfaces.BeaconBlock) ([]byte, [32]byte, error) { +func (v *validator) signBlock(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, epoch primitives.Epoch, slot primitives.Slot, b interfaces.BeaconBlock) ([]byte, [32]byte, error) { domain, err := v.domainData(ctx, epoch, params.BeaconConfig().DomainBeaconProposer[:]) if err != nil { return nil, [32]byte{}, errors.Wrap(err, domainDataErr) @@ -303,7 +303,7 @@ func signVoluntaryExit( signer iface.SigningFunc, pubKey []byte, exit *ethpb.VoluntaryExit, - slot types.Slot, + slot primitives.Slot, ) ([]byte, error) { req := ðpb.DomainRequest{ Epoch: exit.Epoch, diff --git a/validator/client/propose_protect_test.go b/validator/client/propose_protect_test.go index 439e8d4da9..cbf6ca5a23 100644 --- a/validator/client/propose_protect_test.go +++ b/validator/client/propose_protect_test.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -20,7 +20,7 @@ func Test_slashableProposalCheck_PreventsLowerThanMinProposal(t *testing.T) { ctx := context.Background() validator, _, validatorKey, finish := setup(t) defer finish() - lowestSignedSlot := types.Slot(10) + lowestSignedSlot := primitives.Slot(10) var pubKeyBytes [fieldparams.BLSPubkeyLength]byte copy(pubKeyBytes[:], validatorKey.PublicKey().Marshal()) diff --git a/validator/client/propose_test.go b/validator/client/propose_test.go index 9aa4fb2e0e..73bf3703b8 100644 --- a/validator/client/propose_test.go +++ b/validator/client/propose_test.go @@ -16,7 +16,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" blocktest "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks/testing" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -151,7 +151,7 @@ func TestProposeBlock_RequestBlockFailed(t *testing.T) { tests := []struct { name string - slot types.Slot + slot primitives.Slot }{ { name: "phase 0", @@ -431,7 +431,7 @@ func TestProposeBlock_AllowsPastProposals(t *testing.T) { tests := []struct { name string - pastSlot types.Slot + pastSlot primitives.Slot }{ { name: "400 slots ago", @@ -949,7 +949,7 @@ func TestGetGraffiti_Ok(t *testing.T) { graffitiStruct: &graffiti.Graffiti{ Default: "c", Random: []string{"d", "e"}, - Specific: map[types.ValidatorIndex]string{ + Specific: map[primitives.ValidatorIndex]string{ 1: "f", 2: "g", }, @@ -982,7 +982,7 @@ func TestGetGraffiti_Ok(t *testing.T) { graffitiStruct: &graffiti.Graffiti{ Random: []string{"d"}, Default: "c", - Specific: map[types.ValidatorIndex]string{ + Specific: map[primitives.ValidatorIndex]string{ 1: "f", 2: "g", }, diff --git a/validator/client/registration_test.go b/validator/client/registration_test.go index 4d0cf652b9..9fbd5e36da 100644 --- a/validator/client/registration_test.go +++ b/validator/client/registration_test.go @@ -10,7 +10,7 @@ import ( "github.com/pkg/errors" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -109,7 +109,7 @@ func TestValidator_SignValidatorRegistrationRequest(t *testing.T) { }, validatorSetter: func(t *testing.T) *validator { v := validator{ - pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex), + pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex), signedValidatorRegistrations: make(map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1), useWeb: false, genesisTime: 0, @@ -137,7 +137,7 @@ func TestValidator_SignValidatorRegistrationRequest(t *testing.T) { }, validatorSetter: func(t *testing.T) *validator { v := validator{ - pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex), + pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex), signedValidatorRegistrations: make(map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1), useWeb: false, genesisTime: 0, @@ -165,7 +165,7 @@ func TestValidator_SignValidatorRegistrationRequest(t *testing.T) { }, validatorSetter: func(t *testing.T) *validator { v := validator{ - pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex), + pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex), signedValidatorRegistrations: make(map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1), useWeb: false, genesisTime: 0, @@ -193,7 +193,7 @@ func TestValidator_SignValidatorRegistrationRequest(t *testing.T) { }, validatorSetter: func(t *testing.T) *validator { v := validator{ - pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex), + pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex), signedValidatorRegistrations: make(map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1), useWeb: false, genesisTime: 0, diff --git a/validator/client/runner.go b/validator/client/runner.go index 305fcbe5a6..476556131b 100644 --- a/validator/client/runner.go +++ b/validator/client/runner.go @@ -10,7 +10,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/cmd/validator/flags" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/time/slots" "github.com/prysmaticlabs/prysm/v3/validator/client/iface" @@ -165,11 +165,11 @@ func reloadRemoteKeys(ctx context.Context, km keymanager.IKeymanager) { } } -func initializeValidatorAndGetHeadSlot(ctx context.Context, v iface.Validator) (types.Slot, error) { +func initializeValidatorAndGetHeadSlot(ctx context.Context, v iface.Validator) (primitives.Slot, error) { ticker := time.NewTicker(backOffPeriod) defer ticker.Stop() - var headSlot types.Slot + var headSlot primitives.Slot firstTime := true for { if !firstTime { @@ -231,7 +231,7 @@ func initializeValidatorAndGetHeadSlot(ctx context.Context, v iface.Validator) ( return headSlot, nil } -func performRoles(slotCtx context.Context, allRoles map[[48]byte][]iface.ValidatorRole, v iface.Validator, slot types.Slot, wg *sync.WaitGroup, span *trace.Span) { +func performRoles(slotCtx context.Context, allRoles map[[48]byte][]iface.ValidatorRole, v iface.Validator, slot primitives.Slot, wg *sync.WaitGroup, span *trace.Span) { for pubKey, roles := range allRoles { wg.Add(len(roles)) for _, role := range roles { @@ -281,7 +281,7 @@ func isConnectionError(err error) bool { return err != nil && errors.Is(err, iface.ErrConnectionIssue) } -func handleAssignmentError(err error, slot types.Slot) { +func handleAssignmentError(err error, slot primitives.Slot) { if errCode, ok := status.FromError(err); ok && errCode.Code() == codes.NotFound { log.WithField( "epoch", slot/params.BeaconConfig().SlotsPerEpoch, diff --git a/validator/client/runner_test.go b/validator/client/runner_test.go index cffafc9c2b..3869104410 100644 --- a/validator/client/runner_test.go +++ b/validator/client/runner_test.go @@ -11,7 +11,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" validatorserviceconfig "github.com/prysmaticlabs/prysm/v3/config/validator/service" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/validator/client/iface" @@ -69,8 +69,8 @@ func TestUpdateDuties_NextSlot(t *testing.T) { v := &testutil.FakeValidator{Km: &mockKeymanager{accountsChangedFeed: &event.Feed{}}} ctx, cancel := context.WithCancel(context.Background()) - slot := types.Slot(55) - ticker := make(chan types.Slot) + slot := primitives.Slot(55) + ticker := make(chan primitives.Slot) v.NextSlotRet = ticker go func() { ticker <- slot @@ -89,8 +89,8 @@ func TestUpdateDuties_HandlesError(t *testing.T) { v := &testutil.FakeValidator{Km: &mockKeymanager{accountsChangedFeed: &event.Feed{}}} ctx, cancel := context.WithCancel(context.Background()) - slot := types.Slot(55) - ticker := make(chan types.Slot) + slot := primitives.Slot(55) + ticker := make(chan primitives.Slot) v.NextSlotRet = ticker go func() { ticker <- slot @@ -108,8 +108,8 @@ func TestRoleAt_NextSlot(t *testing.T) { v := &testutil.FakeValidator{Km: &mockKeymanager{accountsChangedFeed: &event.Feed{}}} ctx, cancel := context.WithCancel(context.Background()) - slot := types.Slot(55) - ticker := make(chan types.Slot) + slot := primitives.Slot(55) + ticker := make(chan primitives.Slot) v.NextSlotRet = ticker go func() { ticker <- slot @@ -127,8 +127,8 @@ func TestAttests_NextSlot(t *testing.T) { v := &testutil.FakeValidator{Km: &mockKeymanager{accountsChangedFeed: &event.Feed{}}} ctx, cancel := context.WithCancel(context.Background()) - slot := types.Slot(55) - ticker := make(chan types.Slot) + slot := primitives.Slot(55) + ticker := make(chan primitives.Slot) v.NextSlotRet = ticker v.RolesAtRet = []iface.ValidatorRole{iface.RoleAttester} go func() { @@ -147,8 +147,8 @@ func TestProposes_NextSlot(t *testing.T) { v := &testutil.FakeValidator{Km: &mockKeymanager{accountsChangedFeed: &event.Feed{}}} ctx, cancel := context.WithCancel(context.Background()) - slot := types.Slot(55) - ticker := make(chan types.Slot) + slot := primitives.Slot(55) + ticker := make(chan primitives.Slot) v.NextSlotRet = ticker v.RolesAtRet = []iface.ValidatorRole{iface.RoleProposer} go func() { @@ -167,8 +167,8 @@ func TestBothProposesAndAttests_NextSlot(t *testing.T) { v := &testutil.FakeValidator{Km: &mockKeymanager{accountsChangedFeed: &event.Feed{}}} ctx, cancel := context.WithCancel(context.Background()) - slot := types.Slot(55) - ticker := make(chan types.Slot) + slot := primitives.Slot(55) + ticker := make(chan primitives.Slot) v.NextSlotRet = ticker v.RolesAtRet = []iface.ValidatorRole{iface.RoleAttester, iface.RoleProposer} go func() { @@ -190,8 +190,8 @@ func TestAllValidatorsAreExited_NextSlot(t *testing.T) { ctx, cancel := context.WithCancel(context.WithValue(context.Background(), testutil.AllValidatorsAreExitedCtxKey, true)) hook := logTest.NewGlobal() - slot := types.Slot(55) - ticker := make(chan types.Slot) + slot := primitives.Slot(55) + ticker := make(chan primitives.Slot) v.NextSlotRet = ticker go func() { ticker <- slot @@ -238,10 +238,10 @@ func TestKeyReload_RemoteKeymanager(t *testing.T) { km := mock.NewMock() v := &testutil.FakeValidator{Km: &km} - ticker := make(chan types.Slot) + ticker := make(chan primitives.Slot) v.NextSlotRet = ticker go func() { - ticker <- types.Slot(55) + ticker <- primitives.Slot(55) cancel() }() @@ -259,7 +259,7 @@ func TestUpdateProposerSettingsAt_EpochStart(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) hook := logTest.NewGlobal() slot := params.BeaconConfig().SlotsPerEpoch - ticker := make(chan types.Slot) + ticker := make(chan primitives.Slot) v.NextSlotRet = ticker go func() { ticker <- slot @@ -285,7 +285,7 @@ func TestUpdateProposerSettings_ContinuesAfterValidatorRegistrationFails(t *test ctx, cancel := context.WithCancel(context.Background()) hook := logTest.NewGlobal() slot := params.BeaconConfig().SlotsPerEpoch - ticker := make(chan types.Slot) + ticker := make(chan primitives.Slot) v.NextSlotRet = ticker go func() { ticker <- slot diff --git a/validator/client/service.go b/validator/client/service.go index 482ab0d68c..906eaa6b70 100644 --- a/validator/client/service.go +++ b/validator/client/service.go @@ -18,7 +18,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/config/params" validatorserviceconfig "github.com/prysmaticlabs/prysm/v3/config/validator/service" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/validator/accounts/wallet" "github.com/prysmaticlabs/prysm/v3/validator/client/iface" @@ -196,12 +196,12 @@ func (v *ValidatorService) Start() { emitAccountMetrics: v.emitAccountMetrics, startBalances: make(map[[fieldparams.BLSPubkeyLength]byte]uint64), prevBalance: make(map[[fieldparams.BLSPubkeyLength]byte]uint64), - pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex), + pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex), signedValidatorRegistrations: make(map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1), attLogs: make(map[[32]byte]*attSubmitted), domainDataCache: cache, aggregatedSlotCommitteeIDCache: aggregatedSlotCommitteeIDCache, - voteStats: voteStats{startEpoch: types.Epoch(^uint64(0))}, + voteStats: voteStats{startEpoch: primitives.Epoch(^uint64(0))}, syncCommitteeStats: syncCommitteeStats{}, useWeb: v.useWeb, interopKeysConfig: v.interopKeysConfig, diff --git a/validator/client/sync_committee.go b/validator/client/sync_committee.go index ddee00b30a..d65bc7122e 100644 --- a/validator/client/sync_committee.go +++ b/validator/client/sync_committee.go @@ -11,7 +11,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -22,7 +22,7 @@ import ( ) // SubmitSyncCommitteeMessage submits the sync committee message to the beacon chain. -func (v *validator) SubmitSyncCommitteeMessage(ctx context.Context, slot types.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) { +func (v *validator) SubmitSyncCommitteeMessage(ctx context.Context, slot primitives.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) { ctx, span := trace.StartSpan(ctx, "validator.SubmitSyncCommitteeMessage") defer span.End() span.AddAttributes(trace.StringAttribute("validator", fmt.Sprintf("%#x", pubKey))) @@ -47,7 +47,7 @@ func (v *validator) SubmitSyncCommitteeMessage(ctx context.Context, slot types.S log.WithError(err).Error("Could not get sync committee domain data") return } - sszRoot := types.SSZBytes(res.Root) + sszRoot := primitives.SSZBytes(res.Root) r, err := signing.ComputeSigningRoot(&sszRoot, d.SignatureDomain) if err != nil { log.WithError(err).Error("Could not get sync committee message signing root") @@ -92,7 +92,7 @@ func (v *validator) SubmitSyncCommitteeMessage(ctx context.Context, slot types.S } // SubmitSignedContributionAndProof submits the signed sync committee contribution and proof to the beacon chain. -func (v *validator) SubmitSignedContributionAndProof(ctx context.Context, slot types.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) { +func (v *validator) SubmitSignedContributionAndProof(ctx context.Context, slot primitives.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) { ctx, span := trace.StartSpan(ctx, "validator.SubmitSignedContributionAndProof") defer span.End() span.AddAttributes(trace.StringAttribute("validator", fmt.Sprintf("%#x", pubKey))) @@ -187,7 +187,7 @@ func (v *validator) SubmitSignedContributionAndProof(ctx context.Context, slot t } // Signs and returns selection proofs per validator for slot and pub key. -func (v *validator) selectionProofs(ctx context.Context, slot types.Slot, pubKey [fieldparams.BLSPubkeyLength]byte, indexRes *ethpb.SyncSubcommitteeIndexResponse) ([][]byte, error) { +func (v *validator) selectionProofs(ctx context.Context, slot primitives.Slot, pubKey [fieldparams.BLSPubkeyLength]byte, indexRes *ethpb.SyncSubcommitteeIndexResponse) ([][]byte, error) { selectionProofs := make([][]byte, len(indexRes.Indices)) cfg := params.BeaconConfig() size := cfg.SyncCommitteeSize @@ -205,7 +205,7 @@ func (v *validator) selectionProofs(ctx context.Context, slot types.Slot, pubKey } // Signs input slot with domain sync committee selection proof. This is used to create the signature for sync committee selection. -func (v *validator) signSyncSelectionData(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, index uint64, slot types.Slot) (signature []byte, err error) { +func (v *validator) signSyncSelectionData(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, index uint64, slot primitives.Slot) (signature []byte, err error) { domain, err := v.domainData(ctx, slots.ToEpoch(slot), params.BeaconConfig().DomainSyncCommitteeSelectionProof[:]) if err != nil { return nil, err @@ -232,7 +232,7 @@ func (v *validator) signSyncSelectionData(ctx context.Context, pubKey [fieldpara } // This returns the signature of validator signing over sync committee contribution and proof object. -func (v *validator) signContributionAndProof(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, c *ethpb.ContributionAndProof, slot types.Slot) ([]byte, error) { +func (v *validator) signContributionAndProof(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, c *ethpb.ContributionAndProof, slot primitives.Slot) ([]byte, error) { d, err := v.domainData(ctx, slots.ToEpoch(c.Contribution.Slot), params.BeaconConfig().DomainContributionAndProof[:]) if err != nil { return nil, err diff --git a/validator/client/sync_committee_test.go b/validator/client/sync_committee_test.go index e746b86368..7741ac21bb 100644 --- a/validator/client/sync_committee_test.go +++ b/validator/client/sync_committee_test.go @@ -9,7 +9,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/go-bitfield" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -42,8 +42,8 @@ func TestSubmitSyncCommitteeMessage_BadDomainData(t *testing.T) { validator, m, validatorKey, finish := setup(t) defer finish() hook := logTest.NewGlobal() - validatorIndex := types.ValidatorIndex(7) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(7) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ { PublicKey: validatorKey.PublicKey().Marshal(), @@ -74,8 +74,8 @@ func TestSubmitSyncCommitteeMessage_CouldNotSubmit(t *testing.T) { validator, m, validatorKey, finish := setup(t) defer finish() hook := logTest.NewGlobal() - validatorIndex := types.ValidatorIndex(7) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(7) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ { PublicKey: validatorKey.PublicKey().Marshal(), @@ -115,8 +115,8 @@ func TestSubmitSyncCommitteeMessage_OK(t *testing.T) { validator, m, validatorKey, finish := setup(t) defer finish() hook := logTest.NewGlobal() - validatorIndex := types.ValidatorIndex(7) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(7) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ { PublicKey: validatorKey.PublicKey().Marshal(), @@ -153,7 +153,7 @@ func TestSubmitSyncCommitteeMessage_OK(t *testing.T) { validator.SubmitSyncCommitteeMessage(context.Background(), 1, pubKey) require.LogsDoNotContain(t, hook, "Could not") - require.Equal(t, types.Slot(1), generatedMsg.Slot) + require.Equal(t, primitives.Slot(1), generatedMsg.Slot) require.Equal(t, validatorIndex, generatedMsg.ValidatorIndex) require.DeepEqual(t, bytesutil.PadTo(r, 32), generatedMsg.BlockRoot) } @@ -173,8 +173,8 @@ func TestSubmitSignedContributionAndProof_ValidatorDutiesRequestFailure(t *testi func TestSubmitSignedContributionAndProof_GetSyncSubcommitteeIndexFailure(t *testing.T) { hook := logTest.NewGlobal() validator, m, validatorKey, finish := setup(t) - validatorIndex := types.ValidatorIndex(7) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(7) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ { PublicKey: validatorKey.PublicKey().Marshal(), @@ -201,8 +201,8 @@ func TestSubmitSignedContributionAndProof_GetSyncSubcommitteeIndexFailure(t *tes func TestSubmitSignedContributionAndProof_NothingToDo(t *testing.T) { hook := logTest.NewGlobal() validator, m, validatorKey, finish := setup(t) - validatorIndex := types.ValidatorIndex(7) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(7) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ { PublicKey: validatorKey.PublicKey().Marshal(), @@ -220,7 +220,7 @@ func TestSubmitSignedContributionAndProof_NothingToDo(t *testing.T) { Slot: 1, PublicKey: pubKey[:], }, - ).Return(ðpb.SyncSubcommitteeIndexResponse{Indices: []types.CommitteeIndex{}}, nil) + ).Return(ðpb.SyncSubcommitteeIndexResponse{Indices: []primitives.CommitteeIndex{}}, nil) validator.SubmitSignedContributionAndProof(context.Background(), 1, pubKey) require.LogsContain(t, hook, "Empty subcommittee index list, do nothing") @@ -229,8 +229,8 @@ func TestSubmitSignedContributionAndProof_NothingToDo(t *testing.T) { func TestSubmitSignedContributionAndProof_BadDomain(t *testing.T) { hook := logTest.NewGlobal() validator, m, validatorKey, finish := setup(t) - validatorIndex := types.ValidatorIndex(7) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(7) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ { PublicKey: validatorKey.PublicKey().Marshal(), @@ -248,7 +248,7 @@ func TestSubmitSignedContributionAndProof_BadDomain(t *testing.T) { Slot: 1, PublicKey: pubKey[:], }, - ).Return(ðpb.SyncSubcommitteeIndexResponse{Indices: []types.CommitteeIndex{1}}, nil) + ).Return(ðpb.SyncSubcommitteeIndexResponse{Indices: []primitives.CommitteeIndex{1}}, nil) m.validatorClient.EXPECT(). DomainData(gomock.Any(), // ctx @@ -271,8 +271,8 @@ func TestSubmitSignedContributionAndProof_CouldNotGetContribution(t *testing.T) assert.NoError(t, err) validator, m, validatorKey, finish := setupWithKey(t, validatorKey) - validatorIndex := types.ValidatorIndex(7) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(7) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ { PublicKey: validatorKey.PublicKey().Marshal(), @@ -290,7 +290,7 @@ func TestSubmitSignedContributionAndProof_CouldNotGetContribution(t *testing.T) Slot: 1, PublicKey: pubKey[:], }, - ).Return(ðpb.SyncSubcommitteeIndexResponse{Indices: []types.CommitteeIndex{1}}, nil) + ).Return(ðpb.SyncSubcommitteeIndexResponse{Indices: []primitives.CommitteeIndex{1}}, nil) m.validatorClient.EXPECT(). DomainData(gomock.Any(), // ctx @@ -321,8 +321,8 @@ func TestSubmitSignedContributionAndProof_CouldNotSubmitContribution(t *testing. assert.NoError(t, err) validator, m, validatorKey, finish := setupWithKey(t, validatorKey) - validatorIndex := types.ValidatorIndex(7) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(7) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ { PublicKey: validatorKey.PublicKey().Marshal(), @@ -340,7 +340,7 @@ func TestSubmitSignedContributionAndProof_CouldNotSubmitContribution(t *testing. Slot: 1, PublicKey: pubKey[:], }, - ).Return(ðpb.SyncSubcommitteeIndexResponse{Indices: []types.CommitteeIndex{1}}, nil) + ).Return(ðpb.SyncSubcommitteeIndexResponse{Indices: []primitives.CommitteeIndex{1}}, nil) m.validatorClient.EXPECT(). DomainData(gomock.Any(), // ctx @@ -399,8 +399,8 @@ func TestSubmitSignedContributionAndProof_Ok(t *testing.T) { assert.NoError(t, err) validator, m, validatorKey, finish := setupWithKey(t, validatorKey) - validatorIndex := types.ValidatorIndex(7) - committee := []types.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} + validatorIndex := primitives.ValidatorIndex(7) + committee := []primitives.ValidatorIndex{0, 3, 4, 2, validatorIndex, 6, 8, 9, 10} validator.duties = ðpb.DutiesResponse{Duties: []*ethpb.DutiesResponse_Duty{ { PublicKey: validatorKey.PublicKey().Marshal(), @@ -418,7 +418,7 @@ func TestSubmitSignedContributionAndProof_Ok(t *testing.T) { Slot: 1, PublicKey: pubKey[:], }, - ).Return(ðpb.SyncSubcommitteeIndexResponse{Indices: []types.CommitteeIndex{1}}, nil) + ).Return(ðpb.SyncSubcommitteeIndexResponse{Indices: []primitives.CommitteeIndex{1}}, nil) m.validatorClient.EXPECT(). DomainData(gomock.Any(), // ctx diff --git a/validator/client/testutil/helper.go b/validator/client/testutil/helper.go index 511ff9df72..feda39be38 100644 --- a/validator/client/testutil/helper.go +++ b/validator/client/testutil/helper.go @@ -1,7 +1,7 @@ package testutil import ( - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" ) @@ -14,14 +14,14 @@ func GenerateMultipleValidatorStatusResponse(pubkeys [][]byte) *ethpb.MultipleVa resp := ðpb.MultipleValidatorStatusResponse{ PublicKeys: make([][]byte, len(pubkeys)), Statuses: make([]*ethpb.ValidatorStatusResponse, len(pubkeys)), - Indices: make([]types.ValidatorIndex, len(pubkeys)), + Indices: make([]primitives.ValidatorIndex, len(pubkeys)), } for i, key := range pubkeys { resp.PublicKeys[i] = key resp.Statuses[i] = ðpb.ValidatorStatusResponse{ Status: ethpb.ValidatorStatus_UNKNOWN_STATUS, } - resp.Indices[i] = types.ValidatorIndex(i) + resp.Indices[i] = primitives.ValidatorIndex(i) } return resp diff --git a/validator/client/testutil/mock_validator.go b/validator/client/testutil/mock_validator.go index adb492bd49..164fba3260 100644 --- a/validator/client/testutil/mock_validator.go +++ b/validator/client/testutil/mock_validator.go @@ -7,7 +7,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" validatorserviceconfig "github.com/prysmaticlabs/prysm/v3/config/validator/service" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" prysmTime "github.com/prysmaticlabs/prysm/v3/time" "github.com/prysmaticlabs/prysm/v3/validator/client/iface" @@ -43,7 +43,7 @@ type FakeValidator struct { AttestToBlockHeadArg1 uint64 RoleAtArg1 uint64 UpdateDutiesArg1 uint64 - NextSlotRet <-chan types.Slot + NextSlotRet <-chan primitives.Slot PublicKey string UpdateDutiesRet error ProposerSettingsErr error @@ -112,7 +112,7 @@ func (fv *FakeValidator) SlasherReady(_ context.Context) error { } // CanonicalHeadSlot for mocking. -func (fv *FakeValidator) CanonicalHeadSlot(_ context.Context) (types.Slot, error) { +func (fv *FakeValidator) CanonicalHeadSlot(_ context.Context) (primitives.Slot, error) { fv.CanonicalHeadSlotCalled++ if fv.RetryTillSuccess > fv.CanonicalHeadSlotCalled { return 0, iface.ErrConnectionIssue @@ -121,19 +121,19 @@ func (fv *FakeValidator) CanonicalHeadSlot(_ context.Context) (types.Slot, error } // SlotDeadline for mocking. -func (fv *FakeValidator) SlotDeadline(_ types.Slot) time.Time { +func (fv *FakeValidator) SlotDeadline(_ primitives.Slot) time.Time { fv.SlotDeadlineCalled = true return prysmTime.Now() } // NextSlot for mocking. -func (fv *FakeValidator) NextSlot() <-chan types.Slot { +func (fv *FakeValidator) NextSlot() <-chan primitives.Slot { fv.NextSlotCalled = true return fv.NextSlotRet } // UpdateDuties for mocking. -func (fv *FakeValidator) UpdateDuties(_ context.Context, slot types.Slot) error { +func (fv *FakeValidator) UpdateDuties(_ context.Context, slot primitives.Slot) error { fv.UpdateDutiesCalled = true fv.UpdateDutiesArg1 = uint64(slot) return fv.UpdateDutiesRet @@ -146,7 +146,7 @@ func (fv *FakeValidator) UpdateProtections(_ context.Context, _ uint64) error { } // LogValidatorGainsAndLosses for mocking. -func (fv *FakeValidator) LogValidatorGainsAndLosses(_ context.Context, _ types.Slot) error { +func (fv *FakeValidator) LogValidatorGainsAndLosses(_ context.Context, _ primitives.Slot) error { fv.LogValidatorGainsAndLossesCalled = true return nil } @@ -157,7 +157,7 @@ func (fv *FakeValidator) ResetAttesterProtectionData() { } // RolesAt for mocking. -func (fv *FakeValidator) RolesAt(_ context.Context, slot types.Slot) (map[[fieldparams.BLSPubkeyLength]byte][]iface.ValidatorRole, error) { +func (fv *FakeValidator) RolesAt(_ context.Context, slot primitives.Slot) (map[[fieldparams.BLSPubkeyLength]byte][]iface.ValidatorRole, error) { fv.RoleAtCalled = true fv.RoleAtArg1 = uint64(slot) vr := make(map[[fieldparams.BLSPubkeyLength]byte][]iface.ValidatorRole) @@ -166,30 +166,30 @@ func (fv *FakeValidator) RolesAt(_ context.Context, slot types.Slot) (map[[field } // SubmitAttestation for mocking. -func (fv *FakeValidator) SubmitAttestation(_ context.Context, slot types.Slot, _ [fieldparams.BLSPubkeyLength]byte) { +func (fv *FakeValidator) SubmitAttestation(_ context.Context, slot primitives.Slot, _ [fieldparams.BLSPubkeyLength]byte) { fv.AttestToBlockHeadCalled = true fv.AttestToBlockHeadArg1 = uint64(slot) } // ProposeBlock for mocking. -func (fv *FakeValidator) ProposeBlock(_ context.Context, slot types.Slot, _ [fieldparams.BLSPubkeyLength]byte) { +func (fv *FakeValidator) ProposeBlock(_ context.Context, slot primitives.Slot, _ [fieldparams.BLSPubkeyLength]byte) { fv.ProposeBlockCalled = true fv.ProposeBlockArg1 = uint64(slot) } // SubmitAggregateAndProof for mocking. -func (_ *FakeValidator) SubmitAggregateAndProof(_ context.Context, _ types.Slot, _ [fieldparams.BLSPubkeyLength]byte) { +func (_ *FakeValidator) SubmitAggregateAndProof(_ context.Context, _ primitives.Slot, _ [fieldparams.BLSPubkeyLength]byte) { } // SubmitSyncCommitteeMessage for mocking. -func (_ *FakeValidator) SubmitSyncCommitteeMessage(_ context.Context, _ types.Slot, _ [fieldparams.BLSPubkeyLength]byte) { +func (_ *FakeValidator) SubmitSyncCommitteeMessage(_ context.Context, _ primitives.Slot, _ [fieldparams.BLSPubkeyLength]byte) { } // LogAttestationsSubmitted for mocking. func (_ *FakeValidator) LogAttestationsSubmitted() {} // UpdateDomainDataCaches for mocking. -func (_ *FakeValidator) UpdateDomainDataCaches(context.Context, types.Slot) {} +func (_ *FakeValidator) UpdateDomainDataCaches(context.Context, primitives.Slot) {} // BalancesByPubkeys for mocking. func (fv *FakeValidator) BalancesByPubkeys(_ context.Context) map[[fieldparams.BLSPubkeyLength]byte]uint64 { @@ -249,7 +249,7 @@ func (fv *FakeValidator) HandleKeyReload(_ context.Context, newKeys [][fieldpara } // SubmitSignedContributionAndProof for mocking -func (_ *FakeValidator) SubmitSignedContributionAndProof(_ context.Context, _ types.Slot, _ [fieldparams.BLSPubkeyLength]byte) { +func (_ *FakeValidator) SubmitSignedContributionAndProof(_ context.Context, _ primitives.Slot, _ [fieldparams.BLSPubkeyLength]byte) { } // HasProposerSettings for mocking diff --git a/validator/client/validator.go b/validator/client/validator.go index 2a8853e7f9..5d23eee437 100644 --- a/validator/client/validator.go +++ b/validator/client/validator.go @@ -28,7 +28,7 @@ import ( validatorserviceconfig "github.com/prysmaticlabs/prysm/v3/config/validator/service" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -79,12 +79,12 @@ type validator struct { startBalances map[[fieldparams.BLSPubkeyLength]byte]uint64 duties *ethpb.DutiesResponse prevBalance map[[fieldparams.BLSPubkeyLength]byte]uint64 - pubkeyToValidatorIndex map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex + pubkeyToValidatorIndex map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex signedValidatorRegistrations map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1 graffitiOrderedIndex uint64 aggregatedSlotCommitteeIDCache *lru.Cache domainDataCache *ristretto.Cache - highestValidSlot types.Slot + highestValidSlot primitives.Slot genesisTime uint64 blockFeed *event.Feed interopKeysConfig *local.InteropKeymanagerConfig @@ -108,7 +108,7 @@ type validator struct { type validatorStatus struct { publicKey []byte status *ethpb.ValidatorStatusResponse - index types.ValidatorIndex + index primitives.ValidatorIndex } // Done cleans up the validator. @@ -370,7 +370,7 @@ func (v *validator) checkAndLogValidatorStatus(statuses []*validatorStatus, acti activationsPerEpoch := uint64(math.Max(float64(params.BeaconConfig().MinPerEpochChurnLimit), float64(activeValCount/params.BeaconConfig().ChurnLimitQuotient))) - nonexistentIndex := types.ValidatorIndex(^uint64(0)) + nonexistentIndex := primitives.ValidatorIndex(^uint64(0)) var validatorActivated bool for _, status := range statuses { fields := logrus.Fields{ @@ -437,7 +437,7 @@ func logActiveValidatorStatus(statuses []*validatorStatus) { // CanonicalHeadSlot returns the slot of canonical block currently found in the // beacon chain via RPC. -func (v *validator) CanonicalHeadSlot(ctx context.Context) (types.Slot, error) { +func (v *validator) CanonicalHeadSlot(ctx context.Context) (primitives.Slot, error) { ctx, span := trace.StartSpan(ctx, "validator.CanonicalHeadSlot") defer span.End() head, err := v.beaconClient.GetChainHead(ctx, &emptypb.Empty{}) @@ -448,12 +448,12 @@ func (v *validator) CanonicalHeadSlot(ctx context.Context) (types.Slot, error) { } // NextSlot emits the next slot number at the start time of that slot. -func (v *validator) NextSlot() <-chan types.Slot { +func (v *validator) NextSlot() <-chan primitives.Slot { return v.ticker.C() } // SlotDeadline is the start time of the next slot. -func (v *validator) SlotDeadline(slot types.Slot) time.Time { +func (v *validator) SlotDeadline(slot primitives.Slot) time.Time { secs := time.Duration((slot + 1).Mul(params.BeaconConfig().SecondsPerSlot)) return time.Unix(int64(v.genesisTime), 0 /*ns*/).Add(secs * time.Second) } @@ -555,7 +555,7 @@ func retrieveLatestRecord(recs []*kv.AttestationRecord) *kv.AttestationRecord { // UpdateDuties checks the slot number to determine if the validator's // list of upcoming assignments needs to be updated. For example, at the // beginning of a new epoch. -func (v *validator) UpdateDuties(ctx context.Context, slot types.Slot) error { +func (v *validator) UpdateDuties(ctx context.Context, slot primitives.Slot) error { if slot%params.BeaconConfig().SlotsPerEpoch != 0 && v.duties != nil { // Do nothing if not epoch start AND assignments already exist. return nil @@ -591,7 +591,7 @@ func (v *validator) UpdateDuties(ctx context.Context, slot types.Slot) error { v.slashableKeysLock.RUnlock() req := ðpb.DutiesRequest{ - Epoch: types.Epoch(slot / params.BeaconConfig().SlotsPerEpoch), + Epoch: primitives.Epoch(slot / params.BeaconConfig().SlotsPerEpoch), PublicKeys: bytesutil.FromBytes48Array(filteredKeys), } @@ -625,10 +625,10 @@ func (v *validator) UpdateDuties(ctx context.Context, slot types.Slot) error { // subscribeToSubnets iterates through each validator duty, signs each slot, and asks beacon node // to eagerly subscribe to subnets so that the aggregator has attestations to aggregate. func (v *validator) subscribeToSubnets(ctx context.Context, res *ethpb.DutiesResponse) error { - subscribeSlots := make([]types.Slot, 0, len(res.CurrentEpochDuties)+len(res.NextEpochDuties)) - subscribeCommitteeIndices := make([]types.CommitteeIndex, 0, len(res.CurrentEpochDuties)+len(res.NextEpochDuties)) + subscribeSlots := make([]primitives.Slot, 0, len(res.CurrentEpochDuties)+len(res.NextEpochDuties)) + subscribeCommitteeIndices := make([]primitives.CommitteeIndex, 0, len(res.CurrentEpochDuties)+len(res.NextEpochDuties)) subscribeIsAggregator := make([]bool, 0, len(res.CurrentEpochDuties)+len(res.NextEpochDuties)) - subscribeValidatorIndices := make([]types.ValidatorIndex, 0, len(res.CurrentEpochDuties)+len(res.NextEpochDuties)) + subscribeValidatorIndices := make([]primitives.ValidatorIndex, 0, len(res.CurrentEpochDuties)+len(res.NextEpochDuties)) alreadySubscribed := make(map[[64]byte]bool) for _, duty := range res.CurrentEpochDuties { @@ -699,7 +699,7 @@ func (v *validator) subscribeToSubnets(ctx context.Context, res *ethpb.DutiesRes // RolesAt slot returns the validator roles at the given slot. Returns nil if the // validator is known to not have a roles at the slot. Returns UNKNOWN if the // validator assignments are unknown. Otherwise returns a valid ValidatorRole map. -func (v *validator) RolesAt(ctx context.Context, slot types.Slot) (map[[fieldparams.BLSPubkeyLength]byte][]iface.ValidatorRole, error) { +func (v *validator) RolesAt(ctx context.Context, slot primitives.Slot) (map[[fieldparams.BLSPubkeyLength]byte][]iface.ValidatorRole, error) { rolesAt := make(map[[fieldparams.BLSPubkeyLength]byte][]iface.ValidatorRole) for validator, duty := range v.duties.Duties { var roles []iface.ValidatorRole @@ -774,7 +774,7 @@ func (v *validator) Keymanager() (keymanager.IKeymanager, error) { // isAggregator checks if a validator is an aggregator of a given slot and committee, // it uses a modulo calculated by validator count in committee and samples randomness around it. -func (v *validator) isAggregator(ctx context.Context, committee []types.ValidatorIndex, slot types.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) (bool, error) { +func (v *validator) isAggregator(ctx context.Context, committee []primitives.ValidatorIndex, slot primitives.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) (bool, error) { modulo := uint64(1) if len(committee)/int(params.BeaconConfig().TargetAggregatorsPerCommittee) > 1 { modulo = uint64(len(committee)) / params.BeaconConfig().TargetAggregatorsPerCommittee @@ -798,7 +798,7 @@ func (v *validator) isAggregator(ctx context.Context, committee []types.Validato // // modulo = max(1, SYNC_COMMITTEE_SIZE // SYNC_COMMITTEE_SUBNET_COUNT // TARGET_AGGREGATORS_PER_SYNC_SUBCOMMITTEE) // return bytes_to_uint64(hash(signature)[0:8]) % modulo == 0 -func (v *validator) isSyncCommitteeAggregator(ctx context.Context, slot types.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) (bool, error) { +func (v *validator) isSyncCommitteeAggregator(ctx context.Context, slot primitives.Slot, pubKey [fieldparams.BLSPubkeyLength]byte) (bool, error) { res, err := v.validatorClient.GetSyncSubcommitteeIndex(ctx, ðpb.SyncSubcommitteeIndexRequest{ PublicKey: pubKey[:], Slot: slot, @@ -830,7 +830,7 @@ func (v *validator) isSyncCommitteeAggregator(ctx context.Context, slot types.Sl // the fork version changes which can happen once per epoch. Although changing for the fork version // is very rare, a validator should check these data every epoch to be sure the validator is // participating on the correct fork version. -func (v *validator) UpdateDomainDataCaches(ctx context.Context, slot types.Slot) { +func (v *validator) UpdateDomainDataCaches(ctx context.Context, slot primitives.Slot) { for _, d := range [][]byte{ params.BeaconConfig().DomainRandao[:], params.BeaconConfig().DomainBeaconAttester[:], @@ -877,7 +877,7 @@ func (v *validator) AllValidatorsAreExited(ctx context.Context) (bool, error) { return true, nil } -func (v *validator) domainData(ctx context.Context, epoch types.Epoch, domain []byte) (*ethpb.DomainResponse, error) { +func (v *validator) domainData(ctx context.Context, epoch primitives.Epoch, domain []byte) (*ethpb.DomainResponse, error) { v.domainDataLock.Lock() defer v.domainDataLock.Unlock() @@ -902,7 +902,7 @@ func (v *validator) domainData(ctx context.Context, epoch types.Epoch, domain [] return res, nil } -func (v *validator) logDuties(slot types.Slot, duties []*ethpb.DutiesResponse_Duty) { +func (v *validator) logDuties(slot primitives.Slot, duties []*ethpb.DutiesResponse_Duty) { attesterKeys := make([][]string, params.BeaconConfig().SlotsPerEpoch) for i := range attesterKeys { attesterKeys[i] = make([]string, 0) @@ -949,7 +949,7 @@ func (v *validator) logDuties(slot types.Slot, duties []*ethpb.DutiesResponse_Du } } } - for i := types.Slot(0); i < params.BeaconConfig().SlotsPerEpoch; i++ { + for i := primitives.Slot(0); i < params.BeaconConfig().SlotsPerEpoch; i++ { startTime := slots.StartTime(v.genesisTime, slotOffset+i) durationTillDuty := (time.Until(startTime) + time.Second).Truncate(time.Second) // Round up to next second. @@ -1132,7 +1132,7 @@ func (v *validator) buildSignedRegReqs(ctx context.Context, pubkeys [][fieldpara return signedValRegRegs, nil } -func (v *validator) validatorIndex(ctx context.Context, pubkey [fieldparams.BLSPubkeyLength]byte) (types.ValidatorIndex, bool, error) { +func (v *validator) validatorIndex(ctx context.Context, pubkey [fieldparams.BLSPubkeyLength]byte) (primitives.ValidatorIndex, bool, error) { resp, err := v.validatorClient.ValidatorIndex(ctx, ðpb.ValidatorIndexRequest{PublicKey: pubkey[:]}) switch { case status.Code(err) == codes.NotFound: @@ -1147,16 +1147,16 @@ func (v *validator) validatorIndex(ctx context.Context, pubkey [fieldparams.BLSP // This constructs a validator subscribed key, it's used to track // which subnet has already been pending requested. -func validatorSubscribeKey(slot types.Slot, committeeID types.CommitteeIndex) [64]byte { +func validatorSubscribeKey(slot primitives.Slot, committeeID primitives.CommitteeIndex) [64]byte { return bytesutil.ToBytes64(append(bytesutil.Bytes32(uint64(slot)), bytesutil.Bytes32(uint64(committeeID))...)) } // This tracks all validators' voting status. type voteStats struct { - startEpoch types.Epoch + startEpoch primitives.Epoch totalAttestedCount uint64 totalRequestedCount uint64 - totalDistance types.Slot + totalDistance primitives.Slot totalCorrectSource uint64 totalCorrectTarget uint64 totalCorrectHead uint64 diff --git a/validator/client/validator_test.go b/validator/client/validator_test.go index a2f41f85b4..eb19ae6648 100644 --- a/validator/client/validator_test.go +++ b/validator/client/validator_test.go @@ -20,7 +20,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" validatorserviceconfig "github.com/prysmaticlabs/prysm/v3/config/validator/service" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpbservice "github.com/prysmaticlabs/prysm/v3/proto/eth/service" @@ -294,7 +294,7 @@ func TestCanonicalHeadSlot_OK(t *testing.T) { ).Return(ðpb.ChainHead{HeadSlot: 0}, nil) headSlot, err := v.CanonicalHeadSlot(context.Background()) require.NoError(t, err) - assert.Equal(t, types.Slot(0), headSlot, "Mismatch slots") + assert.Equal(t, primitives.Slot(0), headSlot, "Mismatch slots") } func TestWaitMultipleActivation_LogsActivationEpochOK(t *testing.T) { @@ -439,13 +439,13 @@ func TestUpdateDuties_DoesNothingWhenNotEpochStart_AlreadyExistingAssignments(t defer ctrl.Finish() client := mock2.NewMockValidatorClient(ctrl) - slot := types.Slot(1) + slot := primitives.Slot(1) v := validator{ validatorClient: client, duties: ðpb.DutiesResponse{ Duties: []*ethpb.DutiesResponse_Duty{ { - Committee: []types.ValidatorIndex{}, + Committee: []primitives.ValidatorIndex{}, AttesterSlot: 10, CommitteeIndex: 20, }, @@ -518,9 +518,9 @@ func TestUpdateDuties_OK(t *testing.T) { AttesterSlot: params.BeaconConfig().SlotsPerEpoch, ValidatorIndex: 200, CommitteeIndex: 100, - Committee: []types.ValidatorIndex{0, 1, 2, 3}, + Committee: []primitives.ValidatorIndex{0, 1, 2, 3}, PublicKey: []byte("testPubKey_1"), - ProposerSlots: []types.Slot{params.BeaconConfig().SlotsPerEpoch + 1}, + ProposerSlots: []primitives.Slot{params.BeaconConfig().SlotsPerEpoch + 1}, }, }, } @@ -540,7 +540,7 @@ func TestUpdateDuties_OK(t *testing.T) { gomock.Any(), gomock.Any(), gomock.Any(), - ).DoAndReturn(func(_ context.Context, _ *ethpb.CommitteeSubnetsSubscribeRequest, _ []types.ValidatorIndex) (*emptypb.Empty, error) { + ).DoAndReturn(func(_ context.Context, _ *ethpb.CommitteeSubnetsSubscribeRequest, _ []primitives.ValidatorIndex) (*emptypb.Empty, error) { wg.Done() return nil, nil }) @@ -596,7 +596,7 @@ func TestUpdateDuties_OK_FilterBlacklistedPublicKeys(t *testing.T) { gomock.Any(), gomock.Any(), gomock.Any(), - ).DoAndReturn(func(_ context.Context, _ *ethpb.CommitteeSubnetsSubscribeRequest, _ []types.ValidatorIndex) (*emptypb.Empty, error) { + ).DoAndReturn(func(_ context.Context, _ *ethpb.CommitteeSubnetsSubscribeRequest, _ []primitives.ValidatorIndex) (*emptypb.Empty, error) { wg.Done() return nil, nil }) @@ -695,7 +695,7 @@ func TestRolesAt_DoesNotAssignProposer_Slot0(t *testing.T) { { CommitteeIndex: 1, AttesterSlot: 0, - ProposerSlots: []types.Slot{0}, + ProposerSlots: []primitives.Slot{0}, PublicKey: validatorKey.PublicKey().Marshal(), }, }, @@ -713,7 +713,7 @@ func TestRolesAt_DoesNotAssignProposer_Slot0(t *testing.T) { } func TestCheckAndLogValidatorStatus_OK(t *testing.T) { - nonexistentIndex := types.ValidatorIndex(^uint64(0)) + nonexistentIndex := primitives.ValidatorIndex(^uint64(0)) type statusTest struct { name string status *validatorStatus @@ -975,7 +975,7 @@ func TestService_ReceiveBlocks_NilBlock(t *testing.T) { }) connectionErrorChannel := make(chan error) v.ReceiveBlocks(ctx, connectionErrorChannel) - require.Equal(t, types.Slot(0), v.highestValidSlot) + require.Equal(t, primitives.Slot(0), v.highestValidSlot) } func TestService_ReceiveBlocks_SetHighest(t *testing.T) { @@ -994,7 +994,7 @@ func TestService_ReceiveBlocks_SetHighest(t *testing.T) { ðpb.StreamBlocksRequest{VerifiedOnly: true}, ).Return(stream, nil) stream.EXPECT().Context().Return(ctx).AnyTimes() - slot := types.Slot(100) + slot := primitives.Slot(100) stream.EXPECT().Recv().Return( ðpb.StreamBlocksResponse{ Block: ðpb.StreamBlocksResponse_Phase0Block{ @@ -1153,7 +1153,7 @@ func TestValidator_CheckDoppelGanger(t *testing.T) { for i, k := range keys { pkey := k for j := 0; j < attLimit; j++ { - att := createAttestation(10+types.Epoch(j), 12+types.Epoch(j)) + att := createAttestation(10+primitives.Epoch(j), 12+primitives.Epoch(j)) rt, err := att.Data.HashTreeRoot() assert.NoError(t, err) assert.NoError(t, db.SaveAttestationForPubKey(context.Background(), pkey, rt, att)) @@ -1247,10 +1247,10 @@ func TestValidatorAttestationsAreOrdered(t *testing.T) { histories, err := db.AttestationHistoryForPubKey(context.Background(), k) assert.NoError(t, err) r := retrieveLatestRecord(histories) - assert.Equal(t, r.Target, types.Epoch(14)) + assert.Equal(t, r.Target, primitives.Epoch(14)) } -func createAttestation(source, target types.Epoch) *ethpb.IndexedAttestation { +func createAttestation(source, target primitives.Epoch) *ethpb.IndexedAttestation { return ðpb.IndexedAttestation{ Data: ðpb.AttestationData{ Source: ðpb.Checkpoint{ @@ -1272,7 +1272,7 @@ func TestIsSyncCommitteeAggregator_OK(t *testing.T) { v, m, validatorKey, finish := setup(t) defer finish() - slot := types.Slot(1) + slot := primitives.Slot(1) pubKey := validatorKey.PublicKey().Marshal() m.validatorClient.EXPECT().GetSyncSubcommitteeIndex( @@ -1302,7 +1302,7 @@ func TestIsSyncCommitteeAggregator_OK(t *testing.T) { PublicKey: validatorKey.PublicKey().Marshal(), Slot: 1, }, - ).Return(ðpb.SyncSubcommitteeIndexResponse{Indices: []types.CommitteeIndex{0}}, nil /*err*/) + ).Return(ðpb.SyncSubcommitteeIndexResponse{Indices: []primitives.CommitteeIndex{0}}, nil /*err*/) aggregator, err = v.isSyncCommitteeAggregator(context.Background(), slot, bytesutil.ToBytes48(pubKey)) require.NoError(t, err) @@ -1410,7 +1410,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { tests := []struct { name string validatorSetter func(t *testing.T) *validator - feeRecipientMap map[types.ValidatorIndex]string + feeRecipientMap map[primitives.ValidatorIndex]string mockExpectedRequests []ExpectedValidatorRegistration err string logMessages []string @@ -1424,7 +1424,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { validatorClient: client, node: nodeClient, db: db, - pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex), + pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex), signedValidatorRegistrations: make(map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1), useWeb: false, interopKeysConfig: &local.InteropKeymanagerConfig{ @@ -1480,7 +1480,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { ).Return(&empty.Empty{}, nil) return &v }, - feeRecipientMap: map[types.ValidatorIndex]string{ + feeRecipientMap: map[primitives.ValidatorIndex]string{ 1: "0x055Fb65722E7b2455043BFEBf6177F1D2e9738D9", 2: defaultFeeHex, }, @@ -1504,7 +1504,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { validatorClient: client, node: nodeClient, db: db, - pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex), + pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex), signedValidatorRegistrations: make(map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1), useWeb: false, interopKeysConfig: &local.InteropKeymanagerConfig{ @@ -1560,7 +1560,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { ).Return(&empty.Empty{}, nil) return &v }, - feeRecipientMap: map[types.ValidatorIndex]string{ + feeRecipientMap: map[primitives.ValidatorIndex]string{ 1: "0x055Fb65722E7b2455043BFEBf6177F1D2e9738D9", 2: defaultFeeHex, }, @@ -1580,7 +1580,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { validatorClient: client, node: nodeClient, db: db, - pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex), + pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex), signedValidatorRegistrations: make(map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1), useWeb: false, interopKeysConfig: &local.InteropKeymanagerConfig{ @@ -1624,7 +1624,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { }) return &v }, - feeRecipientMap: map[types.ValidatorIndex]string{ + feeRecipientMap: map[primitives.ValidatorIndex]string{ 1: "0x055Fb65722E7b2455043BFEBf6177F1D2e9738D9", 2: defaultFeeHex, }, @@ -1639,7 +1639,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { validatorClient: client, node: nodeClient, db: db, - pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex), + pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex), signedValidatorRegistrations: make(map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1), useWeb: false, interopKeysConfig: &local.InteropKeymanagerConfig{ @@ -1684,7 +1684,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { }).Return(nil, nil) return &v }, - feeRecipientMap: map[types.ValidatorIndex]string{ + feeRecipientMap: map[primitives.ValidatorIndex]string{ 1: defaultFeeHex, }, mockExpectedRequests: []ExpectedValidatorRegistration{ @@ -1702,7 +1702,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { validatorClient: client, node: nodeClient, db: db, - pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex), + pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex), signedValidatorRegistrations: make(map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1), useWeb: false, interopKeysConfig: &local.InteropKeymanagerConfig{ @@ -1743,7 +1743,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { }).Return(nil, nil) return &v }, - feeRecipientMap: map[types.ValidatorIndex]string{ + feeRecipientMap: map[primitives.ValidatorIndex]string{ 1: defaultFeeHex, }, mockExpectedRequests: []ExpectedValidatorRegistration{ @@ -1761,7 +1761,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { validatorClient: client, node: nodeClient, db: db, - pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex), + pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex), signedValidatorRegistrations: make(map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1), useWeb: false, interopKeysConfig: &local.InteropKeymanagerConfig{ @@ -1806,7 +1806,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { v := validator{ validatorClient: client, db: db, - pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex), + pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex), signedValidatorRegistrations: make(map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1), useWeb: false, interopKeysConfig: &local.InteropKeymanagerConfig{ @@ -1844,7 +1844,7 @@ func TestValidator_PushProposerSettings(t *testing.T) { validatorClient: client, node: nodeClient, db: db, - pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]types.ValidatorIndex), + pubkeyToValidatorIndex: make(map[[fieldparams.BLSPubkeyLength]byte]primitives.ValidatorIndex), signedValidatorRegistrations: make(map[[fieldparams.BLSPubkeyLength]byte]*ethpb.SignedValidatorRegistrationV1), useWeb: false, interopKeysConfig: &local.InteropKeymanagerConfig{ diff --git a/validator/client/wait_for_activation_test.go b/validator/client/wait_for_activation_test.go index 10f9bb275d..06b8c1be75 100644 --- a/validator/client/wait_for_activation_test.go +++ b/validator/client/wait_for_activation_test.go @@ -9,7 +9,7 @@ import ( "github.com/golang/mock/gomock" "github.com/pkg/errors" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -418,12 +418,12 @@ func TestWaitForActivation_RemoteKeymanager(t *testing.T) { activeKey := bytesutil.ToBytes48([]byte("active")) km := remotekeymanagermock.NewMock() km.PublicKeys = [][fieldparams.BLSPubkeyLength]byte{inactiveKey, activeKey} - slot := types.Slot(0) + slot := primitives.Slot(0) t.Run("activated", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) hook := logTest.NewGlobal() - tickerChan := make(chan types.Slot) + tickerChan := make(chan primitives.Slot) ticker := &slotutilmock.MockTicker{ Channel: tickerChan, } @@ -458,7 +458,7 @@ func TestWaitForActivation_RemoteKeymanager(t *testing.T) { t.Run("cancelled", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) - tickerChan := make(chan types.Slot) + tickerChan := make(chan primitives.Slot) ticker := &slotutilmock.MockTicker{ Channel: tickerChan, } @@ -480,7 +480,7 @@ func TestWaitForActivation_RemoteKeymanager(t *testing.T) { hook := logTest.NewGlobal() remoteKm := remotekeymanagermock.NewMock() remoteKm.PublicKeys = [][fieldparams.BLSPubkeyLength]byte{inactiveKey} - tickerChan := make(chan types.Slot) + tickerChan := make(chan primitives.Slot) ticker := &slotutilmock.MockTicker{ Channel: tickerChan, } diff --git a/validator/db/iface/interface.go b/validator/db/iface/interface.go index acaf44821e..0aa352620c 100644 --- a/validator/db/iface/interface.go +++ b/validator/db/iface/interface.go @@ -6,7 +6,7 @@ import ( "io" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/monitoring/backup" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/validator/db/kv" @@ -30,11 +30,11 @@ type ValidatorDB interface { SaveGenesisValidatorsRoot(ctx context.Context, genValRoot []byte) error // Proposer protection related methods. - HighestSignedProposal(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (types.Slot, bool, error) - LowestSignedProposal(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (types.Slot, bool, error) + HighestSignedProposal(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (primitives.Slot, bool, error) + LowestSignedProposal(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (primitives.Slot, bool, error) ProposalHistoryForPubKey(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) ([]*kv.Proposal, error) - ProposalHistoryForSlot(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte, slot types.Slot) ([32]byte, bool, error) - SaveProposalHistoryForSlot(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, slot types.Slot, signingRoot []byte) error + ProposalHistoryForSlot(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte, slot primitives.Slot) ([32]byte, bool, error) + SaveProposalHistoryForSlot(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, slot primitives.Slot, signingRoot []byte) error ProposedPublicKeys(ctx context.Context) ([][fieldparams.BLSPubkeyLength]byte, error) // Attester protection related methods. @@ -42,9 +42,9 @@ type ValidatorDB interface { // slashing protection imports. EIPImportBlacklistedPublicKeys(ctx context.Context) ([][fieldparams.BLSPubkeyLength]byte, error) SaveEIPImportBlacklistedPublicKeys(ctx context.Context, publicKeys [][fieldparams.BLSPubkeyLength]byte) error - SigningRootAtTargetEpoch(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte, target types.Epoch) ([32]byte, error) - LowestSignedTargetEpoch(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (types.Epoch, bool, error) - LowestSignedSourceEpoch(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (types.Epoch, bool, error) + SigningRootAtTargetEpoch(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte, target primitives.Epoch) ([32]byte, error) + LowestSignedTargetEpoch(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (primitives.Epoch, bool, error) + LowestSignedSourceEpoch(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (primitives.Epoch, bool, error) AttestedPublicKeys(ctx context.Context) ([][fieldparams.BLSPubkeyLength]byte, error) CheckSlashableAttestation( ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, signingRoot [32]byte, att *ethpb.IndexedAttestation, diff --git a/validator/db/kv/attester_protection.go b/validator/db/kv/attester_protection.go index 9fed67376d..f66b273ec7 100644 --- a/validator/db/kv/attester_protection.go +++ b/validator/db/kv/attester_protection.go @@ -8,7 +8,7 @@ import ( "github.com/pkg/errors" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/monitoring/tracing" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" @@ -31,8 +31,8 @@ type AttestationRecordSaveRequest struct { // for manipulation by database methods. type AttestationRecord struct { PubKey [fieldparams.BLSPubkeyLength]byte - Source types.Epoch - Target types.Epoch + Source primitives.Epoch + Target primitives.Epoch SigningRoot [32]byte } @@ -114,7 +114,7 @@ func (s *Store) AttestationHistoryForPubKey(ctx context.Context, pubKey [fieldpa sourceEpochsBucket := pkBucket.Bucket(attestationSourceEpochsBucket) return sourceEpochsBucket.ForEach(func(sourceBytes, targetEpochsList []byte) error { - targetEpochs := make([]types.Epoch, 0) + targetEpochs := make([]primitives.Epoch, 0) for i := 0; i < len(targetEpochsList); i += 8 { epoch := bytesutil.BytesToEpochBigEndian(targetEpochsList[i : i+8]) targetEpochs = append(targetEpochs, epoch) @@ -211,7 +211,7 @@ func (_ *Store) checkSurroundedVote( } // There can be multiple source epochs attested per target epoch. - attestedSourceEpochs := make([]types.Epoch, 0, len(v)/8) + attestedSourceEpochs := make([]primitives.Epoch, 0, len(v)/8) for i := 0; i < len(v); i += 8 { sourceEpoch := bytesutil.BytesToEpochBigEndian(v[i : i+8]) attestedSourceEpochs = append(attestedSourceEpochs, sourceEpoch) @@ -251,7 +251,7 @@ func (_ *Store) checkSurroundingVote( } // There can be multiple target epochs attested per source epoch. - attestedTargetEpochs := make([]types.Epoch, 0, len(v)/8) + attestedTargetEpochs := make([]primitives.Epoch, 0, len(v)/8) for i := 0; i < len(v); i += 8 { targetEpoch := bytesutil.BytesToEpochBigEndian(v[i : i+8]) attestedTargetEpochs = append(attestedTargetEpochs, targetEpoch) @@ -487,7 +487,7 @@ 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 types.Epoch + var lowestSignedSourceEpoch primitives.Epoch if len(lowestSignedSourceBytes) >= 8 { lowestSignedSourceEpoch = bytesutil.BytesToEpochBigEndian(lowestSignedSourceBytes) } @@ -501,7 +501,7 @@ 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 types.Epoch + var lowestSignedTargetEpoch primitives.Epoch if len(lowestSignedTargetBytes) >= 8 { lowestSignedTargetEpoch = bytesutil.BytesToEpochBigEndian(lowestSignedTargetBytes) } @@ -537,7 +537,7 @@ func (s *Store) AttestedPublicKeys(ctx context.Context) ([][fieldparams.BLSPubke // 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 [fieldparams.BLSPubkeyLength]byte, target types.Epoch) ([32]byte, error) { +func (s *Store) SigningRootAtTargetEpoch(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, target primitives.Epoch) ([32]byte, error) { ctx, span := trace.StartSpan(ctx, "Validator.SigningRootAtTargetEpoch") defer span.End() var signingRoot [32]byte @@ -560,12 +560,12 @@ func (s *Store) SigningRootAtTargetEpoch(ctx context.Context, pubKey [fieldparam // 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 [fieldparams.BLSPubkeyLength]byte) (types.Epoch, bool, error) { +func (s *Store) LowestSignedSourceEpoch(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (primitives.Epoch, bool, error) { ctx, span := trace.StartSpan(ctx, "Validator.LowestSignedSourceEpoch") defer span.End() var err error - var lowestSignedSourceEpoch types.Epoch + var lowestSignedSourceEpoch primitives.Epoch var exists bool err = s.view(func(tx *bolt.Tx) error { bucket := tx.Bucket(lowestSignedSourceBucket) @@ -583,12 +583,12 @@ func (s *Store) LowestSignedSourceEpoch(ctx context.Context, publicKey [fieldpar // 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 [fieldparams.BLSPubkeyLength]byte) (types.Epoch, bool, error) { +func (s *Store) LowestSignedTargetEpoch(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (primitives.Epoch, bool, error) { ctx, span := trace.StartSpan(ctx, "Validator.LowestSignedTargetEpoch") defer span.End() var err error - var lowestSignedTargetEpoch types.Epoch + var lowestSignedTargetEpoch primitives.Epoch var exists bool err = s.view(func(tx *bolt.Tx) error { bucket := tx.Bucket(lowestSignedTargetBucket) diff --git a/validator/db/kv/attester_protection_test.go b/validator/db/kv/attester_protection_test.go index fb76f6dfe0..4a791ef292 100644 --- a/validator/db/kv/attester_protection_test.go +++ b/validator/db/kv/attester_protection_test.go @@ -8,7 +8,7 @@ import ( "testing" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" @@ -24,7 +24,7 @@ func TestPendingAttestationRecords_Flush(t *testing.T) { num := 5 for i := 0; i < num; i++ { queue.Append(&AttestationRecord{ - Target: types.Epoch(i), + Target: primitives.Epoch(i), }) } @@ -141,7 +141,7 @@ func TestStore_CheckSlashableAttestation_SurroundVote_MultipleTargetsPerSource(t func TestStore_CheckSlashableAttestation_SurroundVote_54kEpochs(t *testing.T) { ctx := context.Background() numValidators := 1 - numEpochs := types.Epoch(54000) + numEpochs := primitives.Epoch(54000) pubKeys := make([][fieldparams.BLSPubkeyLength]byte, numValidators) validatorDB := setupDB(t, pubKeys) @@ -157,7 +157,7 @@ func TestStore_CheckSlashableAttestation_SurroundVote_54kEpochs(t *testing.T) { if err != nil { return err } - for epoch := types.Epoch(1); epoch < numEpochs; epoch++ { + for epoch := primitives.Epoch(1); epoch < numEpochs; epoch++ { att := createAttestation(epoch-1, epoch) sourceEpoch := bytesutil.EpochToBytesBigEndian(att.Data.Source.Epoch) targetEpoch := bytesutil.EpochToBytesBigEndian(att.Data.Target.Epoch) @@ -232,10 +232,10 @@ func TestLowestSignedSourceEpoch_SaveRetrieve(t *testing.T) { ) got, _, err := validatorDB.LowestSignedSourceEpoch(ctx, p0) require.NoError(t, err) - require.Equal(t, types.Epoch(100), got) + require.Equal(t, primitives.Epoch(100), got) got, _, err = validatorDB.LowestSignedSourceEpoch(ctx, p1) require.NoError(t, err) - require.Equal(t, types.Epoch(200), got) + require.Equal(t, primitives.Epoch(200), got) // Can replace. require.NoError( @@ -248,10 +248,10 @@ func TestLowestSignedSourceEpoch_SaveRetrieve(t *testing.T) { ) got, _, err = validatorDB.LowestSignedSourceEpoch(ctx, p0) require.NoError(t, err) - require.Equal(t, types.Epoch(99), got) + require.Equal(t, primitives.Epoch(99), got) got, _, err = validatorDB.LowestSignedSourceEpoch(ctx, p1) require.NoError(t, err) - require.Equal(t, types.Epoch(199), got) + require.Equal(t, primitives.Epoch(199), got) // Can not replace. require.NoError( @@ -264,10 +264,10 @@ func TestLowestSignedSourceEpoch_SaveRetrieve(t *testing.T) { ) got, _, err = validatorDB.LowestSignedSourceEpoch(ctx, p0) require.NoError(t, err) - require.Equal(t, types.Epoch(99), got) + require.Equal(t, primitives.Epoch(99), got) got, _, err = validatorDB.LowestSignedSourceEpoch(ctx, p1) require.NoError(t, err) - require.Equal(t, types.Epoch(199), got) + require.Equal(t, primitives.Epoch(199), got) } func TestLowestSignedTargetEpoch_SaveRetrieveReplace(t *testing.T) { @@ -291,10 +291,10 @@ func TestLowestSignedTargetEpoch_SaveRetrieveReplace(t *testing.T) { ) got, _, err := validatorDB.LowestSignedTargetEpoch(ctx, p0) require.NoError(t, err) - require.Equal(t, types.Epoch(100), got) + require.Equal(t, primitives.Epoch(100), got) got, _, err = validatorDB.LowestSignedTargetEpoch(ctx, p1) require.NoError(t, err) - require.Equal(t, types.Epoch(200), got) + require.Equal(t, primitives.Epoch(200), got) // Can replace. require.NoError( @@ -307,10 +307,10 @@ func TestLowestSignedTargetEpoch_SaveRetrieveReplace(t *testing.T) { ) got, _, err = validatorDB.LowestSignedTargetEpoch(ctx, p0) require.NoError(t, err) - require.Equal(t, types.Epoch(99), got) + require.Equal(t, primitives.Epoch(99), got) got, _, err = validatorDB.LowestSignedTargetEpoch(ctx, p1) require.NoError(t, err) - require.Equal(t, types.Epoch(199), got) + require.Equal(t, primitives.Epoch(199), got) // Can not replace. require.NoError( @@ -323,10 +323,10 @@ func TestLowestSignedTargetEpoch_SaveRetrieveReplace(t *testing.T) { ) got, _, err = validatorDB.LowestSignedTargetEpoch(ctx, p0) require.NoError(t, err) - require.Equal(t, types.Epoch(99), got) + require.Equal(t, primitives.Epoch(99), got) got, _, err = validatorDB.LowestSignedTargetEpoch(ctx, p1) require.NoError(t, err) - require.Equal(t, types.Epoch(199), got) + require.Equal(t, primitives.Epoch(199), got) } func TestStore_SaveAttestationsForPubKey(t *testing.T) { @@ -336,7 +336,7 @@ func TestStore_SaveAttestationsForPubKey(t *testing.T) { validatorDB := setupDB(t, pubKeys) atts := make([]*ethpb.IndexedAttestation, 0) signingRoots := make([][32]byte, 0) - for i := types.Epoch(1); i < 10; i++ { + for i := primitives.Epoch(1); i < 10; i++ { atts = append(atts, createAttestation(i-1, i)) var sr [32]byte copy(sr[:], fmt.Sprintf("%d", i)) @@ -381,14 +381,14 @@ func TestSaveAttestationForPubKey_BatchWrites_FullCapacity(t *testing.T) { var wg sync.WaitGroup for i, pubKey := range pubKeys { wg.Add(1) - go func(j types.Epoch, pk [fieldparams.BLSPubkeyLength]byte, w *sync.WaitGroup) { + go func(j primitives.Epoch, pk [fieldparams.BLSPubkeyLength]byte, w *sync.WaitGroup) { defer w.Done() var signingRoot [32]byte copy(signingRoot[:], fmt.Sprintf("%d", j)) att := createAttestation(j, j+1) err := validatorDB.SaveAttestationForPubKey(ctx, pk, signingRoot, att) require.NoError(t, err) - }(types.Epoch(i), pubKey, &wg) + }(primitives.Epoch(i), pubKey, &wg) } wg.Wait() @@ -438,14 +438,14 @@ func TestSaveAttestationForPubKey_BatchWrites_LowCapacity_TimerReached(t *testin var wg sync.WaitGroup for i, pubKey := range pubKeys { wg.Add(1) - go func(j types.Epoch, pk [fieldparams.BLSPubkeyLength]byte, w *sync.WaitGroup) { + go func(j primitives.Epoch, pk [fieldparams.BLSPubkeyLength]byte, w *sync.WaitGroup) { defer w.Done() var signingRoot [32]byte copy(signingRoot[:], fmt.Sprintf("%d", j)) att := createAttestation(j, j+1) err := validatorDB.SaveAttestationForPubKey(ctx, pk, signingRoot, att) require.NoError(t, err) - }(types.Epoch(i), pubKey, &wg) + }(primitives.Epoch(i), pubKey, &wg) } wg.Wait() @@ -481,14 +481,14 @@ func TestSaveAttestationForPubKey_BatchWrites_LowCapacity_TimerReached(t *testin func BenchmarkStore_CheckSlashableAttestation_Surround_SafeAttestation_54kEpochs(b *testing.B) { numValidators := 1 - numEpochs := types.Epoch(54000) + numEpochs := primitives.Epoch(54000) pubKeys := make([][fieldparams.BLSPubkeyLength]byte, numValidators) benchCheckSurroundVote(b, pubKeys, numEpochs, false /* surround */) } func BenchmarkStore_CheckSurroundVote_Surround_Slashable_54kEpochs(b *testing.B) { numValidators := 1 - numEpochs := types.Epoch(54000) + numEpochs := primitives.Epoch(54000) pubKeys := make([][fieldparams.BLSPubkeyLength]byte, numValidators) benchCheckSurroundVote(b, pubKeys, numEpochs, true /* surround */) } @@ -496,7 +496,7 @@ func BenchmarkStore_CheckSurroundVote_Surround_Slashable_54kEpochs(b *testing.B) func benchCheckSurroundVote( b *testing.B, pubKeys [][fieldparams.BLSPubkeyLength]byte, - numEpochs types.Epoch, + numEpochs primitives.Epoch, shouldSurround bool, ) { ctx := context.Background() @@ -521,7 +521,7 @@ func benchCheckSurroundVote( if err != nil { return err } - for epoch := types.Epoch(1); epoch < numEpochs; epoch++ { + for epoch := primitives.Epoch(1); epoch < numEpochs; epoch++ { att := createAttestation(epoch-1, epoch) sourceEpoch := bytesutil.EpochToBytesBigEndian(att.Data.Source.Epoch) targetEpoch := bytesutil.EpochToBytesBigEndian(att.Data.Target.Epoch) @@ -555,7 +555,7 @@ func benchCheckSurroundVote( } } -func createAttestation(source, target types.Epoch) *ethpb.IndexedAttestation { +func createAttestation(source, target primitives.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 5818e58c40..2bc64d73b4 100644 --- a/validator/db/kv/deprecated_attester_protection.go +++ b/validator/db/kv/deprecated_attester_protection.go @@ -5,7 +5,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ) @@ -23,7 +23,7 @@ const ( // deprecatedHistoryData stores the needed data to confirm if an attestation is slashable // or repeated. type deprecatedHistoryData struct { - Source types.Epoch + Source primitives.Epoch SigningRoot []byte } @@ -57,14 +57,14 @@ func emptyHistoryData() *deprecatedHistoryData { // newDeprecatedAttestingHistory creates a new encapsulated attestation history byte array // sized by the latest epoch written. -func newDeprecatedAttestingHistory(target types.Epoch) deprecatedEncodedAttestingHistory { +func newDeprecatedAttestingHistory(target primitives.Epoch) deprecatedEncodedAttestingHistory { relativeTarget := target % params.BeaconConfig().WeakSubjectivityPeriod historyDataSize := (relativeTarget + 1) * historySize arraySize := latestEpochWrittenSize + historyDataSize en := make(deprecatedEncodedAttestingHistory, arraySize) enc := en var err error - for i := types.Epoch(0); i <= target%params.BeaconConfig().WeakSubjectivityPeriod; i++ { + for i := primitives.Epoch(0); i <= target%params.BeaconConfig().WeakSubjectivityPeriod; i++ { enc, err = enc.setTargetData(i, emptyHistoryData()) if err != nil { log.WithError(err).Error("Failed to set empty target data") @@ -73,14 +73,14 @@ func newDeprecatedAttestingHistory(target types.Epoch) deprecatedEncodedAttestin return enc } -func (dh deprecatedEncodedAttestingHistory) getLatestEpochWritten() (types.Epoch, error) { +func (dh deprecatedEncodedAttestingHistory) getLatestEpochWritten() (primitives.Epoch, error) { if err := dh.assertSize(); err != nil { return 0, err } - return types.Epoch(bytesutil.FromBytes8(dh[:latestEpochWrittenSize])), nil + return primitives.Epoch(bytesutil.FromBytes8(dh[:latestEpochWrittenSize])), nil } -func (dh deprecatedEncodedAttestingHistory) setLatestEpochWritten(latestEpochWritten types.Epoch) (deprecatedEncodedAttestingHistory, error) { +func (dh deprecatedEncodedAttestingHistory) setLatestEpochWritten(latestEpochWritten primitives.Epoch) (deprecatedEncodedAttestingHistory, error) { if err := dh.assertSize(); err != nil { return nil, err } @@ -88,7 +88,7 @@ func (dh deprecatedEncodedAttestingHistory) setLatestEpochWritten(latestEpochWri return dh, nil } -func (dh deprecatedEncodedAttestingHistory) getTargetData(target types.Epoch) (*deprecatedHistoryData, error) { +func (dh deprecatedEncodedAttestingHistory) getTargetData(target primitives.Epoch) (*deprecatedHistoryData, error) { if err := dh.assertSize(); err != nil { return nil, err } @@ -99,14 +99,14 @@ func (dh deprecatedEncodedAttestingHistory) getTargetData(target types.Epoch) (* return nil, nil } history := &deprecatedHistoryData{} - history.Source = types.Epoch(bytesutil.FromBytes8(dh[cursor : cursor+sourceSize])) + history.Source = primitives.Epoch(bytesutil.FromBytes8(dh[cursor : cursor+sourceSize])) sr := make([]byte, fieldparams.RootLength) copy(sr, dh[cursor+sourceSize:cursor+historySize]) history.SigningRoot = sr return history, nil } -func (dh deprecatedEncodedAttestingHistory) setTargetData(target types.Epoch, historyData *deprecatedHistoryData) (deprecatedEncodedAttestingHistory, error) { +func (dh deprecatedEncodedAttestingHistory) setTargetData(target primitives.Epoch, historyData *deprecatedHistoryData) (deprecatedEncodedAttestingHistory, error) { if err := dh.assertSize(); err != nil { return nil, err } diff --git a/validator/db/kv/deprecated_attester_protection_test.go b/validator/db/kv/deprecated_attester_protection_test.go index c813b7172a..3b5a3ff0da 100644 --- a/validator/db/kv/deprecated_attester_protection_test.go +++ b/validator/db/kv/deprecated_attester_protection_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -14,7 +14,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, types.Epoch(len(ba))) + assert.Equal(t, latestEpochWrittenSize+historySize*params.BeaconConfig().WeakSubjectivityPeriod, primitives.Epoch(len(ba))) ba = newDeprecatedAttestingHistory(params.BeaconConfig().WeakSubjectivityPeriod) assert.Equal(t, latestEpochWrittenSize+historySize, len(ba)) ba = newDeprecatedAttestingHistory(params.BeaconConfig().WeakSubjectivityPeriod + 1) @@ -37,7 +37,7 @@ func TestGetLatestEpochWritten(t *testing.T) { ha[0] = 28 lew, err := ha.getLatestEpochWritten() require.NoError(t, err) - assert.Equal(t, types.Epoch(28), lew) + assert.Equal(t, primitives.Epoch(28), lew) } func TestSetLatestEpochWritten(t *testing.T) { @@ -63,8 +63,8 @@ func TestSetTargetData(t *testing.T) { type testStruct struct { name string enc deprecatedEncodedAttestingHistory - target types.Epoch - source types.Epoch + target primitives.Epoch + source primitives.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 8652264356..3ae9273223 100644 --- a/validator/db/kv/migration_optimal_attester_protection.go +++ b/validator/db/kv/migration_optimal_attester_protection.go @@ -6,7 +6,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/monitoring/progress" bolt "go.etcd.io/bbolt" @@ -82,7 +82,7 @@ func (s *Store) migrateOptimalAttesterProtectionUp(_ 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 := types.Epoch(0); targetEpoch <= latestEpochWritten; targetEpoch++ { + for targetEpoch := primitives.Epoch(0); targetEpoch <= latestEpochWritten; targetEpoch++ { historicalAtt, err := attestingHistory.getTargetData(targetEpoch) if err != nil { return err @@ -122,8 +122,8 @@ func (s *Store) migrateOptimalAttesterProtectionDown(_ 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[types.Epoch][]byte) - targetEpochsBySource := make(map[types.Epoch][]types.Epoch) + signingRootsByTarget := make(map[primitives.Epoch][]byte) + targetEpochsBySource := make(map[primitives.Epoch][]primitives.Epoch) err = s.view(func(tx *bolt.Tx) error { bkt := tx.Bucket(pubKeysBucket) if bkt == nil { @@ -147,7 +147,7 @@ func (s *Store) migrateOptimalAttesterProtectionDown(_ context.Context) error { } // Next up, extract the target epochs by source. if err := sourceEpochsBucket.ForEach(func(sourceBytes, targetEpochsBytes []byte) error { - targetEpochs := make([]types.Epoch, 0) + targetEpochs := make([]primitives.Epoch, 0) for i := 0; i < len(targetEpochsBytes); i += 8 { targetEpochs = append(targetEpochs, bytesutil.BytesToEpochBigEndian(targetEpochsBytes[i:i+8])) } @@ -176,7 +176,7 @@ func (s *Store) migrateOptimalAttesterProtectionDown(_ context.Context) error { // Now we write the attesting history using the data we extracted // from the buckets accordingly. history := newDeprecatedAttestingHistory(0) - var maxTargetWritten types.Epoch + var maxTargetWritten primitives.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 19e9d4450f..73f34681f8 100644 --- a/validator/db/kv/migration_optimal_attester_protection_test.go +++ b/validator/db/kv/migration_optimal_attester_protection_test.go @@ -6,7 +6,7 @@ import ( "testing" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/testing/require" bolt "go.etcd.io/bbolt" @@ -41,8 +41,8 @@ func Test_migrateOptimalAttesterProtectionUp(t *testing.T) { pubKey := [fieldparams.BLSPubkeyLength]byte{1} history := newDeprecatedAttestingHistory(0) // Attest all epochs from genesis to 50. - numEpochs := types.Epoch(50) - for i := types.Epoch(1); i <= numEpochs; i++ { + numEpochs := primitives.Epoch(50) + for i := primitives.Epoch(1); i <= numEpochs; i++ { var sr [32]byte copy(sr[:], fmt.Sprintf("%d", i)) newHist, err := history.setTargetData(i, &deprecatedHistoryData{ @@ -100,8 +100,8 @@ func Test_migrateOptimalAttesterProtectionUp(t *testing.T) { pubKey := [fieldparams.BLSPubkeyLength]byte{1} history := newDeprecatedAttestingHistory(0) // Attest all epochs from genesis to 50. - numEpochs := types.Epoch(50) - for i := types.Epoch(1); i <= numEpochs; i++ { + numEpochs := primitives.Epoch(50) + for i := primitives.Epoch(1); i <= numEpochs; i++ { var sr [32]byte copy(sr[:], fmt.Sprintf("%d", i)) newHist, err := history.setTargetData(i, &deprecatedHistoryData{ @@ -281,7 +281,7 @@ func Test_migrateOptimalAttesterProtectionDown(t *testing.T) { highestEpoch, err := attestingHistory.getLatestEpochWritten() require.NoError(t, err) // Verify the highest epoch written is 50 from the setup stage. - require.Equal(t, types.Epoch(50), highestEpoch) + require.Equal(t, primitives.Epoch(50), highestEpoch) } return nil }) diff --git a/validator/db/kv/proposer_protection.go b/validator/db/kv/proposer_protection.go index 2665da4975..01f43df9ff 100644 --- a/validator/db/kv/proposer_protection.go +++ b/validator/db/kv/proposer_protection.go @@ -7,7 +7,7 @@ import ( "github.com/pkg/errors" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/time/slots" bolt "go.etcd.io/bbolt" @@ -21,8 +21,8 @@ type ProposalHistoryForPubkey struct { // Proposal representation for a validator public key. type Proposal struct { - Slot types.Slot `json:"slot"` - SigningRoot []byte `json:"signing_root"` + Slot primitives.Slot `json:"slot"` + SigningRoot []byte `json:"signing_root"` } // ProposedPublicKeys retrieves all public keys in our proposals history bucket. @@ -46,7 +46,7 @@ func (s *Store) ProposedPublicKeys(ctx context.Context) ([][fieldparams.BLSPubke // ProposalHistoryForSlot accepts a validator public key and returns the corresponding signing root as well // as a boolean that tells us if we have a proposal history stored at the slot. It is possible we have proposed // a slot but stored a nil signing root, so the boolean helps give full information. -func (s *Store) ProposalHistoryForSlot(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte, slot types.Slot) ([32]byte, bool, error) { +func (s *Store) ProposalHistoryForSlot(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte, slot primitives.Slot) ([32]byte, bool, error) { ctx, span := trace.StartSpan(ctx, "Validator.ProposalHistoryForSlot") defer span.End() @@ -99,7 +99,7 @@ func (s *Store) ProposalHistoryForPubKey(ctx context.Context, publicKey [fieldpa // SaveProposalHistoryForSlot saves the proposal history for the requested validator public key. // We also check if the incoming proposal slot is lower than the lowest signed proposal slot // for the validator and override its value on disk. -func (s *Store) SaveProposalHistoryForSlot(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, slot types.Slot, signingRoot []byte) error { +func (s *Store) SaveProposalHistoryForSlot(ctx context.Context, pubKey [fieldparams.BLSPubkeyLength]byte, slot primitives.Slot, signingRoot []byte) error { ctx, span := trace.StartSpan(ctx, "Validator.SaveProposalHistoryForEpoch") defer span.End() @@ -113,7 +113,7 @@ func (s *Store) SaveProposalHistoryForSlot(ctx context.Context, pubKey [fieldpar // If the incoming slot is lower than the lowest signed proposal slot, override. lowestSignedBkt := tx.Bucket(lowestSignedProposalsBucket) lowestSignedProposalBytes := lowestSignedBkt.Get(pubKey[:]) - var lowestSignedProposalSlot types.Slot + var lowestSignedProposalSlot primitives.Slot if len(lowestSignedProposalBytes) >= 8 { lowestSignedProposalSlot = bytesutil.BytesToSlotBigEndian(lowestSignedProposalBytes) } @@ -126,7 +126,7 @@ func (s *Store) SaveProposalHistoryForSlot(ctx context.Context, pubKey [fieldpar // If the incoming slot is higher than the highest signed proposal slot, override. highestSignedBkt := tx.Bucket(highestSignedProposalsBucket) highestSignedProposalBytes := highestSignedBkt.Get(pubKey[:]) - var highestSignedProposalSlot types.Slot + var highestSignedProposalSlot primitives.Slot if len(highestSignedProposalBytes) >= 8 { highestSignedProposalSlot = bytesutil.BytesToSlotBigEndian(highestSignedProposalBytes) } @@ -146,12 +146,12 @@ func (s *Store) SaveProposalHistoryForSlot(ctx context.Context, pubKey [fieldpar // LowestSignedProposal returns the lowest signed proposal slot for a validator public key. // If no data exists, a boolean of value false is returned. -func (s *Store) LowestSignedProposal(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (types.Slot, bool, error) { +func (s *Store) LowestSignedProposal(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (primitives.Slot, bool, error) { ctx, span := trace.StartSpan(ctx, "Validator.LowestSignedProposal") defer span.End() var err error - var lowestSignedProposalSlot types.Slot + var lowestSignedProposalSlot primitives.Slot var exists bool err = s.view(func(tx *bolt.Tx) error { bucket := tx.Bucket(lowestSignedProposalsBucket) @@ -169,12 +169,12 @@ func (s *Store) LowestSignedProposal(ctx context.Context, publicKey [fieldparams // HighestSignedProposal returns the highest signed proposal slot for a validator public key. // If no data exists, a boolean of value false is returned. -func (s *Store) HighestSignedProposal(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (types.Slot, bool, error) { +func (s *Store) HighestSignedProposal(ctx context.Context, publicKey [fieldparams.BLSPubkeyLength]byte) (primitives.Slot, bool, error) { ctx, span := trace.StartSpan(ctx, "Validator.HighestSignedProposal") defer span.End() var err error - var highestSignedProposalSlot types.Slot + var highestSignedProposalSlot primitives.Slot var exists bool err = s.view(func(tx *bolt.Tx) error { bucket := tx.Bucket(highestSignedProposalsBucket) @@ -190,7 +190,7 @@ func (s *Store) HighestSignedProposal(ctx context.Context, publicKey [fieldparam return highestSignedProposalSlot, exists, err } -func pruneProposalHistoryBySlot(valBucket *bolt.Bucket, newestSlot types.Slot) error { +func pruneProposalHistoryBySlot(valBucket *bolt.Bucket, newestSlot primitives.Slot) error { c := valBucket.Cursor() for k, _ := c.First(); k != nil; k, _ = c.First() { slot := bytesutil.BytesToSlotBigEndian(k) diff --git a/validator/db/kv/proposer_protection_test.go b/validator/db/kv/proposer_protection_test.go index 934def356d..e4fb4a691d 100644 --- a/validator/db/kv/proposer_protection_test.go +++ b/validator/db/kv/proposer_protection_test.go @@ -6,7 +6,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -37,7 +37,7 @@ func TestSaveProposalHistoryForSlot_OK(t *testing.T) { pubkey := [fieldparams.BLSPubkeyLength]byte{3} db := setupDB(t, [][fieldparams.BLSPubkeyLength]byte{pubkey}) - slot := types.Slot(2) + slot := primitives.Slot(2) err := db.SaveProposalHistoryForSlot(context.Background(), pubkey, slot, []byte{1}) require.NoError(t, err, "Saving proposal history failed: %v") @@ -61,7 +61,7 @@ func TestSaveProposalHistoryForPubKey_OK(t *testing.T) { pubkey := [fieldparams.BLSPubkeyLength]byte{3} db := setupDB(t, [][fieldparams.BLSPubkeyLength]byte{pubkey}) - slot := types.Slot(2) + slot := primitives.Slot(2) root := [32]byte{1} err := db.SaveProposalHistoryForSlot(context.Background(), pubkey, slot, root[:]) @@ -113,19 +113,19 @@ func TestPruneProposalHistoryBySlot_OK(t *testing.T) { wsPeriod := params.BeaconConfig().WeakSubjectivityPeriod pubKey := [fieldparams.BLSPubkeyLength]byte{0} tests := []struct { - slots []types.Slot - storedSlots []types.Slot - removedSlots []types.Slot + slots []primitives.Slot + storedSlots []primitives.Slot + removedSlots []primitives.Slot }{ { // Go 2 epochs past pruning point. - slots: []types.Slot{slotsPerEpoch / 2, slotsPerEpoch*5 + 6, slotsPerEpoch.Mul(uint64(wsPeriod+3)) + 8}, - storedSlots: []types.Slot{slotsPerEpoch*5 + 6, slotsPerEpoch.Mul(uint64(wsPeriod+3)) + 8}, - removedSlots: []types.Slot{slotsPerEpoch / 2}, + slots: []primitives.Slot{slotsPerEpoch / 2, slotsPerEpoch*5 + 6, slotsPerEpoch.Mul(uint64(wsPeriod+3)) + 8}, + storedSlots: []primitives.Slot{slotsPerEpoch*5 + 6, slotsPerEpoch.Mul(uint64(wsPeriod+3)) + 8}, + removedSlots: []primitives.Slot{slotsPerEpoch / 2}, }, { // Go 10 epochs past pruning point. - slots: []types.Slot{ + slots: []primitives.Slot{ slotsPerEpoch + 4, slotsPerEpoch * 2, slotsPerEpoch * 3, @@ -133,8 +133,8 @@ func TestPruneProposalHistoryBySlot_OK(t *testing.T) { slotsPerEpoch * 5, slotsPerEpoch.Mul(uint64(wsPeriod+10)) + 8, }, - storedSlots: []types.Slot{slotsPerEpoch.Mul(uint64(wsPeriod+10)) + 8}, - removedSlots: []types.Slot{ + storedSlots: []primitives.Slot{slotsPerEpoch.Mul(uint64(wsPeriod+10)) + 8}, + removedSlots: []primitives.Slot{ slotsPerEpoch + 4, slotsPerEpoch * 2, slotsPerEpoch * 3, @@ -144,8 +144,8 @@ func TestPruneProposalHistoryBySlot_OK(t *testing.T) { }, { // Prune none. - slots: []types.Slot{slotsPerEpoch + 4, slotsPerEpoch*2 + 3, slotsPerEpoch*3 + 4, slotsPerEpoch*4 + 3, slotsPerEpoch*5 + 3}, - storedSlots: []types.Slot{slotsPerEpoch + 4, slotsPerEpoch*2 + 3, slotsPerEpoch*3 + 4, slotsPerEpoch*4 + 3, slotsPerEpoch*5 + 3}, + slots: []primitives.Slot{slotsPerEpoch + 4, slotsPerEpoch*2 + 3, slotsPerEpoch*3 + 4, slotsPerEpoch*4 + 3, slotsPerEpoch*5 + 3}, + storedSlots: []primitives.Slot{slotsPerEpoch + 4, slotsPerEpoch*2 + 3, slotsPerEpoch*3 + 4, slotsPerEpoch*4 + 3, slotsPerEpoch*5 + 3}, }, } signedRoot := bytesutil.PadTo([]byte{1}, 32) @@ -157,7 +157,7 @@ func TestPruneProposalHistoryBySlot_OK(t *testing.T) { require.NoError(t, err, "Saving proposal history failed") } - signingRootsBySlot := make(map[types.Slot][]byte) + signingRootsBySlot := make(map[primitives.Slot][]byte) proposalHistory, err := db.ProposalHistoryForPubKey(context.Background(), pubKey) require.NoError(t, err) @@ -219,7 +219,7 @@ func TestStore_LowestSignedProposal(t *testing.T) { slot, exists, err := validatorDB.LowestSignedProposal(ctx, pubkey) require.NoError(t, err) require.Equal(t, true, exists) - assert.Equal(t, types.Slot(2), slot) + assert.Equal(t, primitives.Slot(2), slot) // We save a higher proposal history. err = validatorDB.SaveProposalHistoryForSlot(ctx, pubkey, 3 /* slot */, dummySigningRoot[:]) @@ -229,7 +229,7 @@ func TestStore_LowestSignedProposal(t *testing.T) { slot, exists, err = validatorDB.LowestSignedProposal(ctx, pubkey) require.NoError(t, err) require.Equal(t, true, exists) - assert.Equal(t, types.Slot(2), slot) + assert.Equal(t, primitives.Slot(2), slot) // We save a lower proposal history. err = validatorDB.SaveProposalHistoryForSlot(ctx, pubkey, 1 /* slot */, dummySigningRoot[:]) @@ -239,7 +239,7 @@ func TestStore_LowestSignedProposal(t *testing.T) { slot, exists, err = validatorDB.LowestSignedProposal(ctx, pubkey) require.NoError(t, err) require.Equal(t, true, exists) - assert.Equal(t, types.Slot(1), slot) + assert.Equal(t, primitives.Slot(1), slot) } func TestStore_HighestSignedProposal(t *testing.T) { @@ -260,7 +260,7 @@ func TestStore_HighestSignedProposal(t *testing.T) { slot, exists, err := validatorDB.HighestSignedProposal(ctx, pubkey) require.NoError(t, err) require.Equal(t, true, exists) - assert.Equal(t, types.Slot(2), slot) + assert.Equal(t, primitives.Slot(2), slot) // We save a lower proposal history. err = validatorDB.SaveProposalHistoryForSlot(ctx, pubkey, 1 /* slot */, dummySigningRoot[:]) @@ -270,7 +270,7 @@ func TestStore_HighestSignedProposal(t *testing.T) { slot, exists, err = validatorDB.HighestSignedProposal(ctx, pubkey) require.NoError(t, err) require.Equal(t, true, exists) - assert.Equal(t, types.Slot(2), slot) + assert.Equal(t, primitives.Slot(2), slot) // We save a higher proposal history. err = validatorDB.SaveProposalHistoryForSlot(ctx, pubkey, 3 /* slot */, dummySigningRoot[:]) @@ -280,5 +280,5 @@ func TestStore_HighestSignedProposal(t *testing.T) { slot, exists, err = validatorDB.HighestSignedProposal(ctx, pubkey) require.NoError(t, err) require.Equal(t, true, exists) - assert.Equal(t, types.Slot(3), slot) + assert.Equal(t, primitives.Slot(3), slot) } diff --git a/validator/db/kv/prune_attester_protection.go b/validator/db/kv/prune_attester_protection.go index 7b155e34e6..e007808bf0 100644 --- a/validator/db/kv/prune_attester_protection.go +++ b/validator/db/kv/prune_attester_protection.go @@ -4,7 +4,7 @@ import ( "context" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" bolt "go.etcd.io/bbolt" "go.opencensus.io/trace" @@ -109,8 +109,8 @@ func pruneBucket(bkt *bolt.Bucket) error { // the slashing protection database. This is computed by taking in an epoch and subtracting // SLASHING_PROTECTION_PRUNING_EPOCHS from the value. For example, if we are keeping track of 512 epochs // in the database, if we pass in epoch 612, then we want to prune all epochs before epoch 100. -func pruningEpochCutoff(epoch types.Epoch) types.Epoch { - minEpoch := types.Epoch(0) +func pruningEpochCutoff(epoch primitives.Epoch) primitives.Epoch { + minEpoch := primitives.Epoch(0) if epoch > params.BeaconConfig().SlashingProtectionPruningEpochs { minEpoch = epoch - params.BeaconConfig().SlashingProtectionPruningEpochs } diff --git a/validator/db/kv/prune_attester_protection_test.go b/validator/db/kv/prune_attester_protection_test.go index f1ec9378e1..ea202829bc 100644 --- a/validator/db/kv/prune_attester_protection_test.go +++ b/validator/db/kv/prune_attester_protection_test.go @@ -7,7 +7,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" "github.com/prysmaticlabs/prysm/v3/testing/require" bolt "go.etcd.io/bbolt" @@ -27,7 +27,7 @@ func TestPruneAttestations_NoPruning(t *testing.T) { err = validatorDB.PruneAttestations(context.Background()) require.NoError(t, err) - startEpoch := types.Epoch(0) + startEpoch := primitives.Epoch(0) err = checkAttestingHistoryAfterPruning( t, validatorDB, @@ -58,7 +58,7 @@ func TestPruneAttestations_OK(t *testing.T) { // Next, verify that we pruned every epoch // from genesis to SLASHING_PROTECTION_PRUNING_EPOCHS - 1. - startEpoch := types.Epoch(0) + startEpoch := primitives.Epoch(0) for _, pk := range pks { err := checkAttestingHistoryAfterPruning( t, @@ -114,7 +114,7 @@ func BenchmarkPruneAttestations(b *testing.B) { // 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(validatorDB *Store, pubKey [48]byte, numEpochs types.Epoch) error { +func setupAttestationsForEveryEpoch(validatorDB *Store, pubKey [48]byte, numEpochs primitives.Epoch) error { return validatorDB.update(func(tx *bolt.Tx) error { bucket := tx.Bucket(pubKeysBucket) pkBucket, err := bucket.CreateBucketIfNotExists(pubKey[:]) @@ -129,7 +129,7 @@ func setupAttestationsForEveryEpoch(validatorDB *Store, pubKey [48]byte, numEpoc if err != nil { return err } - for sourceEpoch := types.Epoch(0); sourceEpoch < numEpochs; sourceEpoch++ { + for sourceEpoch := primitives.Epoch(0); sourceEpoch < numEpochs; sourceEpoch++ { targetEpoch := sourceEpoch + 1 targetEpochBytes := bytesutil.EpochToBytesBigEndian(targetEpoch) sourceEpochBytes := bytesutil.EpochToBytesBigEndian(sourceEpoch) @@ -155,7 +155,7 @@ func checkAttestingHistoryAfterPruning( validatorDB *Store, pubKey [fieldparams.BLSPubkeyLength]byte, startEpoch, - numEpochs types.Epoch, + numEpochs primitives.Epoch, shouldBePruned bool, ) error { return validatorDB.view(func(tx *bolt.Tx) error { diff --git a/validator/graffiti/parse_graffiti.go b/validator/graffiti/parse_graffiti.go index 51f362112c..e1d745940d 100644 --- a/validator/graffiti/parse_graffiti.go +++ b/validator/graffiti/parse_graffiti.go @@ -5,7 +5,7 @@ import ( "os" "strings" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "gopkg.in/yaml.v2" ) @@ -18,10 +18,10 @@ const ( // Graffiti is a graffiti container. type Graffiti struct { Hash [32]byte - Default string `yaml:"default,omitempty"` - Ordered []string `yaml:"ordered,omitempty"` - Random []string `yaml:"random,omitempty"` - Specific map[types.ValidatorIndex]string `yaml:"specific,omitempty"` + Default string `yaml:"default,omitempty"` + Ordered []string `yaml:"ordered,omitempty"` + Random []string `yaml:"random,omitempty"` + Specific map[primitives.ValidatorIndex]string `yaml:"specific,omitempty"` } // ParseGraffitiFile parses the graffiti file and returns the graffiti struct. diff --git a/validator/graffiti/parse_graffiti_test.go b/validator/graffiti/parse_graffiti_test.go index 2c2ed352ec..02ada192d9 100644 --- a/validator/graffiti/parse_graffiti_test.go +++ b/validator/graffiti/parse_graffiti_test.go @@ -5,7 +5,7 @@ import ( "path/filepath" "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/hash" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -100,7 +100,7 @@ specific: wanted := &Graffiti{ Hash: hash.Hash(input), - Specific: map[types.ValidatorIndex]string{ + Specific: map[primitives.ValidatorIndex]string{ 1234: "Yolo", 555: "What's up", 703727: "Meow", @@ -149,7 +149,7 @@ specific: "Mr E was here", "Mr F was here", }, - Specific: map[types.ValidatorIndex]string{ + Specific: map[primitives.ValidatorIndex]string{ 1234: "Yolo", 555: "What's up", 703727: "Meow", diff --git a/validator/keymanager/remote-web3signer/v1/custom_mappers.go b/validator/keymanager/remote-web3signer/v1/custom_mappers.go index 76d0df26de..4091ee3c17 100644 --- a/validator/keymanager/remote-web3signer/v1/custom_mappers.go +++ b/validator/keymanager/remote-web3signer/v1/custom_mappers.go @@ -5,14 +5,14 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/pkg/errors" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/network/forks" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/time/slots" ) // MapForkInfo maps the eth2.ForkInfo proto to the Web3Signer spec. -func MapForkInfo(slot types.Slot, genesisValidatorsRoot []byte) (*ForkInfo, error) { +func MapForkInfo(slot primitives.Slot, genesisValidatorsRoot []byte) (*ForkInfo, error) { fork, err := forks.Fork(slots.ToEpoch(slot)) if err != nil { return nil, errors.Wrap(err, "could not get fork info") diff --git a/validator/keymanager/remote-web3signer/v1/custom_mappers_test.go b/validator/keymanager/remote-web3signer/v1/custom_mappers_test.go index c898b8ee71..47f26dd80e 100644 --- a/validator/keymanager/remote-web3signer/v1/custom_mappers_test.go +++ b/validator/keymanager/remote-web3signer/v1/custom_mappers_test.go @@ -6,7 +6,7 @@ import ( "github.com/prysmaticlabs/go-bitfield" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" v1 "github.com/prysmaticlabs/prysm/v3/validator/keymanager/remote-web3signer/v1" "github.com/prysmaticlabs/prysm/v3/validator/keymanager/remote-web3signer/v1/mock" @@ -528,7 +528,7 @@ func TestMapContributionAndProof(t *testing.T) { func TestMapForkInfo(t *testing.T) { type args struct { - slot types.Slot + slot primitives.Slot genesisValidatorsRoot []byte } diff --git a/validator/slashing-protection-history/export_test.go b/validator/slashing-protection-history/export_test.go index e2acfa0540..b22d80bdfe 100644 --- a/validator/slashing-protection-history/export_test.go +++ b/validator/slashing-protection-history/export_test.go @@ -6,7 +6,7 @@ import ( "testing" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" dbtest "github.com/prysmaticlabs/prysm/v3/validator/db/testing" @@ -42,8 +42,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 := types.Epoch(0) - lowestTargetEpoch := types.Epoch(4) + lowestSourceEpoch := primitives.Epoch(0) + lowestTargetEpoch := primitives.Epoch(4) require.NoError(t, validatorDB.SaveAttestationForPubKey(ctx, pubKeys[0], [32]byte{4}, createAttestation( lowestSourceEpoch, @@ -86,8 +86,8 @@ func Test_getSignedAttestationsByPubKey(t *testing.T) { // We write a real attesting history to disk for the public key with // source epoch 0 and target epoch 1000. - lowestSourceEpoch := types.Epoch(0) - lowestTargetEpoch := types.Epoch(1000) + lowestSourceEpoch := primitives.Epoch(0) + lowestTargetEpoch := primitives.Epoch(1000) // Next up, we simulate a DB affected by the bug where the next entry // has a target epoch less than the previous one. @@ -128,8 +128,8 @@ func Test_getSignedAttestationsByPubKey(t *testing.T) { // We write a real attesting history to disk for the public key with // source epoch 1 and target epoch 1000. - lowestSourceEpoch := types.Epoch(1) - lowestTargetEpoch := types.Epoch(1000) + lowestSourceEpoch := primitives.Epoch(1) + lowestTargetEpoch := primitives.Epoch(1000) // Next up, we simulate a DB affected by the bug where the next entry // has a target epoch less than the previous one. diff --git a/validator/slashing-protection-history/helpers.go b/validator/slashing-protection-history/helpers.go index af26b28f00..90dc59a1e6 100644 --- a/validator/slashing-protection-history/helpers.go +++ b/validator/slashing-protection-history/helpers.go @@ -8,7 +8,7 @@ import ( "github.com/k0kubun/go-ansi" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/schollz/progressbar/v3" ) @@ -36,21 +36,21 @@ func Uint64FromString(str string) (uint64, error) { } // EpochFromString converts a string into Epoch. -func EpochFromString(str string) (types.Epoch, error) { +func EpochFromString(str string) (primitives.Epoch, error) { e, err := strconv.ParseUint(str, 10, 64) if err != nil { - return types.Epoch(e), err + return primitives.Epoch(e), err } - return types.Epoch(e), nil + return primitives.Epoch(e), nil } // SlotFromString converts a string into Slot. -func SlotFromString(str string) (types.Slot, error) { +func SlotFromString(str string) (primitives.Slot, error) { s, err := strconv.ParseUint(str, 10, 64) if err != nil { - return types.Slot(s), err + return primitives.Slot(s), err } - return types.Slot(s), nil + return primitives.Slot(s), nil } // PubKeyFromHex takes in a hex string, verifies its length as 48 bytes, and converts that representation. diff --git a/validator/slashing-protection-history/helpers_test.go b/validator/slashing-protection-history/helpers_test.go index 383c17ea75..abe9d43651 100644 --- a/validator/slashing-protection-history/helpers_test.go +++ b/validator/slashing-protection-history/helpers_test.go @@ -7,7 +7,7 @@ import ( "testing" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) func Test_uint64FromString(t *testing.T) { @@ -67,7 +67,7 @@ func Test_uint64FromString(t *testing.T) { t.Errorf("EpochFromString() error = %v, wantErr %v", err, tt.wantErr) return } - if got != types.Epoch(tt.want) { + if got != primitives.Epoch(tt.want) { t.Errorf("EpochFromString() got = %v, want %v", got, tt.want) } }) @@ -77,7 +77,7 @@ func Test_uint64FromString(t *testing.T) { t.Errorf("SlotFromString() error = %v, wantErr %v", err, tt.wantErr) return } - if got != types.Slot(tt.want) { + if got != primitives.Slot(tt.want) { t.Errorf("SlotFromString() got = %v, want %v", got, tt.want) } }) diff --git a/validator/slashing-protection-history/import.go b/validator/slashing-protection-history/import.go index ab4e49bc51..a56d81a0bc 100644 --- a/validator/slashing-protection-history/import.go +++ b/validator/slashing-protection-history/import.go @@ -9,7 +9,7 @@ import ( "github.com/pkg/errors" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1/slashings" @@ -246,7 +246,7 @@ func filterSlashablePubKeysFromBlocks(_ context.Context, historyByPubKey map[[fi // then we consider that proposer public key as slashable. slashablePubKeys := make([][fieldparams.BLSPubkeyLength]byte, 0) for pubKey, proposals := range historyByPubKey { - seenSigningRootsBySlot := make(map[types.Slot][]byte) + seenSigningRootsBySlot := make(map[primitives.Slot][]byte) for _, blk := range proposals.Proposals { if signingRoot, ok := seenSigningRootsBySlot[blk.Slot]; ok { if signingRoot == nil || !bytes.Equal(signingRoot, blk.SigningRoot) { @@ -269,8 +269,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[types.Epoch][32]byte) - targetEpochsBySource := make(map[types.Epoch][]types.Epoch) + signingRootsByTarget := make(map[primitives.Epoch][32]byte) + targetEpochsBySource := make(map[primitives.Epoch][]primitives.Epoch) Loop: for _, att := range signedAtts { // Check for double votes. @@ -367,7 +367,7 @@ func transformSignedAttestations(pubKey [fieldparams.BLSPubkeyLength]byte, atts return historicalAtts, nil } -func createAttestation(source, target types.Epoch) *ethpb.IndexedAttestation { +func createAttestation(source, target primitives.Epoch) *ethpb.IndexedAttestation { return ðpb.IndexedAttestation{ Data: ðpb.AttestationData{ Source: ðpb.Checkpoint{ diff --git a/validator/slashing-protection-history/import_test.go b/validator/slashing-protection-history/import_test.go index ebb2a38b3c..2736856c02 100644 --- a/validator/slashing-protection-history/import_test.go +++ b/validator/slashing-protection-history/import_test.go @@ -10,7 +10,7 @@ import ( "testing" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ethpb "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" @@ -151,7 +151,7 @@ func TestStore_ImportInterchangeData_OK(t *testing.T) { receivedProposalHistory, err := validatorDB.ProposalHistoryForPubKey(ctx, publicKeys[i]) require.NoError(t, err) - rootsBySlot := make(map[types.Slot][]byte) + rootsBySlot := make(map[primitives.Slot][]byte) for _, proposal := range receivedProposalHistory { rootsBySlot[proposal.Slot] = proposal.SigningRoot } diff --git a/validator/slashing-protection-history/round_trip_test.go b/validator/slashing-protection-history/round_trip_test.go index 1987abbd7e..e02c67affa 100644 --- a/validator/slashing-protection-history/round_trip_test.go +++ b/validator/slashing-protection-history/round_trip_test.go @@ -7,7 +7,7 @@ import ( "fmt" "testing" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/validator/db/kv" @@ -218,7 +218,7 @@ func TestImportInterchangeData_OK(t *testing.T) { proposals := proposalHistory[i].Proposals receivedProposalHistory, err := validatorDB.ProposalHistoryForPubKey(ctx, publicKeys[i]) require.NoError(t, err) - rootsBySlot := make(map[types.Slot][]byte) + rootsBySlot := make(map[primitives.Slot][]byte) for _, proposal := range receivedProposalHistory { rootsBySlot[proposal.Slot] = proposal.SigningRoot } diff --git a/validator/testing/protection_history.go b/validator/testing/protection_history.go index 0c4409a318..a4c17fbcae 100644 --- a/validator/testing/protection_history.go +++ b/validator/testing/protection_history.go @@ -5,7 +5,7 @@ import ( fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" - types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" "github.com/prysmaticlabs/prysm/v3/crypto/rand" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" @@ -59,7 +59,7 @@ func MockAttestingAndProposalHistories(pubkeys [][fieldparams.BLSPubkeyLength]by proposalData := make([]kv.ProposalHistoryForPubkey, numValidators) gen := rand.NewGenerator() for v := 0; v < numValidators; v++ { - latestTarget := types.Epoch(gen.Intn(int(params.BeaconConfig().WeakSubjectivityPeriod) / 1000)) + latestTarget := primitives.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 { @@ -67,7 +67,7 @@ func MockAttestingAndProposalHistories(pubkeys [][fieldparams.BLSPubkeyLength]by } historicalAtts := make([]*kv.AttestationRecord, 0) proposals := make([]kv.Proposal, 0) - for i := types.Epoch(1); i < latestTarget; i++ { + for i := primitives.Epoch(1); i < latestTarget; i++ { var signingRoot [32]byte signingRootStr := fmt.Sprintf("%d", i) copy(signingRoot[:], signingRootStr) @@ -78,12 +78,12 @@ func MockAttestingAndProposalHistories(pubkeys [][fieldparams.BLSPubkeyLength]by PubKey: pubkeys[v], }) } - for i := types.Epoch(1); i <= latestTarget; i++ { + for i := primitives.Epoch(1); i <= latestTarget; i++ { var signingRoot [32]byte signingRootStr := fmt.Sprintf("%d", i) copy(signingRoot[:], signingRootStr) proposals = append(proposals, kv.Proposal{ - Slot: types.Slot(i), + Slot: primitives.Slot(i), SigningRoot: signingRoot[:], }) }